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