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