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