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