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