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