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