]> git.mxchange.org Git - core.git/blob - framework/main/classes/template/class_BaseTemplateEngine.php
imported ApplicationEntryPoint
[core.git] / framework / main / classes / template / class_BaseTemplateEngine.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Template\Engine;
4
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\EntryPoint\ApplicationEntryPoint;
8 use CoreFramework\Factory\ObjectFactory;
9 use CoreFramework\Filesystem\FileNotFoundException;
10 use CoreFramework\Generic\EmptyVariableException;
11 use CoreFramework\Manager\ManageableApplication;
12 use CoreFramework\Object\BaseFrameworkSystem;
13 use CoreFramework\Response\Responseable;
14
15 /**
16  * A generic template engine
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.shipsimu.org
23  *
24  * This program is free software: you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation, either version 3 of the License, or
27  * (at your option) any later version.
28  *
29  * This program is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  * GNU General Public License for more details.
33  *
34  * You should have received a copy of the GNU General Public License
35  * along with this program. If not, see <http://www.gnu.org/licenses/>.
36  */
37 class BaseTemplateEngine extends BaseFrameworkSystem {
38         /**
39          * The local path name where all templates and sub folders for special
40          * templates are stored. We will internally determine the language plus
41          * "html" for web templates or "emails" for email templates
42          */
43         private $templateBasePath = '';
44
45         /**
46          * Template type
47          */
48         private $templateType = 'html';
49
50         /**
51          * The extension for web and email templates (not compiled templates)
52          */
53         private $templateExtension = '.tpl';
54
55         /**
56          * The extension for code templates (not compiled templates)
57          */
58         private $codeExtension = '.ctp';
59
60         /**
61          * Path relative to $templateBasePath and language code for compiled code-templates
62          */
63         private $compileOutputPath = 'templates/_compiled/';
64
65         /**
66          * The path name for all templates
67          */
68         private $genericBasePath = 'templates/';
69
70         /**
71          * The raw (maybe uncompiled) template
72          */
73         private $rawTemplateData = '';
74
75         /**
76          * Template data with compiled-in variables
77          */
78         private $compiledData = '';
79
80         /**
81          * The last loaded template's FQFN for debugging the engine
82          */
83         private $lastTemplate = '';
84
85         /**
86          * The variable stack for the templates
87          */
88         private $varStack = array();
89
90         /**
91          * Loaded templates for recursive protection and detection
92          */
93         private $loadedTemplates = array();
94
95         /**
96          * Compiled templates for recursive protection and detection
97          */
98         private $compiledTemplates = array();
99
100         /**
101          * Loaded raw template data
102          */
103         private $loadedRawData = NULL;
104
105         /**
106          * Raw templates which are linked in code templates
107          */
108         private $rawTemplates = NULL;
109
110         /**
111          * A regular expression for variable=value pairs
112          */
113         private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
114
115         /**
116          * A regular expression for filtering out code tags
117          *
118          * E.g.: {?template:variable=value;var2=value2;[...]?}
119          */
120         private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
121
122         /**
123          * A regular expression to find template comments like <!-- Comment here //-->
124          */
125         private $regExpComments = '/<!--[\w\W]*?(\/\/){0,1}-->/';
126
127         /**
128          * Loaded helpers
129          */
130         private $helpers = array();
131
132         /**
133          * Current variable group
134          */
135         private $currGroup = 'general';
136
137         /**
138          * All template groups except "general"
139          */
140         private $variableGroups = array();
141
142         /**
143          * Code begin
144          */
145         private $codeBegin = '<?php';
146
147         /**
148          * Code end
149          */
150         private $codeEnd = '?>';
151
152         /**
153          * Language support is enabled by default
154          */
155         private $languageSupport = true;
156
157         /**
158          * XML compacting is disabled by default
159          */
160         private $xmlCompacting = false;
161
162         // Exception codes for the template engine
163         const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0x110;
164         const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
165         const EXCEPTION_INVALID_VIEW_HELPER           = 0x112;
166         const EXCEPTION_VARIABLE_IS_MISSING           = 0x113;
167
168         /**
169          * Protected constructor
170          *
171          * @param       $className      Name of the class
172          * @return      void
173          */
174         protected function __construct ($className) {
175                 // Call parent constructor
176                 parent::__construct($className);
177
178                 // Init file I/O instance
179                 $ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
180
181                 // Set it
182                 $this->setFileIoInstance($ioInstance);
183         }
184
185         /**
186          * Search for a variable in the stack
187          *
188          * @param       $variableName   The variable we are looking for
189          * @param       $variableGroup  Optional variable group to look in
190          * @return      $index                  false means not found, >=0 means found on a specific index
191          */
192         private function getVariableIndex ($variableName, $variableGroup = NULL) {
193                 // Replace all dashes to underscores to match variables with configuration entries
194                 $variableName = trim(self::convertDashesToUnderscores($variableName));
195
196                 // First everything is not found
197                 $found = false;
198
199                 // If the stack is NULL, use the current group
200                 if (is_null($variableGroup)) {
201                         // Use current group
202                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
203                         $variableGroup = $this->currGroup;
204                 } // END - if
205
206                 // Is the group there?
207                 if ($this->isVarStackSet($variableGroup)) {
208                         // Now search for it
209                         foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
210                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
211                                 // Is the entry found?
212                                 if ($currEntry['name'] == $variableName) {
213                                         // Found!
214                                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
215                                         $found = $index;
216                                         break;
217                                 } // END - if
218                         } // END - foreach
219                 } // END - if
220
221                 // Return the current position
222                 return $found;
223         }
224
225         /**
226          * Checks whether the given variable group is set
227          *
228          * @param       $variableGroup  Variable group to check
229          * @return      $isSet                  Whether the given variable group is set
230          */
231         protected final function isVarStackSet ($variableGroup) {
232                 // Check it
233                 $isSet = isset($this->varStack[$variableGroup]);
234
235                 // Return result
236                 return $isSet;
237         }
238
239         /**
240          * Getter for given variable group
241          *
242          * @param       $variableGroup  Variable group to check
243          * @return      $varStack               Found variable group
244          */
245         public final function getVarStack ($variableGroup) {
246                 return $this->varStack[$variableGroup];
247         }
248
249         /**
250          * Setter for given variable group
251          *
252          * @param       $variableGroup  Variable group to check
253          * @param       $varStack               Variable stack to check
254          * @return      void
255          */
256         protected final function setVarStack ($variableGroup, array $varStack) {
257                 $this->varStack[$variableGroup]  = $varStack;
258         }
259
260         /**
261          * Return a content of a variable or null if not found
262          *
263          * @param       $variableName   The variable we are looking for
264          * @param       $variableGroup  Optional variable group to look in
265          * @return      $content                Content of the variable or null if not found
266          */
267         protected function readVariable ($variableName, $variableGroup = NULL) {
268                 // Replace all dashes to underscores to match variables with configuration entries
269                 $variableName = trim(self::convertDashesToUnderscores($variableName));
270
271                 // First everything is not found
272                 $content = NULL;
273
274                 // If the stack is NULL, use the current group
275                 if (is_null($variableGroup)) {
276                         // Use current group
277                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
278                         $variableGroup = $this->currGroup;
279                 } // END - if
280
281                 // Get variable index
282                 $found = $this->getVariableIndex($variableName, $variableGroup);
283
284                 // Is the variable found?
285                 if ($found !== false) {
286                         // Read it
287                         $content = $this->getVariableValue($variableGroup, $found);
288                 } // END - if
289
290                 // Return the current position
291                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
292                 return $content;
293         }
294
295         /**
296          * Add a variable to the stack
297          *
298          * @param       $variableName   Name of variable to add
299          * @param       $value                  Value we want to store in the variable
300          * @return      void
301          */
302         private function addVariable ($variableName, $value) {
303                 // Set general variable group
304                 $this->setVariableGroup('general');
305
306                 // Add it to the stack
307                 $this->addGroupVariable($variableName, $value);
308         }
309
310         /**
311          * Returns all variables of current group or empty array
312          *
313          * @return      $result         Whether array of found variables or empty array
314          */
315         private function readCurrentGroup () {
316                 // Default is not found
317                 $result = array();
318
319                 // Is the group there?
320                 if ($this->isVarStackSet($this->currGroup)) {
321                         // Then use it
322                         $result = $this->getVarStack($this->currGroup);
323                 } // END - if
324
325                 // Return result
326                 return $result;
327         }
328
329         /**
330          * Settter for variable group
331          *
332          * @param       $groupName      Name of variable group
333          * @param       $add            Whether add this group
334          * @return      void
335          */
336         public function setVariableGroup ($groupName, $add = true) {
337                 // Set group name
338                 //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
339                 $this->currGroup = $groupName;
340
341                 // Skip group 'general'
342                 if (($groupName != 'general') && ($add === true)) {
343                         $this->variableGroups[$groupName] = 'OK';
344                 } // END - if
345         }
346
347
348         /**
349          * Adds a variable to current group
350          *
351          * @param       $variableName   Variable to set
352          * @param       $value                  Value to store in variable
353          * @return      void
354          */
355         public function addGroupVariable ($variableName, $value) {
356                 // Replace all dashes to underscores to match variables with configuration entries
357                 $variableName = trim(self::convertDashesToUnderscores($variableName));
358
359                 // Debug message
360                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
361
362                 // Get current variables in group
363                 $currVars = $this->readCurrentGroup();
364
365                 // Append our variable
366                 array_push($currVars, $this->generateVariableArray($variableName, $value));
367
368                 // Add it to the stack
369                 $this->setVarStack($this->currGroup, $currVars);
370         }
371
372         /**
373          * Getter for variable value, throws a NoVariableException if the variable is not found
374          *
375          * @param       $variableGroup  Variable group to use
376          * @param       $index          Index in variable array
377          * @return      $value          Value to set
378          */
379         private function getVariableValue ($variableGroup, $index) {
380                 // Return it
381                 return $this->varStack[$variableGroup][$index]['value'];
382         }
383
384         /**
385          * Modify an entry on the stack
386          *
387          * @param       $variableName   The variable we are looking for
388          * @param       $value                  The value we want to store in the variable
389          * @return      void
390          * @throws      NoVariableException     If the given variable is not found
391          */
392         private function modifyVariable ($variableName, $value) {
393                 // Replace all dashes to underscores to match variables with configuration entries
394                 $variableName = trim(self::convertDashesToUnderscores($variableName));
395
396                 // Get index for variable
397                 $index = $this->getVariableIndex($variableName);
398
399                 // Is the variable set?
400                 if ($index === false) {
401                         // Unset variables cannot be modified
402                         throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
403                 } // END - if
404
405                 // Then modify it
406                 $this->setVariableValue($this->currGroup, $index, $value);
407         }
408
409         /**
410          * Sets a variable value for given variable group and index
411          *
412          * @param       $variableGroup  Variable group to use
413          * @param       $index          Index in variable array
414          * @param       $value          Value to set
415          * @return      void
416          */
417         private function setVariableValue ($variableGroup, $index, $value) {
418                 $this->varStack[$variableGroup][$index]['value'] = $value;
419         }
420
421         /**
422          * Sets a variable within given group. This method does detect if the
423          * variable is already set. If so, the variable got modified, otherwise
424          * added.
425          *
426          * @param       $variableGroup          Variable group to use
427          * @param       $variableName   Variable to set
428          * @param       $value                  Value to set
429          * @return      void
430          */
431         protected function setVariable ($variableGroup, $variableName, $value) {
432                 // Replace all dashes to underscores to match variables with configuration entries
433                 $variableName = trim(self::convertDashesToUnderscores($variableName));
434
435                 // Get index for variable
436                 $index = $this->getVariableIndex($variableName);
437
438                 // Is the variable set?
439                 if ($index === false) {
440                         // Is the stack there?
441                         if (!isset($this->varStack[$variableGroup])) {
442                                 // Then initialize it here
443                                 $this->varStack[$variableGroup] = array();
444                         } // END - if
445
446                         // Not found, add it
447                         array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
448                 } else {
449                         // Then modify it
450                         $this->setVariableValue($this->currGroup, $index, $value);
451                 }
452         }
453
454         /**
455          * "Generates" (better returns) an array for all variables for given
456          * variable/value pay.
457          *
458          * @param       $variableName   Variable to set
459          * @param       $value                  Value to set
460          * @return      $varData                Variable data array
461          */
462         private function generateVariableArray ($variableName, $value) {
463                 // Replace all dashes to underscores to match variables with configuration entries
464                 $variableName = trim(self::convertDashesToUnderscores($variableName));
465
466                 // Generate the temporary array
467                 $varData = array(
468                         'name'  => $variableName,
469                         'value' => $value
470                 );
471
472                 // And return it
473                 return $varData;
474         }
475
476         /**
477          * Setter for template type. Only 'html', 'emails' and 'compiled' should
478          * be sent here
479          *
480          * @param       $templateType   The current template's type
481          * @return      void
482          */
483         protected final function setTemplateType ($templateType) {
484                 $this->templateType = (string) $templateType;
485         }
486
487         /**
488          * Getter for template type
489          *
490          * @return      $templateType   The current template's type
491          */
492         public final function getTemplateType () {
493                 return $this->templateType;
494         }
495
496         /**
497          * Setter for the last loaded template's FQFN
498          *
499          * @param       $template       The last loaded template
500          * @return      void
501          */
502         private final function setLastTemplate ($template) {
503                 $this->lastTemplate = (string) $template;
504         }
505
506         /**
507          * Getter for the last loaded template's FQFN
508          *
509          * @return      $template       The last loaded template
510          */
511         private final function getLastTemplate () {
512                 return $this->lastTemplate;
513         }
514
515         /**
516          * Setter for base path
517          *
518          * @param               $templateBasePath               The relative base path for all templates
519          * @return      void
520          */
521         protected final function setTemplateBasePath ($templateBasePath) {
522                 // And set it
523                 $this->templateBasePath = (string) $templateBasePath;
524         }
525
526         /**
527          * Getter for base path
528          *
529          * @return      $templateBasePath               The relative base path for all templates
530          */
531         public final function getTemplateBasePath () {
532                 // And set it
533                 return $this->templateBasePath;
534         }
535
536         /**
537          * Getter for generic base path
538          *
539          * @return      $templateBasePath               The relative base path for all templates
540          */
541         public final function getGenericBasePath () {
542                 // And set it
543                 return $this->genericBasePath;
544         }
545
546         /**
547          * Setter for template extension
548          *
549          * @param               $templateExtension      The file extension for all uncompiled
550          *                                                      templates
551          * @return      void
552          */
553         protected final function setRawTemplateExtension ($templateExtension) {
554                 // And set it
555                 $this->templateExtension = (string) $templateExtension;
556         }
557
558         /**
559          * Setter for code template extension
560          *
561          * @param               $codeExtension          The file extension for all uncompiled
562          *                                                      templates
563          * @return      void
564          */
565         protected final function setCodeTemplateExtension ($codeExtension) {
566                 // And set it
567                 $this->codeExtension = (string) $codeExtension;
568         }
569
570         /**
571          * Getter for template extension
572          *
573          * @return      $templateExtension      The file extension for all uncompiled
574          *                                                      templates
575          */
576         public final function getRawTemplateExtension () {
577                 // And set it
578                 return $this->templateExtension;
579         }
580
581         /**
582          * Getter for code-template extension
583          *
584          * @return      $codeExtension          The file extension for all code-
585          *                                                      templates
586          */
587         public final function getCodeTemplateExtension () {
588                 // And set it
589                 return $this->codeExtension;
590         }
591
592         /**
593          * Setter for path of compiled templates
594          *
595          * @param       $compileOutputPath      The local base path for all compiled
596          *                                                              templates
597          * @return      void
598          */
599         protected final function setCompileOutputPath ($compileOutputPath) {
600                 // And set it
601                 $this->compileOutputPath = (string) $compileOutputPath;
602         }
603
604         /**
605          * Unsets the given offset in the variable group
606          *
607          * @param       $index                  Index to unset
608          * @param       $variableGroup  Variable group (default: currGroup)
609          * @return      void
610          */
611         protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
612                 // Is the variable group not set?
613                 if (is_null($variableGroup)) {
614                         // Then set it to current
615                         $variableGroup = $this->currGroup;
616                 } // END - if
617
618                 // Is the entry there?
619                 if (!isset($this->varStack[$variableGroup][$index])) {
620                         // Abort here, we need fixing!
621                         $this->debugInstance();
622                 } // END - if
623
624                 // Remove it
625                 unset($this->varStack[$variableGroup][$index]);
626         }
627
628         /**
629          * Private setter for raw template data
630          *
631          * @param       $rawTemplateData        The raw data from the template
632          * @return      void
633          */
634         protected final function setRawTemplateData ($rawTemplateData) {
635                 // And store it in this class
636                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
637                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
638                 $this->rawTemplateData = (string) $rawTemplateData;
639         }
640
641         /**
642          * Getter for raw template data
643          *
644          * @return      $rawTemplateData        The raw data from the template
645          */
646         public final function getRawTemplateData () {
647                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
648                 return $this->rawTemplateData;
649         }
650
651         /**
652          * Private setter for compiled templates
653          *
654          * @return      void
655          */
656         private final function setCompiledData ($compiledData) {
657                 // And store it in this class
658                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
659                 $this->compiledData = (string) $compiledData;
660         }
661
662         /**
663          * Getter for compiled templates, must be public for e.g. Mailer classes.
664          *
665          * @return      $compiledData   Compiled template data
666          */
667         public final function getCompiledData () {
668                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
669                 return $this->compiledData;
670         }
671
672         /**
673          * Private loader for all template types
674          *
675          * @param       $templateName   The template we shall load
676          * @param       $extOther       An other extension to use
677          * @return      void
678          * @throws      FileNotFoundException   If the template was not found
679          */
680         protected function loadTemplate ($templateName, $extOther = '') {
681                 // Get extension for the template if empty
682                 if (empty($extOther)) {
683                         // None provided, so get the raw one
684                         $ext = $this->getRawTemplateExtension();
685                 } else {
686                         // Then use it!
687                         $ext = (string) $extOther;
688                 }
689
690                 /*
691                  * Construct the FQFN for the template without language as language is
692                  * now entirely done by php_intl. These old thing with language-based
693                  * template paths comes from an older time.
694                  */
695                 $fqfn = sprintf('%s%s%s%s%s%s',
696                         $this->getTemplateBasePath(),
697                         $this->getGenericBasePath(),
698                         $this->getTemplateType(),
699                         DIRECTORY_SEPARATOR,
700                         (string) $templateName,
701                         $ext
702                 );
703
704                 // First try this
705                 try {
706                         // Load the raw template data
707                         $this->loadRawTemplateData($fqfn);
708                 } catch (FileNotFoundException $e) {
709                         // If we shall load a code-template we need to switch the file extension
710                         if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
711                                 // Switch over to the code-template extension and try it again
712                                 $ext = $this->getCodeTemplateExtension();
713
714                                 // Try it again...
715                                 $this->loadTemplate($templateName, $ext);
716                         } else {
717                                 // Throw it again
718                                 throw new FileNotFoundException($fqfn, self::EXCEPTION_FILE_NOT_FOUND);
719                         }
720                 }
721
722         }
723
724         /**
725          * A private loader for raw template names
726          *
727          * @param       $fqfn   The full-qualified file name for a template
728          * @return      void
729          */
730         private function loadRawTemplateData ($fqfn) {
731                 // Some debug code to look on the file which is being loaded
732                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: FQFN=' . $fqfn);
733
734                 // Load the raw template
735                 $rawTemplateData = $this->getFileIoInstance()->loadFileContents($fqfn);
736
737                 // Store the template's contents into this class
738                 $this->setRawTemplateData($rawTemplateData);
739
740                 // Remember the template's FQFN
741                 $this->setLastTemplate($fqfn);
742         }
743
744         /**
745          * Try to assign an extracted template variable as a "content" or 'config'
746          * variable.
747          *
748          * @param       $variableName           The variable's name (shall be content or config)
749          *                                                      by default
750          * @param       $variableName   The variable we want to assign
751          * @return      void
752          */
753         private function assignTemplateVariable ($variableName, $var) {
754                 // Replace all dashes to underscores to match variables with configuration entries
755                 $variableName = trim(self::convertDashesToUnderscores($variableName));
756
757                 // Debug message
758                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
759
760                 // Is it not a config variable?
761                 if ($variableName != 'config') {
762                         // Regular template variables
763                         $this->assignVariable($variableName, '');
764                 } else {
765                         // Configuration variables
766                         $this->assignConfigVariable($var);
767                 }
768         }
769
770         /**
771          * Extract variables from a given raw data stream
772          *
773          * @param       $rawData        The raw template data we shall analyze
774          * @return      void
775          */
776         private function extractVariablesFromRawData ($rawData) {
777                 // Cast to string
778                 $rawData = (string) $rawData;
779
780                 // Search for variables
781                 preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
782
783                 // Debug message
784                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
785
786                 // Did we find some variables?
787                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
788                         // Initialize all missing variables
789                         foreach ($variableMatches[3] as $key => $var) {
790                                 // Variable name
791                                 $variableName = $variableMatches[1][$key];
792
793                                 // Workarround: Do not assign empty variables
794                                 if (!empty($var)) {
795                                         // Try to assign it, empty strings are being ignored
796                                         $this->assignTemplateVariable($variableName, $var);
797                                 } // END - if
798                         } // END - foreach
799                 } // END - if
800         }
801
802         /**
803          * Main analysis of the loaded template
804          *
805          * @param       $templateMatches        Found template place-holders, see below
806          * @return      void
807          *
808          *---------------------------------
809          * Structure of $templateMatches:
810          *---------------------------------
811          * [0] => Array - An array with all full matches
812          * [1] => Array - An array with left part (before the ':') of a match
813          * [2] => Array - An array with right part of a match including ':'
814          * [3] => Array - An array with right part of a match excluding ':'
815          */
816         private function analyzeTemplate (array $templateMatches) {
817                 // Backup raw template data
818                 $backup = $this->getRawTemplateData();
819
820                 // Initialize some arrays
821                 if (is_null($this->loadedRawData)) {
822                         // Initialize both
823                         $this->loadedRawData = array();
824                         $this->rawTemplates = array();
825                 } // END - if
826
827                 // Load all requested templates
828                 foreach ($templateMatches[1] as $template) {
829                         // Load and compile only templates which we have not yet loaded
830                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
831                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
832                                 // Debug message
833                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
834
835                                 // Template not found, but maybe variable assigned?
836                                 if ($this->getVariableIndex($template) !== false) {
837                                         // Use that content here
838                                         $this->loadedRawData[$template] = $this->readVariable($template);
839
840                                         // Recursive protection:
841                                         array_push($this->loadedTemplates, $template);
842                                 } else {
843                                         // Then try to search for code-templates
844                                         try {
845                                                 // Load the code template and remember it's contents
846                                                 $this->loadCodeTemplate($template);
847                                                 $this->loadedRawData[$template] = $this->getRawTemplateData();
848
849                                                 // Remember this template for recursion detection
850                                                 // RECURSIVE PROTECTION!
851                                                 array_push($this->loadedTemplates, $template);
852                                         } catch (FileNotFoundException $e) {
853                                                 // Even this is not done... :/
854                                                 array_push($this->rawTemplates, $template);
855                                         }
856                                 }
857                         } // END - if
858                 } // END - foreach
859
860                 // Restore the raw template data
861                 $this->setRawTemplateData($backup);
862         }
863
864         /**
865          * Compile a given raw template code and remember it for later usage
866          *
867          * @param       $code           The raw template code
868          * @param       $template       The template's name
869          * @return      void
870          */
871         private function compileCode ($code, $template) {
872                 // Is this template already compiled?
873                 if (in_array($template, $this->compiledTemplates)) {
874                         // Abort here...
875                         return;
876                 } // END - if
877
878                 // Remember this template being compiled
879                 array_push($this->compiledTemplates, $template);
880
881                 // Compile the loaded code in five steps:
882                 //
883                 // 1. Backup current template data
884                 $backup = $this->getRawTemplateData();
885
886                 // 2. Set the current template's raw data as the new content
887                 $this->setRawTemplateData($code);
888
889                 // 3. Compile the template data
890                 $this->compileTemplate();
891
892                 // 4. Remember it's contents
893                 $this->loadedRawData[$template] = $this->getRawTemplateData();
894
895                 // 5. Restore the previous raw content from backup variable
896                 $this->setRawTemplateData($backup);
897         }
898
899         /**
900          * Insert all given and loaded templates by running through all loaded
901          * codes and searching for their place-holder in the main template
902          *
903          * @param       $templateMatches        See method analyzeTemplate()
904          * @return      void
905          */
906         private function insertAllTemplates (array $templateMatches) {
907                 // Run through all loaded codes
908                 foreach ($this->loadedRawData as $template => $code) {
909
910                         // Search for the template
911                         $foundIndex = array_search($template, $templateMatches[1]);
912
913                         // Lookup the matching template replacement
914                         if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
915
916                                 // Get the current raw template
917                                 $rawData = $this->getRawTemplateData();
918
919                                 // Replace the space holder with the template code
920                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
921
922                                 // Set the new raw data
923                                 $this->setRawTemplateData($rawData);
924                         } // END - if
925                 } // END - foreach
926         }
927
928         /**
929          * Load all extra raw templates
930          *
931          * @return      void
932          */
933         private function loadExtraRawTemplates () {
934                 // Are there some raw templates we need to load?
935                 if (count($this->rawTemplates) > 0) {
936                         // Try to load all raw templates
937                         foreach ($this->rawTemplates as $key => $template) {
938                                 try {
939                                         // Load the template
940                                         $this->loadHtmlTemplate($template);
941
942                                         // Remember it's contents
943                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
944
945                                         // Remove it from the loader list
946                                         unset($this->rawTemplates[$key]);
947
948                                         // Remember this template for recursion detection
949                                         // RECURSIVE PROTECTION!
950                                         array_push($this->loadedTemplates, $template);
951                                 } catch (FileNotFoundException $e) {
952                                         // This template was never found. We silently ignore it
953                                         unset($this->rawTemplates[$key]);
954                                 }
955                         } // END - foreach
956                 } // END - if
957         }
958
959         /**
960          * Assign all found template variables
961          *
962          * @param       $varMatches             An array full of variable/value pairs.
963          * @return      void
964          * @todo        Unfinished work or don't die here.
965          */
966         private function assignAllVariables (array $varMatches) {
967                 // Debug message
968                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
969
970                 // Search for all variables
971                 foreach ($varMatches[1] as $key => $var) {
972                         // Replace all dashes to underscores to match variables with configuration entries
973                         $var = trim(self::convertDashesToUnderscores($var));
974
975                         // Debug message
976                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
977
978                         // Detect leading equals
979                         if (substr($varMatches[2][$key], 0, 1) == '=') {
980                                 // Remove and cast it
981                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
982                         } // END - if
983
984                         // Do we have some quotes left and right side? Then it is free text
985                         if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
986                                 // Free string detected! Which we can assign directly
987                                 $this->assignVariable($var, $varMatches[3][$key]);
988                         } elseif (!empty($varMatches[2][$key])) {
989                                 // @TODO Non-string found so we need some deeper analysis...
990                                 ApplicationEntryPoint::app_exit('Deeper analysis not yet implemented!');
991                         }
992                 } // END - foreach
993         }
994
995         /**
996          * Compiles all loaded raw templates
997          *
998          * @param       $templateMatches        See method analyzeTemplate() for details
999          * @return      void
1000          */
1001         private function compileRawTemplateData (array $templateMatches) {
1002                 // Debug message
1003                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
1004
1005                 // Are some code-templates found which we need to compile?
1006                 if (count($this->loadedRawData) > 0) {
1007                         // Then compile all!
1008                         foreach ($this->loadedRawData as $template => $code) {
1009                                 // Debug message
1010                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
1011
1012                                 // Is this template already compiled?
1013                                 if (in_array($template, $this->compiledTemplates)) {
1014                                         // Then skip it
1015                                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
1016                                         continue;
1017                                 } // END - if
1018
1019                                 // Search for the template
1020                                 $foundIndex = array_search($template, $templateMatches[1]);
1021
1022                                 // Lookup the matching variable data
1023                                 if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
1024                                         // Split it up with another reg. exp. into variable=value pairs
1025                                         preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
1026                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
1027
1028                                         // Assign all variables
1029                                         $this->assignAllVariables($varMatches);
1030                                 } // END - if (isset($templateMatches ...
1031
1032                                 // Compile the loaded template
1033                                 $this->compileCode($code, $template);
1034                         } // END - foreach ($this->loadedRawData ...
1035
1036                         // Insert all templates
1037                         $this->insertAllTemplates($templateMatches);
1038                 } // END - if (count($this->loadedRawData) ...
1039         }
1040
1041         /**
1042          * Inserts all raw templates into their respective variables
1043          *
1044          * @return      void
1045          */
1046         private function insertRawTemplates () {
1047                 // Load all templates
1048                 foreach ($this->rawTemplates as $template => $content) {
1049                         // Set the template as a variable with the content
1050                         $this->assignVariable($template, $content);
1051                 }
1052         }
1053
1054         /**
1055          * Finalizes the compilation of all template variables
1056          *
1057          * @return      void
1058          */
1059         private function finalizeVariableCompilation () {
1060                 // Get the content
1061                 $content = $this->getRawTemplateData();
1062                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
1063
1064                 // Do we have the stack?
1065                 if (!$this->isVarStackSet('general')) {
1066                         // Abort here silently
1067                         // @TODO This silent abort should be logged, maybe.
1068                         return;
1069                 } // END - if
1070
1071                 // Walk through all variables
1072                 foreach ($this->getVarStack('general') as $currEntry) {
1073                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
1074                         // Replace all [$var] or {?$var?} with the content
1075                         // @TODO Old behaviour, will become obsolete!
1076                         $content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1077
1078                         // @TODO Yet another old way
1079                         $content = str_replace('[' . $currEntry['name'] . ']', $currEntry['value'], $content);
1080
1081                         // The new behaviour
1082                         $content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
1083                 } // END - for
1084
1085                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
1086
1087                 // Set the content back
1088                 $this->setRawTemplateData($content);
1089         }
1090
1091         /**
1092          * Load a specified HTML template into the engine
1093          *
1094          * @param       $template       The web template we shall load which is located in
1095          *                                              'html' by default
1096          * @return      void
1097          */
1098         public function loadHtmlTemplate ($template) {
1099                 // Set template type
1100                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
1101
1102                 // Load the special template
1103                 $this->loadTemplate($template);
1104         }
1105
1106         /**
1107          * Assign (add) a given variable with a value
1108          *
1109          * @param       $variableName   The variable we are looking for
1110          * @param       $value                  The value we want to store in the variable
1111          * @return      void
1112          * @throws      EmptyVariableException  If the variable name is left empty
1113          */
1114         public final function assignVariable ($variableName, $value) {
1115                 // Replace all dashes to underscores to match variables with configuration entries
1116                 $variableName = trim(self::convertDashesToUnderscores($variableName));
1117
1118                 // Empty variable found?
1119                 if (empty($variableName)) {
1120                         // Throw an exception
1121                         throw new EmptyVariableException(array($this, 'variableName'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
1122                 } // END - if
1123
1124                 // First search for the variable if it was already added
1125                 $index = $this->getVariableIndex($variableName);
1126
1127                 // Was it found?
1128                 if ($index === false) {
1129                         // Add it to the stack
1130                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1131                         $this->addVariable($variableName, $value);
1132                 } elseif (!empty($value)) {
1133                         // Modify the stack entry
1134                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
1135                         $this->modifyVariable($variableName, $value);
1136                 }
1137         }
1138
1139         /**
1140          * Removes a given variable
1141          *
1142          * @param       $variableName   The variable we are looking for
1143          * @param       $variableGroup  Name of variable group (default: 'general')
1144          * @return      void
1145          */
1146         public final function removeVariable ($variableName, $variableGroup = 'general') {
1147                 // First search for the variable if it was already added
1148                 $index = $this->getVariableIndex($variableName, $variableGroup);
1149
1150                 // Was it found?
1151                 if ($index !== false) {
1152                         // Remove this variable
1153                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
1154                         $this->unsetVariableStackOffset($index, $variableGroup);
1155                 } // END - if
1156         }
1157
1158         /**
1159          * Assigns the last loaded raw template content with a given variable
1160          *
1161          * @param       $templateName   Name of the template we want to assign
1162          * @param       $variableName   Name of the variable we want to assign
1163          * @return      void
1164          */
1165         public function assignTemplateWithVariable ($templateName, $variableName) {
1166                 // Get the content from last loaded raw template
1167                 $content = $this->getRawTemplateData();
1168
1169                 // Assign the variable
1170                 $this->assignVariable($variableName, $content);
1171
1172                 // Purge raw content
1173                 $this->setRawTemplateData('');
1174         }
1175
1176         /**
1177          * Assign a given congfiguration variable with a value
1178          *
1179          * @param       $variableName   The configuration variable we want to assign
1180          * @return      void
1181          */
1182         public function assignConfigVariable ($variableName) {
1183                 // Replace all dashes to underscores to match variables with configuration entries
1184                 $variableName = trim(self::convertDashesToUnderscores($variableName));
1185
1186                 // Sweet and simple...
1187                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
1188                 $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
1189         }
1190
1191         /**
1192          * Assigns a lot variables into the stack of currently loaded template.
1193          * This method should only be used in very rare circumstances, e.g. when
1194          * you have to copy a whole set of variables into the template engine.
1195          * Before you use this method, please make sure you have considered all
1196          * other possiblities.
1197          *
1198          * @param       $variables      An array with variables to be assigned
1199          * @return      void
1200          */
1201         public function assignMultipleVariables (array $variables) {
1202                 // "Inject" all
1203                 foreach ($variables as $name => $value) {
1204                         // Set variable with name for 'config' group
1205                         $this->assignVariable($name, $value);
1206                 } // END - foreach
1207         }
1208
1209         /**
1210          * Assigns all the application data with template variables
1211          *
1212          * @param       $applicationInstance    A manageable application instance
1213          * @return      void
1214          */
1215         public function assignApplicationData (ManageableApplication $applicationInstance) {
1216                 // Get long name and assign it
1217                 $this->assignVariable('app_full_name' , $applicationInstance->getAppName());
1218
1219                 // Get short name and assign it
1220                 $this->assignVariable('app_short_name', $applicationInstance->getAppShortName());
1221
1222                 // Get version number and assign it
1223                 $this->assignVariable('app_version'   , $applicationInstance->getAppVersion());
1224
1225                 // Assign extra application-depending data
1226                 $applicationInstance->assignExtraTemplateData($this);
1227         }
1228
1229         /**
1230          * Load a specified code template into the engine
1231          *
1232          * @param       $template       The code template we shall load which is
1233          *                                              located in 'code' by default
1234          * @return      void
1235          */
1236         public function loadCodeTemplate ($template) {
1237                 // Set template type
1238                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
1239
1240                 // Load the special template
1241                 $this->loadTemplate($template);
1242         }
1243
1244         /**
1245          * Load a specified email template into the engine
1246          *
1247          * @param       $template       The email template we shall load which is
1248          *                                              located in 'emails' by default
1249          * @return      void
1250          */
1251         public function loadEmailTemplate ($template) {
1252                 // Set template type
1253                 $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
1254
1255                 // Load the special template
1256                 $this->loadTemplate($template);
1257         }
1258
1259         /**
1260          * Compiles configuration place-holders in all variables. This 'walks'
1261          * through the variable group 'general'. It interprets all values from that
1262          * variables as configuration entries after compiling them.
1263          *
1264          * @return      void
1265          */
1266         public final function compileConfigInVariables () {
1267                 // Do we have the stack?
1268                 if (!$this->isVarStackSet('general')) {
1269                         // Abort here silently
1270                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
1271                         return;
1272                 } // END - if
1273
1274                 // Iterate through all general variables
1275                 foreach ($this->getVarStack('general') as $index => $currVariable) {
1276                         // Compile the value
1277                         $value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
1278
1279                         // Debug message
1280                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
1281
1282                         // Remove it from stack
1283                         $this->removeVariable($currVariable['name'], 'general');
1284                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
1285
1286                         // Is it a configuration key?
1287                         if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
1288                                 // The value itself is a configuration entry
1289                                 $this->assignConfigVariable($value);
1290                         } else {
1291                                 // Re-assign the value directly
1292                                 $this->assignVariable($currVariable['name'], $value);
1293                         }
1294                 } // END - foreach
1295         }
1296
1297         /**
1298          * Compile all variables by inserting their respective values
1299          *
1300          * @return      void
1301          * @todo        Make this code some nicer...
1302          */
1303         public final function compileVariables () {
1304                 // Initialize the $content array
1305                 $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
1306                 $dummy = array();
1307
1308                 // Iterate through all general variables
1309                 foreach ($this->getVarStack('general') as $currVariable) {
1310                         // Transfer it's name/value combination to the $content array
1311                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
1312                         $dummy[$currVariable['name']] = $currVariable['value'];
1313                 }// END - if
1314
1315                 // Set the new variable (don't remove the second dollar!)
1316                 $$validVar = $dummy;
1317
1318                 // Remove some variables
1319                 unset($index);
1320                 unset($currVariable);
1321
1322                 // Run the compilation three times to get content from helper classes in
1323                 $cnt = 0;
1324                 while ($cnt < 3) {
1325                         // Finalize the compilation of template variables
1326                         $this->finalizeVariableCompilation();
1327
1328                         // Prepare the eval() command for comiling the template
1329                         $eval = sprintf('$result = "%s";',
1330                                 addslashes($this->getRawTemplateData())
1331                         );
1332
1333                         // This loop does remove the backslashes (\) in PHP parameters
1334                         while (strpos($eval, $this->codeBegin) !== false) {
1335                                 // Get left part before "<?"
1336                                 $evalLeft = substr($eval, 0, strpos($eval, $this->codeBegin));
1337
1338                                 // Get all from right of "<?"
1339                                 $evalRight = substr($eval, (strpos($eval, $this->codeBegin) + 5));
1340
1341                                 // Cut middle part out and remove escapes
1342                                 $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, $this->codeEnd)));
1343                                 $evalMiddle = stripslashes($evalMiddle);
1344
1345                                 // Remove the middle part from right one
1346                                 $evalRight = substr($evalRight, (strpos($evalRight, $this->codeEnd) + 2));
1347
1348                                 // And put all together
1349                                 $eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
1350                         } // END - while
1351
1352                         // Prepare PHP code for eval() command
1353                         $eval = str_replace(
1354                                 '<%php', '";',
1355                                 str_replace(
1356                                         '%>',
1357                                         "\n\$result .= \"",
1358                                         $eval
1359                                 )
1360                         );
1361
1362                         // Run the constructed command. This will "compile" all variables in
1363                         eval($eval);
1364
1365                         // Goes something wrong?
1366                         if ((!isset($result)) || (empty($result))) {
1367                                 // Output eval command
1368                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Failed eval() code: <pre>%s</pre>', $this->markupCode($eval, true)), true);
1369
1370                                 // Output backtrace here
1371                                 $this->debugBackTrace();
1372                         } // END - if
1373
1374                         // Set raw template data
1375                         $this->setRawTemplateData($result);
1376                         $cnt++;
1377                 } // END - while
1378
1379                 // Final variable assignment
1380                 $this->finalizeVariableCompilation();
1381
1382                 // Set the new content
1383                 $this->setCompiledData($this->getRawTemplateData());
1384         }
1385
1386         /**
1387          * Compile all required templates into the current loaded one
1388          *
1389          * @return      void
1390          * @throws      UnexpectedTemplateTypeException If the template type is
1391          *                                                                                      not "code"
1392          * @throws      InvalidArrayCountException              If an unexpected array
1393          *                                                                                      count has been found
1394          */
1395         public function compileTemplate () {
1396                 // Get code type to make things shorter
1397                 $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
1398
1399                 // We will only work with template type "code" from configuration
1400                 if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
1401                         // Abort here
1402                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
1403                 } // END - if
1404
1405                 // Get the raw data.
1406                 $rawData = $this->getRawTemplateData();
1407
1408                 // Remove double spaces and trim leading/trailing spaces
1409                 $rawData = trim(str_replace('  ', ' ', $rawData));
1410
1411                 // Search for raw variables
1412                 $this->extractVariablesFromRawData($rawData);
1413
1414                 // Search for code-tags which are {? ?}
1415                 preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
1416
1417                 // Debug message
1418                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
1419
1420                 // Analyze the matches array
1421                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
1422                         // Entries are found:
1423                         //
1424                         // The main analysis
1425                         $this->analyzeTemplate($templateMatches);
1426
1427                         // Compile raw template data
1428                         $this->compileRawTemplateData($templateMatches);
1429
1430                         // Are there some raw templates left for loading?
1431                         $this->loadExtraRawTemplates();
1432
1433                         // Are some raw templates found and loaded?
1434                         if (count($this->rawTemplates) > 0) {
1435                                 // Insert all raw templates
1436                                 $this->insertRawTemplates();
1437
1438                                 // Remove the raw template content as well
1439                                 $this->setRawTemplateData('');
1440                         } // END - if
1441                 } // END - if($templateMatches ...
1442         }
1443
1444         /**
1445          * Loads a given view helper (by name)
1446          *
1447          * @param       $helperName             The helper's name
1448          * @return      void
1449          */
1450         protected function loadViewHelper ($helperName) {
1451                 // Is this view helper loaded?
1452                 if (!isset($this->helpers[$helperName])) {
1453                         // Create a class name
1454                         $className = self::convertToClassName($helperName) . 'ViewHelper';
1455
1456                         // Generate new instance
1457                         $this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
1458                 } // END - if
1459
1460                 // Return the requested instance
1461                 return $this->helpers[$helperName];
1462         }
1463
1464         /**
1465          * Transfers the content of this template engine to a given response instance
1466          *
1467          * @param       $responseInstance       An instance of a Responseable class
1468          * @return      void
1469          */
1470         public function transferToResponse (Responseable $responseInstance) {
1471                 // Get the content and set it in response class
1472                 $responseInstance->writeToBody($this->getCompiledData());
1473         }
1474
1475         /**
1476          * "Compiles" a variable by replacing {?var?} with it's content
1477          *
1478          * @param       $rawCode                        Raw code to compile
1479          * @param       $setMatchAsCode         Sets $match if readVariable() returns empty result
1480          * @return      $rawCode        Compile code with inserted variable value
1481          */
1482         public function compileRawCode ($rawCode, $setMatchAsCode=false) {
1483                 // Find the variables
1484                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1485                 preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
1486
1487                 // Compile all variables
1488                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
1489                 foreach ($varMatches[0] as $match) {
1490                         // Add variable tags around it
1491                         $varCode = '{?' . $match . '?}';
1492
1493                         // Debug message
1494                         //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
1495
1496                         // Is the variable found in code? (safes some calls)
1497                         if (strpos($rawCode, $varCode) !== false) {
1498                                 // Debug message
1499                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
1500
1501                                 // Use $match as new value or $value from read variable?
1502                                 if ($setMatchAsCode === true) {
1503                                         // Insert match
1504                                         $rawCode = str_replace($varCode, $match, $rawCode);
1505                                 } else {
1506                                         // Read the variable
1507                                         $value = $this->readVariable($match);
1508
1509                                         // Insert value
1510                                         $rawCode = str_replace($varCode, $value, $rawCode);
1511                                 }
1512                         } // END - if
1513                 } // END - foreach
1514
1515                 // Return the compiled data
1516                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
1517                 return $rawCode;
1518         }
1519
1520         /**
1521          * Getter for variable group array
1522          *
1523          * @return      $variableGroups All variable groups
1524          */
1525         public final function getVariableGroups () {
1526                 return $this->variableGroups;
1527         }
1528
1529         /**
1530          * Renames a variable in code and in stack
1531          *
1532          * @param       $oldName        Old name of variable
1533          * @param       $newName        New name of variable
1534          * @return      void
1535          */
1536         public function renameVariable ($oldName, $newName) {
1537                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
1538                 // Get raw template code
1539                 $rawData = $this->getRawTemplateData();
1540
1541                 // Replace it
1542                 $rawData = str_replace($oldName, $newName, $rawData);
1543
1544                 // Set the code back
1545                 $this->setRawTemplateData($rawData);
1546         }
1547
1548         /**
1549          * Renders the given XML content
1550          *
1551          * @param       $content        Valid XML content or if not set the current loaded raw content
1552          * @return      void
1553          * @throws      XmlParserException      If an XML error was found
1554          */
1555         public function renderXmlContent ($content = NULL) {
1556                 // Is the content set?
1557                 if (is_null($content)) {
1558                         // Get current content
1559                         $content = $this->getRawTemplateData();
1560                 } // END - if
1561
1562                 // Get a XmlParser instance
1563                 $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
1564
1565                 // Check if XML compacting is enabled
1566                 if ($this->isXmlCompactingEnabled()) {
1567                         // Yes, so get a decorator class for transparent compacting
1568                         $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
1569                 } // END - if
1570
1571                 // Parse the XML document
1572                 $parserInstance->parseXmlContent($content);
1573         }
1574
1575         /**
1576          * Enables or disables language support
1577          *
1578          * @param       $languageSupport        New language support setting
1579          * @return      void
1580          */
1581         public final function enableLanguageSupport ($languageSupport = true) {
1582                 $this->languageSupport = (bool) $languageSupport;
1583         }
1584
1585         /**
1586          * Checks whether language support is enabled
1587          *
1588          * @return      $languageSupport        Whether language support is enabled or disabled
1589          */
1590         public final function isLanguageSupportEnabled () {
1591                 return $this->languageSupport;
1592         }
1593
1594         /**
1595          * Enables or disables XML compacting
1596          *
1597          * @param       $xmlCompacting  New XML compacting setting
1598          * @return      void
1599          */
1600         public final function enableXmlCompacting ($xmlCompacting = true) {
1601                 $this->xmlCompacting = (bool) $xmlCompacting;
1602         }
1603
1604         /**
1605          * Checks whether XML compacting is enabled
1606          *
1607          * @return      $xmlCompacting  Whether XML compacting is enabled or disabled
1608          */
1609         public final function isXmlCompactingEnabled () {
1610                 return $this->xmlCompacting;
1611         }
1612
1613         /**
1614          * Removes all commentd, tabs and new-line characters to compact the content
1615          *
1616          * @param       $uncompactedContent             The uncompacted content
1617          * @return      $compactedContent               The compacted content
1618          */
1619         public function compactContent ($uncompactedContent) {
1620                 // First, remove all tab/new-line/revert characters
1621                 $compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
1622
1623                 // Then regex all comments like <!-- //--> away
1624                 preg_match_all($this->regExpComments, $compactedContent, $matches);
1625
1626                 // Do we have entries?
1627                 if (isset($matches[0][0])) {
1628                         // Remove all
1629                         foreach ($matches[0] as $match) {
1630                                 // Remove the match
1631                                 $compactedContent = str_replace($match, '', $compactedContent);
1632                         } // END - foreach
1633                 } // END - if
1634
1635                 // Set the content again
1636                 $this->setRawTemplateData($compactedContent);
1637
1638                 // Return compacted content
1639                 return $compactedContent;
1640         }
1641
1642 }