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