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