c40b183c021148b0cc3fba84b297083080e53bf7
[core.git] / inc / classes / main / template / class_BaseTemplateEngine.php
1 <?php
2 /**
3  * A generic template engine
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007 - 2009 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class BaseTemplateEngine extends BaseFrameworkSystem {
25         /**
26          * The local path name where all templates and sub folders for special
27          * templates are stored. We will internally determine the language plus
28          * "html" for web templates or "emails" for email templates
29          */
30         private $basePath = '';
31
32         /**
33          * Template type
34          */
35         private $templateType = 'html';
36
37         /**
38          * The extension for web and email templates (not compiled templates)
39          */
40         private $templateExtension = '.tpl';
41
42         /**
43          * The extension for code templates (not compiled templates)
44          */
45         private $codeExtension = '.ctp';
46
47         /**
48          * Path relative to $basePath and language code for compiled code-templates
49          */
50         private $compileOutputPath = 'templates/_compiled';
51
52         /**
53          * The raw (maybe uncompiled) template
54          */
55         private $rawTemplateData = '';
56
57         /**
58          * Template data with compiled-in variables
59          */
60         private $compiledData = '';
61
62         /**
63          * The last loaded template's FQFN for debugging the engine
64          */
65         private $lastTemplate = '';
66
67         /**
68          * The variable stack for the templates
69          */
70         private $varStack = array();
71
72         /**
73          * Loaded templates for recursive protection and detection
74          */
75         private $loadedTemplates = array();
76
77         /**
78          * Compiled templates for recursive protection and detection
79          */
80         private $compiledTemplates = array();
81
82         /**
83          * Loaded raw template data
84          */
85         private $loadedRawData = null;
86
87         /**
88          * Raw templates which are linked in code templates
89          */
90         private $rawTemplates = null;
91
92         /**
93          * A regular expression for variable=value pairs
94          */
95         private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
96
97         /**
98          * A regular expression for filtering out code tags
99          *
100          * E.g.: {?template:variable=value;var2=value2;[...]?}
101          */
102         private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
103
104         /**
105          * Loaded helpers
106          */
107         private $helpers = array();
108
109         /**
110          * Current variable group
111          */
112         private $currGroup = 'general';
113
114         /**
115          * All template groups except "general"
116          */
117         private $varGroups = array();
118
119         /**
120          * Code begin
121          */
122         private $codeBegin = '<?php';
123
124         /**
125          * Code end
126          */
127         private $codeEnd = '?>';
128
129         // Exception codes for the template engine
130         const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0x110;
131         const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
132         const EXCEPTION_INVALID_VIEW_HELPER           = 0x112;
133
134         /**
135          * Protected constructor
136          *
137          * @param       $className      Name of the class
138          * @return      void
139          */
140         protected function __construct ($className) {
141                 // Call parent constructor
142                 parent::__construct($className);
143
144                 // Clean up a little
145                 $this->removeNumberFormaters();
146                 $this->removeSystemArray();
147         }
148
149         /**
150          * Search for a variable in the stack
151          *
152          * @param       $var    The variable we are looking for
153          * @return      $idx    FALSE means not found, >=0 means found on a specific index
154          */
155         private function isVariableAlreadySet ($var) {
156                 // First everything is not found
157                 $found = false;
158
159                 // Is the group there?
160                 if (isset($this->varStack[$this->currGroup])) {
161                         // Now search for it
162                         foreach ($this->varStack[$this->currGroup] as $idx => $currEntry) {
163                                 //* DEBUG: */ echo __METHOD__.":currGroup={$this->currGroup},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
164                                 // Is the entry found?
165                                 if ($currEntry['name'] == $var) {
166                                         // Found!
167                                         //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
168                                         $found = $idx;
169                                         break;
170                                 } // END - if
171                         } // END - foreach
172                 } // END - if
173
174                 // Return the current position
175                 return $found;
176         }
177
178         /**
179          * Return a content of a variable or null if not found
180          *
181          * @param       $var            The variable we are looking for
182          * @return      $content        Content of the variable or null if not found
183          */
184         protected function readVariable ($var) {
185                 // First everything is not found
186                 $content = null;
187
188                 // Get variable index
189                 $found = $this->isVariableAlreadySet($var);
190
191                 // Is the variable found?
192                 if ($found !== false) {
193                         // Read it
194                         $found = $this->varStack[$this->currGroup][$found]['value'];
195                 } // END - if
196
197                 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
198
199                 // Return the current position
200                 return $found;
201         }
202
203         /**
204          * Add a variable to the stack
205          *
206          * @param       $var    The variable we are looking for
207          * @param       $value  The value we want to store in the variable
208          * @return      void
209          */
210         private function addVariable ($var, $value) {
211                 // Set general variable group
212                 $this->setVariableGroup('general');
213
214                 // Add it to the stack
215                 $this->addGroupVariable($var, $value);
216         }
217
218         /**
219          * Returns all variables of current group or empty array
220          *
221          * @return      $result         Wether array of found variables or empty array
222          */
223         private function readCurrentGroup () {
224                 // Default is not found
225                 $result = array();
226
227                 // Is the group there?
228                 if (isset($this->varStack[$this->currGroup])) {
229                         // Then use it
230                         $result = $this->varStack[$this->currGroup];
231                 } // END - if
232
233                 // Return result
234                 return $result;
235         }
236
237         /**
238          * Settter for variable group
239          *
240          * @param       $groupName      Name of variable group
241          * @param       $add            Wether add this group
242          * @retur4n     void
243          */
244         public function setVariableGroup ($groupName, $add = true) {
245                 // Set group name
246                 //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
247                 $this->currGroup = $groupName;
248
249                 // Skip group 'general'
250                 if (($groupName != 'general') && ($add === true)) {
251                         $this->varGroups[$groupName] = 'OK';
252                 } // END - if
253         }
254
255
256         /**
257          * Adds a variable to current group
258          *
259          * @param       $var    Variable to set
260          * @param       $value  Value to store in variable
261          * @return      void
262          */
263         public function addGroupVariable ($var, $value) {
264                 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
265
266                 // Get current variables in group
267                 $currVars = $this->readCurrentGroup();
268
269                 // Append our variable
270                 $currVars[] = array(
271                         'name'  => $var,
272                         'value' => $value
273                 );
274
275                 // Add it to the stack
276                 $this->varStack[$this->currGroup] = $currVars;
277         }
278
279         /**
280          * Modify an entry on the stack
281          *
282          * @param       $var    The variable we are looking for
283          * @param       $value  The value we want to store in the variable
284          * @return      void
285          */
286         private function modifyVariable ($var, $value) {
287                 // Get index for variable
288                 $idx = $this->isVariableAlreadySet($var);
289
290                 // Is the variable set?
291                 if ($idx !== false) {
292                         // Then modify it
293                         $this->varStack[$this->currGroup][$idx]['value'] = $value;
294                 } // END - if
295         }
296
297         /**
298          * Setter for template type. Only 'html', 'emails' and 'compiled' should
299          * be sent here
300          *
301          * @param       $templateType   The current template's type
302          * @return      void
303          */
304         private final function setTemplateType ($templateType) {
305                 $this->templateType = (string) $templateType;
306         }
307
308         /**
309          * Setter for the last loaded template's FQFN
310          *
311          * @param       $template       The last loaded template
312          * @return      void
313          */
314         private final function setLastTemplate ($template) {
315                 $this->lastTemplate = (string) $template;
316         }
317
318         /**
319          * Getter for the last loaded template's FQFN
320          *
321          * @return      $template       The last loaded template
322          */
323         private final function getLastTemplate () {
324                 return $this->lastTemplate;
325         }
326
327         /**
328          * Setter for base path
329          *
330          * @param               $basePath               The local base path for all templates
331          * @return      void
332          */
333         public final function setBasePath ($basePath) {
334                 // And set it
335                 $this->basePath = (string) $basePath;
336         }
337
338         /**
339          * Getter for base path
340          *
341          * @return      $basePath               The local base path for all templates
342          */
343         public final function getBasePath () {
344                 // And set it
345                 return $this->basePath;
346         }
347
348         /**
349          * Setter for template extension
350          *
351          * @param               $templateExtension      The file extension for all uncompiled
352          *                                                      templates
353          * @return      void
354          */
355         public final function setRawTemplateExtension ($templateExtension) {
356                 // And set it
357                 $this->templateExtension = (string) $templateExtension;
358         }
359
360         /**
361          * Setter for code template extension
362          *
363          * @param               $codeExtension          The file extension for all uncompiled
364          *                                                      templates
365          * @return      void
366          */
367         public final function setCodeTemplateExtension ($codeExtension) {
368                 // And set it
369                 $this->codeExtension = (string) $codeExtension;
370         }
371
372         /**
373          * Getter for template extension
374          *
375          * @return      $templateExtension      The file extension for all uncompiled
376          *                                                      templates
377          */
378         public final function getRawTemplateExtension () {
379                 // And set it
380                 return $this->templateExtension;
381         }
382
383         /**
384          * Getter for code-template extension
385          *
386          * @return      $codeExtension          The file extension for all code-
387          *                                                      templates
388          */
389         public final function getCodeTemplateExtension () {
390                 // And set it
391                 return $this->codeExtension;
392         }
393
394         /**
395          * Setter for path of compiled templates
396          *
397          * @param       $compileOutputPath      The local base path for all compiled
398          *                                                              templates
399          * @return      void
400          */
401         public final function setCompileOutputPath ($compileOutputPath) {
402                 // And set it
403                 $this->compileOutputPath = (string) $compileOutputPath;
404         }
405
406         /**
407          * Getter for template type
408          *
409          * @return      $templateType   The current template's type
410          */
411         public final function getTemplateType () {
412                 return $this->templateType;
413         }
414
415         /**
416          * Assign (add) a given variable with a value
417          *
418          * @param       $var    The variable we are looking for
419          * @param       $value  The value we want to store in the variable
420          * @return      void
421          * @throws      EmptyVariableException  If the variable name is left empty
422          */
423         public final function assignVariable ($var, $value) {
424                 // Trim spaces of variable name
425                 $var = trim($var);
426
427                 // Empty variable found?
428                 if (empty($var)) {
429                         // Throw an exception
430                         throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
431                 } // END - if
432
433                 // First search for the variable if it was already added
434                 $idx = $this->isVariableAlreadySet($var);
435
436                 // Was it found?
437                 if ($idx === false) {
438                         // Add it to the stack
439                         //* DEBUG: */ echo "ADD: ".$var."<br />\n";
440                         $this->addVariable($var, $value);
441                 } elseif (!empty($value)) {
442                         // Modify the stack entry
443                         //* DEBUG: */ echo "MOD: ".$var."<br />\n";
444                         $this->modifyVariable($var, $value);
445                 }
446         }
447
448         /**
449          * Removes a given variable
450          *
451          * @param       $var    The variable we are looking for
452          * @return      void
453          */
454         public final function removeVariable ($var) {
455                 // First search for the variable if it was already added
456                 $idx = $this->isVariableAlreadySet($var);
457
458                 // Was it found?
459                 if ($idx !== false) {
460                         // Remove this variable
461                         $this->varStack->offsetUnset($idx);
462                 }
463         }
464
465         /**
466          * Private setter for raw template data
467          *
468          * @param       $rawTemplateData        The raw data from the template
469          * @return      void
470          */
471         protected final function setRawTemplateData ($rawTemplateData) {
472                 // And store it in this class
473                 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($rawTemplateData).' Bytes set.<br />\n';
474                 //* DEBUG: */ echo $this->currGroup.' variables: '.count($this->varStack[$this->currGroup]).', groups='.count($this->varStack).'<br />\n';
475                 $this->rawTemplateData = (string) $rawTemplateData;
476         }
477
478         /**
479          * Getter for raw template data
480          *
481          * @return      $rawTemplateData        The raw data from the template
482          */
483         public final function getRawTemplateData () {
484                 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->rawTemplateData).' Bytes read.<br />\n';
485                 return $this->rawTemplateData;
486         }
487
488         /**
489          * Private setter for compiled templates
490          *
491          * @return      void
492          */
493         private final function setCompiledData ($compiledData) {
494                 // And store it in this class
495                 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($compiledData).' Bytes set.<br />\n';
496                 $this->compiledData = (string) $compiledData;
497         }
498
499         /**
500          * Getter for compiled templates
501          *
502          * @return      $compiledData   Compiled template data
503          */
504         public final function getCompiledData () {
505                 //* DEBUG: */ echo __METHOD__.':'.$this->getUniqueId().': '.strlen($this->compiledData).' Bytes read.<br />\n';
506                 return $this->compiledData;
507         }
508
509         /**
510          * Private loader for all template types
511          *
512          * @param       $template       The template we shall load
513          * @return      void
514          */
515         private function loadTemplate ($template) {
516                 // Get extension for the template
517                 $ext = $this->getRawTemplateExtension();
518
519                 // If we shall load a code-template we need to switch the file extension
520                 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
521                         // Switch over to the code-template extension
522                         $ext = $this->getCodeTemplateExtension();
523                 } // END - if
524
525                 // Construct the FQFN for the template by honoring the current language
526                 $fqfn = sprintf("%s%s/%s/%s%s",
527                         $this->getBasePath(),
528                         $this->getLanguageInstance()->getLanguageCode(),
529                         $this->getTemplateType(),
530                         (string) $template,
531                         $ext
532                 );
533
534                 // Load the raw template data
535                 $this->loadRawTemplateData($fqfn);
536         }
537
538         /**
539          * A private loader for raw template names
540          *
541          * @param       $fqfn   The full-qualified file name for a template
542          * @return      void
543          */
544         private function loadRawTemplateData ($fqfn) {
545                 // Get a input/output instance from the middleware
546                 $ioInstance = $this->getFileIoInstance();
547
548                 // Some debug code to look on the file which is being loaded
549                 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
550
551                 // Load the raw template
552                 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
553
554                 // Store the template's contents into this class
555                 $this->setRawTemplateData($rawTemplateData);
556
557                 // Remember the template's FQFN
558                 $this->setLastTemplate($fqfn);
559         }
560
561         /**
562          * Try to assign an extracted template variable as a "content" or 'config'
563          * variable.
564          *
565          * @param       $varName        The variable's name (shall be content orconfig) by
566          *                                              default
567          * @param       $var            The variable we want to assign
568          */
569         private function assignTemplateVariable ($varName, $var) {
570                 // Is it not a config variable?
571                 if ($varName != 'config') {
572                         // Regular template variables
573                         $this->assignVariable($var, '');
574                 } else {
575                         // Configuration variables
576                         $this->assignConfigVariable($var);
577                 }
578         }
579
580         /**
581          * Extract variables from a given raw data stream
582          *
583          * @param       $rawData        The raw template data we shall analyze
584          * @return      void
585          */
586         private function extractVariablesFromRawData ($rawData) {
587                 // Cast to string
588                 $rawData = (string) $rawData;
589
590                 // Search for variables
591                 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
592
593                 // Did we find some variables?
594                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
595                         // Initialize all missing variables
596                         foreach ($variableMatches[3] as $key => $var) {
597                                 // Variable name
598                                 $varName = $variableMatches[1][$key];
599
600                                 // Workarround: Do not assign empty variables
601                                 if (!empty($var)) {
602                                         // Try to assign it, empty strings are being ignored
603                                         $this->assignTemplateVariable($varName, $var);
604                                 } // END - if
605                         } // END - foreach
606                 } // END - if
607         }
608
609         /**
610          * Main analysis of the loaded template
611          *
612          * @param       $templateMatches        Found template place-holders, see below
613          * @return      void
614          *
615          *---------------------------------
616          * Structure of $templateMatches:
617          *---------------------------------
618          * [0] => Array - An array with all full matches
619          * [1] => Array - An array with left part (before the ':') of a match
620          * [2] => Array - An array with right part of a match including ':'
621          * [3] => Array - An array with right part of a match excluding ':'
622          */
623         private function analyzeTemplate (array $templateMatches) {
624                 // Backup raw template data
625                 $backup = $this->getRawTemplateData();
626
627                 // Initialize some arrays
628                 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
629
630                 // Load all requested templates
631                 foreach ($templateMatches[1] as $template) {
632
633                         // Load and compile only templates which we have not yet loaded
634                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
635                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
636
637                                 // Template not found, but maybe variable assigned?
638                                 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
639                                 if ($this->isVariableAlreadySet($template) !== false) {
640                                         // Use that content here
641                                         $this->loadedRawData[$template] = $this->readVariable($template);
642
643                                         // Recursive protection:
644                                         $this->loadedTemplates[] = $template;
645                                 } elseif (isset($this->varStack['config'][$template])) {
646                                         // Use that content here
647                                         $this->loadedRawData[$template] = $this->varStack['config'][$template];
648
649                                         // Recursive protection:
650                                         $this->loadedTemplates[] = $template;
651                                 } else {
652                                         // Then try to search for code-templates
653                                         try {
654                                                 // Load the code template and remember it's contents
655                                                 $this->loadCodeTemplate($template);
656                                                 $this->loadedRawData[$template] = $this->getRawTemplateData();
657
658                                                 // Remember this template for recursion detection
659                                                 // RECURSIVE PROTECTION!
660                                                 $this->loadedTemplates[] = $template;
661                                         } catch (FileNotFoundException $e) {
662                                                 // Even this is not done... :/
663                                                 $this->rawTemplates[] = $template;
664                                         } catch (FilePointerNotOpenedException $e) {
665                                                 // Even this is not done... :/
666                                                 $this->rawTemplates[] = $template;
667                                         }
668                                 }
669                         } // END - if
670                 } // END - foreach
671
672                 // Restore the raw template data
673                 $this->setRawTemplateData($backup);
674         }
675
676         /**
677          * Compile a given raw template code and remember it for later usage
678          *
679          * @param       $code           The raw template code
680          * @param       $template       The template's name
681          * @return      void
682          */
683         private function compileCode ($code, $template) {
684                 // Is this template already compiled?
685                 if (in_array($template, $this->compiledTemplates)) {
686                         // Abort here...
687                         return;
688                 } // END - if
689
690                 // Remember this template being compiled
691                 $this->compiledTemplates[] = $template;
692
693                 // Compile the loaded code in five steps:
694                 //
695                 // 1. Backup current template data
696                 $backup = $this->getRawTemplateData();
697
698                 // 2. Set the current template's raw data as the new content
699                 $this->setRawTemplateData($code);
700
701                 // 3. Compile the template data
702                 $this->compileTemplate();
703
704                 // 4. Remember it's contents
705                 $this->loadedRawData[$template] = $this->getRawTemplateData();
706
707                 // 5. Restore the previous raw content from backup variable
708                 $this->setRawTemplateData($backup);
709         }
710
711         /**
712          * Insert all given and loaded templates by running through all loaded
713          * codes and searching for their place-holder in the main template
714          *
715          * @param       $templateMatches        See method analyzeTemplate()
716          * @return      void
717          */
718         private function insertAllTemplates (array $templateMatches) {
719                 // Run through all loaded codes
720                 foreach ($this->loadedRawData as $template => $code) {
721
722                         // Search for the template
723                         $foundIndex = array_search($template, $templateMatches[1]);
724
725                         // Lookup the matching template replacement
726                         if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
727
728                                 // Get the current raw template
729                                 $rawData = $this->getRawTemplateData();
730
731                                 // Replace the space holder with the template code
732                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
733
734                                 // Set the new raw data
735                                 $this->setRawTemplateData($rawData);
736                         } // END - if
737                 } // END - foreach
738         }
739
740         /**
741          * Load all extra raw templates
742          *
743          * @return      void
744          */
745         private function loadExtraRawTemplates () {
746                 // Are there some raw templates we need to load?
747                 if (count($this->rawTemplates) > 0) {
748                         // Try to load all raw templates
749                         foreach ($this->rawTemplates as $key => $template) {
750                                 try {
751                                         // Load the template
752                                         $this->loadWebTemplate($template);
753
754                                         // Remember it's contents
755                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
756
757                                         // Remove it from the loader list
758                                         unset($this->rawTemplates[$key]);
759
760                                         // Remember this template for recursion detection
761                                         // RECURSIVE PROTECTION!
762                                         $this->loadedTemplates[] = $template;
763                                 } catch (FileNotFoundException $e) {
764                                         // This template was never found. We silently ignore it
765                                         unset($this->rawTemplates[$key]);
766                                 } catch (FilePointerNotOpenedException $e) {
767                                         // This template was never found. We silently ignore it
768                                         unset($this->rawTemplates[$key]);
769                                 }
770                         } // END - foreach
771                 } // END - if
772         }
773
774         /**
775          * Assign all found template variables
776          *
777          * @param       $varMatches             An array full of variable/value pairs.
778          * @return      void
779          * @todo        Unfinished work or don't die here.
780          */
781         private function assignAllVariables (array $varMatches) {
782                 // Search for all variables
783                 foreach ($varMatches[1] as $key => $var) {
784
785                         // Detect leading equals
786                         if (substr($varMatches[2][$key], 0, 1) == '=') {
787                                 // Remove and cast it
788                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
789                         } // END - if
790
791                         // Do we have some quotes left and right side? Then it is free text
792                         if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
793                                 // Free string detected! Which we can assign directly
794                                 $this->assignVariable($var, $varMatches[3][$key]);
795                         } elseif (!empty($varMatches[2][$key])) {
796                                 // @TODO Non-string found so we need some deeper analysis...
797                                 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
798                         }
799
800                 } // for ($varMatches ...
801         }
802         /**
803          * Compiles all loaded raw templates
804          *
805          * @param       $templateMatches        See method analyzeTemplate() for details
806          * @return      void
807          */
808         private function compileRawTemplateData (array $templateMatches) {
809                 // Are some code-templates found which we need to compile?
810                 if (count($this->loadedRawData) > 0) {
811
812                         // Then compile all!
813                         foreach ($this->loadedRawData as $template => $code) {
814
815                                 // Is this template already compiled?
816                                 if (in_array($template, $this->compiledTemplates)) {
817                                         // Then skip it
818                                         continue;
819                                 }
820
821                                 // Search for the template
822                                 $foundIndex = array_search($template, $templateMatches[1]);
823
824                                 // Lookup the matching variable data
825                                 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
826
827                                         // Split it up with another reg. exp. into variable=value pairs
828                                         preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
829
830                                         // Assign all variables
831                                         $this->assignAllVariables($varMatches);
832
833                                 } // END - if (isset($templateMatches ...
834
835                                 // Compile the loaded template
836                                 $this->compileCode($code, $template);
837
838                         } // END - foreach ($this->loadedRawData ...
839
840                         // Insert all templates
841                         $this->insertAllTemplates($templateMatches);
842
843                 } // END - if (count($this->loadedRawData) ...
844         }
845
846         /**
847          * Inserts all raw templates into their respective variables
848          *
849          * @return      void
850          */
851         private function insertRawTemplates () {
852                 // Load all templates
853                 foreach ($this->rawTemplates as $template => $content) {
854                         // Set the template as a variable with the content
855                         $this->assignVariable($template, $content);
856                 }
857         }
858
859         /**
860          * Finalizes the compilation of all template variables
861          *
862          * @return      void
863          */
864         private function finalizeVariableCompilation () {
865                 // Get the content
866                 $content = $this->getRawTemplateData();
867                 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
868
869                 // Walk through all variables
870                 foreach ($this->varStack['general'] as $currEntry) {
871                         //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
872                         // Replace all [$var] or {?$var?} with the content
873                         // @TODO Old behaviour, will become obsolete!
874                         $content = str_replace("\$content[".$currEntry['name'].']', $currEntry['value'], $content);
875
876                         // @TODO Yet another old way
877                         $content = str_replace('['.$currEntry['name'].']', $currEntry['value'], $content);
878
879                         // The new behaviour
880                         $content = str_replace('{?'.$currEntry['name'].'?}', $currEntry['value'], $content);
881                 } // END - for
882
883                 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
884
885                 // Set the content back
886                 $this->setRawTemplateData($content);
887         }
888
889         /**
890          * Load a specified web template into the engine
891          *
892          * @param       $template       The web template we shall load which is located in
893          *                                              'html' by default
894          * @return      void
895          */
896         public function loadWebTemplate ($template) {
897                 // Set template type
898                 $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
899
900                 // Load the special template
901                 $this->loadTemplate($template);
902         }
903
904         /**
905          * Assign a given congfiguration variable with a value
906          *
907          * @param       $var    The configuration variable we want to assign
908          * @return      void
909          */
910         public function assignConfigVariable ($var) {
911                 // Sweet and simple...
912                 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
913                 $this->varStack['config'][$var] = $this->getConfigInstance()->readConfig($var);
914         }
915
916         /**
917          * Load a specified email template into the engine
918          *
919          * @param       $template       The email template we shall load which is located in
920          *                                              'emails' by default
921          * @return      void
922          */
923         public function loadEmailTemplate ($template) {
924                 // Set template type
925                 $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
926
927                 // Load the special template
928                 $this->loadTemplate($template);
929         }
930
931         /**
932          * Load a specified code template into the engine
933          *
934          * @param       $template       The code template we shall load which is
935          *                                              located in 'code' by default
936          * @return      void
937          */
938         public function loadCodeTemplate ($template) {
939                 // Set template type
940                 $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
941
942                 // Load the special template
943                 $this->loadTemplate($template);
944         }
945
946         /**
947          * Compile all variables by inserting their respective values
948          *
949          * @return      void
950          * @todo        Make this code some nicer...
951          */
952         public final function compileVariables () {
953                 // Initialize the $content array
954                 $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
955                 $dummy = array();
956
957                 // Iterate through all general variables
958                 foreach ($this->varStack['general'] as $currVariable) {
959                         // Transfer it's name/value combination to the $content array
960                         //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
961                         $dummy[$currVariable['name']] = $currVariable['value'];
962                 }// END - if
963
964                 // Set the new variable (don't remove the second dollar!)
965                 $$validVar = $dummy;
966
967                 // Prepare all configuration variables
968                 $config = null;
969                 if (isset($this->varStack['config'])) {
970                         $config = $this->varStack['config'];
971                 } // END - if
972
973                 // Remove some variables
974                 unset($idx);
975                 unset($currVariable);
976
977                 // Run the compilation three times to get content from helper classes in
978                 $cnt = 0;
979                 while ($cnt < 3) {
980                         // Finalize the compilation of template variables
981                         $this->finalizeVariableCompilation();
982
983                         // Prepare the eval() command for comiling the template
984                         $eval = sprintf("\$result = \"%s\";",
985                                 addslashes($this->getRawTemplateData())
986                         );
987
988                         // This loop does remove the backslashes (\) in PHP parameters
989                         while (strpos($eval, $this->codeBegin) !== false) {
990                                 // Get left part before "<?"
991                                 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
992
993                                 // Get all from right of "<?"
994                                 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
995
996                                 // Cut middle part out and remove escapes
997                                 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
998                                 $evalMiddle = stripslashes($evalMiddle);
999
1000                                 // Remove the middle part from right one
1001                                 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1002
1003                                 // And put all together
1004                                 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1005                         } // END - while
1006
1007                         // Prepare PHP code for eval() command
1008                         $eval = str_replace(
1009                                 "<%php", "\";",
1010                                 str_replace(
1011                                         "%>",
1012                                         "\n\$result .= \"",
1013                                         $eval
1014                                 )
1015                         );
1016
1017                         // Run the constructed command. This will "compile" all variables in
1018                         @eval($eval);
1019
1020                         // Goes something wrong?
1021                         if (!isset($result)) {
1022                                 // Output eval command
1023                                 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1024
1025                                 // Output backtrace here
1026                                 $this->debugBackTrace();
1027                         } // END - if
1028
1029                         // Set raw template data
1030                         $this->setRawTemplateData($result);
1031                         $cnt++;
1032                 } // END - while
1033
1034                 // Final variable assignment
1035                 $this->finalizeVariableCompilation();
1036
1037                 // Set the new content
1038                 $this->setCompiledData($this->getRawTemplateData());
1039         }
1040
1041         /**
1042          * Compile all required templates into the current loaded one
1043          *
1044          * @return      void
1045          * @throws      UnexpectedTemplateTypeException If the template type is
1046          *                                                                                      not "code"
1047          * @throws      InvalidArrayCountException              If an unexpected array
1048          *                                                                                      count has been found
1049          */
1050         public function compileTemplate () {
1051                 // We will only work with template type "code" from configuration
1052                 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
1053                         // Abort here
1054                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1055                 } // END - if
1056
1057                 // Get the raw data.
1058                 $rawData = $this->getRawTemplateData();
1059
1060                 // Remove double spaces and trim leading/trailing spaces
1061                 $rawData = trim(str_replace('  ', ' ', $rawData));
1062
1063                 // Search for raw variables
1064                 $this->extractVariablesFromRawData($rawData);
1065
1066                 // Search for code-tags which are {? ?}
1067                 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1068
1069                 // Analyze the matches array
1070                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1071                         // Entries are found:
1072                         //
1073                         // The main analysis
1074                         $this->analyzeTemplate($templateMatches);
1075
1076                         // Compile raw template data
1077                         $this->compileRawTemplateData($templateMatches);
1078
1079                         // Are there some raw templates left for loading?
1080                         $this->loadExtraRawTemplates();
1081
1082                         // Are some raw templates found and loaded?
1083                         if (count($this->rawTemplates) > 0) {
1084
1085                                 // Insert all raw templates
1086                                 $this->insertRawTemplates();
1087
1088                                 // Remove the raw template content as well
1089                                 $this->setRawTemplateData('');
1090
1091                         } // END - if
1092
1093                 } // END - if($templateMatches ...
1094         }
1095
1096         /**
1097          * A old deprecated method
1098          *
1099          * @return      void
1100          * @deprecated
1101          * @see         BaseTemplateEngine::transferToResponse
1102          */
1103         public function output () {
1104                 // Check which type of template we have
1105                 switch ($this->getTemplateType()) {
1106                         case 'html': // Raw HTML templates can be send to the output buffer
1107                                 // Quick-N-Dirty:
1108                                 $this->getWebOutputInstance()->output($this->getCompiledData());
1109                                 break;
1110
1111                         default: // Unknown type found
1112                                 // Construct message
1113                                 $msg = sprintf("[%s-&gt;%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1114                                         $this->__toString(),
1115                                         __FUNCTION__,
1116                                         $this->getTemplateType()
1117                                 );
1118
1119                                 // Write the problem to the world...
1120                                 $this->debugOutput($msg);
1121                                 break;
1122                 } // END - switch
1123         }
1124
1125         /**
1126          * Loads a given view helper (by name)
1127          *
1128          * @param       $helperName             The helper's name
1129          * @return      void
1130          */
1131         protected function loadViewHelper ($helperName) {
1132                 // Make first character upper case, rest low
1133                 $helperName = $this->convertToClassName($helperName);
1134
1135                 // Is this view helper loaded?
1136                 if (!isset($this->helpers[$helperName])) {
1137                         // Create a class name
1138                         $className = "{$helperName}ViewHelper";
1139
1140                         // Generate new instance
1141                         $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1142                 } // END - if
1143
1144                 // Return the requested instance
1145                 return $this->helpers[$helperName];
1146         }
1147
1148         /**
1149          * Assigns the last loaded raw template content with a given variable
1150          *
1151          * @param       $templateName   Name of the template we want to assign
1152          * @param       $variableName   Name of the variable we want to assign
1153          * @return      void
1154          */
1155         public function assignTemplateWithVariable ($templateName, $variableName) {
1156                 // Get the content from last loaded raw template
1157                 $content = $this->getRawTemplateData();
1158
1159                 // Assign the variable
1160                 $this->assignVariable($variableName, $content);
1161
1162                 // Purge raw content
1163                 $this->setRawTemplateData('');
1164         }
1165
1166         /**
1167          * Transfers the content of this template engine to a given response instance
1168          *
1169          * @param       $responseInstance       An instance of a response class
1170          * @return      void
1171          */
1172         public function transferToResponse (Responseable $responseInstance) {
1173                 // Get the content and set it in response class
1174                 $responseInstance->writeToBody($this->getCompiledData());
1175         }
1176
1177         /**
1178          * Assigns all the application data with template variables
1179          *
1180          * @param       $appInstance    A manageable application instance
1181          * @return      void
1182          */
1183         public function assignApplicationData (ManageableApplication $appInstance) {
1184                 // Get long name and assign it
1185                 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1186
1187                 // Get short name and assign it
1188                 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1189
1190                 // Get version number and assign it
1191                 $this->assignVariable('app_version'   , $appInstance->getAppVersion());
1192
1193                 // Assign extra application-depending data
1194                 $appInstance->assignExtraTemplateData($this);
1195         }
1196
1197         /**
1198          * "Compiles" a variable by replacing {?var?} with it's content
1199          *
1200          * @param       $rawCode        Raw code to compile
1201          * @return      $rawCode        Compile code with inserted variable value
1202          */
1203         public function compileRawCode ($rawCode) {
1204                 // Find the variables
1205                 //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1206                 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1207
1208                 // Compile all variables
1209                 //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
1210                 foreach ($varMatches[0] as $match) {
1211                         // Add variable tags around it
1212                         $varCode = '{?' . $match . '?}';
1213
1214                         // Is the variable found in code? (safes some calls)
1215                         if (strpos($rawCode, $varCode) !== false) {
1216                                 // Replace the variable with it's value, if found
1217                                 //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
1218                                 $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
1219                         } // END - if
1220                 } // END - foreach
1221
1222                 // Return the compiled data
1223                 return $rawCode;
1224         }
1225
1226         /**
1227          * Getter for variable group array
1228          *
1229          * @return      $vargroups      All variable groups
1230          */
1231         public final function getVariableGroups () {
1232                 return $this->varGroups;
1233         }
1234
1235         /**
1236          * Renames a variable in code and in stack
1237          *
1238          * @param       $oldName        Old name of variable
1239          * @param       $newName        New name of variable
1240          * @return      void
1241          */
1242         public function renameVariable ($oldName, $newName) {
1243                 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1244                 // Get raw template code
1245                 $rawData = $this->getRawTemplateData();
1246
1247                 // Replace it
1248                 $rawData = str_replace($oldName, $newName, $rawData);
1249
1250                 // Set the code back
1251                 $this->setRawTemplateData($rawData);
1252         }
1253
1254         /**
1255          * Renders the given XML content
1256          *
1257          * @param       $content        Valid XML content or if not set the current loaded raw content
1258          * @return      void
1259          * @throws      XmlParserException      If an XML error was found
1260          */
1261         public final function renderXmlContent ($content = null) {
1262                 // Is the content set?
1263                 if (is_null($content)) {
1264                         // Get current content
1265                         $content = $this->getRawTemplateData();
1266                 } // END - if
1267
1268                 // Convert all to UTF8
1269                 if (function_exists('recode')) {
1270                         $content = recode("html..utf8", $content);
1271                 } else {
1272                         // @TODO We need to find a fallback solution here
1273                 } // END - if
1274
1275                 // Get an XML parser
1276                 $xmlParser = xml_parser_create();
1277
1278                 // Force case-folding to on
1279                 xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
1280
1281                 // Set object
1282                 xml_set_object($xmlParser, $this);
1283
1284                 // Set handler call-backs
1285                 xml_set_element_handler($xmlParser, 'startElement', 'endElement');
1286                 xml_set_character_data_handler($xmlParser, 'characterHandler');
1287
1288                 // Now parse the XML tree
1289                 if (!xml_parse($xmlParser, $content)) {
1290                         // Error found in XML!
1291                         //die('<pre>'.htmlentities($content).'</pre>');
1292                         throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
1293                 } // END - if
1294
1295                 // Free the parser
1296                 xml_parser_free($xmlParser);
1297         }
1298 }
1299
1300 // [EOF]
1301 ?>