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