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