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