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