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