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