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