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