]> git.mxchange.org Git - core.git/blob - framework/main/classes/template/class_BaseTemplateEngine.php
Some updates:
[core.git] / framework / main / classes / template / class_BaseTemplateEngine.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Template\Engine;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
10 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
11 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
12 use Org\Mxchange\CoreFramework\Response\Responseable;
13
14 // Import SPL stuff
15 use \InvalidArgumentException;
16 use \SplFileInfo;
17
18 /**
19  * A generic template engine
20  *
21  * @author              Roland Haeder <webmaster@shipsimu.org>
22  * @version             0.0.0
23 <<<<<<< HEAD:framework/main/classes/template/class_BaseTemplateEngine.php
24  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
25 =======
26  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
27 >>>>>>> Some updates::inc/main/classes/template/class_BaseTemplateEngine.php
28  * @license             GNU GPL 3.0 or any newer version
29  * @link                http://www.shipsimu.org
30  *
31  * This program is free software: you can redistribute it and/or modify
32  * it under the terms of the GNU General Public License as published by
33  * the Free Software Foundation, either version 3 of the License, or
34  * (at your option) any later version.
35  *
36  * This program is distributed in the hope that it will be useful,
37  * but WITHOUT ANY WARRANTY; without even the implied warranty of
38  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
39  * GNU General Public License for more details.
40  *
41  * You should have received a copy of the GNU General Public License
42  * along with this program. If not, see <http://www.gnu.org/licenses/>.
43  */
44 abstract class BaseTemplateEngine extends BaseFrameworkSystem {
45         /**
46          * The local path name where all templates and sub folders for special
47          * templates are stored. We will internally determine the language plus
48          * "html" for web templates or "emails" for email templates
49          */
50         private $templateBasePath = '';
51
52         /**
53          * Template type
54          */
55         private $templateType = 'html';
56
57         /**
58          * The extension for web and email templates (not compiled templates)
59          */
60         private $templateExtension = '.tpl';
61
62         /**
63          * The extension for code templates (not compiled templates)
64          */
65         private $codeExtension = '.ctp';
66
67         /**
68          * Path relative to $templateBasePath and language code for compiled code-templates
69          */
70         private $compileOutputPath = 'templates/_compiled/';
71
72         /**
73          * The path name for all templates
74          */
75         private $genericBasePath = 'templates/';
76
77         /**
78          * The raw (maybe uncompiled) template
79          */
80         private $rawTemplateData = '';
81
82         /**
83          * Template data with compiled-in variables
84          */
85         private $compiledData = '';
86
87         /**
88          * The last loaded template's file instance (SplFileInfo)
89          */
90         private $lastTemplate = NULL;
91
92         /**
93          * The variable stack for the templates
94          */
95         private $varStack = array();
96
97         /**
98          * Loaded templates for recursive protection and detection
99          */
100         private $loadedTemplates = array();
101
102         /**
103          * Compiled templates for recursive protection and detection
104          */
105         private $compiledTemplates = array();
106
107         /**
108          * Loaded raw template data
109          */
110         private $loadedRawData = NULL;
111
112         /**
113          * Raw templates which are linked in code templates
114          */
115         private $rawTemplates = NULL;
116
117         /**
118          * A regular expression for variable=value pairs
119          */
120         private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
121
122         /**
123          * A regular expression for filtering out code tags
124          *
125          * E.g.: {?template:variable=value;var2=value2;[...]?}
126          */
127         private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
128
129         /**
130          * A regular expression to find template comments like <!-- Comment here //-->
131          */
132         private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
133
134         /**
135          * Loaded helpers
136          */
137         private $helpers = array();
138
139         /**
140          * Current variable group
141          */
142         private $currGroup = 'general';
143
144         /**
145          * All template groups except "general"
146          */
147         private $variableGroups = array();
148
149         /**
150          * Code begin
151          */
152         private $codeBegin = '<?php';
153
154         /**
155          * Code end
156          */
157         private $codeEnd = '?>';
158
159         /**
160          * Language support is enabled by default
161          */
162         private $languageSupport = true;
163
164         /**
165          * XML compacting is disabled by default
166          */
167         private $xmlCompacting = false;
168
169         // Exception codes for the template engine
170         const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0x110;
171         const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
172         const EXCEPTION_INVALID_VIEW_HELPER           = 0x112;
173         const EXCEPTION_VARIABLE_IS_MISSING           = 0x113;
174
175         /**
176          * Protected constructor
177          *
178          * @param       $className      Name of the class
179          * @return      void
180          */
181         protected function __construct ($className) {
182                 // Call parent constructor
183                 parent::__construct($className);
184
185                 // Init file I/O instance
186                 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
187
188                 // Set it
189                 $this->setFileIoInstance($ioInstance);
190         }
191
192         /**
193          * Search for a variable in the stack
194          *
195          * @param       $variableName   The variable we are looking for
196          * @param       $variableGroup  Optional variable group to look in
197          * @return      $index                  false means not found, >=0 means found on a specific index
198          */
199         private function getVariableIndex ($variableName, $variableGroup = NULL) {
200                 // Replace all dashes to underscores to match variables with configuration entries
201                 $variableName = trim(self::convertDashesToUnderscores($variableName));
202
203                 // First everything is not found
204                 $found = false;
205
206                 // If the stack is NULL, use the current group
207                 if (is_null($variableGroup)) {
208                         // Use current group
209                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
210                         $variableGroup = $this->currGroup;
211                 } // END - if
212
213                 // Is the group there?
214                 if ($this->isVarStackSet($variableGroup)) {
215                         // Now search for it
216                         foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
217                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
218                                 // Is the entry found?
219                                 if ($currEntry['name'] == $variableName) {
220                                         // Found!
221                                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
222                                         $found = $index;
223                                         break;
224                                 } // END - if
225                         } // END - foreach
226                 } // END - if
227
228                 // Return the current position
229                 return $found;
230         }
231
232         /**
233          * Checks whether the given variable group is set
234          *
235          * @param       $variableGroup  Variable group to check
236          * @return      $isSet                  Whether the given variable group is set
237          */
238         protected final function isVarStackSet ($variableGroup) {
239                 // Check it
240                 $isSet = isset($this->varStack[$variableGroup]);
241
242                 // Return result
243                 return $isSet;
244         }
245
246         /**
247          * Getter for given variable group
248          *
249          * @param       $variableGroup  Variable group to check
250          * @return      $varStack               Found variable group
251          */
252         public final function getVarStack ($variableGroup) {
253                 return $this->varStack[$variableGroup];
254         }
255
256         /**
257          * Setter for given variable group
258          *
259          * @param       $variableGroup  Variable group to check
260          * @param       $varStack               Variable stack to check
261          * @return      void
262          */
263         protected final function setVarStack ($variableGroup, array $varStack) {
264                 $this->varStack[$variableGroup]  = $varStack;
265         }
266
267         /**
268          * Return a content of a variable or null if not found
269          *
270          * @param       $variableName   The variable we are looking for
271          * @param       $variableGroup  Optional variable group to look in
272          * @return      $content                Content of the variable or null if not found
273          */
274         protected function readVariable ($variableName, $variableGroup = NULL) {
275                 // Replace all dashes to underscores to match variables with configuration entries
276                 $variableName = trim(self::convertDashesToUnderscores($variableName));
277
278                 // First everything is not found
279                 $content = NULL;
280
281                 // If the stack is NULL, use the current group
282                 if (is_null($variableGroup)) {
283                         // Use current group
284                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
285                         $variableGroup = $this->currGroup;
286                 } // END - if
287
288                 // Get variable index
289                 $found = $this->getVariableIndex($variableName, $variableGroup);
290
291                 // Is the variable found?
292                 if ($found !== false) {
293                         // Read it
294                         $content = $this->getVariableValue($variableGroup, $found);
295                 } // END - if
296
297                 // Return the current position
298                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
299                 return $content;
300         }
301
302         /**
303          * Add a variable to the stack
304          *
305          * @param       $variableName   Name of variable to add
306          * @param       $value                  Value we want to store in the variable
307          * @return      void
308          */
309         private function addVariable ($variableName, $value) {
310                 // Set general variable group
311                 $this->setVariableGroup('general');
312
313                 // Add it to the stack
314                 $this->addGroupVariable($variableName, $value);
315         }
316
317         /**
318          * Returns all variables of current group or empty array
319          *
320          * @return      $result         Whether array of found variables or empty array
321          */
322         private function readCurrentGroup () {
323                 // Default is not found
324                 $result = array();
325
326                 // Is the group there?
327                 if ($this->isVarStackSet($this->currGroup)) {
328                         // Then use it
329                         $result = $this->getVarStack($this->currGroup);
330                 } // END - if
331
332                 // Return result
333                 return $result;
334         }
335
336         /**
337          * Settter for variable group
338          *
339          * @param       $groupName      Name of variable group
340          * @param       $add            Whether add this group
341          * @return      void
342          */
343         public function setVariableGroup ($groupName, $add = true) {
344                 // Set group name
345                 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
346                 $this->currGroup = $groupName;
347
348                 // Skip group 'general'
349                 if (($groupName != 'general') && ($add === true)) {
350                         $this->variableGroups[$groupName] = 'OK';
351                 } // END - if
352         }
353
354
355         /**
356          * Adds a variable to current group
357          *
358          * @param       $variableName   Variable to set
359          * @param       $value                  Value to store in variable
360          * @return      void
361          */
362         public function addGroupVariable ($variableName, $value) {
363                 // Replace all dashes to underscores to match variables with configuration entries
364                 $variableName = trim(self::convertDashesToUnderscores($variableName));
365
366                 // Debug message
367                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
368
369                 // Get current variables in group
370                 $currVars = $this->readCurrentGroup();
371
372                 // Append our variable
373                 array_push($currVars, $this->generateVariableArray($variableName, $value));
374
375                 // Add it to the stack
376                 $this->setVarStack($this->currGroup, $currVars);
377         }
378
379         /**
380          * Getter for variable value, throws a NoVariableException if the variable is not found
381          *
382          * @param       $variableGroup  Variable group to use
383          * @param       $index          Index in variable array
384          * @return      $value          Value to set
385          */
386         private function getVariableValue ($variableGroup, $index) {
387                 // Return it
388                 return $this->varStack[$variableGroup][$index]['value'];
389         }
390
391         /**
392          * Modify an entry on the stack
393          *
394          * @param       $variableName   The variable we are looking for
395          * @param       $value                  The value we want to store in the variable
396          * @return      void
397          * @throws      NoVariableException     If the given variable is not found
398          */
399         private function modifyVariable ($variableName, $value) {
400                 // Replace all dashes to underscores to match variables with configuration entries
401                 $variableName = trim(self::convertDashesToUnderscores($variableName));
402
403                 // Get index for variable
404                 $index = $this->getVariableIndex($variableName);
405
406                 // Is the variable set?
407                 if ($index === false) {
408                         // Unset variables cannot be modified
409                         throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
410                 } // END - if
411
412                 // Then modify it
413                 $this->setVariableValue($this->currGroup, $index, $value);
414         }
415
416         /**
417          * Sets a variable value for given variable group and index
418          *
419          * @param       $variableGroup  Variable group to use
420          * @param       $index          Index in variable array
421          * @param       $value          Value to set
422          * @return      void
423          */
424         private function setVariableValue ($variableGroup, $index, $value) {
425                 $this->varStack[$variableGroup][$index]['value'] = $value;
426         }
427
428         /**
429          * Sets a variable within given group. This method does detect if the
430          * variable is already set. If so, the variable got modified, otherwise
431          * added.
432          *
433          * @param       $variableGroup          Variable group to use
434          * @param       $variableName   Variable to set
435          * @param       $value                  Value to set
436          * @return      void
437          */
438         protected function setVariable ($variableGroup, $variableName, $value) {
439                 // Replace all dashes to underscores to match variables with configuration entries
440                 $variableName = trim(self::convertDashesToUnderscores($variableName));
441
442                 // Get index for variable
443                 $index = $this->getVariableIndex($variableName);
444
445                 // Is the variable set?
446                 if ($index === false) {
447                         // Is the stack there?
448                         if (!isset($this->varStack[$variableGroup])) {
449                                 // Then initialize it here
450                                 $this->varStack[$variableGroup] = array();
451                         } // END - if
452
453                         // Not found, add it
454                         array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
455                 } else {
456                         // Then modify it
457                         $this->setVariableValue($this->currGroup, $index, $value);
458                 }
459         }
460
461         /**
462          * "Generates" (better returns) an array for all variables for given
463          * variable/value pay.
464          *
465          * @param       $variableName   Variable to set
466          * @param       $value                  Value to set
467          * @return      $varData                Variable data array
468          */
469         private function generateVariableArray ($variableName, $value) {
470                 // Replace all dashes to underscores to match variables with configuration entries
471                 $variableName = trim(self::convertDashesToUnderscores($variableName));
472
473                 // Generate the temporary array
474                 $varData = array(
475                         'name'  => $variableName,
476                         'value' => $value
477                 );
478
479                 // And return it
480                 return $varData;
481         }
482
483         /**
484          * Setter for template type. Only 'html', 'emails' and 'compiled' should
485          * be sent here
486          *
487          * @param       $templateType   The current template's type
488          * @return      void
489          */
490         protected final function setTemplateType ($templateType) {
491                 $this->templateType = (string) $templateType;
492         }
493
494         /**
495          * Getter for template type
496          *
497          * @return      $templateType   The current template's type
498          */
499         public final function getTemplateType () {
500                 return $this->templateType;
501         }
502
503         /**
504          * Setter for the last loaded template's file instance
505          *
506          * @param       $template       The last loaded template
507          * @return      void
508          */
509         private final function setLastTemplate (SplFileInfo $fileInstance) {
510                 $this->lastTemplate = $fileInstance;
511         }
512
513         /**
514          * Getter for the last loaded template's file instance
515          *
516          * @return      $template       The last loaded template
517          */
518         private final function getLastTemplate () {
519                 return $this->lastTemplate;
520         }
521
522         /**
523          * Setter for base path
524          *
525          * @param               $templateBasePath               The relative base path for all templates
526          * @return      void
527          */
528         protected final function setTemplateBasePath ($templateBasePath) {
529                 // And set it
530                 $this->templateBasePath = (string) $templateBasePath;
531         }
532
533         /**
534          * Getter for base path
535          *
536          * @return      $templateBasePath               The relative base path for all templates
537          */
538         public final function getTemplateBasePath () {
539                 // And set it
540                 return $this->templateBasePath;
541         }
542
543         /**
544          * Getter for generic base path
545          *
546          * @return      $templateBasePath               The relative base path for all templates
547          */
548         public final function getGenericBasePath () {
549                 // And set it
550                 return $this->genericBasePath;
551         }
552
553         /**
554          * Setter for template extension
555          *
556          * @param               $templateExtension      The file extension for all uncompiled
557          *                                                      templates
558          * @return      void
559          */
560         protected final function setRawTemplateExtension ($templateExtension) {
561                 // And set it
562                 $this->templateExtension = (string) $templateExtension;
563         }
564
565         /**
566          * Setter for code template extension
567          *
568          * @param               $codeExtension          The file extension for all uncompiled
569          *                                                      templates
570          * @return      void
571          */
572         protected final function setCodeTemplateExtension ($codeExtension) {
573                 // And set it
574                 $this->codeExtension = (string) $codeExtension;
575         }
576
577         /**
578          * Getter for template extension
579          *
580          * @return      $templateExtension      The file extension for all uncompiled
581          *                                                      templates
582          */
583         public final function getRawTemplateExtension () {
584                 // And set it
585                 return $this->templateExtension;
586         }
587
588         /**
589          * Getter for code-template extension
590          *
591          * @return      $codeExtension          The file extension for all code-
592          *                                                      templates
593          */
594         public final function getCodeTemplateExtension () {
595                 // And set it
596                 return $this->codeExtension;
597         }
598
599         /**
600          * Setter for path of compiled templates
601          *
602          * @param       $compileOutputPath      The local base path for all compiled
603          *                                                              templates
604          * @return      void
605          */
606         protected final function setCompileOutputPath ($compileOutputPath) {
607                 // And set it
608                 $this->compileOutputPath = (string) $compileOutputPath;
609         }
610
611         /**
612          * Unsets the given offset in the variable group
613          *
614          * @param       $index                  Index to unset
615          * @param       $variableGroup  Variable group (default: currGroup)
616          * @return      void
617          */
618         protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
619                 // Is the variable group not set?
620                 if (is_null($variableGroup)) {
621                         // Then set it to current
622                         $variableGroup = $this->currGroup;
623                 } // END - if
624
625                 // Is the entry there?
626                 if (!isset($this->varStack[$variableGroup][$index])) {
627                         // Abort here, we need fixing!
628                         $this->debugInstance();
629                 } // END - if
630
631                 // Remove it
632                 unset($this->varStack[$variableGroup][$index]);
633         }
634
635         /**
636          * Private setter for raw template data
637          *
638          * @param       $rawTemplateData        The raw data from the template
639          * @return      void
640          */
641         protected final function setRawTemplateData ($rawTemplateData) {
642                 // And store it in this class
643                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
644                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
645                 $this->rawTemplateData = (string) $rawTemplateData;
646         }
647
648         /**
649          * Getter for raw template data
650          *
651          * @return      $rawTemplateData        The raw data from the template
652          */
653         public final function getRawTemplateData () {
654                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
655                 return $this->rawTemplateData;
656         }
657
658         /**
659          * Private setter for compiled templates
660          *
661          * @return      void
662          */
663         private final function setCompiledData ($compiledData) {
664                 // And store it in this class
665                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
666                 $this->compiledData = (string) $compiledData;
667         }
668
669         /**
670          * Getter for compiled templates, must be public for e.g. Mailer classes.
671          *
672          * @return      $compiledData   Compiled template data
673          */
674         public final function getCompiledData () {
675                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
676                 return $this->compiledData;
677         }
678
679         /**
680          * Private loader for all template types
681          *
682          * @param       $templateName   The template we shall load
683          * @param       $extOther       An other extension to use
684          * @return      void
685          * @throws      FileNotFoundException   If the template was not found
686          */
687         protected function loadTemplate ($templateName, $extOther = '') {
688                 // Get extension for the template if empty
689                 if (empty($extOther)) {
690                         // None provided, so get the raw one
691                         $ext = $this->getRawTemplateExtension();
692                 } else {
693                         // Then use it!
694                         $ext = (string) $extOther;
695                 }
696
697                 /*
698                  * Construct the FQFN for the template without language as language is
699                  * now entirely done by php_intl. These old thing with language-based
700                  * template paths comes from an older time.
701                  */
702                 $fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
703                         $this->getTemplateBasePath(),
704                         $this->getGenericBasePath(),
705                         $this->getTemplateType(),
706                         DIRECTORY_SEPARATOR,
707                         (string) $templateName,
708                         $ext
709                 ));
710
711                 // First try this
712                 try {
713                         // Load the raw template data
714                         $this->loadRawTemplateData($fileInstance);
715                 } catch (FileNotFoundException $e) {
716                         // If we shall load a code-template we need to switch the file extension
717                         if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
718                                 // Switch over to the code-template extension and try it again
719                                 $ext = $this->getCodeTemplateExtension();
720
721                                 // Try it again...
722                                 $this->loadTemplate($templateName, $ext);
723                         } else {
724                                 // Throw it again
725                                 throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
726                         }
727                 }
728
729         }
730
731         /**
732          * A private loader for raw template names
733          *
734          * @param       $fileInstance   An instance of a SplFileInfo class
735          * @return      void
736          */
737         private function loadRawTemplateData (SplFileInfo $fileInstance) {
738                 // Some debug code to look on the file which is being loaded
739                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: fileInstance=' . $fileInstance);
740
741                 // Load the raw template
742                 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
743
744                 // Store the template's contents into this class
745                 $this->setRawTemplateData($rawTemplateData);
746
747                 // Remember the template's file instance
748                 $this->setLastTemplate($fileInstance);
749         }
750
751         /**
752          * Try to assign an extracted template variable as a "content" or 'config'
753          * variable.
754          *
755          * @param       $variableName           The variable's name (shall be content or config)
756          *                                                      by default
757          * @param       $variableName   The variable we want to assign
758          * @return      void
759          */
760         private function assignTemplateVariable ($variableName, $var) {
761                 // Replace all dashes to underscores to match variables with configuration entries
762                 $variableName = trim(self::convertDashesToUnderscores($variableName));
763
764                 // Debug message
765                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
766
767                 // Is it not a config variable?
768                 if ($variableName != 'config') {
769                         // Regular template variables
770                         $this->assignVariable($variableName, '');
771                 } else {
772                         // Configuration variables
773                         $this->assignConfigVariable($var);
774                 }
775         }
776
777         /**
778          * Extract variables from a given raw data stream
779          *
780          * @param       $rawData        The raw template data we shall analyze
781          * @return      void
782          */
783         private function extractVariablesFromRawData ($rawData) {
784                 // Cast to string
785                 $rawData = (string) $rawData;
786
787                 // Search for variables
788                 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
789
790                 // Debug message
791                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
792
793                 // Did we find some variables?
794                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
795                         // Initialize all missing variables
796                         foreach ($variableMatches[3] as $key => $var) {
797                                 // Variable name
798                                 $variableName = $variableMatches[1][$key];
799
800                                 // Workarround: Do not assign empty variables
801                                 if (!empty($var)) {
802                                         // Try to assign it, empty strings are being ignored
803                                         $this->assignTemplateVariable($variableName, $var);
804                                 } // END - if
805                         } // END - foreach
806                 } // END - if
807         }
808
809         /**
810          * Main analysis of the loaded template
811          *
812          * @param       $templateMatches        Found template place-holders, see below
813          * @return      void
814          *
815          *---------------------------------
816          * Structure of $templateMatches:
817          *---------------------------------
818          * [0] => Array - An array with all full matches
819          * [1] => Array - An array with left part (before the ':') of a match
820          * [2] => Array - An array with right part of a match including ':'
821          * [3] => Array - An array with right part of a match excluding ':'
822          */
823         private function analyzeTemplate (array $templateMatches) {
824                 // Backup raw template data
825                 $backup = $this->getRawTemplateData();
826
827                 // Initialize some arrays
828                 if (is_null($this->loadedRawData)) {
829                         // Initialize both
830                         $this->loadedRawData = array();
831                         $this->rawTemplates = array();
832                 } // END - if
833
834                 // Load all requested templates
835                 foreach ($templateMatches[1] as $template) {
836                         // Load and compile only templates which we have not yet loaded
837                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
838                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
839                                 // Debug message
840                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
841
842                                 // Template not found, but maybe variable assigned?
843                                 if ($this->getVariableIndex($template) !== false) {
844                                         // Use that content here
845                                         $this->loadedRawData[$template] = $this->readVariable($template);
846
847                                         // Recursive protection:
848                                         array_push($this->loadedTemplates, $template);
849                                 } else {
850                                         // Then try to search for code-templates
851                                         try {
852                                                 // Load the code template and remember it's contents
853                                                 $this->loadCodeTemplate($template);
854                                                 $this->loadedRawData[$template] = $this->getRawTemplateData();
855
856                                                 // Remember this template for recursion detection
857                                                 // RECURSIVE PROTECTION!
858                                                 array_push($this->loadedTemplates, $template);
859                                         } catch (FileNotFoundException $e) {
860                                                 // Even this is not done... :/
861                                                 array_push($this->rawTemplates, $template);
862                                         }
863                                 }
864                         } // END - if
865                 } // END - foreach
866
867                 // Restore the raw template data
868                 $this->setRawTemplateData($backup);
869         }
870
871         /**
872          * Compile a given raw template code and remember it for later usage
873          *
874          * @param       $code           The raw template code
875          * @param       $template       The template's name
876          * @return      void
877          */
878         private function compileCode ($code, $template) {
879                 // Is this template already compiled?
880                 if (in_array($template, $this->compiledTemplates)) {
881                         // Abort here...
882                         return;
883                 } // END - if
884
885                 // Remember this template being compiled
886                 array_push($this->compiledTemplates, $template);
887
888                 // Compile the loaded code in five steps:
889                 //
890                 // 1. Backup current template data
891                 $backup = $this->getRawTemplateData();
892
893                 // 2. Set the current template's raw data as the new content
894                 $this->setRawTemplateData($code);
895
896                 // 3. Compile the template data
897                 $this->compileTemplate();
898
899                 // 4. Remember it's contents
900                 $this->loadedRawData[$template] = $this->getRawTemplateData();
901
902                 // 5. Restore the previous raw content from backup variable
903                 $this->setRawTemplateData($backup);
904         }
905
906         /**
907          * Insert all given and loaded templates by running through all loaded
908          * codes and searching for their place-holder in the main template
909          *
910          * @param       $templateMatches        See method analyzeTemplate()
911          * @return      void
912          */
913         private function insertAllTemplates (array $templateMatches) {
914                 // Run through all loaded codes
915                 foreach ($this->loadedRawData as $template => $code) {
916
917                         // Search for the template
918                         $foundIndex = array_search($template, $templateMatches[1]);
919
920                         // Lookup the matching template replacement
921                         if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
922
923                                 // Get the current raw template
924                                 $rawData = $this->getRawTemplateData();
925
926                                 // Replace the space holder with the template code
927                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
928
929                                 // Set the new raw data
930                                 $this->setRawTemplateData($rawData);
931                         } // END - if
932                 } // END - foreach
933         }
934
935         /**
936          * Load all extra raw templates
937          *
938          * @return      void
939          */
940         private function loadExtraRawTemplates () {
941                 // Are there some raw templates we need to load?
942                 if (count($this->rawTemplates) > 0) {
943                         // Try to load all raw templates
944                         foreach ($this->rawTemplates as $key => $template) {
945                                 try {
946                                         // Load the template
947                                         $this->loadHtmlTemplate($template);
948
949                                         // Remember it's contents
950                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
951
952                                         // Remove it from the loader list
953                                         unset($this->rawTemplates[$key]);
954
955                                         // Remember this template for recursion detection
956                                         // RECURSIVE PROTECTION!
957                                         array_push($this->loadedTemplates, $template);
958                                 } catch (FileNotFoundException $e) {
959                                         // This template was never found. We silently ignore it
960                                         unset($this->rawTemplates[$key]);
961                                 }
962                         } // END - foreach
963                 } // END - if
964         }
965
966         /**
967          * Assign all found template variables
968          *
969          * @param       $varMatches             An array full of variable/value pairs.
970          * @return      void
971          * @todo        Unfinished work or don't die here.
972          */
973         private function assignAllVariables (array $varMatches) {
974                 // Debug message
975                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
976
977                 // Search for all variables
978                 foreach ($varMatches[1] as $key => $var) {
979                         // Replace all dashes to underscores to match variables with configuration entries
980                         $var = trim(self::convertDashesToUnderscores($var));
981
982                         // Debug message
983                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
984
985                         // Detect leading equals
986                         if (substr($varMatches[2][$key], 0, 1) == '=') {
987                                 // Remove and cast it
988                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
989                         } // END - if
990
991                         // Do we have some quotes left and right side? Then it is free text
992                         if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
993                                 // Free string detected! Which we can assign directly
994                                 $this->assignVariable($var, $varMatches[3][$key]);
995                         } elseif (!empty($varMatches[2][$key])) {
996                                 // @TODO Non-string found so we need some deeper analysis...
997                                 ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
998                         }
999                 } // END - foreach
1000         }
1001
1002         /**
1003          * Compiles all loaded raw templates
1004          *
1005          * @param       $templateMatches        See method analyzeTemplate() for details
1006          * @return      void
1007          */
1008         private function compileRawTemplateData (array $templateMatches) {
1009                 // Debug message
1010                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1011
1012                 // Are some code-templates found which we need to compile?
1013                 if (count($this->loadedRawData) > 0) {
1014                         // Then compile all!
1015                         foreach ($this->loadedRawData as $template => $code) {
1016                                 // Debug message
1017                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1018
1019                                 // Is this template already compiled?
1020                                 if (in_array($template, $this->compiledTemplates)) {
1021                                         // Then skip it
1022                                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1023                                         continue;
1024                                 } // END - if
1025
1026                                 // Search for the template
1027                                 $foundIndex = array_search($template, $templateMatches[1]);
1028
1029                                 // Lookup the matching variable data
1030                                 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1031                                         // Split it up with another reg. exp. into variable=value pairs
1032                                         preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1033                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1034
1035                                         // Assign all variables
1036                                         $this->assignAllVariables($varMatches);
1037                                 } // END - if (isset($templateMatches ...
1038
1039                                 // Compile the loaded template
1040                                 $this->compileCode($code, $template);
1041                         } // END - foreach ($this->loadedRawData ...
1042
1043                         // Insert all templates
1044                         $this->insertAllTemplates($templateMatches);
1045                 } // END - if (count($this->loadedRawData) ...
1046         }
1047
1048         /**
1049          * Inserts all raw templates into their respective variables
1050          *
1051          * @return      void
1052          */
1053         private function insertRawTemplates () {
1054                 // Load all templates
1055                 foreach ($this->rawTemplates as $template => $content) {
1056                         // Set the template as a variable with the content
1057                         $this->assignVariable($template, $content);
1058                 }
1059         }
1060
1061         /**
1062          * Finalizes the compilation of all template variables
1063          *
1064          * @return      void
1065          */
1066         private function finalizeVariableCompilation () {
1067                 // Get the content
1068                 $content = $this->getRawTemplateData();
1069                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1070
1071                 // Do we have the stack?
1072                 if (!$this->isVarStackSet('general')) {
1073                         // Abort here silently
1074                         // @TODO This silent abort should be logged, maybe.
1075                         return;
1076                 } // END - if
1077
1078                 // Walk through all variables
1079                 foreach ($this->getVarStack('general') as $currEntry) {
1080                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1081                         // Replace all [$var] or {?$var?} with the content
1082                         // @TODO Old behaviour, will become obsolete!
1083                         $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1084
1085                         // @TODO Yet another old way
1086                         $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1087
1088                         // The new behaviour
1089                         $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1090                 } // END - for
1091
1092                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1093
1094                 // Set the content back
1095                 $this->setRawTemplateData($content);
1096         }
1097
1098         /**
1099          * Load a specified HTML template into the engine
1100          *
1101          * @param       $template       The web template we shall load which is located in
1102          *                                              'html' by default
1103          * @return      void
1104          */
1105         public function loadHtmlTemplate ($template) {
1106                 // Set template type
1107                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1108
1109                 // Load the special template
1110                 $this->loadTemplate($template);
1111         }
1112
1113         /**
1114          * Assign (add) a given variable with a value
1115          *
1116          * @param       $variableName   The variable we are looking for
1117          * @param       $value                  The value we want to store in the variable
1118          * @return      void
1119          * @throws      InvalidArgumentException        If the variable name is left empty
1120          */
1121         public final function assignVariable ($variableName, $value) {
1122                 // Replace all dashes to underscores to match variables with configuration entries
1123                 $variableName = trim(self::convertDashesToUnderscores($variableName));
1124
1125                 // Empty variable found?
1126                 if (empty($variableName)) {
1127                         // Throw an exception
1128                         throw new InvalidArgumentException('Parameter "variableName" is empty');
1129                 } // END - if
1130
1131                 // First search for the variable if it was already added
1132                 $index = $this->getVariableIndex($variableName);
1133
1134                 // Was it found?
1135                 if ($index === false) {
1136                         // Add it to the stack
1137                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1138                         $this->addVariable($variableName, $value);
1139                 } elseif (!empty($value)) {
1140                         // Modify the stack entry
1141                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1142                         $this->modifyVariable($variableName, $value);
1143                 }
1144         }
1145
1146         /**
1147          * Removes a given variable
1148          *
1149          * @param       $variableName   The variable we are looking for
1150          * @param       $variableGroup  Name of variable group (default: 'general')
1151          * @return      void
1152          */
1153         public final function removeVariable ($variableName, $variableGroup = 'general') {
1154                 // First search for the variable if it was already added
1155                 $index = $this->getVariableIndex($variableName, $variableGroup);
1156
1157                 // Was it found?
1158                 if ($index !== false) {
1159                         // Remove this variable
1160                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1161                         $this->unsetVariableStackOffset($index, $variableGroup);
1162                 } // END - if
1163         }
1164
1165         /**
1166          * Assigns the last loaded raw template content with a given variable
1167          *
1168          * @param       $templateName   Name of the template we want to assign
1169          * @param       $variableName   Name of the variable we want to assign
1170          * @return      void
1171          */
1172         public function assignTemplateWithVariable ($templateName, $variableName) {
1173                 // Get the content from last loaded raw template
1174                 $content = $this->getRawTemplateData();
1175
1176                 // Assign the variable
1177                 $this->assignVariable($variableName, $content);
1178
1179                 // Purge raw content
1180                 $this->setRawTemplateData('');
1181         }
1182
1183         /**
1184          * Assign a given congfiguration variable with a value
1185          *
1186          * @param       $variableName   The configuration variable we want to assign
1187          * @return      void
1188          */
1189         public function assignConfigVariable ($variableName) {
1190                 // Replace all dashes to underscores to match variables with configuration entries
1191                 $variableName = trim(self::convertDashesToUnderscores($variableName));
1192
1193                 // Sweet and simple...
1194                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1195                 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1196         }
1197
1198         /**
1199          * Assigns a lot variables into the stack of currently loaded template.
1200          * This method should only be used in very rare circumstances, e.g. when
1201          * you have to copy a whole set of variables into the template engine.
1202          * Before you use this method, please make sure you have considered all
1203          * other possiblities.
1204          *
1205          * @param       $variables      An array with variables to be assigned
1206          * @return      void
1207          */
1208         public function assignMultipleVariables (array $variables) {
1209                 // "Inject" all
1210                 foreach ($variables as $name => $value) {
1211                         // Set variable with name for 'config' group
1212                         $this->assignVariable($name, $value);
1213                 } // END - foreach
1214         }
1215
1216         /**
1217          * Assigns all the application data with template variables
1218          *
1219          * @param       $applicationInstance    A manageable application instance
1220          * @return      void
1221          */
1222         public function assignApplicationData (ManageableApplication $applicationInstance) {
1223                 // Get long name and assign it
1224                 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1225
1226                 // Get short name and assign it
1227                 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1228
1229                 // Get version number and assign it
1230                 $this->assignVariable('app_version'   , $applicationInstance->getAppVersion());
1231
1232                 // Assign extra application-depending data
1233                 $applicationInstance->assignExtraTemplateData($this);
1234         }
1235
1236         /**
1237          * Load a specified code template into the engine
1238          *
1239          * @param       $template       The code template we shall load which is
1240          *                                              located in 'code' by default
1241          * @return      void
1242          */
1243         public function loadCodeTemplate ($template) {
1244                 // Set template type
1245                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1246
1247                 // Load the special template
1248                 $this->loadTemplate($template);
1249         }
1250
1251         /**
1252          * Load a specified email template into the engine
1253          *
1254          * @param       $template       The email template we shall load which is
1255          *                                              located in 'emails' by default
1256          * @return      void
1257          */
1258         public function loadEmailTemplate ($template) {
1259                 // Set template type
1260                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1261
1262                 // Load the special template
1263                 $this->loadTemplate($template);
1264         }
1265
1266         /**
1267          * Compiles configuration place-holders in all variables. This 'walks'
1268          * through the variable group 'general'. It interprets all values from that
1269          * variables as configuration entries after compiling them.
1270          *
1271          * @return      void
1272          */
1273         public final function compileConfigInVariables () {
1274                 // Do we have the stack?
1275                 if (!$this->isVarStackSet('general')) {
1276                         // Abort here silently
1277                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1278                         return;
1279                 } // END - if
1280
1281                 // Iterate through all general variables
1282                 foreach ($this->getVarStack('general') as $index => $currVariable) {
1283                         // Compile the value
1284                         $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1285
1286                         // Debug message
1287                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1288
1289                         // Remove it from stack
1290                         $this->removeVariable($currVariable['name'], 'general');
1291                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1292
1293                         // Is it a configuration key?
1294                         if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1295                                 // The value itself is a configuration entry
1296                                 $this->assignConfigVariable($value);
1297                         } else {
1298                                 // Re-assign the value directly
1299                                 $this->assignVariable($currVariable['name'], $value);
1300                         }
1301                 } // END - foreach
1302         }
1303
1304         /**
1305          * Compile all variables by inserting their respective values
1306          *
1307          * @return      void
1308          * @todo        Make this code some nicer...
1309          */
1310         public final function compileVariables () {
1311                 // Initialize the $content array
1312                 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1313                 $dummy = array();
1314
1315                 // Iterate through all general variables
1316                 foreach ($this->getVarStack('general') as $currVariable) {
1317                         // Transfer it's name/value combination to the $content array
1318                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1319                         $dummy[$currVariable['name']] = $currVariable['value'];
1320                 }// END - if
1321
1322                 // Set the new variable (don't remove the second dollar!)
1323                 $$validVar = $dummy;
1324
1325                 // Remove some variables
1326                 unset($index);
1327                 unset($currVariable);
1328
1329                 // Run the compilation three times to get content from helper classes in
1330                 $cnt = 0;
1331                 while ($cnt < 3) {
1332                         // Finalize the compilation of template variables
1333                         $this->finalizeVariableCompilation();
1334
1335                         // Prepare the eval() command for comiling the template
1336                         $eval = sprintf('$result = "%s";',
1337                                 addslashes($this->getRawTemplateData())
1338                         );
1339
1340                         // This loop does remove the backslashes (\) in PHP parameters
1341                         while (strpos($eval, $this->codeBegin) !== false) {
1342                                 // Get left part before "<?"
1343                                 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1344
1345                                 // Get all from right of "<?"
1346                                 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1347
1348                                 // Cut middle part out and remove escapes
1349                                 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1350                                 $evalMiddle = stripslashes($evalMiddle);
1351
1352                                 // Remove the middle part from right one
1353                                 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1354
1355                                 // And put all together
1356                                 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1357                         } // END - while
1358
1359                         // Prepare PHP code for eval() command
1360                         $eval = str_replace(
1361                                 '<%php', '";',
1362                                 str_replace(
1363                                         '%>',
1364                                         "\n\$result .= \"",
1365                                         $eval
1366                                 )
1367                         );
1368
1369                         // Run the constructed command. This will "compile" all variables in
1370                         eval($eval);
1371
1372                         // Goes something wrong?
1373                         if ((!isset($result)) || (empty($result))) {
1374                                 // Output eval command
1375                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1376
1377                                 // Output backtrace here
1378                                 $this->debugBackTrace();
1379                         } // END - if
1380
1381                         // Set raw template data
1382                         $this->setRawTemplateData($result);
1383                         $cnt++;
1384                 } // END - while
1385
1386                 // Final variable assignment
1387                 $this->finalizeVariableCompilation();
1388
1389                 // Set the new content
1390                 $this->setCompiledData($this->getRawTemplateData());
1391         }
1392
1393         /**
1394          * Compile all required templates into the current loaded one
1395          *
1396          * @return      void
1397          * @throws      UnexpectedTemplateTypeException If the template type is
1398          *                                                                                      not "code"
1399          * @throws      InvalidArrayCountException              If an unexpected array
1400          *                                                                                      count has been found
1401          */
1402         public function compileTemplate () {
1403                 // Get code type to make things shorter
1404                 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1405
1406                 // We will only work with template type "code" from configuration
1407                 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1408                         // Abort here
1409                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1410                 } // END - if
1411
1412                 // Get the raw data.
1413                 $rawData = $this->getRawTemplateData();
1414
1415                 // Remove double spaces and trim leading/trailing spaces
1416                 $rawData = trim(str_replace('  ', ' ', $rawData));
1417
1418                 // Search for raw variables
1419                 $this->extractVariablesFromRawData($rawData);
1420
1421                 // Search for code-tags which are {? ?}
1422                 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1423
1424                 // Debug message
1425                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
1426
1427                 // Analyze the matches array
1428                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1429                         // Entries are found:
1430                         //
1431                         // The main analysis
1432                         $this->analyzeTemplate($templateMatches);
1433
1434                         // Compile raw template data
1435                         $this->compileRawTemplateData($templateMatches);
1436
1437                         // Are there some raw templates left for loading?
1438                         $this->loadExtraRawTemplates();
1439
1440                         // Are some raw templates found and loaded?
1441                         if (count($this->rawTemplates) > 0) {
1442                                 // Insert all raw templates
1443                                 $this->insertRawTemplates();
1444
1445                                 // Remove the raw template content as well
1446                                 $this->setRawTemplateData('');
1447                         } // END - if
1448                 } // END - if($templateMatches ...
1449         }
1450
1451         /**
1452          * Loads a given view helper (by name)
1453          *
1454          * @param       $helperName             The helper's name
1455          * @return      void
1456          */
1457         protected function loadViewHelper ($helperName) {
1458                 // Is this view helper loaded?
1459                 if (!isset($this->helpers[$helperName])) {
1460                         // Create a class name
1461                         $className = self::convertToClassName($helperName) . 'ViewHelper';
1462
1463                         // Generate new instance
1464                         $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1465                 } // END - if
1466
1467                 // Return the requested instance
1468                 return $this->helpers[$helperName];
1469         }
1470
1471         /**
1472          * Transfers the content of this template engine to a given response instance
1473          *
1474          * @param       $responseInstance       An instance of a Responseable class
1475          * @return      void
1476          */
1477         public function transferToResponse (Responseable $responseInstance) {
1478                 // Get the content and set it in response class
1479                 $responseInstance->writeToBody($this->getCompiledData());
1480         }
1481
1482         /**
1483          * "Compiles" a variable by replacing {?var?} with it's content
1484          *
1485          * @param       $rawCode                        Raw code to compile
1486          * @param       $setMatchAsCode         Sets $match if readVariable() returns empty result
1487          * @return      $rawCode        Compile code with inserted variable value
1488          */
1489         public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1490                 // Find the variables
1491                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1492                 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1493
1494                 // Compile all variables
1495                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
1496                 foreach ($varMatches[0] as $match) {
1497                         // Add variable tags around it
1498                         $varCode = '{?' . $match . '?}';
1499
1500                         // Debug message
1501                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1502
1503                         // Is the variable found in code? (safes some calls)
1504                         if (strpos($rawCode, $varCode) !== false) {
1505                                 // Debug message
1506                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1507
1508                                 // Use $match as new value or $value from read variable?
1509                                 if ($setMatchAsCode === true) {
1510                                         // Insert match
1511                                         $rawCode = str_replace($varCode, $match, $rawCode);
1512                                 } else {
1513                                         // Read the variable
1514                                         $value = $this->readVariable($match);
1515
1516                                         // Insert value
1517                                         $rawCode = str_replace($varCode, $value, $rawCode);
1518                                 }
1519                         } // END - if
1520                 } // END - foreach
1521
1522                 // Return the compiled data
1523                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1524                 return $rawCode;
1525         }
1526
1527         /**
1528          * Getter for variable group array
1529          *
1530          * @return      $variableGroups All variable groups
1531          */
1532         public final function getVariableGroups () {
1533                 return $this->variableGroups;
1534         }
1535
1536         /**
1537          * Renames a variable in code and in stack
1538          *
1539          * @param       $oldName        Old name of variable
1540          * @param       $newName        New name of variable
1541          * @return      void
1542          */
1543         public function renameVariable ($oldName, $newName) {
1544                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1545                 // Get raw template code
1546                 $rawData = $this->getRawTemplateData();
1547
1548                 // Replace it
1549                 $rawData = str_replace($oldName, $newName, $rawData);
1550
1551                 // Set the code back
1552                 $this->setRawTemplateData($rawData);
1553         }
1554
1555         /**
1556          * Renders the given XML content
1557          *
1558          * @param       $content        Valid XML content or if not set the current loaded raw content
1559          * @return      void
1560          * @throws      XmlParserException      If an XML error was found
1561          */
1562         public function renderXmlContent ($content = NULL) {
1563                 // Is the content set?
1564                 if (is_null($content)) {
1565                         // Get current content
1566                         $content = $this->getRawTemplateData();
1567                 } // END - if
1568
1569                 // Get a XmlParser instance
1570                 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1571
1572                 // Check if XML compacting is enabled
1573                 if ($this->isXmlCompactingEnabled()) {
1574                         // Yes, so get a decorator class for transparent compacting
1575                         $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1576                 } // END - if
1577
1578                 // Parse the XML document
1579                 $parserInstance->parseXmlContent($content);
1580         }
1581
1582         /**
1583          * Enables or disables language support
1584          *
1585          * @param       $languageSupport        New language support setting
1586          * @return      void
1587          */
1588         public final function enableLanguageSupport ($languageSupport = true) {
1589                 $this->languageSupport = (bool) $languageSupport;
1590         }
1591
1592         /**
1593          * Checks whether language support is enabled
1594          *
1595          * @return      $languageSupport        Whether language support is enabled or disabled
1596          */
1597         public final function isLanguageSupportEnabled () {
1598                 return $this->languageSupport;
1599         }
1600
1601         /**
1602          * Enables or disables XML compacting
1603          *
1604          * @param       $xmlCompacting  New XML compacting setting
1605          * @return      void
1606          */
1607         public final function enableXmlCompacting ($xmlCompacting = true) {
1608                 $this->xmlCompacting = (bool) $xmlCompacting;
1609         }
1610
1611         /**
1612          * Checks whether XML compacting is enabled
1613          *
1614          * @return      $xmlCompacting  Whether XML compacting is enabled or disabled
1615          */
1616         public final function isXmlCompactingEnabled () {
1617                 return $this->xmlCompacting;
1618         }
1619
1620         /**
1621          * Removes all commentd, tabs and new-line characters to compact the content
1622          *
1623          * @param       $uncompactedContent             The uncompacted content
1624          * @return      $compactedContent               The compacted content
1625          */
1626         public function compactContent ($uncompactedContent) {
1627                 // First, remove all tab/new-line/revert characters
1628                 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1629
1630                 // Then regex all comments like <!-- //--> away
1631                 preg_match_all($this->regExpComments, $compactedContent, $matches);
1632
1633                 // Do we have entries?
1634                 if (isset($matches[0][0])) {
1635                         // Remove all
1636                         foreach ($matches[0] as $match) {
1637                                 // Remove the match
1638                                 $compactedContent = str_replace($match, '', $compactedContent);
1639                         } // END - foreach
1640                 } // END - if
1641
1642                 // Set the content again
1643                 $this->setRawTemplateData($compactedContent);
1644
1645                 // Return compacted content
1646                 return $compactedContent;
1647         }
1648
1649 }