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