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