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