Template engine does now insert all variables (work-around)
[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@mxchange.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   = 0xa00;
113         const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0xa01;
114         const EXCEPTION_INVALID_VIEW_HELPER           = 0xa02;
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("Template-Engine");
127
128                 // Create unique ID number
129                 $this->createUniqueID();
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 = $tplInstance->getConfigInstance();
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          * Initialize the variable stack. This holds all variables for later
288          * compilation.
289          *
290          * @return      void
291          */
292         public final function initVariableStack () {
293                 $this->varStack = new FrameworkArrayObject();
294         }
295
296         /**
297          * Setter for base path
298          *
299          * @param               $basePath               The local base path for all templates
300          * @return      void
301          */
302         public final function setBasePath ($basePath) {
303                 // Cast it
304                 $basePath = (string) $basePath;
305
306                 // And set it
307                 $this->basePath = $basePath;
308         }
309
310         /**
311          * Getter for base path
312          *
313          * @return      $basePath               The local base path for all templates
314          */
315         public final function getBasePath () {
316                 // And set it
317                 return $this->basePath;
318         }
319
320         /**
321          * Setter for template extension
322          *
323          * @param               $templateExtension      The file extension for all uncompiled
324          *                                                      templates
325          * @return      void
326          */
327         public final function setRawTemplateExtension ($templateExtension) {
328                 // Cast it
329                 $templateExtension = (string) $templateExtension;
330
331                 // And set it
332                 $this->templateExtension = $templateExtension;
333         }
334
335         /**
336          * Setter for code template extension
337          *
338          * @param               $codeExtension          The file extension for all uncompiled
339          *                                                      templates
340          * @return      void
341          */
342         public final function setCodeTemplateExtension ($codeExtension) {
343                 // Cast it
344                 $codeExtension = (string) $codeExtension;
345
346                 // And set it
347                 $this->codeExtension = $codeExtension;
348         }
349
350         /**
351          * Getter for template extension
352          *
353          * @return      $templateExtension      The file extension for all uncompiled
354          *                                                      templates
355          */
356         public final function getRawTemplateExtension () {
357                 // And set it
358                 return $this->templateExtension;
359         }
360
361         /**
362          * Getter for code-template extension
363          *
364          * @return      $codeExtension          The file extension for all code-
365          *                                                      templates
366          */
367         public final function getCodeTemplateExtension () {
368                 // And set it
369                 return $this->codeExtension;
370         }
371
372         /**
373          * Setter for path of compiled templates
374          *
375          * @param               $compileOutputPath              The local base path for all
376          *                                                              compiled templates
377          * @return      void
378          */
379         public final function setCompileOutputPath ($compileOutputPath) {
380                 // Cast it
381                 $compileOutputPath = (string) $compileOutputPath;
382
383                 // And set it
384                 $this->compileOutputPath = $compileOutputPath;
385         }
386
387         /**
388          * Setter for template type. Only "html", "emails" and "compiled" should
389          * be sent here
390          *
391          * @param               $templateType   The current template's type
392          * @return      void
393          */
394         private final function setTemplateType ($templateType) {
395                 // Cast it
396                 $templateType = (string) $templateType;
397
398                 // And set it (only 2 letters)
399                 $this->templateType = $templateType;
400         }
401
402         /**
403          * Getter for template type
404          *
405          * @return      $templateType   The current template's type
406          */
407         public final function getTemplateType () {
408                 return $this->templateType;
409         }
410
411         /**
412          * Setter for the last loaded template's FQFN
413          *
414          * @param               $template               The last loaded template
415          * @return      void
416          */
417         private final function setLastTemplate ($template) {
418                 // Cast it to string
419                 $template = (string) $template;
420                 $this->lastTemplate = $template;
421         }
422
423         /**
424          * Getter for the last loaded template's FQFN
425          *
426          * @return      $template               The last loaded template
427          */
428         private final function getLastTemplate () {
429                 return $this->lastTemplate;
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          * Assign a given congfiguration variable with a value
455          *
456          * @param               $var            The configuration variable we are looking for
457          * @param               $value  The value we want to store in the variable
458          * @return      void
459          */
460         public final function assignConfigVariable ($var, $value) {
461                 // Sweet and simple...
462                 $this->configVariables[$var] = $value;
463         }
464
465         /**
466          * Removes a given variable
467          *
468          * @param               $var            The variable we are looking for
469          * @return      void
470          */
471         public final function removeVariable ($var) {
472                 // First search for the variable if it was already added
473                 $idx = $this->isVariableAlreadySet($var);
474
475                 // Was it found?
476                 if ($idx !== false) {
477                         // Remove this variable
478                         $this->varStack->offsetUnset($idx);
479                 }
480         }
481
482         /**
483          * Private setter for raw template data
484          *
485          * @param               $rawTemplateData        The raw data from the template
486          * @return      void
487          */
488         private final function setRawTemplateData ($rawTemplateData) {
489                 // Cast it to string
490                 $rawTemplateData = (string) $rawTemplateData;
491
492                 // And store it in this class
493                 $this->rawTemplateData = $rawTemplateData;
494         }
495
496         /**
497          * Private setter for compiled templates
498          */
499         private final function setCompiledData ($compiledData) {
500                 // Cast it to string
501                 $compiledData = (string) $compiledData;
502
503                 // And store it in this class
504                 $this->compiledData = $compiledData;
505         }
506
507         /**
508          * Private loader for all template types
509          *
510          * @param               $template               The template we shall load
511          * @return      void
512          */
513         private final function loadTemplate ($template) {
514                 // Cast it to string
515                 $template = (string) $template;
516
517                 // Get extension for the template
518                 $ext = $this->getRawTemplateExtension();
519
520                 // If we shall load a code-template we need to switch the file extension
521                 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig("code_template_type")) {
522                         // Switch over to the code-template extension
523                         $ext = $this->getCodeTemplateExtension();
524                 }
525
526                 // Construct the FQFN for the template by honoring the current language
527                 $fqfn = sprintf("%s%s/%s/%s%s",
528                         $this->getBasePath(),
529                         $this->getLanguageInstance()->getLanguageCode(),
530                         $this->getTemplateType(),
531                         $template,
532                         $ext
533                 );
534
535                 // Load the raw template data
536                 $this->loadRawTemplateData($fqfn);
537         }
538
539         /**
540          * A private loader for raw template names
541          *
542          * @param               $fqfn   The full-qualified file name for a template
543          * @return      void
544          * @throws      NullPointerException    If $inputInstance is null
545          * @throws      NoObjectException               If $inputInstance is not an object
546          * @throws      MissingMethodException  If $inputInstance is missing a
547          *                                                              required method
548          */
549         private function loadRawTemplateData ($fqfn) {
550                 // Debug message
551                 if ((defined('DEBUG_TEMPLATE')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Template <strong>%s</strong> vom Typ <strong>%s</strong> wird geladen.<br />\n",
552                         $this->__toString(),
553                         $template,
554                         $this->getTemplateType()
555                 ));
556
557                 // Get a input/output instance from the middleware
558                 $ioInstance = $this->getFileIOInstance();
559
560                 // Validate the instance
561                 if (is_null($ioInstance)) {
562                         // Throw exception
563                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
564                 } elseif (!is_object($ioInstance)) {
565                         // Throw another exception
566                         throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT);
567                 } elseif (!method_exists($ioInstance, 'loadFileContents')) {
568                         // Throw yet another exception
569                         throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD);
570                 }
571
572                 // Load the raw template
573                 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
574
575                 // Debug message
576                 if ((defined('DEBUG_TEMPLATE')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%s</strong> Byte Rohdaten geladen.<br />\n",
577                         $this->__toString(),
578                         strlen($rawTemplateData)
579                 ));
580
581                 // Store the template's contents into this class
582                 $this->setRawTemplateData($rawTemplateData);
583
584                 // Remember the template's FQFN
585                 $this->setLastTemplate($fqfn);
586         }
587
588         /**
589          * Try to assign an extracted template variable as a "content" or "config"
590          * variable.
591          *
592          * @param               $varName                The variable's name (shall be content or
593          *                                              config) by default
594          * @param               $var                    The variable we want to assign
595          */
596         private function assignTemplateVariable ($varName, $var) {
597                 // Is it not a config variable?
598                 if ($varName != "config") {
599                         // Regular template variables
600                         $this->assignVariable($var, "");
601                 } else {
602                         // Configuration variables
603                         $this->assignConfigVariable($var, $this->getConfigInstance()->readConfig($var));
604                 }
605         }
606
607         /**
608          * Extract variables from a given raw data stream
609          *
610          * @param       $rawData        The raw template data we shall analyze
611          * @return      void
612          * @throws      InvalidTemplateVariableNameException    If a variable name
613          *                                                                                                      in a template is
614          *                                                                                                      invalid
615          */
616         private function extractVariablesFromRawData ($rawData) {
617                 // Cast to string
618                 $rawData = (string) $rawData;
619
620                 // Search for variables
621                 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
622
623                 // Did we find some variables?
624                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
625                         // Initialize all missing variables
626                         foreach ($variableMatches[3] as $key=>$var) {
627                                 // Is the variable name valid?
628                                 if (($variableMatches[1][$key] != $this->getConfigInstance()->readConfig("tpl_valid_var")) && ($variableMatches[1][$key] != "config")) {
629                                         // Invalid variable name
630                                         throw new InvalidTemplateVariableNameException(array($this, $this->getLastTemplate(), $variableMatches[1][$key], $this->getConfigInstance()), self::EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR);
631                                 }
632
633                                 // Try to assign it, empty strings are being ignored
634                                 $this->assignTemplateVariable($variableMatches[1][$key], $var);
635                         }
636                 }
637         }
638
639         /**
640          * Main analysis of the loaded template
641          *
642          * @param               $templateMatches        Found template place-holders, see below
643          * @return      void
644          *
645          *---------------------------------
646          * Structure of $templateMatches:
647          *---------------------------------
648          * [0] => Array - An array with all full matches
649          * [1] => Array - An array with left part (before the ":") of a match
650          * [2] => Array - An array with right part of a match including ":"
651          * [3] => Array - An array with right part of a match excluding ":"
652          */
653         private function analyzeTemplate (array $templateMatches) {
654                 // Backup raw template data
655                 $backup = $this->getRawTemplateData();
656
657                 // Initialize some arrays
658                 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
659
660                 // Load all requested templates
661                 foreach ($templateMatches[1] as $template) {
662
663                         // Load and compile only templates which we have not yet loaded
664                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
665                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
666
667                                 // Then try to search for code-templates first
668                                 try {
669                                         // Load the code template and remember it's contents
670                                         $this->loadCodeTemplate($template);
671                                         $this->loadedRawData[$template] = $this->getRawTemplateData();
672
673                                         // Remember this template for recursion detection
674                                         // RECURSIVE PROTECTION!
675                                         $this->loadedTemplates[] = $template;
676                                 } catch (FilePointerNotOpenedException $e) {
677                                         // Template not found, but maybe variable assigned?
678                                         if ($this->isVariableAlreadySet($template) !== false) {
679                                                 // Use that content here
680                                                 $this->loadedRawData[$template] = $this->readVariable($template);
681
682                                                 // Recursive protection:
683                                                 $this->loadedTemplates[] = $template;
684                                         } else {
685                                                 // Even this is not done... :/
686                                                 $this->rawTemplates[] = $template;
687                                         }
688                                 }
689
690                         } // if ((!isset( ...
691
692                 } // for ($templateMatches ...
693
694                 // Restore the raw template data
695                 $this->setRawTemplateData($backup);
696         }
697
698         /**
699          * Compile a given raw template code and remember it for later usage
700          *
701          * @param               $code           The raw template code
702          * @param               $template               The template's name
703          * @return      void
704          */
705         private function compileCode ($code, $template) {
706                 // Is this template already compiled?
707                 if (in_array($template, $this->compiledTemplates)) {
708                         // Abort here...
709                         return;
710                 }
711
712                 // Remember this template being compiled
713                 $this->compiledTemplates[] = $template;
714
715                 // Compile the loaded code in five steps:
716                 //
717                 // 1. Backup current template data
718                 $backup = $this->getRawTemplateData();
719
720                 // 2. Set the current template's raw data as the new content
721                 $this->setRawTemplateData($code);
722
723                 // 3. Compile the template data
724                 $this->compileTemplate();
725
726                 // 4. Remember it's contents
727                 $this->loadedRawData[$template] = $this->getRawTemplateData();
728
729                 // 5. Restore the previous raw content from backup variable
730                 $this->setRawTemplateData($backup);
731         }
732
733         /**
734          * Insert all given and loaded templates by running through all loaded
735          * codes and searching for their place-holder in the main template
736          *
737          * @param               $templateMatches        See method analyzeTemplate()
738          * @return      void
739          */
740         private function insertAllTemplates (array $templateMatches) {
741                 // Run through all loaded codes
742                 foreach ($this->loadedRawData as $template=>$code) {
743
744                         // Search for the template
745                         $foundIndex = array_search($template, $templateMatches[1]);
746
747                         // Lookup the matching template replacement
748                         if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
749
750                                 // Get the current raw template
751                                 $rawData = $this->getRawTemplateData();
752
753                                 // Replace the space holder with the template code
754                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
755
756                                 // Set the new raw data
757                                 $this->setRawTemplateData($rawData);
758
759                         } // END - if
760
761                 } // END - foreach
762         }
763
764         /**
765          * Load all extra raw templates
766          *
767          * @return      void
768          */
769         private function loadExtraRawTemplates () {
770                 // Are there some raw templates we need to load?
771                 if (count($this->rawTemplates) > 0) {
772                         // Try to load all raw templates
773                         foreach ($this->rawTemplates as $key => $template) {
774                                 try {
775                                         // Load the template
776                                         $this->loadWebTemplate($template);
777
778                                         // Remember it's contents
779                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
780
781                                         // Remove it from the loader list
782                                         unset($this->rawTemplates[$key]);
783
784                                         // Remember this template for recursion detection
785                                         // RECURSIVE PROTECTION!
786                                         $this->loadedTemplates[] = $template;
787                                 } catch (FilePointerNotOpenedException $e) {
788                                         // This template was never found. We silently ignore it
789                                         unset($this->rawTemplates[$key]);
790                                 }
791                         }
792                 }
793         }
794
795         /**
796          * Assign all found template variables
797          *
798          * @param               $varMatches     An array full of variable/value pairs.
799          * @return      void
800          */
801         private function assignAllVariables (array $varMatches) {
802                 // Search for all variables
803                 foreach ($varMatches[1] as $key=>$var) {
804
805                         // Detect leading equals
806                         if (substr($varMatches[2][$key], 0, 1) == "=") {
807                                 // Remove and cast it
808                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
809                         }
810
811                         // Do we have some quotes left and right side? Then it is free text
812                         if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
813                                 // Free string detected! Which we can assign directly
814                                 $this->assignVariable($var, $varMatches[3][$key]);
815                         } elseif (!empty($varMatches[2][$key])) {
816                                 // Non-string found so we need some deeper analysis...
817                                 // @TODO Unfinished work or don't die here.
818                                 die("Deeper analysis not yet implemented!");
819                         }
820
821                 } // for ($varMatches ...
822         }
823         /**
824          * Compiles all loaded raw templates
825          *
826          * @param               $templateMatches        See method analyzeTemplate() for details
827          * @return      void
828          */
829         private function compileRawTemplateData (array $templateMatches) {
830                 // Are some code-templates found which we need to compile?
831                 if (count($this->loadedRawData) > 0) {
832
833                         // Then compile all!
834                         foreach ($this->loadedRawData as $template=>$code) {
835
836                                 // Is this template already compiled?
837                                 if (in_array($template, $this->compiledTemplates)) {
838                                         // Then skip it
839                                         continue;
840                                 }
841
842                                 // Search for the template
843                                 $foundIndex = array_search($template, $templateMatches[1]);
844
845                                 // Lookup the matching variable data
846                                 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
847
848                                         // Split it up with another reg. exp. into variable=value pairs
849                                         preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
850
851                                         // Assign all variables
852                                         $this->assignAllVariables($varMatches);
853
854                                 } // END - if (isset($templateMatches ...
855
856                                 // Compile the loaded template
857                                 $this->compileCode($code, $template);
858
859                         } // END - foreach ($this->loadedRawData ...
860
861                         // Insert all templates
862                         $this->insertAllTemplates($templateMatches);
863
864                 } // END - if (count($this->loadedRawData) ...
865         }
866
867         /**
868          * Inserts all raw templates into their respective variables
869          *
870          * @return      void
871          */
872         private function insertRawTemplates () {
873                 // Load all templates
874                 foreach ($this->rawTemplates as $template=>$content) {
875                         // Set the template as a variable with the content
876                         $this->assignVariable($template, $content);
877                 }
878         }
879
880         /**
881          * Finalizes the compilation of all template variables
882          *
883          * @return      void
884          */
885         private function finalizeVariableCompilation () {
886                 // Get the content
887                 $content = $this->getRawTemplateData();
888
889                 // Walk through all variables
890                 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
891
892                         // Get current entry
893                         $currEntry = $idx->current();
894
895                         // Replace all [$var] or {?$var?} with the content
896                         $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
897                         $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
898                         $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
899
900                 } // END - for
901
902                 // Set the content back
903                 $this->setRawTemplateData($content);
904         }
905
906         /**
907          * Getter for raw template data
908          *
909          * @return      $rawTemplateData        The raw data from the template
910          */
911         public final function getRawTemplateData () {
912                 return $this->rawTemplateData;
913         }
914
915         /**
916          * Getter for compiled templates
917          */
918         public final function getCompiledData () {
919                 return $this->compiledData;
920         }
921
922         /**
923          * Load a specified web template into the engine
924          *
925          * @param               $template               The web template we shall load which is
926          *                                              located in "html" by default
927          * @return      void
928          */
929         public final function loadWebTemplate ($template) {
930                 // Set template type
931                 $this->setTemplateType($this->getConfigInstance()->readConfig("web_template_type"));
932
933                 // Load the special template
934                 $this->loadTemplate($template);
935         }
936
937         /**
938          * Load a specified email template into the engine
939          *
940          * @param               $template               The email template we shall load which is
941          *                                              located in "emails" by default
942          * @return      void
943          */
944         public final function loadEmailTemplate ($template) {
945                 // Set template type
946                 $this->setTemplateType($this->getConfigInstance()->readConfig("email_template_type"));
947
948                 // Load the special template
949                 $this->loadTemplate($template);
950         }
951
952         /**
953          * Load a specified code template into the engine
954          *
955          * @param               $template               The code template we shall load which is
956          *                                              located in "code" by default
957          * @return      void
958          */
959         public final function loadCodeTemplate ($template) {
960                 // Set template type
961                 $this->setTemplateType($this->getConfigInstance()->readConfig("code_template_type"));
962
963                 // Load the special template
964                 $this->loadTemplate($template);
965         }
966
967         /**
968          * Compile all variables by inserting their respective values
969          *
970          * @return      void
971          */
972         public final function compileVariables () {
973                 // Initialize the $content array
974                 $validVar = $this->getConfigInstance()->readConfig("tpl_valid_var");
975                 $dummy = array();
976
977                 // Iterate through all variables
978                 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
979
980                         // Get current variable from the stack
981                         $currVariable = $idx->current();
982
983                         // Transfer it's name/value combination to the $content array
984                         $dummy[$currVariable['name']] = $currVariable['value'];
985
986                 }// END - if
987
988                 // Set the new variable (don't remove the second dollar !)
989                 $$validVar = $dummy;
990
991                 // Prepare all configuration variables
992                 $config = $this->configVariables;
993
994                 // Remove some variables
995                 unset($idx);
996                 unset($currVariable);
997
998                 // Finalize the compilation of template variables
999                 $this->finalizeVariableCompilation();
1000
1001                 // Prepare the eval() command for comiling the template
1002                 $eval = sprintf("\$this->setCompiledData(\"%s\");",
1003                         addslashes($this->getRawTemplateData())
1004                 );
1005
1006                 // Debug message
1007                 if (((defined('DEBUG_EVAL')) || (defined('DEBUG_ALL'))) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konstruierte PHP-Anweisung: <pre><em>%s</em></pre><br />\n",
1008                         $this->__toString(),
1009                         htmlentities($eval)
1010                 ));
1011
1012                 // Run the constructed command. This will "compile" all variables in
1013                 eval($eval);
1014         }
1015
1016         /**
1017          * Compile all required templates into the current loaded one
1018          *
1019          * @return      void
1020          * @throws      UnexpectedTemplateTypeException If the template type is
1021          *                                                                              not "code"
1022          * @throws      InvalidArrayCountException              If an unexpected array
1023          *                                                                              count has been found
1024          */
1025         public final function compileTemplate () {
1026                 // We will only work with template type "code" from configuration
1027                 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig("code_template_type")) {
1028                         // Abort here
1029                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig("code_template_type")), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1030                 } // END - if
1031
1032                 // Get the raw data.
1033                 $rawData = $this->getRawTemplateData();
1034
1035                 // Remove double spaces and trim leading/trailing spaces
1036                 $rawData = trim(str_replace("  ", " ", $rawData));
1037
1038                 // Search for raw variables
1039                 $this->extractVariablesFromRawData($rawData);
1040
1041                 // Search for code-tags which are {? ?}
1042                 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1043
1044                 // Analyze the matches array
1045                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1046                         // Entries are found:
1047                         //
1048                         // The main analysis
1049                         $this->analyzeTemplate($templateMatches);
1050
1051                         // Compile raw template data
1052                         $this->compileRawTemplateData($templateMatches);
1053
1054                         // Are there some raw templates left for loading?
1055                         $this->loadExtraRawTemplates();
1056
1057                         // Are some raw templates found and loaded?
1058                         if (count($this->rawTemplates) > 0) {
1059
1060                                 // Insert all raw templates
1061                                 $this->insertRawTemplates();
1062
1063                                 // Remove the raw template content as well
1064                                 $this->setRawTemplateData("");
1065
1066                         } // END - if
1067
1068                 } // END - if($templateMatches ...
1069         }
1070
1071         /**
1072          * Output the compiled page to the outside world. In case of web templates
1073          * this would be vaild (X)HTML code. And in case of email templates this
1074          * would store a prepared email body inside the template engine.
1075          *
1076          * @return      void
1077          */
1078         public final function output () {
1079                 // Check which type of template we have
1080                 switch ($this->getTemplateType()) {
1081                 case "html": // Raw HTML templates can be send to the output buffer
1082                         // Quick-N-Dirty:
1083                         $this->getWebOutputInstance()->output($this->getCompiledData());
1084                         break;
1085
1086                 default: // Unknown type found
1087                         // Construct message
1088                         $msg = sprintf("[%s:] Unknown/unsupported template type <strong>%s</strong> detected.",
1089                                 $this->__toString(),
1090                                 $this->getTemplateType()
1091                         );
1092
1093                         if ((is_object($this->getDebugInstance())) && (method_exists($this->getDebugInstance(), 'output'))) {
1094                                 // Use debug output handler
1095                                 $this->getDebugInstance()->output($msg);
1096                                 die();
1097                         } else {
1098                                 // Put directly out
1099                                 // DO NOT REWRITE THIS TO app_die() !!!
1100                                 die($msg);
1101                         }
1102                         break;
1103                 }
1104         }
1105
1106         /**
1107          * Loads a given view helper (by name)
1108          *
1109          * @param       $helperName     The helper's name
1110          * @return      void
1111          * @throws      ViewHelperNotFoundException     If the given view helper was not found
1112          */
1113         protected function loadViewHelper ($helperName) {
1114                 // Make first character upper case, rest low
1115                 $helperName = ucfirst($helperName);
1116
1117                 // Is this view helper loaded?
1118                 if (!isset($this->helpers[$helperName])) {
1119                         // Create a class name
1120                         $className = "{$helperName}ViewHelper";
1121
1122                         // Does this class exists?
1123                         if (!class_exists($className)) {
1124                                 // Abort here!
1125                                 throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
1126                         }
1127
1128                         // Generate new instance
1129                         $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
1130                                 $helperName,
1131                                 $className,
1132                                 $className
1133                         );
1134
1135                         // Run the code
1136                         eval($eval);
1137                 }
1138
1139                 // Return the requested instance
1140                 return $this->helpers[$helperName];
1141         }
1142
1143         /**
1144          * Assigns the last loaded raw template content with a given variable
1145          *
1146          * @param       $templateName   Name of the template we want to assign
1147          * @param       $variableName   Name of the variable we want to assign
1148          * @return      void
1149          */
1150         public function assignTemplateWithVariable ($templateName, $variableName) {
1151                 // Get the content from last loaded raw template
1152                 $content = $this->getRawTemplateData();
1153
1154                 // Assign the variable
1155                 $this->assignVariable($variableName, $content);
1156
1157                 // Purge raw content
1158                 $this->setRawTemplateData("");
1159         }
1160
1161         /**
1162          * Transfers the content of this template engine to a given response instance
1163          *
1164          * @param       $responseInstance       An instance of a response class
1165          * @return      void
1166          */
1167         public function transferToResponse (Responseable $responseInstance) {
1168                 // Get the content and set it in the response class
1169                 $responseInstance->writeToBody($this->getCompiledData());
1170         }
1171 }
1172
1173 // [EOF]
1174 ?>