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