Fake template engine added, variables can now be compiled for config entries:
[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                         $content = $this->varStack[$this->currGroup][$found]['value'];
201                 } // END - if
202
203                 // Return the current position
204                 //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", content[".gettype($content)."]=".$content."<br />\n";
205                 return $content;
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                 } // END - if
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      FileIoException 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                 // Is language support enabled?
543                 if ($this->isLanguageSupportEnabled()) {
544                         // Construct the FQFN for the template by honoring the current language
545                         $fqfn = sprintf("%s%s%s%s/%s/%s%s",
546                                 $this->getConfigInstance()->getConfigEntry('base_path'),
547                                 $this->getTemplateBasePath(),
548                                 $this->getGenericBasePath(),
549                                 $this->getLanguageInstance()->getLanguageCode(),
550                                 $this->getTemplateType(),
551                                 (string) $template,
552                                 $ext
553                         );
554                 } else {
555                         // Construct the FQFN for the template without language
556                         $fqfn = sprintf("%s%s%s%s/%s%s",
557                                 $this->getConfigInstance()->getConfigEntry('base_path'),
558                                 $this->getTemplateBasePath(),
559                                 $this->getGenericBasePath(),
560                                 $this->getTemplateType(),
561                                 (string) $template,
562                                 $ext
563                         );
564                 }
565
566                 // First try this
567                 try {
568                         // Load the raw template data
569                         $this->loadRawTemplateData($fqfn);
570                 } catch (FileIoException $e) {
571                         // If we shall load a code-template we need to switch the file extension
572                         if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('web_template_type')) && (empty($extOther))) {
573                                 // Switch over to the code-template extension and try it again
574                                 $ext = $this->getCodeTemplateExtension();
575
576                                 // Try it again...
577                                 $this->loadTemplate($template, $ext);
578                         } else {
579                                 // Throw it again
580                                 throw new FileIoException($fqfn, FrameworkFileInputPointer::EXCEPTION_FILE_NOT_FOUND);
581                         }
582                 }
583
584         }
585
586         /**
587          * A private loader for raw template names
588          *
589          * @param       $fqfn   The full-qualified file name for a template
590          * @return      void
591          */
592         private function loadRawTemplateData ($fqfn) {
593                 // Get a input/output instance from the middleware
594                 $ioInstance = $this->getFileIoInstance();
595
596                 // Some debug code to look on the file which is being loaded
597                 //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
598
599                 // Load the raw template
600                 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
601
602                 // Store the template's contents into this class
603                 $this->setRawTemplateData($rawTemplateData);
604
605                 // Remember the template's FQFN
606                 $this->setLastTemplate($fqfn);
607         }
608
609         /**
610          * Try to assign an extracted template variable as a "content" or 'config'
611          * variable.
612          *
613          * @param       $varName        The variable's name (shall be content orconfig) by
614          *                                              default
615          * @param       $var            The variable we want to assign
616          */
617         private function assignTemplateVariable ($varName, $var) {
618                 // Is it not a config variable?
619                 if ($varName != 'config') {
620                         // Regular template variables
621                         $this->assignVariable($var, '');
622                 } else {
623                         // Configuration variables
624                         $this->assignConfigVariable($var);
625                 }
626         }
627
628         /**
629          * Extract variables from a given raw data stream
630          *
631          * @param       $rawData        The raw template data we shall analyze
632          * @return      void
633          */
634         private function extractVariablesFromRawData ($rawData) {
635                 // Cast to string
636                 $rawData = (string) $rawData;
637
638                 // Search for variables
639                 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
640
641                 // Did we find some variables?
642                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
643                         // Initialize all missing variables
644                         foreach ($variableMatches[3] as $key => $var) {
645                                 // Variable name
646                                 $varName = $variableMatches[1][$key];
647
648                                 // Workarround: Do not assign empty variables
649                                 if (!empty($var)) {
650                                         // Try to assign it, empty strings are being ignored
651                                         $this->assignTemplateVariable($varName, $var);
652                                 } // END - if
653                         } // END - foreach
654                 } // END - if
655         }
656
657         /**
658          * Main analysis of the loaded template
659          *
660          * @param       $templateMatches        Found template place-holders, see below
661          * @return      void
662          *
663          *---------------------------------
664          * Structure of $templateMatches:
665          *---------------------------------
666          * [0] => Array - An array with all full matches
667          * [1] => Array - An array with left part (before the ':') of a match
668          * [2] => Array - An array with right part of a match including ':'
669          * [3] => Array - An array with right part of a match excluding ':'
670          */
671         private function analyzeTemplate (array $templateMatches) {
672                 // Backup raw template data
673                 $backup = $this->getRawTemplateData();
674
675                 // Initialize some arrays
676                 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
677
678                 // Load all requested templates
679                 foreach ($templateMatches[1] as $template) {
680
681                         // Load and compile only templates which we have not yet loaded
682                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
683                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
684
685                                 // Template not found, but maybe variable assigned?
686                                 //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
687                                 if ($this->isVariableAlreadySet($template) !== false) {
688                                         // Use that content here
689                                         $this->loadedRawData[$template] = $this->readVariable($template);
690
691                                         // Recursive protection:
692                                         $this->loadedTemplates[] = $template;
693                                 } elseif (isset($this->varStack['config'][$template])) {
694                                         // Use that content here
695                                         $this->loadedRawData[$template] = $this->varStack['config'][$template];
696
697                                         // Recursive protection:
698                                         $this->loadedTemplates[] = $template;
699                                 } else {
700                                         // Then try to search for code-templates
701                                         try {
702                                                 // Load the code template and remember it's contents
703                                                 $this->loadCodeTemplate($template);
704                                                 $this->loadedRawData[$template] = $this->getRawTemplateData();
705
706                                                 // Remember this template for recursion detection
707                                                 // RECURSIVE PROTECTION!
708                                                 $this->loadedTemplates[] = $template;
709                                         } catch (FileIoException $e) {
710                                                 // Even this is not done... :/
711                                                 $this->rawTemplates[] = $template;
712                                         }
713                                 }
714                         } // END - if
715                 } // END - foreach
716
717                 // Restore the raw template data
718                 $this->setRawTemplateData($backup);
719         }
720
721         /**
722          * Compile a given raw template code and remember it for later usage
723          *
724          * @param       $code           The raw template code
725          * @param       $template       The template's name
726          * @return      void
727          */
728         private function compileCode ($code, $template) {
729                 // Is this template already compiled?
730                 if (in_array($template, $this->compiledTemplates)) {
731                         // Abort here...
732                         return;
733                 } // END - if
734
735                 // Remember this template being compiled
736                 $this->compiledTemplates[] = $template;
737
738                 // Compile the loaded code in five steps:
739                 //
740                 // 1. Backup current template data
741                 $backup = $this->getRawTemplateData();
742
743                 // 2. Set the current template's raw data as the new content
744                 $this->setRawTemplateData($code);
745
746                 // 3. Compile the template data
747                 $this->compileTemplate();
748
749                 // 4. Remember it's contents
750                 $this->loadedRawData[$template] = $this->getRawTemplateData();
751
752                 // 5. Restore the previous raw content from backup variable
753                 $this->setRawTemplateData($backup);
754         }
755
756         /**
757          * Insert all given and loaded templates by running through all loaded
758          * codes and searching for their place-holder in the main template
759          *
760          * @param       $templateMatches        See method analyzeTemplate()
761          * @return      void
762          */
763         private function insertAllTemplates (array $templateMatches) {
764                 // Run through all loaded codes
765                 foreach ($this->loadedRawData as $template => $code) {
766
767                         // Search for the template
768                         $foundIndex = array_search($template, $templateMatches[1]);
769
770                         // Lookup the matching template replacement
771                         if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
772
773                                 // Get the current raw template
774                                 $rawData = $this->getRawTemplateData();
775
776                                 // Replace the space holder with the template code
777                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
778
779                                 // Set the new raw data
780                                 $this->setRawTemplateData($rawData);
781                         } // END - if
782                 } // END - foreach
783         }
784
785         /**
786          * Load all extra raw templates
787          *
788          * @return      void
789          */
790         private function loadExtraRawTemplates () {
791                 // Are there some raw templates we need to load?
792                 if (count($this->rawTemplates) > 0) {
793                         // Try to load all raw templates
794                         foreach ($this->rawTemplates as $key => $template) {
795                                 try {
796                                         // Load the template
797                                         $this->loadWebTemplate($template);
798
799                                         // Remember it's contents
800                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
801
802                                         // Remove it from the loader list
803                                         unset($this->rawTemplates[$key]);
804
805                                         // Remember this template for recursion detection
806                                         // RECURSIVE PROTECTION!
807                                         $this->loadedTemplates[] = $template;
808                                 } catch (FileIoException $e) {
809                                         // This template was never found. We silently ignore it
810                                         unset($this->rawTemplates[$key]);
811                                 }
812                         } // END - foreach
813                 } // END - if
814         }
815
816         /**
817          * Assign all found template variables
818          *
819          * @param       $varMatches             An array full of variable/value pairs.
820          * @return      void
821          * @todo        Unfinished work or don't die here.
822          */
823         private function assignAllVariables (array $varMatches) {
824                 // Search for all variables
825                 foreach ($varMatches[1] as $key => $var) {
826
827                         // Detect leading equals
828                         if (substr($varMatches[2][$key], 0, 1) == '=') {
829                                 // Remove and cast it
830                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
831                         } // END - if
832
833                         // Do we have some quotes left and right side? Then it is free text
834                         if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
835                                 // Free string detected! Which we can assign directly
836                                 $this->assignVariable($var, $varMatches[3][$key]);
837                         } elseif (!empty($varMatches[2][$key])) {
838                                 // @TODO Non-string found so we need some deeper analysis...
839                                 ApplicationEntryPoint::app_die('Deeper analysis not yet implemented!');
840                         }
841
842                 } // for ($varMatches ...
843         }
844         /**
845          * Compiles all loaded raw templates
846          *
847          * @param       $templateMatches        See method analyzeTemplate() for details
848          * @return      void
849          */
850         private function compileRawTemplateData (array $templateMatches) {
851                 // Are some code-templates found which we need to compile?
852                 if (count($this->loadedRawData) > 0) {
853
854                         // Then compile all!
855                         foreach ($this->loadedRawData as $template => $code) {
856
857                                 // Is this template already compiled?
858                                 if (in_array($template, $this->compiledTemplates)) {
859                                         // Then skip it
860                                         continue;
861                                 }
862
863                                 // Search for the template
864                                 $foundIndex = array_search($template, $templateMatches[1]);
865
866                                 // Lookup the matching variable data
867                                 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
868
869                                         // Split it up with another reg. exp. into variable=value pairs
870                                         preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
871
872                                         // Assign all variables
873                                         $this->assignAllVariables($varMatches);
874
875                                 } // END - if (isset($templateMatches ...
876
877                                 // Compile the loaded template
878                                 $this->compileCode($code, $template);
879
880                         } // END - foreach ($this->loadedRawData ...
881
882                         // Insert all templates
883                         $this->insertAllTemplates($templateMatches);
884
885                 } // END - if (count($this->loadedRawData) ...
886         }
887
888         /**
889          * Inserts all raw templates into their respective variables
890          *
891          * @return      void
892          */
893         private function insertRawTemplates () {
894                 // Load all templates
895                 foreach ($this->rawTemplates as $template => $content) {
896                         // Set the template as a variable with the content
897                         $this->assignVariable($template, $content);
898                 }
899         }
900
901         /**
902          * Finalizes the compilation of all template variables
903          *
904          * @return      void
905          */
906         private function finalizeVariableCompilation () {
907                 // Get the content
908                 $content = $this->getRawTemplateData();
909                 //* DEBUG: */ echo __METHOD__.': content before='.strlen($content).' ('.md5($content).')<br />\n';
910
911                 // Walk through all variables
912                 foreach ($this->varStack['general'] as $currEntry) {
913                         //* DEBUG: */ echo __METHOD__.': name='.$currEntry['name'].', value=<pre>'.htmlentities($currEntry['value']).'</pre>\n';
914                         // Replace all [$var] or {?$var?} with the content
915                         // @TODO Old behaviour, will become obsolete!
916                         $content = str_replace("\$content[".$currEntry['name'].']', $currEntry['value'], $content);
917
918                         // @TODO Yet another old way
919                         $content = str_replace('['.$currEntry['name'].']', $currEntry['value'], $content);
920
921                         // The new behaviour
922                         $content = str_replace('{?'.$currEntry['name'].'?}', $currEntry['value'], $content);
923                 } // END - for
924
925                 //* DEBUG: */ echo __METHOD__.': content after='.strlen($content).' ('.md5($content).')<br />\n';
926
927                 // Set the content back
928                 $this->setRawTemplateData($content);
929         }
930
931         /**
932          * Load a specified web template into the engine
933          *
934          * @param       $template       The web template we shall load which is located in
935          *                                              'html' by default
936          * @return      void
937          */
938         public function loadWebTemplate ($template) {
939                 // Set template type
940                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('web_template_type'));
941
942                 // Load the special template
943                 $this->loadTemplate($template);
944         }
945
946         /**
947          * Assign a given congfiguration variable with a value
948          *
949          * @param       $var    The configuration variable we want to assign
950          * @return      void
951          */
952         public function assignConfigVariable ($var) {
953                 // Sweet and simple...
954                 //* DEBUG: */ echo __METHOD__.':var={$var}<br />\n';
955                 $this->varStack['config'][$var] = $this->getConfigInstance()->getConfigEntry($var);
956         }
957
958         /**
959          * Load a specified email template into the engine
960          *
961          * @param       $template       The email template we shall load which is located in
962          *                                              'emails' by default
963          * @return      void
964          * @deprecated
965          * @see         See loadCodeTemplate()
966          */
967         public function loadEmailTemplate ($template) {
968                 // Set template type
969                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
970
971                 // Load the special template
972                 $this->loadTemplate($template);
973         }
974
975         /**
976          * Load a specified code template into the engine
977          *
978          * @param       $template       The code template we shall load which is
979          *                                              located in 'code' by default
980          * @return      void
981          */
982         public function loadCodeTemplate ($template) {
983                 // Set template type
984                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_template_type'));
985
986                 // Load the special template
987                 $this->loadTemplate($template);
988         }
989
990         /**
991          * Compiles configuration place-holders in all variables. This 'walks'
992          * through the variable stack 'general'. It interprets all values from that
993          * variables as configuration entries after compiling them.
994          *
995          * @return      void
996          */
997         public final function compileConfigInVariables () {
998                 // Iterate through all general variables
999                 foreach ($this->varStack['general'] as $idx=>$currVariable) {
1000                         // Compile the value
1001                         $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1002
1003                         // Remove it from stack
1004                         unset($this->varStack['general'][$idx]);
1005
1006                         // Re-assign the variable
1007                         $this->assignConfigVariable($value);
1008                 } // END - foreach
1009         }
1010
1011         /**
1012          * Compile all variables by inserting their respective values
1013          *
1014          * @return      void
1015          * @todo        Make this code some nicer...
1016          */
1017         public final function compileVariables () {
1018                 // Initialize the $content array
1019                 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1020                 $dummy = array();
1021
1022                 // Iterate through all general variables
1023                 foreach ($this->varStack['general'] as $currVariable) {
1024                         // Transfer it's name/value combination to the $content array
1025                         //* DEBUG: */ echo $currVariable['name'].'=<pre>'.htmlentities($currVariable['value']).'</pre>\n';
1026                         $dummy[$currVariable['name']] = $currVariable['value'];
1027                 }// END - if
1028
1029                 // Set the new variable (don't remove the second dollar!)
1030                 $$validVar = $dummy;
1031
1032                 // Prepare all configuration variables
1033                 $config = null;
1034                 if (isset($this->varStack['config'])) {
1035                         $config = $this->varStack['config'];
1036                 } // END - if
1037
1038                 // Remove some variables
1039                 unset($idx);
1040                 unset($currVariable);
1041
1042                 // Run the compilation three times to get content from helper classes in
1043                 $cnt = 0;
1044                 while ($cnt < 3) {
1045                         // Finalize the compilation of template variables
1046                         $this->finalizeVariableCompilation();
1047
1048                         // Prepare the eval() command for comiling the template
1049                         $eval = sprintf("\$result = \"%s\";",
1050                                 addslashes($this->getRawTemplateData())
1051                         );
1052
1053                         // This loop does remove the backslashes (\) in PHP parameters
1054                         while (strpos($eval, $this->codeBegin) !== false) {
1055                                 // Get left part before "<?"
1056                                 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1057
1058                                 // Get all from right of "<?"
1059                                 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1060
1061                                 // Cut middle part out and remove escapes
1062                                 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1063                                 $evalMiddle = stripslashes($evalMiddle);
1064
1065                                 // Remove the middle part from right one
1066                                 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1067
1068                                 // And put all together
1069                                 $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
1070                         } // END - while
1071
1072                         // Prepare PHP code for eval() command
1073                         $eval = str_replace(
1074                                 "<%php", "\";",
1075                                 str_replace(
1076                                         "%>",
1077                                         "\n\$result .= \"",
1078                                         $eval
1079                                 )
1080                         );
1081
1082                         // Run the constructed command. This will "compile" all variables in
1083                         eval($eval);
1084
1085                         // Goes something wrong?
1086                         if ((!isset($result)) || (empty($result))) {
1087                                 // Output eval command
1088                                 $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
1089
1090                                 // Output backtrace here
1091                                 $this->debugBackTrace();
1092                         } // END - if
1093
1094                         // Set raw template data
1095                         $this->setRawTemplateData($result);
1096                         $cnt++;
1097                 } // END - while
1098
1099                 // Final variable assignment
1100                 $this->finalizeVariableCompilation();
1101
1102                 // Set the new content
1103                 $this->setCompiledData($this->getRawTemplateData());
1104         }
1105
1106         /**
1107          * Compile all required templates into the current loaded one
1108          *
1109          * @return      void
1110          * @throws      UnexpectedTemplateTypeException If the template type is
1111          *                                                                                      not "code"
1112          * @throws      InvalidArrayCountException              If an unexpected array
1113          *                                                                                      count has been found
1114          */
1115         public function compileTemplate () {
1116                 // We will only work with template type "code" from configuration
1117                 if ($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('code_template_type')) {
1118                         // Abort here
1119                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1120                 } // END - if
1121
1122                 // Get the raw data.
1123                 $rawData = $this->getRawTemplateData();
1124
1125                 // Remove double spaces and trim leading/trailing spaces
1126                 $rawData = trim(str_replace('  ', ' ', $rawData));
1127
1128                 // Search for raw variables
1129                 $this->extractVariablesFromRawData($rawData);
1130
1131                 // Search for code-tags which are {? ?}
1132                 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1133
1134                 // Analyze the matches array
1135                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1136                         // Entries are found:
1137                         //
1138                         // The main analysis
1139                         $this->analyzeTemplate($templateMatches);
1140
1141                         // Compile raw template data
1142                         $this->compileRawTemplateData($templateMatches);
1143
1144                         // Are there some raw templates left for loading?
1145                         $this->loadExtraRawTemplates();
1146
1147                         // Are some raw templates found and loaded?
1148                         if (count($this->rawTemplates) > 0) {
1149
1150                                 // Insert all raw templates
1151                                 $this->insertRawTemplates();
1152
1153                                 // Remove the raw template content as well
1154                                 $this->setRawTemplateData('');
1155
1156                         } // END - if
1157
1158                 } // END - if($templateMatches ...
1159         }
1160
1161         /**
1162          * A old deprecated method
1163          *
1164          * @return      void
1165          * @deprecated
1166          * @see         BaseTemplateEngine::transferToResponse
1167          */
1168         public function output () {
1169                 // Check which type of template we have
1170                 switch ($this->getTemplateType()) {
1171                         case 'html': // Raw HTML templates can be send to the output buffer
1172                                 // Quick-N-Dirty:
1173                                 $this->getWebOutputInstance()->output($this->getCompiledData());
1174                                 break;
1175
1176                         default: // Unknown type found
1177                                 // Construct message
1178                                 $msg = sprintf("[%s-&gt;%s] Unknown/unsupported template type <span class=\"data\">%s</span> detected.",
1179                                         $this->__toString(),
1180                                         __FUNCTION__,
1181                                         $this->getTemplateType()
1182                                 );
1183
1184                                 // Write the problem to the world...
1185                                 $this->debugOutput($msg);
1186                                 break;
1187                 } // END - switch
1188         }
1189
1190         /**
1191          * Loads a given view helper (by name)
1192          *
1193          * @param       $helperName             The helper's name
1194          * @return      void
1195          */
1196         protected function loadViewHelper ($helperName) {
1197                 // Make first character upper case, rest low
1198                 $helperName = $this->convertToClassName($helperName);
1199
1200                 // Is this view helper loaded?
1201                 if (!isset($this->helpers[$helperName])) {
1202                         // Create a class name
1203                         $className = "{$helperName}ViewHelper";
1204
1205                         // Generate new instance
1206                         $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1207                 } // END - if
1208
1209                 // Return the requested instance
1210                 return $this->helpers[$helperName];
1211         }
1212
1213         /**
1214          * Assigns the last loaded raw template content with a given variable
1215          *
1216          * @param       $templateName   Name of the template we want to assign
1217          * @param       $variableName   Name of the variable we want to assign
1218          * @return      void
1219          */
1220         public function assignTemplateWithVariable ($templateName, $variableName) {
1221                 // Get the content from last loaded raw template
1222                 $content = $this->getRawTemplateData();
1223
1224                 // Assign the variable
1225                 $this->assignVariable($variableName, $content);
1226
1227                 // Purge raw content
1228                 $this->setRawTemplateData('');
1229         }
1230
1231         /**
1232          * Transfers the content of this template engine to a given response instance
1233          *
1234          * @param       $responseInstance       An instance of a response class
1235          * @return      void
1236          */
1237         public function transferToResponse (Responseable $responseInstance) {
1238                 // Get the content and set it in response class
1239                 $responseInstance->writeToBody($this->getCompiledData());
1240         }
1241
1242         /**
1243          * Assigns all the application data with template variables
1244          *
1245          * @param       $appInstance    A manageable application instance
1246          * @return      void
1247          */
1248         public function assignApplicationData (ManageableApplication $appInstance) {
1249                 // Get long name and assign it
1250                 $this->assignVariable('app_full_name' , $appInstance->getAppName());
1251
1252                 // Get short name and assign it
1253                 $this->assignVariable('app_short_name', $appInstance->getAppShortName());
1254
1255                 // Get version number and assign it
1256                 $this->assignVariable('app_version'   , $appInstance->getAppVersion());
1257
1258                 // Assign extra application-depending data
1259                 $appInstance->assignExtraTemplateData($this);
1260         }
1261
1262         /**
1263          * "Compiles" a variable by replacing {?var?} with it's content
1264          *
1265          * @param       $rawCode                        Raw code to compile
1266          * @param       $setMatchAsCode         Sets $match if readVariable() returns empty result
1267          * @return      $rawCode        Compile code with inserted variable value
1268          */
1269         public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1270                 // Find the variables
1271                 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1272                 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1273
1274                 // Compile all variables
1275                 //* DEBUG: */ echo __METHOD__.":<pre>".print_r($varMatches, true)."</pre>\n";
1276                 foreach ($varMatches[0] as $match) {
1277                         // Add variable tags around it
1278                         $varCode = '{?' . $match . '?}';
1279
1280                         // Is the variable found in code? (safes some calls)
1281                         if (strpos($rawCode, $varCode) !== false) {
1282                                 // Replace the variable with it's value, if found
1283                                 $value = $this->readVariable($match);
1284                                 //* DEBUG: */ echo __METHOD__.": match=".$match.",value[".gettype($value)."]=".$value."<br />\n";
1285                                 if (($setMatchAsCode === true) && (is_null($value))) {
1286                                         // Insert match
1287                                         $rawCode = str_replace($varCode, $match, $rawCode);
1288                                 } else {
1289                                         // Insert value
1290                                         $rawCode = str_replace($varCode, $value, $rawCode);
1291                                 }
1292                         } // END - if
1293                 } // END - foreach
1294
1295                 // Return the compiled data
1296                 //* DEBUG: */ echo __METHOD__.":rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
1297                 return $rawCode;
1298         }
1299
1300         /**
1301          * Getter for variable group array
1302          *
1303          * @return      $vargroups      All variable groups
1304          */
1305         public final function getVariableGroups () {
1306                 return $this->varGroups;
1307         }
1308
1309         /**
1310          * Renames a variable in code and in stack
1311          *
1312          * @param       $oldName        Old name of variable
1313          * @param       $newName        New name of variable
1314          * @return      void
1315          */
1316         public function renameVariable ($oldName, $newName) {
1317                 //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
1318                 // Get raw template code
1319                 $rawData = $this->getRawTemplateData();
1320
1321                 // Replace it
1322                 $rawData = str_replace($oldName, $newName, $rawData);
1323
1324                 // Set the code back
1325                 $this->setRawTemplateData($rawData);
1326         }
1327
1328         /**
1329          * Renders the given XML content
1330          *
1331          * @param       $content        Valid XML content or if not set the current loaded raw content
1332          * @return      void
1333          * @throws      XmlParserException      If an XML error was found
1334          */
1335         public function renderXmlContent ($content = null) {
1336                 // Is the content set?
1337                 if (is_null($content)) {
1338                         // Get current content
1339                         $content = $this->getRawTemplateData();
1340                 } // END - if
1341
1342                 // Get a XmlParser instance
1343                 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1344
1345                 // Parse the XML document
1346                 $parserInstance->parseXmlContent($content);
1347         }
1348
1349         /**
1350          * Enables or disables language support
1351          *
1352          * @param       $languageSupport        New language support setting
1353          * @return      void
1354          */
1355         public final function enableLanguageSupport ($languageSupport = true) {
1356                 $this->languageSupport = (bool) $languageSupport;
1357         }
1358
1359         /**
1360          * Checks wether language support is enabled
1361          *
1362          * @return      $languageSupport        Wether language support is enabled or disabled
1363          */
1364         public final function isLanguageSupportEnabled () {
1365                 return $this->languageSupport;
1366         }
1367 }
1368
1369 // [EOF]
1370 ?>