74542634f7466235ec2e3b87e8a5547df81c6ce3
[mailer.git] / inc / classes / main / template / class_TemplateEngine.php
1 <?php
2 /**
3  * The own template engine for loading caching and sending out the web pages
4  * and emails.
5  *
6  * @author              Roland Haeder <webmaster@mxchange.org>
7  * @version             0.3.0
8  * @copyright   Copyright(c) 2007, 2008 Roland Haeder, this is free software
9  * @license             GNU GPL 3.0 or any newer version
10  * @link                http://www.mxchange.org
11  *
12  * This program is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation, either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  */
25 class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate {
26         /**
27          * The local path name where all templates and sub folders for special
28          * templates are stored. We will internally determine the language plus
29          * "html" for web templates or "emails" for email templates
30          */
31         private $basePath = "";
32
33         /**
34          * The extension for web and email templates (not compiled templates)
35          */
36         private $templateExtension = ".tpl";
37
38         /**
39          * The extension for code templates (not compiled templates)
40          */
41         private $codeExtension = ".ctp";
42
43         /**
44          * Path relative to $basePath and language code for compiled code-templates
45          */
46         private $compileOutputPath = "templates/_compiled";
47
48         /**
49          * The raw (maybe uncompiled) template
50          */
51         private $rawTemplateData = "";
52
53         /**
54          * Template data with compiled-in variables
55          */
56         private $compiledData = "";
57
58         /**
59          * The last loaded template's FQFN for debugging the engine
60          */
61         private $lastTemplate = "";
62
63         /**
64          * The variable stack for the templates. This must be initialized and
65          * shall become an instance of FrameworkArrayObject.
66          */
67         private $varStack = null;
68
69         /**
70          * Configuration variables in a simple array
71          */
72         private $configVariables = array();
73
74         /**
75          * The language instance which should link to an object of LanguageSystem
76          */
77         private $langInstance = null;
78
79         /**
80          * Loaded templates for recursive protection and detection
81          */
82         private $loadedTemplates = array();
83
84         /**
85          * Compiled templates for recursive protection and detection
86          */
87         private $compiledTemplates = array();
88
89         /**
90          * Loaded raw template data
91          */
92         private $loadedRawData = null;
93
94         /**
95          * Raw templates which are linked in code templates
96          */
97         private $rawTemplates = null;
98
99         /**
100          * A regular expression for variable=value pairs
101          */
102         private $regExpVarValue = '/([\w_]+)(="([^"]*)"|=([\w_]+))?/';
103
104         /**
105          * A regular expression for filtering out code tags
106          *
107          * E.g.: {?template:variable=value;var2=value2;[...]?}
108          */
109         private $regExpCodeTags = '/\{\?([a-z_]+)(:("[^"]+"|[^?}]+)+)?\?\}/';
110
111         // Exception codes for the template engine
112         const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0xa00;
113         const TEMPLATE_CONTAINS_INVALID_VAR_EXCEPTION = 0xa01;
114
115         /**
116          * Private constructor
117          *
118          * @return      void
119          */
120         private final function __construct () {
121                 // Call parent constructor
122                 parent::constructor(__CLASS__);
123
124                 // Set part description
125                 $this->setPartDescr("Template-Engine");
126
127                 // Create unique ID number
128                 $this->createUniqueID();
129
130                 // Clean up a little
131                 $this->removeNumberFormaters();
132                 $this->removeSystemArray();
133         }
134
135         /**
136          * Creates an instance of the class TemplateEngine and prepares it for usage
137          *
138          * @param               $basePath               The local base path for all templates
139          * @param               $langInstance   An instance of LanguageSystem (default)
140          * @param               $ioInstance     An instance of FileIOHandler (default, middleware!)
141          * @return      $tplInstance    An instance of TemplateEngine
142          * @throws      BasePathIsEmptyException                If the provided $basePath is empty
143          * @throws      InvalidBasePathStringException  If $basePath is no string
144          * @throws      BasePathIsNoDirectoryException  If $basePath is no
145          *                                                                              directory or not found
146          * @throws      BasePathReadProtectedException  If $basePath is
147          *                                                                              read-protected
148          */
149         public final static function createTemplateEngine ($basePath, $langInstance, $ioInstance) {
150                 // Get a new instance
151                 $tplInstance = new TemplateEngine();
152
153                 // Is the base path valid?
154                 if (empty($basePath)) {
155                         // Base path is empty
156                         throw new BasePathIsEmptyException($tplInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
157                 } elseif (!is_string($basePath)) {
158                         // Is not a string
159                         throw new InvalidBasePathStringException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_STRING);
160                 } elseif (!is_dir($basePath)) {
161                         // Is not a path
162                         throw new BasePathIsNoDirectoryException(array($tplInstance, $basePath), self::EXCEPTION_INVALID_PATH_NAME);
163                 } elseif (!is_readable($basePath)) {
164                         // Is not readable
165                         throw new BasePathReadProtectedException(array($tplInstance, $basePath), self::EXCEPTION_READ_PROTECED_PATH);
166                 }
167
168                 // Get configuration instance
169                 $cfgInstance = $tplInstance->getConfigInstance();
170
171                 // Set the base path
172                 $tplInstance->setBasePath($basePath);
173
174                 // Initialize the variable stack
175                 $tplInstance->initVariableStack();
176
177                 // Set the language and IO instances
178                 $tplInstance->setLanguageInstance($langInstance);
179                 $tplInstance->setIOInstance($ioInstance);
180
181                 // Set template extensions
182                 $tplInstance->setRawTemplateExtension($cfgInstance->readConfig("raw_template_extension"));
183                 $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig("code_template_extension"));
184
185                 // Absolute output path for compiled templates
186                 $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig("compile_output_path"));
187
188                 // Return the prepared instance
189                 return $tplInstance;
190         }
191
192         /**
193          * Search for a variable in the stack
194          *
195          * @param               $var            The variable we are looking for
196          * @return      $idx            FALSE means not found, > 0 means found on a specific index
197          */
198         private function isVariableAlreadySet ($var) {
199                 // First everything is not found
200                 $found = false;
201
202                 // Now search for it
203                 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
204                         // Get current item
205                         $currEntry = $idx->current();
206
207                         // Is the entry found?
208                         if ($currEntry['name'] == $var) {
209                                 // Found!
210                                 $found = $idx->key();
211                                 break;
212                         }
213                 }
214
215                 // Return the current position
216                 return $found;
217         }
218
219         /**
220          * Add a variable to the stack
221          *
222          * @param               $var            The variable we are looking for
223          * @param               $value  The value we want to store in the variable
224          * @return      void
225          */
226         private function addVariable ($var, $value) {
227                 // Add it to the stack
228                 $this->varStack->append(array(
229                         'name'  => $var,
230                         'value' => $value
231                 ));
232         }
233
234         /**
235          * Modify an entry on the stack
236          *
237          * @param               $var            The variable we are looking for
238          * @param               $value  The value we want to store in the variable
239          * @return      void
240          */
241         private function modifyVariable ($var, $value) {
242                 // It should be there so let's look again...
243                 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
244                         // Get current entry
245                         $currEntry = $idx->current();
246
247                         // Is this the requested variable?
248                         if ($currEntry['name'] == $var) {
249                                 // Change it to the other value
250                                 $this->varStack->offsetSet($idx->key(), array(
251                                         'name'  => $var,
252                                         'value' => $value
253                                 ));
254                         }
255                 }
256         }
257
258         /**
259          * Initialize the variable stack. This holds all variables for later
260          * compilation.
261          *
262          * @return      void
263          */
264         public final function initVariableStack () {
265                 $this->varStack = new FrameworkArrayObject();
266         }
267
268         /**
269          * Setter for language instance which should be LanguageSystem
270          *
271          * @param               $langInstance           The language instance
272          * @return      void
273          */
274         public final function setLanguageInstance (ManageableLanguage $langInstance) {
275                 $this->langInstance = $langInstance;
276         }
277
278         /**
279          * Setter for file I/O instance which should be FileIOHandler
280          *
281          * @param               $ioInstance             The file I/O instance
282          * @return      void
283          */
284         public final function setIOInstance (FileIOHandler $ioInstance) {
285                 $this->ioInstance = $ioInstance;
286         }
287
288         /**
289          * Getter for file I/O instance which should be FileIOHandler
290          *
291          * @return      $ioInstance             The file I/O instance
292          */
293         public final function getIOInstance () {
294                 return $this->ioInstance;
295         }
296
297         /**
298          * Setter for base path
299          *
300          * @param               $basePath               The local base path for all templates
301          * @return      void
302          */
303         public final function setBasePath ($basePath) {
304                 // Cast it
305                 $basePath = (string) $basePath;
306
307                 // And set it
308                 $this->basePath = $basePath;
309         }
310
311         /**
312          * Getter for base path
313          *
314          * @return      $basePath               The local base path for all templates
315          */
316         public final function getBasePath () {
317                 // And set it
318                 return $this->basePath;
319         }
320
321         /**
322          * Setter for template extension
323          *
324          * @param               $templateExtension      The file extension for all uncompiled
325          *                                                      templates
326          * @return      void
327          */
328         public final function setRawTemplateExtension ($templateExtension) {
329                 // Cast it
330                 $templateExtension = (string) $templateExtension;
331
332                 // And set it
333                 $this->templateExtension = $templateExtension;
334         }
335
336         /**
337          * Setter for code template extension
338          *
339          * @param               $codeExtension          The file extension for all uncompiled
340          *                                                      templates
341          * @return      void
342          */
343         public final function setCodeTemplateExtension ($codeExtension) {
344                 // Cast it
345                 $codeExtension = (string) $codeExtension;
346
347                 // And set it
348                 $this->codeExtension = $codeExtension;
349         }
350
351         /**
352          * Getter for template extension
353          *
354          * @return      $templateExtension      The file extension for all uncompiled
355          *                                                      templates
356          */
357         public final function getRawTemplateExtension () {
358                 // And set it
359                 return $this->templateExtension;
360         }
361
362         /**
363          * Getter for code-template extension
364          *
365          * @return      $codeExtension          The file extension for all code-
366          *                                                      templates
367          */
368         public final function getCodeTemplateExtension () {
369                 // And set it
370                 return $this->codeExtension;
371         }
372
373         /**
374          * Setter for path of compiled templates
375          *
376          * @param               $compileOutputPath              The local base path for all
377          *                                                              compiled templates
378          * @return      void
379          */
380         public final function setCompileOutputPath ($compileOutputPath) {
381                 // Cast it
382                 $compileOutputPath = (string) $compileOutputPath;
383
384                 // And set it
385                 $this->compileOutputPath = $compileOutputPath;
386         }
387
388         /**
389          * Setter for template type. Only "html", "emails" and "compiled" should
390          * be sent here
391          *
392          * @param               $templateType   The current template's type
393          * @return      void
394          */
395         private final function setTemplateType ($templateType) {
396                 // Cast it
397                 $templateType = (string) $templateType;
398
399                 // And set it (only 2 letters)
400                 $this->templateType = $templateType;
401         }
402
403         /**
404          * Getter for template type
405          *
406          * @return      $templateType   The current template's type
407          */
408         public final function getTemplateType () {
409                 return $this->templateType;
410         }
411
412         /**
413          * Setter for the last loaded template's FQFN
414          *
415          * @param               $template               The last loaded template
416          * @return      void
417          */
418         private final function setLastTemplate ($template) {
419                 // Cast it to string
420                 $template = (string) $template;
421                 $this->lastTemplate = $template;
422         }
423
424         /**
425          * Getter for the last loaded template's FQFN
426          *
427          * @return      $template               The last loaded template
428          */
429         private final function getLastTemplate () {
430                 return $this->lastTemplate;
431         }
432
433         /**
434          * Assign (add) a given variable with a value
435          *
436          * @param               $var            The variable we are looking for
437          * @param               $value  The value we want to store in the variable
438          * @return      void
439          */
440         public final function assignVariable ($var, $value) {
441                 // First search for the variable if it was already added
442                 $idx = $this->isVariableAlreadySet($var);
443
444                 // Was it found?
445                 if ($idx === false) {
446                         // Add it to the stack
447                         $this->addVariable($var, $value);
448                 } elseif (!empty($value)) {
449                         // Modify the stack entry
450                         $this->modifyVariable($var, $value);
451                 }
452         }
453
454         /**
455          * Assign a given congfiguration variable with a value
456          *
457          * @param               $var            The configuration variable we are looking for
458          * @param               $value  The value we want to store in the variable
459          * @return      void
460          */
461         public final function assignConfigVariable ($var, $value) {
462                 // Sweet and simple...
463                 $this->configVariables[$var] = $value;
464         }
465
466         /**
467          * Removes a given variable
468          *
469          * @param               $var            The variable we are looking for
470          * @return      void
471          */
472         public final function removeVariable ($var) {
473                 // First search for the variable if it was already added
474                 $idx = $this->isVariableAlreadySet($var);
475
476                 // Was it found?
477                 if ($idx !== false) {
478                         // Remove this variable
479                         $this->varStack->offsetUnset($idx);
480                 }
481         }
482
483         /**
484          * Private setter for raw template data
485          *
486          * @param               $rawTemplateData        The raw data from the template
487          * @return      void
488          */
489         private final function setRawTemplateData ($rawTemplateData) {
490                 // Cast it to string
491                 $rawTemplateData = (string) $rawTemplateData;
492
493                 // And store it in this class
494                 $this->rawTemplateData = $rawTemplateData;
495         }
496
497         /**
498          * Private setter for compiled templates
499          */
500         private final function setCompiledData ($compiledData) {
501                 // Cast it to string
502                 $compiledData = (string) $compiledData;
503
504                 // And store it in this class
505                 $this->compiledData = $compiledData;
506         }
507
508         /**
509          * Private loader for all template types
510          *
511          * @param               $template               The template we shall load
512          * @return      void
513          */
514         private final function loadTemplate ($template) {
515                 // Cast it to string
516                 $template = (string) $template;
517
518                 // Get extension for the template
519                 $ext = $this->getRawTemplateExtension();
520
521                 // If we shall load a code-template we need to switch the file extension
522                 if ($this->getTemplateType() == $this->getConfigInstance()->readConfig("code_template_type")) {
523                         // Switch over to the code-template extension
524                         $ext = $this->getCodeTemplateExtension();
525                 }
526
527                 // Construct the FQFN for the template by honoring the current language
528                 $fqfn = sprintf("%s%s/%s/%s%s",
529                         $this->getBasePath(),
530                         $this->langInstance->getLanguageCode(),
531                         $this->getTemplateType(),
532                         $template,
533                         $ext
534                 );
535
536                 // Load the raw template data
537                 $this->loadRawTemplateData($fqfn);
538         }
539
540         /**
541          * A private loader for raw template names
542          *
543          * @param               $fqfn   The full-qualified file name for a template
544          * @return      void
545          * @throws      NullPointerException    If $inputInstance is null
546          * @throws      NoObjectException               If $inputInstance is not an object
547          * @throws      MissingMethodException  If $inputInstance is missing a
548          *                                                              required method
549          */
550         private function loadRawTemplateData ($fqfn) {
551                 // Debug message
552                 if ((defined('DEBUG_TEMPLATE')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Template <strong>%s</strong> vom Typ <strong>%s</strong> wird geladen.<br />\n",
553                         $this->__toString(),
554                         $template,
555                         $this->getTemplateType()
556                 ));
557
558                 // Get a input/output instance from the middleware
559                 $ioInstance = $this->getIOInstance();
560
561                 // Validate the instance
562                 if (is_null($ioInstance)) {
563                         // Throw exception
564                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
565                 } elseif (!is_object($ioInstance)) {
566                         // Throw another exception
567                         throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT);
568                 } elseif (!method_exists($ioInstance, 'loadFileContents')) {
569                         // Throw yet another exception
570                         throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD);
571                 }
572
573                 // Load the raw template
574                 $rawTemplateData = $ioInstance->loadFileContents($fqfn);
575
576                 // Debug message
577                 if ((defined('DEBUG_TEMPLATE')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%s</strong> Byte Rohdaten geladen.<br />\n",
578                         $this->__toString(),
579                         strlen($rawTemplateData)
580                 ));
581
582                 // Store the template's contents into this class
583                 $this->setRawTemplateData($rawTemplateData);
584
585                 // Remember the template's FQFN
586                 $this->setLastTemplate($fqfn);
587         }
588
589         /**
590          * Try to assign an extracted template variable as a "content" or "config"
591          * variable.
592          *
593          * @param               $varName                The variable's name (shall be content or
594          *                                              config) by default
595          * @param               $var                    The variable we want to assign
596          */
597         private function assignTemplateVariable ($varName, $var) {
598                 // Is it not a config variable?
599                 if ($varName != "config") {
600                         // Regular template variables
601                         $this->assignVariable($var, "");
602                 } else {
603                         // Configuration variables
604                         $this->assignConfigVariable($var, $this->getConfigInstance()->readConfig($var));
605                 }
606         }
607
608         /**
609          * Extract variables from a given raw data stream
610          *
611          * @param               $rawData                The raw template data we shall analyze
612          * @return      void
613          * @throws      InvalidTemplateVariableNameException    If a variable name
614          *                                                                                      in a template is
615          *                                                                                      invalid
616          */
617         private function extractVariablesFromRawData ($rawData) {
618                 // Cast to string
619                 $rawData = (string) $rawData;
620
621                 // Search for variables
622                 @preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
623
624                 // Did we find some variables?
625                 if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
626                         // Initialize all missing variables
627                         foreach ($variableMatches[3] as $key=>$var) {
628                                 // Is the variable name valid?
629                                 if (($variableMatches[1][$key] != $this->getConfigInstance()->readConfig("tpl_valid_var")) && ($variableMatches[1][$key] != "config")) {
630                                         // Invalid variable name
631                                         throw new InvalidTemplateVariableNameException(array($this, $this->getLastTemplate(), $variableMatches[1][$key], $this->getConfigInstance()), self::TEMPLATE_CONTAINS_INVALID_VAR_EXCEPTION);
632                                 }
633
634                                 // Try to assign it, empty strings are being ignored
635                                 $this->assignTemplateVariable($variableMatches[1][$key], $var);
636                         }
637                 }
638         }
639
640         /**
641          * Main analysis of the loaded template
642          *
643          * @param               $templateMatches        Found template place-holders, see below
644          * @return      void
645          *
646          *---------------------------------
647          * Structure of $templateMatches:
648          *---------------------------------
649          * [0] => Array - An array with all full matches
650          * [1] => Array - An array with left part (before the ":") of a match
651          * [2] => Array - An array with right part of a match including ":"
652          * [3] => Array - An array with right part of a match excluding ":"
653          */
654         private function analyzeTemplate ($templateMatches) {
655                 // Backup raw template data
656                 $backup = $this->getRawTemplateData();
657
658                 // Initialize some arrays
659                 if (is_null($this->loadedRawData)) { $this->loadedRawData = array(); $this->rawTemplates = array(); }
660
661                 // Load all requested templates
662                 foreach ($templateMatches[1] as $template) {
663
664                         // Load and compile only templates which we have not yet loaded
665                         // RECURSIVE PROTECTION! BE CAREFUL HERE!
666                         if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
667
668                                 // Then try to search for code-templates first
669                                 try {
670                                         // Load the code template and remember it's contents
671                                         $this->loadCodeTemplate($template);
672                                         $this->loadedRawData[$template] = $this->getRawTemplateData();
673
674                                         // Remember this template for recursion detection
675                                         // RECURSIVE PROTECTION!
676                                         $this->loadedTemplates[] = $template;
677                                 } catch (FilePointerNotOpenedException $e) {
678                                         // Template not found!
679                                         $this->rawTemplates[] = $template;
680                                 }
681
682                         } // if ((!isset( ...
683
684                 } // for ($templateMatches ...
685
686                 // Restore the raw template data
687                 $this->setRawTemplateData($backup);
688         }
689
690         /**
691          * Compile a given raw template code and remember it for later usage
692          *
693          * @param               $code           The raw template code
694          * @param               $template               The template's name
695          * @return      void
696          */
697         private function compileCode ($code, $template) {
698                 // Is this template already compiled?
699                 if (in_array($template, $this->compiledTemplates)) {
700                         // Abort here...
701                         return;
702                 }
703
704                 // Remember this template being compiled
705                 $this->compiledTemplates[] = $template;
706
707                 // Compile the loaded code in five steps:
708                 //
709                 // 1. Backup current template data
710                 $backup = $this->getRawTemplateData();
711
712                 // 2. Set the current template's raw data as the new content
713                 $this->setRawTemplateData($code);
714
715                 // 3. Compile the template data
716                 $this->compileTemplate();
717
718                 // 4. Remember it's contents
719                 $this->loadedRawData[$template] = $this->getRawTemplateData();
720
721                 // 5. Restore the previous raw content from backup variable
722                 $this->setRawTemplateData($backup);
723         }
724
725         /**
726          * Insert all given and loaded templates by running through all loaded
727          * codes and searching for their place-holder in the main template
728          *
729          * @param               $templateMatches        See method analyzeTemplate()
730          * @return      void
731          */
732         private function insertAllTemplates ($templateMatches) {
733                 // Run through all loaded codes
734                 foreach ($this->loadedRawData as $template => $code) {
735
736                         // Search for the template
737                         $foundIndex = array_search($template, $templateMatches[1]);
738
739                         // Lookup the matching template replacement
740                         if (isset($templateMatches[0][$foundIndex])) {
741
742                                 // Get the current raw template
743                                 $rawData = $this->getRawTemplateData();
744
745                                 // Replace the space holder with the template code
746                                 $rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
747
748                                 // Set the new raw data
749                                 $this->setRawTemplateData($rawData);
750                         }
751                 }
752         }
753
754         /**
755          * Load all extra raw templates
756          *
757          * @return      void
758          */
759         private function loadExtraRawTemplates () {
760                 // Are there some raw templates we need to load?
761                 if (count($this->rawTemplates) > 0) {
762                         // Try to load all raw templates
763                         foreach ($this->rawTemplates as $key => $template) {
764                                 try {
765                                         // Load the template
766                                         $this->loadWebTemplate($template);
767
768                                         // Remember it's contents
769                                         $this->rawTemplates[$template] = $this->getRawTemplateData();
770
771                                         // Remove it from the loader list
772                                         unset($this->rawTemplates[$key]);
773
774                                         // Remember this template for recursion detection
775                                         // RECURSIVE PROTECTION!
776                                         $this->loadedTemplates[] = $template;
777                                 } catch (FilePointerNotOpenedException $e) {
778                                         // This template was never found. We silently ignore it
779                                         unset($this->rawTemplates[$key]);
780                                 }
781                         }
782                 }
783         }
784
785         /**
786          * Assign all found template variables
787          *
788          * @param               $varMatches     An array full of variable/value pairs.
789          * @return      void
790          */
791         private function assignAllVariables ($varMatches) {
792                 // Search for all variables
793                 foreach ($varMatches[1] as $key=>$var) {
794
795                         // Detect leading equals
796                         if (substr($varMatches[2][$key], 0, 1) == "=") {
797                                 // Remove and cast it
798                                 $varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
799                         }
800
801                         // Do we have some quotes left and right side? Then it is free text
802                         if ((substr($varMatches[2][$key], 0, 1) == "\"") && (substr($varMatches[2][$key], -1, 1) == "\"")) {
803                                 // Free string detected! Which we can assign directly
804                                 $this->assignVariable($var, $varMatches[3][$key]);
805                         } else {
806                                 // Non-string found so we need some deeper analysis...
807                                 die("Deeper analysis not yet implemented!");
808                         }
809
810                 } // for ($varMatches ...
811         }
812         /**
813          * Compiles all loaded raw templates
814          *
815          * @param               $templateMatches        See method analyzeTemplate() for details
816          * @return      void
817          */
818         private function compileRawTemplateData ($templateMatches) {
819                 // Are some code-templates found which we need to compile?
820                 if (count($this->loadedRawData) > 0) {
821
822                         // Then compile all!
823                         foreach ($this->loadedRawData as $template => $code) {
824
825                                 // Search for the template
826                                 $foundIndex = array_search($template, $templateMatches[1]);
827
828                                 // Lookup the matching variable data
829                                 if (isset($templateMatches[3][$foundIndex])) {
830
831                                         // Split it up with another reg. exp. into variable=value pairs
832                                         @preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
833
834                                         // Assign all variables
835                                         $this->assignAllVariables($varMatches);
836
837                                 } // END - if (isset($templateMatches ...
838
839                                 // Compile the loaded template
840                                 $this->compileCode($code, $template);
841
842                         } // END - foreach ($this->loadedRawData ...
843
844                         // Insert all templates
845                         $this->insertAllTemplates($templateMatches);
846
847                 } // END - if (count($this->loadedRawData) ...
848         }
849
850         /**
851          * Getter for raw template data
852          *
853          * @return      $rawTemplateData        The raw data from the template
854          */
855         public final function getRawTemplateData () {
856                 return $this->rawTemplateData;
857         }
858
859         /**
860          * Getter for compiled templates
861          */
862         public final function getCompiledData () {
863                 return $this->compiledData;
864         }
865
866         /**
867          * Load a specified web template into the engine
868          *
869          * @param               $template               The web template we shall load which is
870          *                                              located in "html" by default
871          * @return      void
872          */
873         public final function loadWebTemplate ($template) {
874                 // Set template type
875                 $this->setTemplateType($this->getConfigInstance()->readConfig("web_template_type"));
876
877                 // Load the special template
878                 $this->loadTemplate($template);
879         }
880
881         /**
882          * Load a specified email template into the engine
883          *
884          * @param               $template               The email template we shall load which is
885          *                                              located in "emails" by default
886          * @return      void
887          */
888         public final function loadEmailTemplate ($template) {
889                 // Set template type
890                 $this->setTemplateType($this->getConfigInstance()->readConfig("email_template_type"));
891
892                 // Load the special template
893                 $this->loadTemplate($template);
894         }
895
896         /**
897          * Load a specified code template into the engine
898          *
899          * @param               $template               The code template we shall load which is
900          *                                              located in "code" by default
901          * @return      void
902          */
903         public final function loadCodeTemplate ($template) {
904                 // Set template type
905                 $this->setTemplateType($this->getConfigInstance()->readConfig("code_template_type"));
906
907                 // Load the special template
908                 $this->loadTemplate($template);
909         }
910
911         /**
912          * Compile all variables by inserting their respective values
913          *
914          * @return      void
915          */
916         public final function compileVariables () {
917                 // Initialize the $content array
918                 $validVar = $this->getConfigInstance()->readConfig("tpl_valid_var");
919                 $dummy = array();
920
921                 // Iterate through all variables
922                 for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
923                         // Get current variable from the stack
924                         $currVariable = $idx->current();
925
926                         // Transfer it's name/value combination to the $content array
927                         $dummy[$currVariable['name']] = $currVariable['value'];
928                 }
929                 $$validVar = $dummy;
930
931                 // Prepare all configuration variables
932                 $config = $this->configVariables;
933
934                 // Remove some variables
935                 unset($idx);
936                 unset($currVariable);
937
938                 // Prepare the eval() command for comiling the template
939                 $eval = sprintf("\$this->setCompiledData(\"%s\");",
940                         addslashes($this->getRawTemplateData())
941                 );
942
943                 // Debug message
944                 if (((defined('DEBUG_EVAL')) || (defined('DEBUG_ALL'))) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Konstruierte PHP-Anweisung: <pre><em>%s</em></pre><br />\n",
945                         $this->__toString(),
946                         htmlentities($eval)
947                 ));
948
949                 // Run the constructed command. This will "compile" all variables in
950                 eval($eval);
951         }
952
953         /**
954          * Compile all required templates into the current loaded one
955          *
956          * @return      void
957          * @throws      UnexpectedTemplateTypeException If the template type is
958          *                                                                              not "code"
959          * @throws      InvalidArrayCountException              If an unexpected array
960          *                                                                              count has been found
961          */
962         public final function compileTemplate () {
963                 // We will only work with template type "code" from configuration
964                 if ($this->getTemplateType() != $this->getConfigInstance()->readConfig("code_template_type")) {
965                         // Abort here
966                         throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig("code_template_type")), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
967                 }
968
969                 // Get the raw data. Thanks to Flobee(R) for given me a hint using the
970                 // modifier "m" in regular expressions. I had implemented a regex here
971                 // like this: (\n|\r)
972                 $rawData = $this->getRawTemplateData();
973
974                 // Remove double spaces and trim leading/trailing spaces
975                 $rawData = trim(str_replace("  ", " ", $rawData));
976
977                 // Search for raw variables
978                 $this->extractVariablesFromRawData($rawData);
979
980                 // Search for code-tags which are {? ?}
981                 @preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
982
983                 // Analyze the matches array
984                 if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
985                         // Entries are found:
986                         //
987                         // The main analysis
988                         $this->analyzeTemplate($templateMatches);
989
990                         // Compile raw template data
991                         $this->compileRawTemplateData($templateMatches);
992
993                         // Are there some raw templates left for loading?
994                         $this->loadExtraRawTemplates();
995
996                         // Are some raw templates found and loaded?
997                         if (count($this->rawTemplates) > 0) {
998                                 die("NOT YET IMPLEMENTED");
999                         }
1000                 } // END - if($templateMatches ...
1001         }
1002
1003         /**
1004          * Output the compiled page to the outside world. In case of web templates
1005          * this would be vaild (X)HTML code. And in case of email templates this
1006          * would store a prepared email body inside the template engine.
1007          *
1008          * @return      void
1009          */
1010         public final function output () {
1011                 // Check which type of template we have
1012                 switch ($this->getTemplateType()) {
1013                 case "html": // Raw HTML templates can be send to the output buffer
1014                         // Quick-N-Dirty:
1015                         $this->getWebOutputInstance()->output($this->getCompiledData());
1016                         break;
1017
1018                 default: // Unknown type found
1019                         if ((is_object($this->getDebugInstance())) && (method_exists($this->getDebugInstance(), 'output'))) {
1020                                 // Use debug output handler
1021                                 $this->getDebugInstance()->output(sprintf("[%s:] Unbekannter Template-Typ <strong>%s</strong> erkannt.",
1022                                         $this->__toString(),
1023                                         $this->getTemplateType()
1024                                 ));
1025                                 die();
1026                         } else {
1027                                 // Put directly out
1028                                 // DO NOT REWRITE THIS TO app_die() !!!
1029                                 die(sprintf("[%s:] Unbekannter Template-Typ <strong>%s</strong> erkannt.",
1030                                         $this->__toString(),
1031                                         $this->getTemplateType()
1032                                 ));
1033                         }
1034                         break;
1035                 }
1036         }
1037 }
1038
1039 // [EOF]
1040 ?>