Fixes for image generation
[shipsimu.git] / inc / classes / main / template / class_BaseTemplateEngine.php
index 7188fda70d6f9e2241ce30355554c5b71660f3ca..7e1aa7c194f0fb6d1a015e4b640aa3f104396b3b 100644 (file)
@@ -4,7 +4,7 @@
  *
  * @author             Roland Haeder <webmaster@ship-simu.org>
  * @version            0.0.0
- * @copyright  Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, this is free software
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.ship-simu.org
  *
@@ -65,15 +65,9 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
        private $lastTemplate = "";
 
        /**
-        * The variable stack for the templates. This must be initialized and
-        * shall become an instance of FrameworkArrayObject.
+        * The variable stack for the templates
         */
-       private $varStack = null;
-
-       /**
-        * Configuration variables in a simple array
-        */
-       private $configVariables = array();
+       private $varStack = array();
 
        /**
         * Loaded templates for recursive protection and detection
@@ -112,20 +106,20 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        private $helpers = array();
 
-       // Exception codes for the template engine
-       const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0x020;
-       const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x021;
-       const EXCEPTION_INVALID_VIEW_HELPER           = 0x022;
+       /**
+        * Current variable group
+        */
+       private $currGroup = 'general';
 
        /**
-        * Initialize the variable stack. This holds all variables for later
-        * compilation.
-        *
-        * @return      void
+        * All template groups except "general"
         */
-       public final function initVariableStack () {
-               $this->varStack = new FrameworkArrayObject("FakedVariableStack");
-       }
+       private $varGroups = array();
+
+       // Exception codes for the template engine
+       const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0x110;
+       const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
+       const EXCEPTION_INVALID_VIEW_HELPER           = 0x112;
 
        /**
         * Protected constructor
@@ -152,18 +146,20 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                // First everything is not found
                $found = false;
 
-               // Now search for it
-               for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
-                       // Get current item
-                       $currEntry = $idx->current();
-
-                       // Is the entry found?
-                       if ($currEntry['name'] == $var) {
-                               // Found!
-                               $found = $idx->key();
-                               break;
-                       }
-               }
+               // Is the group there?
+               if (isset($this->varStack[$this->currGroup])) {
+                       // Now search for it
+                       foreach ($this->varStack[$this->currGroup] as $idx => $currEntry) {
+                               //* DEBUG: */ echo __METHOD__.":currGroup={$this->currGroup},idx={$idx},currEntry={$currEntry['name']},var={$var}<br />\n";
+                               // Is the entry found?
+                               if ($currEntry['name'] == $var) {
+                                       // Found!
+                                       //* DEBUG: */ echo __METHOD__.":FOUND!<br />\n";
+                                       $found = $idx;
+                                       break;
+                               } // END - if
+                       } // END - foreach
+               } // END - if
 
                // Return the current position
                return $found;
@@ -175,25 +171,23 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @param       $var            The variable we are looking for
         * @return      $content        Content of the variable or null if not found
         */
-       private function readVariable ($var) {
+       protected function readVariable ($var) {
                // First everything is not found
                $content = null;
 
-               // Now search for it
-               for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
-                       // Get current item
-                       $currEntry = $idx->current();
+               // Get variable index
+               $found = $this->isVariableAlreadySet($var);
 
-                       // Is the entry found?
-                       if ($currEntry['name'] == $var) {
-                               // Found!
-                               $content = $currEntry['value'];
-                               break;
-                       }
-               }
+               // Is the variable found?
+               if ($found !== false) {
+                       // Read it
+                       $found = $this->varStack[$this->currGroup][$found]['value'];
+               } // END - if
+
+               //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.",var=".$var.", found=".$found."<br />\n";
 
                // Return the current position
-               return $content;
+               return $found;
        }
 
        /**
@@ -204,11 +198,72 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        private function addVariable ($var, $value) {
+               // Set general variable group
+               $this->setVariableGroup('general');
+
                // Add it to the stack
-               $this->varStack->append(array(
-                       'name'  => trim($var),
-                       'value' => trim($value)
-               ));
+               $this->addGroupVariable($var, $value);
+       }
+
+       /**
+        * Returns all variables of current group or empty array
+        *
+        * @return      $result         Wether array of found variables or empty array
+        */
+       private function readCurrentGroup () {
+               // Default is not found
+               $result = array();
+
+               // Is the group there?
+               if (isset($this->varStack[$this->currGroup])) {
+                       // Then use it
+                       $result = $this->varStack[$this->currGroup];
+               } // END - if
+
+               // Return result
+               return $result;
+       }
+
+       /**
+        * Settter for variable group
+        *
+        * @param       $groupName      Name of variable group
+        * @param       $add            Wether add this group
+        * @retur4n     void
+        */
+       public function setVariableGroup ($groupName, $add = true) {
+               // Set group name
+               //* DEBIG: */ echo __METHOD__.": currGroup=".$groupName."<br />\n";
+               $this->currGroup = $groupName;
+
+               // Skip group 'general'
+               if (($groupName != 'general') && ($add === true)) {
+                       $this->varGroups[$groupName] = 'OK';
+               } // END - if
+       }
+
+
+       /**
+        * Adds a variable to current group
+        *
+        * @param       $var    Variable to set
+        * @param       $value  Value to store in variable
+        * @return      void
+        */
+       public function addGroupVariable ($var, $value) {
+               //* DEBUG: */ echo __METHOD__.": group=".$this->currGroup.", var=".$var.", value=".$value."<br />\n";
+
+               // Get current variables in group
+               $currVars = $this->readCurrentGroup();
+
+               // Append our variable
+               $currVars[] = array(
+                       'name'  => $var,
+                       'value' => $value
+               );
+
+               // Add it to the stack
+               $this->varStack[$this->currGroup] = $currVars;
        }
 
        /**
@@ -219,20 +274,14 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        private function modifyVariable ($var, $value) {
-               // It should be there so let's look again...
-               for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
-                       // Get current entry
-                       $currEntry = $idx->current();
-
-                       // Is this the requested variable?
-                       if ($currEntry['name'] == $var) {
-                               // Change it to the other value
-                               $this->varStack->offsetSet($idx->key(), array(
-                                       'name'  => $var,
-                                       'value' => $value
-                               ));
-                       }
-               }
+               // Get index for variable
+               $idx = $this->isVariableAlreadySet($var);
+
+               // Is the variable set?
+               if ($idx !== false) {
+                       // Then modify it
+                       $this->varStack[$this->currGroup][$idx]['value'] = $value;
+               } // END - if
        }
 
        /**
@@ -243,11 +292,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        private final function setTemplateType ($templateType) {
-               // Cast it
-               $templateType = (string) $templateType;
-
-               // And set it (only 2 letters)
-               $this->templateType = $templateType;
+               $this->templateType = (string) $templateType;
        }
 
        /**
@@ -257,9 +302,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        private final function setLastTemplate ($template) {
-               // Cast it to string
-               $template = (string) $template;
-               $this->lastTemplate = $template;
+               $this->lastTemplate = (string) $template;
        }
 
        /**
@@ -278,11 +321,8 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        public final function setBasePath ($basePath) {
-               // Cast it
-               $basePath = (string) $basePath;
-
                // And set it
-               $this->basePath = $basePath;
+               $this->basePath = (string) $basePath;
        }
 
        /**
@@ -303,11 +343,8 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        public final function setRawTemplateExtension ($templateExtension) {
-               // Cast it
-               $templateExtension = (string) $templateExtension;
-
                // And set it
-               $this->templateExtension = $templateExtension;
+               $this->templateExtension = (string) $templateExtension;
        }
 
        /**
@@ -318,11 +355,8 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        public final function setCodeTemplateExtension ($codeExtension) {
-               // Cast it
-               $codeExtension = (string) $codeExtension;
-
                // And set it
-               $this->codeExtension = $codeExtension;
+               $this->codeExtension = (string) $codeExtension;
        }
 
        /**
@@ -355,11 +389,8 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        public final function setCompileOutputPath ($compileOutputPath) {
-               // Cast it
-               $compileOutputPath = (string) $compileOutputPath;
-
                // And set it
-               $this->compileOutputPath = $compileOutputPath;
+               $this->compileOutputPath = (string) $compileOutputPath;
        }
 
        /**
@@ -377,17 +408,29 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @param       $var    The variable we are looking for
         * @param       $value  The value we want to store in the variable
         * @return      void
+        * @throws      EmptyVariableException  If the variable name is left empty
         */
        public final function assignVariable ($var, $value) {
+               // Trim spaces of variable name
+               $var = trim($var);
+
+               // Empty variable found?
+               if (empty($var)) {
+                       // Throw an exception
+                       throw new EmptyVariableException(array($this, 'var'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
+               } // END - if
+
                // First search for the variable if it was already added
                $idx = $this->isVariableAlreadySet($var);
 
                // Was it found?
                if ($idx === false) {
                        // Add it to the stack
+                       //* DEBUG: */ echo "ADD: ".$var."<br />\n";
                        $this->addVariable($var, $value);
                } elseif (!empty($value)) {
                        // Modify the stack entry
+                       //* DEBUG: */ echo "MOD: ".$var."<br />\n";
                        $this->modifyVariable($var, $value);
                }
        }
@@ -415,12 +458,21 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @param       $rawTemplateData        The raw data from the template
         * @return      void
         */
-       private final function setRawTemplateData ($rawTemplateData) {
-               // Cast it to string
-               $rawTemplateData = (string) $rawTemplateData;
-
+       protected final function setRawTemplateData ($rawTemplateData) {
                // And store it in this class
-               $this->rawTemplateData = $rawTemplateData;
+               //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($rawTemplateData)." Bytes set.<br />\n";
+               //* DEBUG: */ echo $this->currGroup." variables: ".count($this->varStack[$this->currGroup]).", groups=".count($this->varStack)."<br />\n";
+               $this->rawTemplateData = (string) $rawTemplateData;
+       }
+
+       /**
+        * Getter for raw template data
+        *
+        * @return      $rawTemplateData        The raw data from the template
+        */
+       public final function getRawTemplateData () {
+               //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($this->rawTemplateData)." Bytes read.<br />\n";
+               return $this->rawTemplateData;
        }
 
        /**
@@ -429,11 +481,19 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        private final function setCompiledData ($compiledData) {
-               // Cast it to string
-               $compiledData = (string) $compiledData;
-
                // And store it in this class
-               $this->compiledData = $compiledData;
+               //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($compiledData)." Bytes set.<br />\n";
+               $this->compiledData = (string) $compiledData;
+       }
+
+       /**
+        * Getter for compiled templates
+        *
+        * @return      $compiledData   Compiled template data
+        */
+       public final function getCompiledData () {
+               //* DEBUG: */ echo __METHOD__.":".$this->getUniqueId().": ".strlen($this->compiledData)." Bytes read.<br />\n";
+               return $this->compiledData;
        }
 
        /**
@@ -443,9 +503,6 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @return      void
         */
        private function loadTemplate ($template) {
-               // Cast it to string
-               $template = (string) $template;
-
                // Get extension for the template
                $ext = $this->getRawTemplateExtension();
 
@@ -460,7 +517,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                        $this->getBasePath(),
                        $this->getLanguageInstance()->getLanguageCode(),
                        $this->getTemplateType(),
-                       $template,
+                       (string) $template,
                        $ext
                );
 
@@ -473,28 +530,13 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         *
         * @param       $fqfn   The full-qualified file name for a template
         * @return      void
-        * @throws      NullPointerException    If $inputInstance is null
-        * @throws      NoObjectException               If $inputInstance is not an object
-        * @throws      MissingMethodException  If $inputInstance is missing a
-        *                                                                      required method
         */
        private function loadRawTemplateData ($fqfn) {
                // Get a input/output instance from the middleware
                $ioInstance = $this->getFileIoInstance();
 
-               // Validate the instance
-               if (is_null($ioInstance)) {
-                       // Throw exception
-                       throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
-               } elseif (!is_object($ioInstance)) {
-                       // Throw another exception
-                       throw new NoObjectException($ioInstance, self::EXCEPTION_IS_NO_OBJECT);
-               } elseif (!method_exists($ioInstance, 'loadFileContents')) {
-                       // Throw yet another exception
-                       throw new MissingMethodException(array($ioInstance, 'loadFileContents'), self::EXCEPTION_MISSING_METHOD);
-               }
-
-               /* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
+               // Some debug code to look on the file which is being loaded
+               //* DEBUG: */ echo __METHOD__.": FQFN=".$fqfn."<br />\n";
 
                // Load the raw template
                $rawTemplateData = $ioInstance->loadFileContents($fqfn);
@@ -507,7 +549,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
        }
 
        /**
-        * Try to assign an extracted template variable as a "content" or "config"
+        * Try to assign an extracted template variable as a "content" or 'config'
         * variable.
         *
         * @param       $varName        The variable's name (shall be content orconfig) by
@@ -516,7 +558,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        private function assignTemplateVariable ($varName, $var) {
                // Is it not a config variable?
-               if ($varName != "config") {
+               if ($varName != 'config') {
                        // Regular template variables
                        $this->assignVariable($var, "");
                } else {
@@ -541,9 +583,15 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                // Did we find some variables?
                if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
                        // Initialize all missing variables
-                       foreach ($variableMatches[3] as $key=>$var) {
-                               // Try to assign it, empty strings are being ignored
-                               $this->assignTemplateVariable($variableMatches[1][$key], $var);
+                       foreach ($variableMatches[3] as $key => $var) {
+                               // Variable name
+                               $varName = $variableMatches[1][$key];
+
+                               // Workarround: Do not assign empty variables
+                               if (!empty($var)) {
+                                       // Try to assign it, empty strings are being ignored
+                                       $this->assignTemplateVariable($varName, $var);
+                               } // END - if
                        } // END - foreach
                } // END - if
        }
@@ -577,10 +625,17 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                        if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
 
                                // Template not found, but maybe variable assigned?
+                               //* DEBUG: */ echo __METHOD__.":template={$template}<br />\n";
                                if ($this->isVariableAlreadySet($template) !== false) {
                                        // Use that content here
                                        $this->loadedRawData[$template] = $this->readVariable($template);
 
+                                       // Recursive protection:
+                                       $this->loadedTemplates[] = $template;
+                               } elseif (isset($this->varStack['config'][$template])) {
+                                       // Use that content here
+                                       $this->loadedRawData[$template] = $this->varStack['config'][$template];
+
                                        // Recursive protection:
                                        $this->loadedTemplates[] = $template;
                                } else {
@@ -620,7 +675,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                if (in_array($template, $this->compiledTemplates)) {
                        // Abort here...
                        return;
-               }
+               } // END - if
 
                // Remember this template being compiled
                $this->compiledTemplates[] = $template;
@@ -652,7 +707,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        private function insertAllTemplates (array $templateMatches) {
                // Run through all loaded codes
-               foreach ($this->loadedRawData as $template=>$code) {
+               foreach ($this->loadedRawData as $template => $code) {
 
                        // Search for the template
                        $foundIndex = array_search($template, $templateMatches[1]);
@@ -668,9 +723,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
 
                                // Set the new raw data
                                $this->setRawTemplateData($rawData);
-
                        } // END - if
-
                } // END - foreach
        }
 
@@ -704,8 +757,8 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                                        // This template was never found. We silently ignore it
                                        unset($this->rawTemplates[$key]);
                                }
-                       }
-               }
+                       } // END - foreach
+               } // END - if
        }
 
        /**
@@ -717,7 +770,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        private function assignAllVariables (array $varMatches) {
                // Search for all variables
-               foreach ($varMatches[1] as $key=>$var) {
+               foreach ($varMatches[1] as $key => $var) {
 
                        // Detect leading equals
                        if (substr($varMatches[2][$key], 0, 1) == "=") {
@@ -747,7 +800,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                if (count($this->loadedRawData) > 0) {
 
                        // Then compile all!
-                       foreach ($this->loadedRawData as $template=>$code) {
+                       foreach ($this->loadedRawData as $template => $code) {
 
                                // Is this template already compiled?
                                if (in_array($template, $this->compiledTemplates)) {
@@ -787,7 +840,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        private function insertRawTemplates () {
                // Load all templates
-               foreach ($this->rawTemplates as $template=>$content) {
+               foreach ($this->rawTemplates as $template => $content) {
                        // Set the template as a variable with the content
                        $this->assignVariable($template, $content);
                }
@@ -801,44 +854,33 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
        private function finalizeVariableCompilation () {
                // Get the content
                $content = $this->getRawTemplateData();
+               //* DEBUG: */ echo __METHOD__.": content before=".strlen($content)." (".md5($content).")<br />\n";
 
                // Walk through all variables
-               for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
-                       // Get current entry
-                       $currEntry = $idx->current();
-
+               foreach ($this->varStack['general'] as $currEntry) {
+                       //* DEBUG: */ echo __METHOD__.": name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
                        // Replace all [$var] or {?$var?} with the content
-                       //* DEBUG: */ echo "name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
+                       // Old behaviour, will become obsolete!
                        $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
+
+                       // Yet another old way
                        $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
+
+                       // The new behaviour
                        $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
                } // END - for
 
+               //* DEBUG: */ echo __METHOD__.": content after=".strlen($content)." (".md5($content).")<br />\n";
+
                // Set the content back
                $this->setRawTemplateData($content);
        }
 
-       /**
-        * Getter for raw template data
-        *
-        * @return      $rawTemplateData        The raw data from the template
-        */
-       public final function getRawTemplateData () {
-               return $this->rawTemplateData;
-       }
-
-       /**
-        * Getter for compiled templates
-        */
-       public final function getCompiledData () {
-               return $this->compiledData;
-       }
-
        /**
         * Load a specified web template into the engine
         *
-        * @param               $template               The web template we shall load which is
-        *                                              located in "html" by default
+        * @param       $template       The web template we shall load which is located in
+        *                                              "html" by default
         * @return      void
         */
        public function loadWebTemplate ($template) {
@@ -857,14 +899,15 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        public function assignConfigVariable ($var) {
                // Sweet and simple...
-               $this->configVariables[$var] = $this->getConfigInstance()->readConfig($var);
+               //* DEBUG: */ echo __METHOD__.":var={$var}<br />\n";
+               $this->varStack['config'][$var] = $this->getConfigInstance()->readConfig($var);
        }
 
        /**
         * Load a specified email template into the engine
         *
-        * @param               $template               The email template we shall load which is
-        *                                              located in "emails" by default
+        * @param       $template       The email template we shall load which is located in
+        *                                              "emails" by default
         * @return      void
         */
        public function loadEmailTemplate ($template) {
@@ -878,7 +921,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
        /**
         * Load a specified code template into the engine
         *
-        * @param               $template               The code template we shall load which is
+        * @param       $template       The code template we shall load which is
         *                                              located in "code" by default
         * @return      void
         */
@@ -901,23 +944,21 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
                $dummy = array();
 
-               // Iterate through all variables
-               for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
-
-                       // Get current variable from the stack
-                       $currVariable = $idx->current();
-
+               // Iterate through all general variables
+               foreach ($this->varStack['general'] as $currVariable) {
                        // Transfer it's name/value combination to the $content array
                        //* DEBUG: */ echo $currVariable['name']."=<pre>".htmlentities($currVariable['value'])."</pre>\n";
                        $dummy[$currVariable['name']] = $currVariable['value'];
-
                }// END - if
 
-               // Set the new variable (don't remove the second dollar !)
+               // Set the new variable (don't remove the second dollar!)
                $$validVar = $dummy;
 
                // Prepare all configuration variables
-               $config = $this->configVariables;
+               $config = null;
+               if (isset($this->varStack['config'])) {
+                       $config = $this->varStack['config'];
+               } // END - if
 
                // Remove some variables
                unset($idx);
@@ -935,18 +976,12 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                        );
 
                        // This loop does remove the backslashes (\) in PHP parameters
-                       while (strpos($eval, "<?") !== false) {
+                       while (strpos($eval, "<?php") !== false) {
                                // Get left part before "<?"
-                               $evalLeft = substr($eval, 0, strpos($eval, "<?"));
+                               $evalLeft = substr($eval, 0, strpos($eval, "<?php"));
 
                                // Get all from right of "<?"
-                               $evalRight = substr($eval, (strpos($eval, "<?") + 2));
-
-                               // Is this a full PHP tag?
-                               if (substr(strtolower($evalRight), 0, 3) == "php") {
-                                       // Remove "php" string from full PHP tag
-                                       $evalRight = substr($evalRight, 3);
-                               } // END - if
+                               $evalRight = substr($eval, (strpos($eval, "<?php") + 5));
 
                                // Cut middle part out and remove escapes
                                $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
@@ -960,7 +995,6 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                        } // END - while
 
                        // Prepare PHP code for eval() command
-                       $evalLength = strlen($eval);
                        $eval = str_replace(
                                "<%php", "\";",
                                str_replace(
@@ -968,11 +1002,8 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                                )
                        );
 
-                       // Did something change?
-                       if (strlen($eval) != $eval) {
-                               // Run the constructed command. This will "compile" all variables in
-                               @eval($eval);
-                       } // END - if
+                       // Run the constructed command. This will "compile" all variables in
+                       @eval($eval);
 
                        // Goes something wrong?
                        if (!isset($result)) {
@@ -980,16 +1011,19 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                                $this->debugOutput(sprintf("Failed eval() code: <pre>%s</pre>", $this->markupCode($eval, true)), true);
 
                                // Output backtrace here
-                               $this->debugBacktrace();
+                               $this->debugBackTrace();
                        } // END - if
 
                        // Set raw template data
                        $this->setRawTemplateData($result);
                        $cnt++;
-               }
+               } // END - while
+
+               // Final variable assignment
+               $this->finalizeVariableCompilation();
 
                // Set the new content
-               $this->setCompiledData($result);
+               $this->setCompiledData($this->getRawTemplateData());
        }
 
        /**
@@ -1001,7 +1035,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @throws      InvalidArrayCountException              If an unexpected array
         *                                                                                      count has been found
         */
-       public final function compileTemplate () {
+       public function compileTemplate () {
                // We will only work with template type "code" from configuration
                if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
                        // Abort here
@@ -1048,13 +1082,13 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
        }
 
        /**
-        * Output the compiled page to the outside world. In case of web templates
-        * this would be vaild (X)HTML code. And in case of email templates this
-        * would store a prepared email body inside the template engine.
+        * A old deprecated method
         *
         * @return      void
+        * @deprecated
+        * @see         BaseTemplateEngine::transferToResponse
         */
-       public final function output () {
+       public function output () {
                // Check which type of template we have
                switch ($this->getTemplateType()) {
                case "html": // Raw HTML templates can be send to the output buffer
@@ -1079,7 +1113,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
        /**
         * Loads a given view helper (by name)
         *
-        * @param       $helperName     The helper's name
+        * @param       $helperName             The helper's name
         * @return      void
         * @throws      ViewHelperNotFoundException     If the given view helper was not found
         */
@@ -1096,7 +1130,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
                        if (!class_exists($className)) {
                                // Abort here!
                                throw new ViewHelperNotFoundException(array($this, $helperName), self::EXCEPTION_INVALID_VIEW_HELPER);
-                       }
+                       } // END - if
 
                        // Generate new instance
                        $eval = sprintf("\$this->helpers[%s] = %s::create%s();",
@@ -1107,7 +1141,7 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
 
                        // Run the code
                        eval($eval);
-               }
+               } // END - if
 
                // Return the requested instance
                return $this->helpers[$helperName];
@@ -1150,13 +1184,16 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         */
        public function assignApplicationData (ManageableApplication $appInstance) {
                // Get long name and assign it
-               $this->assignVariable("app_full_name" , $appInstance->getAppName());
+               $this->assignVariable('app_full_name' , $appInstance->getAppName());
 
                // Get short name and assign it
-               $this->assignVariable("app_short_name", $appInstance->getAppShortName());
+               $this->assignVariable('app_short_name', $appInstance->getAppShortName());
 
                // Get version number and assign it
-               $this->assignVariable("app_version"   , $appInstance->getAppVersion());
+               $this->assignVariable('app_version'   , $appInstance->getAppVersion());
+
+               // Assign extra application-depending data
+               $appInstance->assignExtraTemplateData($this);
        }
 
        /**
@@ -1165,19 +1202,97 @@ class BaseTemplateEngine extends BaseFrameworkSystem {
         * @param       $rawCode        Raw code to compile
         * @return      $rawCode        Compile code with inserted variable value
         */
-       protected function compileRawCode ($rawCode) {
+       public function compileRawCode ($rawCode) {
                // Find the variables
+               //* DEBUG: */ echo "rawCode=<pre>".htmlentities($rawCode)."</pre>\n";
                preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
 
                // Compile all variables
+               //* DEBUG: */ echo "<pre>".print_r($varMatches, true)."</pre>";
                foreach ($varMatches[0] as $match) {
-                       // Replace the variable with it's value, if found
-                       $rawCode = str_replace("{?".$match."?}", $this->readVariable($match), $rawCode);
+                       // Add variable tags around it
+                       $varCode = "{?".$match."?}";
+
+                       // Is the variable found in code? (safes some calls)
+                       if (strpos($rawCode, $varCode) !== false) {
+                               // Replace the variable with it's value, if found
+                               //* DEBUG: */ echo __METHOD__.": match=".$match."<br />\n";
+                               $rawCode = str_replace($varCode, $this->readVariable($match), $rawCode);
+                       } // END - if
                } // END - foreach
 
                // Return the compiled data
                return $rawCode;
        }
+
+       /**
+        * Getter for variable group array
+        *
+        * @return      $vargroups      All variable groups
+        */
+       public final function getVariableGroups () {
+               return $this->varGroups;
+       }
+
+       /**
+        * Renames a variable in code and in stack
+        *
+        * @param       $oldName        Old name of variable
+        * @param       $newName        New name of variable
+        * @return      void
+        */
+       public function renameVariable ($oldName, $newName) {
+               //* DEBUG: */ echo __METHOD__.": oldName={$oldName}, newName={$newName}<br />\n";
+               // Get raw template code
+               $rawData = $this->getRawTemplateData();
+
+               // Replace it
+               $rawData = str_replace($oldName, $newName, $rawData);
+
+               // Set the code back
+               $this->setRawTemplateData($rawData);
+       }
+
+       /**
+        * Renders the given XML content
+        *
+        * @param       $content        Valid XML content or if not set the current loaded raw content
+        * @return      void
+        * @throws      XmlParserException      If an XML error was found
+        */
+       public final function renderXmlContent ($content = null) {
+               // Is the content set?
+               if (is_null($content)) {
+                       // Get current content
+                       $content = $this->getRawTemplateData();
+               } // END - if
+
+               // Convert all to UTF8
+               $content = recode("html..utf8", $content);
+
+               // Get an XML parser
+               $xmlParser = xml_parser_create();
+
+               // Force case-folding to on
+               xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
+
+               // Set object
+               xml_set_object($xmlParser, $this);
+
+               // Set handler call-backs
+               xml_set_element_handler($xmlParser, 'startElement', 'endElement');
+               xml_set_character_data_handler($xmlParser, 'characterHandler');
+
+               // Now parse the XML tree
+               if (!xml_parse($xmlParser, $content)) {
+                       // Error found in XML!
+                       //die("<pre>".htmlentities($content)."</pre>");
+                       throw new XmlParserException(array($this, $xmlParser), BaseHelper::EXCEPTION_XML_PARSER_ERROR);
+               } // END - if
+
+               // Free the parser
+               xml_parser_free($xmlParser);
+       }
 }
 
 // [EOF]