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