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