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