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