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