Merge branch 'contrib'
[core.git] / inc / classes / main / 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 - 2013 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 $varGroups = 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($this->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($this->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->varGroups[$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($this->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       $varGroup       Variable group to use
363          * @param       $index          Index in variable array
364          * @return      $value          Value to set
365          */
366         private function getVariableValue ($varGroup, $index) {
367                 // Return it
368                 return $this->varStack[$varGroup][$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($this->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       $varGroup       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 ($varGroup, $index, $value) {
405                 $this->varStack[$varGroup][$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       $varGroup               Variable group to use
414          * @param       $variableName   Variable to set
415          * @param       $value                  Value to set
416          * @return      void
417          */
418         protected function setVariable ($varGroup, $variableName, $value) {
419                 // Replace all dashes to underscores to match variables with configuration entries
420                 $variableName = trim($this->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[$varGroup])) {
429                                 // Then initialize it here
430                                 $this->varStack[$varGroup] = array();
431                         } // END - if
432
433                         // Not found, add it
434                         array_push($this->varStack[$varGroup], $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($this->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          * Setter for the last loaded template's FQFN
476          *
477          * @param       $template       The last loaded template
478          * @return      void
479          */
480         private final function setLastTemplate ($template) {
481                 $this->lastTemplate = (string) $template;
482         }
483
484         /**
485          * Getter for the last loaded template's FQFN
486          *
487          * @return      $template       The last loaded template
488          */
489         private final function getLastTemplate () {
490                 return $this->lastTemplate;
491         }
492
493         /**
494          * Setter for base path
495          *
496          * @param               $templateBasePath               The relative base path for all templates
497          * @return      void
498          */
499         public final function setTemplateBasePath ($templateBasePath) {
500                 // And set it
501                 $this->templateBasePath = (string) $templateBasePath;
502         }
503
504         /**
505          * Getter for base path
506          *
507          * @return      $templateBasePath               The relative base path for all templates
508          */
509         public final function getTemplateBasePath () {
510                 // And set it
511                 return $this->templateBasePath;
512         }
513
514         /**
515          * Getter for generic base path
516          *
517          * @return      $templateBasePath               The relative base path for all templates
518          */
519         public final function getGenericBasePath () {
520                 // And set it
521                 return $this->genericBasePath;
522         }
523
524         /**
525          * Setter for template extension
526          *
527          * @param               $templateExtension      The file extension for all uncompiled
528          *                                                      templates
529          * @return      void
530          */
531         public final function setRawTemplateExtension ($templateExtension) {
532                 // And set it
533                 $this->templateExtension = (string) $templateExtension;
534         }
535
536         /**
537          * Setter for code template extension
538          *
539          * @param               $codeExtension          The file extension for all uncompiled
540          *                                                      templates
541          * @return      void
542          */
543         public final function setCodeTemplateExtension ($codeExtension) {
544                 // And set it
545                 $this->codeExtension = (string) $codeExtension;
546         }
547
548         /**
549          * Getter for template extension
550          *
551          * @return      $templateExtension      The file extension for all uncompiled
552          *                                                      templates
553          */
554         public final function getRawTemplateExtension () {
555                 // And set it
556                 return $this->templateExtension;
557         }
558
559         /**
560          * Getter for code-template extension
561          *
562          * @return      $codeExtension          The file extension for all code-
563          *                                                      templates
564          */
565         public final function getCodeTemplateExtension () {
566                 // And set it
567                 return $this->codeExtension;
568         }
569
570         /**
571          * Setter for path of compiled templates
572          *
573          * @param       $compileOutputPath      The local base path for all compiled
574          *                                                              templates
575          * @return      void
576          */
577         public final function setCompileOutputPath ($compileOutputPath) {
578                 // And set it
579                 $this->compileOutputPath = (string) $compileOutputPath;
580         }
581
582         /**
583          * Getter for template type
584          *
585          * @return      $templateType   The current template's type
586          */
587         public final function getTemplateType () {
588                 return $this->templateType;
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
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      FileIoException 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                 // Is language support enabled?
678                 if ($this->isLanguageSupportEnabled()) {
679                         // Construct the FQFN for the template by honoring the current language
680                         $fqfn = sprintf('%s%s%s%s/%s/%s%s',
681                                 $this->getConfigInstance()->getConfigEntry('base_path'),
682                                 $this->getTemplateBasePath(),
683                                 $this->getGenericBasePath(),
684                                 $this->getLanguageInstance()->getLanguageCode(),
685                                 $this->getTemplateType(),
686                                 (string) $template,
687                                 $ext
688                         );
689                 } else {
690                         // Construct the FQFN for the template without language
691                         $fqfn = sprintf('%s%s%s%s/%s%s',
692                                 $this->getConfigInstance()->getConfigEntry('base_path'),
693                                 $this->getTemplateBasePath(),
694                                 $this->getGenericBasePath(),
695                                 $this->getTemplateType(),
696                                 (string) $template,
697                                 $ext
698                         );
699                 }
700
701                 // First try this
702                 try {
703                         // Load the raw template data
704                         $this->loadRawTemplateData($fqfn);
705                 } catch (FileIoException $e) {
706                         // If we shall load a code-template we need to switch the file extension
707                         if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
708                                 // Switch over to the code-template extension and try it again
709                                 $ext = $this->getCodeTemplateExtension();
710
711                                 // Try it again...
712                                 $this->loadTemplate($template, $ext);
713                         } else {
714                                 // Throw it again
715                                 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
716                         }
717                 }
718
719         }
720
721         /**
722          * A private loader for raw template names
723          *
724          * @param       $fqfn   The full-qualified file name for a template
725          * @return      void
726          */
727         private function loadRawTemplateData ($fqfn) {
728                 // Some debug code to look on the file which is being loaded
729                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
730
731                 // Load the raw template
732                 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
733
734                 // Store the template's contents into this class
735                 $this->setRawTemplateData($rawTemplateData);
736
737                 // Remember the template's FQFN
738                 $this->setLastTemplate($fqfn);
739         }
740
741         /**
742          * Try to assign an extracted template variable as a "content" or 'config'
743          * variable.
744          *
745          * @param       $varName                The variable's name (shall be content or config)
746          *                                                      by default
747          * @param       $variableName   The variable we want to assign
748          * @return      void
749          */
750         private function assignTemplateVariable ($varName, $var) {
751                 // Replace all dashes to underscores to match variables with configuration entries
752                 $variableName = trim($this->convertDashesToUnderscores($variableName));
753
754                 // Debug message
755                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: varName=' . $varName . ',variableName=' . $variableName);
756
757                 // Is it not a config variable?
758                 if ($varName != 'config') {
759                         // Regular template variables
760                         $this->assignVariable($variableName, '');
761                 } else {
762                         // Configuration variables
763                         $this->assignConfigVariable($variableName);
764                 }
765         }
766
767         /**
768          * Extract variables from a given raw data stream
769          *
770          * @param       $rawData        The raw template data we shall analyze
771          * @return      void
772          */
773         private function extractVariablesFromRawData ($rawData) {
774                 // Cast to string
775                 $rawData = (string) $rawData;
776
777                 // Search for variables
778                 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
779
780                 // Debug message
781                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, TRUE));
782
783                 // Did we find some variables?
784                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
785                         // Initialize all missing variables
786                         foreach ($variableMatches[3] as $key => $var) {
787                                 // Variable name
788                                 $varName = $variableMatches[1][$key];
789
790                                 // Workarround: Do not assign empty variables
791                                 if (!empty($var)) {
792                                         // Try to assign it, empty strings are being ignored
793                                         $this->assignTemplateVariable($varName, $var);
794                                 } // END - if
795                         } // END - foreach
796                 } // END - if
797         }
798
799         /**
800          * Main analysis of the loaded template
801          *
802          * @param       $templateMatches        Found template place-holders, see below
803          * @return      void
804          *
805          *---------------------------------
806          * Structure of $templateMatches:
807          *---------------------------------
808          * [0] => Array - An array with all full matches
809          * [1] => Array - An array with left part (before the ':') of a match
810          * [2] => Array - An array with right part of a match including ':'
811          * [3] => Array - An array with right part of a match excluding ':'
812          */
813         private function analyzeTemplate (array $templateMatches) {
814                 // Backup raw template data
815                 $backup = $this->getRawTemplateData();
816
817                 // Initialize some arrays
818                 if (is_null($this->loadedRawData)) {
819                         // Initialize both
820                         $this->loadedRawData = array();
821                         $this->rawTemplates = array();
822                 } // END - if
823
824                 // Load all requested templates
825                 foreach ($templateMatches[1] as $template) {
826                         // Load and compile only templates which we have not yet loaded
827                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
828                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
829                                 // Debug message
830                                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
831
832                                 // Template not found, but maybe variable assigned?
833                                 if ($this->getVariableIndex($template, 'config') !== FALSE) {
834                                         // Use that content here
835                                         $this->loadedRawData[$template] = $this->readVariable($template, 'config');
836
837                                         // Recursive protection:
838                                         array_push($this->loadedTemplates, $template);
839                                 } elseif ($this->getVariableIndex($template) !== FALSE) {
840                                         // Use that content here
841                                         $this->loadedRawData[$template] = $this->readVariable($template);
842
843                                         // Recursive protection:
844                                         array_push($this->loadedTemplates, $template);
845                                 } else {
846                                         // Then try to search for code-templates
847                                         try {
848                                                 // Load the code template and remember it's contents
849                                                 $this->loadCodeTemplate($template);
850                                                 $this->loadedRawData[$template] = $this->getRawTemplateData();
851
852                                                 // Remember this template for recursion detection
853                                                 // RECURSIVE PROTECTION!
854                                                 array_push($this->loadedTemplates, $template);
855                                         } catch (FileIoException $e) {
856                                                 // Even this is not done... :/
857                                                 array_push($this->rawTemplates, $template);
858                                         }
859                                 }
860                         } // END - if
861                 } // END - foreach
862
863                 // Restore the raw template data
864                 $this->setRawTemplateData($backup);
865         }
866
867         /**
868          * Compile a given raw template code and remember it for later usage
869          *
870          * @param       $code           The raw template code
871          * @param       $template       The template's name
872          * @return      void
873          */
874         private function compileCode ($code, $template) {
875                 // Is this template already compiled?
876                 if (in_array($template, $this->compiledTemplates)) {
877                         // Abort here...
878                         return;
879                 } // END - if
880
881                 // Remember this template being compiled
882                 array_push($this->compiledTemplates, $template);
883
884                 // Compile the loaded code in five steps:
885                 //
886                 // 1. Backup current template data
887                 $backup = $this->getRawTemplateData();
888
889                 // 2. Set the current template's raw data as the new content
890                 $this->setRawTemplateData($code);
891
892                 // 3. Compile the template data
893                 $this->compileTemplate();
894
895                 // 4. Remember it's contents
896                 $this->loadedRawData[$template] = $this->getRawTemplateData();
897
898                 // 5. Restore the previous raw content from backup variable
899                 $this->setRawTemplateData($backup);
900         }
901
902         /**
903          * Insert all given and loaded templates by running through all loaded
904          * codes and searching for their place-holder in the main template
905          *
906          * @param       $templateMatches        See method analyzeTemplate()
907          * @return      void
908          */
909         private function insertAllTemplates (array $templateMatches) {
910                 // Run through all loaded codes
911                 foreach ($this->loadedRawData as $template => $code) {
912
913                         // Search for the template
914                         $foundIndex = array_search($template, $templateMatches[1]);
915
916                         // Lookup the matching template replacement
917                         if (($foundIndex !== FALSE) && (isset($templateMatches[0][$foundIndex]))) {
918
919                                 // Get the current raw template
920                                 $rawData = $this->getRawTemplateData();
921
922                                 // Replace the space holder with the template code
923                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
924
925                                 // Set the new raw data
926                                 $this->setRawTemplateData($rawData);
927                         } // END - if
928                 } // END - foreach
929         }
930
931         /**
932          * Load all extra raw templates
933          *
934          * @return      void
935          */
936         private function loadExtraRawTemplates () {
937                 // Are there some raw templates we need to load?
938                 if (count($this->rawTemplates) > 0) {
939                         // Try to load all raw templates
940                         foreach ($this->rawTemplates as $key => $template) {
941                                 try {
942                                         // Load the template
943                                         $this->loadWebTemplate($template);
944
945                                         // Remember it's contents
946                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
947
948                                         // Remove it from the loader list
949                                         unset($this->rawTemplates[$key]);
950
951                                         // Remember this template for recursion detection
952                                         // RECURSIVE PROTECTION!
953                                         array_push($this->loadedTemplates, $template);
954                                 } catch (FileIoException $e) {
955                                         // This template was never found. We silently ignore it
956                                         unset($this->rawTemplates[$key]);
957                                 }
958                         } // END - foreach
959                 } // END - if
960         }
961
962         /**
963          * Assign all found template variables
964          *
965          * @param       $varMatches             An array full of variable/value pairs.
966          * @return      void
967          * @todo        Unfinished work or don't die here.
968          */
969         private function assignAllVariables (array $varMatches) {
970                 // Debug message
971                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
972
973                 // Search for all variables
974                 foreach ($varMatches[1] as $key => $var) {
975                         // Replace all dashes to underscores to match variables with configuration entries
976                         $var = trim($this->convertDashesToUnderscores($var));
977
978                         // Debug message
979                         self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
980
981                         // Detect leading equals
982                         if (substr($varMatches[2][$key], 0, 1) == '=') {
983                                 // Remove and cast it
984                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
985                         } // END - if
986
987                         // Do we have some quotes left and right side? Then it is free text
988                         if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
989                                 // Free string detected! Which we can assign directly
990                                 $this->assignVariable($var, $varMatches[3][$key]);
991                         } elseif (!empty($varMatches[2][$key])) {
992                                 // @TODO Non-string found so we need some deeper analysis...
993                                 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
994                         }
995                 } // END - foreach
996         }
997
998         /**
999          * Compiles all loaded raw templates
1000          *
1001          * @param       $templateMatches        See method analyzeTemplate() for details
1002          * @return      void
1003          */
1004         private function compileRawTemplateData (array $templateMatches) {
1005                 // Debug message
1006                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1007
1008                 // Are some code-templates found which we need to compile?
1009                 if (count($this->loadedRawData) > 0) {
1010                         // Then compile all!
1011                         foreach ($this->loadedRawData as $template => $code) {
1012                                 // Debug message
1013                                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1014
1015                                 // Is this template already compiled?
1016                                 if (in_array($template, $this->compiledTemplates)) {
1017                                         // Then skip it
1018                                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1019                                         continue;
1020                                 } // END - if
1021
1022                                 // Search for the template
1023                                 $foundIndex = array_search($template, $templateMatches[1]);
1024
1025                                 // Lookup the matching variable data
1026                                 if (($foundIndex !== FALSE) && (isset($templateMatches[3][$foundIndex]))) {
1027                                         // Split it up with another reg. exp. into variable=value pairs
1028                                         preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1029                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, TRUE));
1030
1031                                         // Assign all variables
1032                                         $this->assignAllVariables($varMatches);
1033                                 } // END - if (isset($templateMatches ...
1034
1035                                 // Compile the loaded template
1036                                 $this->compileCode($code, $template);
1037                         } // END - foreach ($this->loadedRawData ...
1038
1039                         // Insert all templates
1040                         $this->insertAllTemplates($templateMatches);
1041                 } // END - if (count($this->loadedRawData) ...
1042         }
1043
1044         /**
1045          * Inserts all raw templates into their respective variables
1046          *
1047          * @return      void
1048          */
1049         private function insertRawTemplates () {
1050                 // Load all templates
1051                 foreach ($this->rawTemplates as $template => $content) {
1052                         // Set the template as a variable with the content
1053                         $this->assignVariable($template, $content);
1054                 }
1055         }
1056
1057         /**
1058          * Finalizes the compilation of all template variables
1059          *
1060          * @return      void
1061          */
1062         private function finalizeVariableCompilation () {
1063                 // Get the content
1064                 $content = $this->getRawTemplateData();
1065                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1066
1067                 // Do we have the stack?
1068                 if (!$this->isVarStackSet('general')) {
1069                         // Abort here silently
1070                         // @TODO This silent abort should be logged, maybe.
1071                         return;
1072                 } // END - if
1073
1074                 // Walk through all variables
1075                 foreach ($this->getVarStack('general') as $currEntry) {
1076                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1077                         // Replace all [$var] or {?$var?} with the content
1078                         // @TODO Old behaviour, will become obsolete!
1079                         $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1080
1081                         // @TODO Yet another old way
1082                         $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1083
1084                         // The new behaviour
1085                         $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1086                 } // END - for
1087
1088                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1089
1090                 // Set the content back
1091                 $this->setRawTemplateData($content);
1092         }
1093
1094         /**
1095          * Load a specified web template into the engine
1096          *
1097          * @param       $template       The web template we shall load which is located in
1098          *                                              'html' by default
1099          * @return      void
1100          */
1101         public function loadWebTemplate ($template) {
1102                 // Set template type
1103                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
1104
1105                 // Load the special template
1106                 $this->loadTemplate($template);
1107         }
1108
1109         /**
1110          * Assign (add) a given variable with a value
1111          *
1112          * @param       $variableName   The variable we are looking for
1113          * @param       $value                  The value we want to store in the variable
1114          * @return      void
1115          * @throws      EmptyVariableException  If the variable name is left empty
1116          */
1117         public final function assignVariable ($variableName, $value) {
1118                 // Replace all dashes to underscores to match variables with configuration entries
1119                 $variableName = trim($this->convertDashesToUnderscores($variableName));
1120
1121                 // Empty variable found?
1122                 if (empty($variableName)) {
1123                         // Throw an exception
1124                         throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1125                 } // END - if
1126
1127                 // First search for the variable if it was already added
1128                 $index = $this->getVariableIndex($variableName);
1129
1130                 // Was it found?
1131                 if ($index === FALSE) {
1132                         // Add it to the stack
1133                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1134                         $this->addVariable($variableName, $value);
1135                 } elseif (!empty($value)) {
1136                         // Modify the stack entry
1137                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1138                         $this->modifyVariable($variableName, $value);
1139                 }
1140         }
1141
1142         /**
1143          * Removes a given variable
1144          *
1145          * @param       $variableName   The variable we are looking for
1146          * @param       $variableGroup  Name of variable group (default: 'general')
1147          * @return      void
1148          */
1149         public final function removeVariable ($variableName, $variableGroup = 'general') {
1150                 // First search for the variable if it was already added
1151                 $index = $this->getVariableIndex($variableName, $variableGroup);
1152
1153                 // Was it found?
1154                 if ($index !== FALSE) {
1155                         // Remove this variable
1156                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1157                         $this->unsetVariableStackOffset($index, $variableGroup);
1158                 } // END - if
1159         }
1160
1161         /**
1162          * Assigns the last loaded raw template content with a given variable
1163          *
1164          * @param       $templateName   Name of the template we want to assign
1165          * @param       $variableName   Name of the variable we want to assign
1166          * @return      void
1167          */
1168         public function assignTemplateWithVariable ($templateName, $variableName) {
1169                 // Get the content from last loaded raw template
1170                 $content = $this->getRawTemplateData();
1171
1172                 // Assign the variable
1173                 $this->assignVariable($variableName, $content);
1174
1175                 // Purge raw content
1176                 $this->setRawTemplateData('');
1177         }
1178
1179         /**
1180          * Assign a given congfiguration variable with a value
1181          *
1182          * @param       $variableName   The configuration variable we want to assign
1183          * @return      void
1184          */
1185         public function assignConfigVariable ($variableName) {
1186                 // Replace all dashes to underscores to match variables with configuration entries
1187                 $variableName = trim($this->convertDashesToUnderscores($variableName));
1188
1189                 // Sweet and simple...
1190                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1191                 $this->setVariable('config', $variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1192         }
1193
1194         /**
1195          * Injects an array of config variables into the stack of currently loaded
1196          * template. This method should only be used in very rare circumstances,
1197          * e.g. when you have to copy a whole set of variables into the template
1198          * engine. Before you use this method, please make sure you have considered
1199          * all other possiblities.
1200          *
1201          * @param       $variables      An array with variables to be injected
1202          * @return      void
1203          */
1204         public function injectConfigVariables (array $variables) {
1205                 // "Inject" all
1206                 foreach ($variables as $name => $value) {
1207                         // Set variable with name for 'config' group
1208                         $this->setVariable('config', $name, $value);
1209                 } // END - foreach
1210         }
1211
1212         /**
1213          * Assigns all the application data with template variables
1214          *
1215          * @param       $applicationInstance    A manageable application instance
1216          * @return      void
1217          */
1218         public function assignApplicationData (ManageableApplication $applicationInstance) {
1219                 // Get long name and assign it
1220                 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1221
1222                 // Get short name and assign it
1223                 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1224
1225                 // Get version number and assign it
1226                 $this->assignVariable('app_version'   , $applicationInstance->getAppVersion());
1227
1228                 // Assign extra application-depending data
1229                 $applicationInstance->assignExtraTemplateData($this);
1230         }
1231
1232         /**
1233          * Load a specified code template into the engine
1234          *
1235          * @param       $template       The code template we shall load which is
1236          *                                              located in 'code' by default
1237          * @return      void
1238          */
1239         public function loadCodeTemplate ($template) {
1240                 // Set template type
1241                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
1242
1243                 // Load the special template
1244                 $this->loadTemplate($template);
1245         }
1246
1247         /**
1248          * Compiles configuration place-holders in all variables. This 'walks'
1249          * through the variable group 'general'. It interprets all values from that
1250          * variables as configuration entries after compiling them.
1251          *
1252          * @return      void
1253          */
1254         public final function compileConfigInVariables () {
1255                 // Do we have the stack?
1256                 if (!$this->isVarStackSet('general')) {
1257                         // Abort here silently
1258                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1259                         return;
1260                 } // END - if
1261
1262                 // Iterate through all general variables
1263                 foreach ($this->getVarStack('general') as $index => $currVariable) {
1264                         // Compile the value
1265                         $value = $this->compileRawCode($this->readVariable($currVariable['name']), TRUE);
1266
1267                         // Debug message
1268                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1269
1270                         // Remove it from stack
1271                         $this->removeVariable($currVariable['name'], 'general');
1272                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1273
1274                         // Is it a configuration key?
1275                         if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1276                                 // The value itself is a configuration entry
1277                                 $this->assignConfigVariable($value);
1278                         } else {
1279                                 // Re-assign the value directly
1280                                 $this->setVariable('config', $currVariable['name'], $value);
1281                         }
1282                 } // END - foreach
1283         }
1284
1285         /**
1286          * Compile all variables by inserting their respective values
1287          *
1288          * @return      void
1289          * @todo        Make this code some nicer...
1290          */
1291         public final function compileVariables () {
1292                 // Initialize the $content array
1293                 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1294                 $dummy = array();
1295
1296                 // Iterate through all general variables
1297                 foreach ($this->getVarStack('general') as $currVariable) {
1298                         // Transfer it's name/value combination to the $content array
1299                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1300                         $dummy[$currVariable['name']] = $currVariable['value'];
1301                 }// END - if
1302
1303                 // Set the new variable (don't remove the second dollar!)
1304                 $$validVar = $dummy;
1305
1306                 // Remove some variables
1307                 unset($index);
1308                 unset($currVariable);
1309
1310                 // Run the compilation three times to get content from helper classes in
1311                 $cnt = 0;
1312                 while ($cnt < 3) {
1313                         // Finalize the compilation of template variables
1314                         $this->finalizeVariableCompilation();
1315
1316                         // Prepare the eval() command for comiling the template
1317                         $eval = sprintf('$result = "%s";',
1318                                 addslashes($this->getRawTemplateData())
1319                         );
1320
1321                         // This loop does remove the backslashes (\) in PHP parameters
1322                         while (strpos($eval, $this->codeBegin) !== FALSE) {
1323                                 // Get left part before "<?"
1324                                 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1325
1326                                 // Get all from right of "<?"
1327                                 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1328
1329                                 // Cut middle part out and remove escapes
1330                                 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1331                                 $evalMiddle = stripslashes($evalMiddle);
1332
1333                                 // Remove the middle part from right one
1334                                 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1335
1336                                 // And put all together
1337                                 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1338                         } // END - while
1339
1340                         // Prepare PHP code for eval() command
1341                         $eval = str_replace(
1342                                 '<%php', '";',
1343                                 str_replace(
1344                                         '%>',
1345                                         "\n\$result .= \"",
1346                                         $eval
1347                                 )
1348                         );
1349
1350                         // Run the constructed command. This will "compile" all variables in
1351                         eval($eval);
1352
1353                         // Goes something wrong?
1354                         if ((!isset($result)) || (empty($result))) {
1355                                 // Output eval command
1356                                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, TRUE)), TRUE);
1357
1358                                 // Output backtrace here
1359                                 $this->debugBackTrace();
1360                         } // END - if
1361
1362                         // Set raw template data
1363                         $this->setRawTemplateData($result);
1364                         $cnt++;
1365                 } // END - while
1366
1367                 // Final variable assignment
1368                 $this->finalizeVariableCompilation();
1369
1370                 // Set the new content
1371                 $this->setCompiledData($this->getRawTemplateData());
1372         }
1373
1374         /**
1375          * Compile all required templates into the current loaded one
1376          *
1377          * @return      void
1378          * @throws      UnexpectedTemplateTypeException If the template type is
1379          *                                                                                      not "code"
1380          * @throws      InvalidArrayCountException              If an unexpected array
1381          *                                                                                      count has been found
1382          */
1383         public function compileTemplate () {
1384                 // Get code type to make things shorter
1385                 $codeType = $this->getConfigInstance()->getConfigEntry('code_template_type');
1386
1387                 // We will only work with template type "code" from configuration
1388                 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1389                         // Abort here
1390                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1391                 } // END - if
1392
1393                 // Get the raw data.
1394                 $rawData = $this->getRawTemplateData();
1395
1396                 // Remove double spaces and trim leading/trailing spaces
1397                 $rawData = trim(str_replace('  ', ' ', $rawData));
1398
1399                 // Search for raw variables
1400                 $this->extractVariablesFromRawData($rawData);
1401
1402                 // Search for code-tags which are {? ?}
1403                 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1404
1405                 // Debug message
1406                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , TRUE));
1407
1408                 // Analyze the matches array
1409                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1410                         // Entries are found:
1411                         //
1412                         // The main analysis
1413                         $this->analyzeTemplate($templateMatches);
1414
1415                         // Compile raw template data
1416                         $this->compileRawTemplateData($templateMatches);
1417
1418                         // Are there some raw templates left for loading?
1419                         $this->loadExtraRawTemplates();
1420
1421                         // Are some raw templates found and loaded?
1422                         if (count($this->rawTemplates) > 0) {
1423                                 // Insert all raw templates
1424                                 $this->insertRawTemplates();
1425
1426                                 // Remove the raw template content as well
1427                                 $this->setRawTemplateData('');
1428                         } // END - if
1429                 } // END - if($templateMatches ...
1430         }
1431
1432         /**
1433          * Loads a given view helper (by name)
1434          *
1435          * @param       $helperName             The helper's name
1436          * @return      void
1437          */
1438         protected function loadViewHelper ($helperName) {
1439                 // Is this view helper loaded?
1440                 if (!isset($this->helpers[$helperName])) {
1441                         // Create a class name
1442                         $className = $this->convertToClassName($helperName) . 'ViewHelper';
1443
1444                         // Generate new instance
1445                         $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1446                 } // END - if
1447
1448                 // Return the requested instance
1449                 return $this->helpers[$helperName];
1450         }
1451
1452         /**
1453          * Transfers the content of this template engine to a given response instance
1454          *
1455          * @param       $responseInstance       An instance of a response class
1456          * @return      void
1457          */
1458         public function transferToResponse (Responseable $responseInstance) {
1459                 // Get the content and set it in response class
1460                 $responseInstance->writeToBody($this->getCompiledData());
1461         }
1462
1463         /**
1464          * "Compiles" a variable by replacing {?var?} with it's content
1465          *
1466          * @param       $rawCode                        Raw code to compile
1467          * @param       $setMatchAsCode         Sets $match if readVariable() returns empty result
1468          * @return      $rawCode        Compile code with inserted variable value
1469          */
1470         public function compileRawCode ($rawCode, $setMatchAsCode=FALSE) {
1471                 // Find the variables
1472                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1473                 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1474
1475                 // Compile all variables
1476                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, TRUE) . '</pre>');
1477                 foreach ($varMatches[0] as $match) {
1478                         // Add variable tags around it
1479                         $varCode = '{?' . $match . '?}';
1480
1481                         // Debug message
1482                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1483
1484                         // Is the variable found in code? (safes some calls)
1485                         if (strpos($rawCode, $varCode) !== FALSE) {
1486                                 // Debug message
1487                                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1488
1489                                 // Use $match as new value or $value from read variable?
1490                                 if ($setMatchAsCode === TRUE) {
1491                                         // Insert match
1492                                         $rawCode = str_replace($varCode, $match, $rawCode);
1493                                 } else {
1494                                         // Read the variable
1495                                         $value = $this->readVariable($match);
1496
1497                                         // Insert value
1498                                         $rawCode = str_replace($varCode, $value, $rawCode);
1499                                 }
1500                         } // END - if
1501                 } // END - foreach
1502
1503                 // Return the compiled data
1504                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1505                 return $rawCode;
1506         }
1507
1508         /**
1509          * Getter for variable group array
1510          *
1511          * @return      $vargroups      All variable groups
1512          */
1513         public final function getVariableGroups () {
1514                 return $this->varGroups;
1515         }
1516
1517         /**
1518          * Renames a variable in code and in stack
1519          *
1520          * @param       $oldName        Old name of variable
1521          * @param       $newName        New name of variable
1522          * @return      void
1523          */
1524         public function renameVariable ($oldName, $newName) {
1525                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1526                 // Get raw template code
1527                 $rawData = $this->getRawTemplateData();
1528
1529                 // Replace it
1530                 $rawData = str_replace($oldName, $newName, $rawData);
1531
1532                 // Set the code back
1533                 $this->setRawTemplateData($rawData);
1534         }
1535
1536         /**
1537          * Renders the given XML content
1538          *
1539          * @param       $content        Valid XML content or if not set the current loaded raw content
1540          * @return      void
1541          * @throws      XmlParserException      If an XML error was found
1542          */
1543         public function renderXmlContent ($content = NULL) {
1544                 // Is the content set?
1545                 if (is_null($content)) {
1546                         // Get current content
1547                         $content = $this->getRawTemplateData();
1548                 } // END - if
1549
1550                 // Get a XmlParser instance
1551                 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1552
1553                 // Check if we have XML compacting enabled
1554                 if ($this->isXmlCompactingEnabled()) {
1555                         // Yes, so get a decorator class for transparent compacting
1556                         $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1557                 } // END - if
1558
1559                 // Parse the XML document
1560                 $parserInstance->parseXmlContent($content);
1561         }
1562
1563         /**
1564          * Enables or disables language support
1565          *
1566          * @param       $languageSupport        New language support setting
1567          * @return      void
1568          */
1569         public final function enableLanguageSupport ($languageSupport = TRUE) {
1570                 $this->languageSupport = (bool) $languageSupport;
1571         }
1572
1573         /**
1574          * Checks whether language support is enabled
1575          *
1576          * @return      $languageSupport        Whether language support is enabled or disabled
1577          */
1578         public final function isLanguageSupportEnabled () {
1579                 return $this->languageSupport;
1580         }
1581
1582         /**
1583          * Enables or disables XML compacting
1584          *
1585          * @param       $xmlCompacting  New XML compacting setting
1586          * @return      void
1587          */
1588         public final function enableXmlCompacting ($xmlCompacting = TRUE) {
1589                 $this->xmlCompacting = (bool) $xmlCompacting;
1590         }
1591
1592         /**
1593          * Checks whether XML compacting is enabled
1594          *
1595          * @return      $xmlCompacting  Whether XML compacting is enabled or disabled
1596          */
1597         public final function isXmlCompactingEnabled () {
1598                 return $this->xmlCompacting;
1599         }
1600
1601         /**
1602          * Removes all commentd, tabs and new-line characters to compact the content
1603          *
1604          * @param       $uncompactedContent             The uncompacted content
1605          * @return      $compactedContent               The compacted content
1606          */
1607         public function compactContent ($uncompactedContent) {
1608                 // First, remove all tab/new-line/revert characters
1609                 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1610
1611                 // Then regex all comments like <!-- //--> away
1612                 preg_match_all($this->regExpComments, $compactedContent, $matches);
1613
1614                 // Do we have entries?
1615                 if (isset($matches[0][0])) {
1616                         // Remove all
1617                         foreach ($matches[0] as $match) {
1618                                 // Remove the match
1619                                 $compactedContent = str_replace($match, '', $compactedContent);
1620                         } // END - foreach
1621                 } // END - if
1622
1623                 // Set the content again
1624                 $this->setRawTemplateData($compactedContent);
1625
1626                 // Return compacted content
1627                 return $compactedContent;
1628         }
1629 }
1630
1631 // [EOF]
1632 ?>