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