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