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