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