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