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