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