]> git.mxchange.org Git - shipsimu.git/blobdiff - inc/classes/main/template/class_TemplateEngine.php
Login and auth classes added. WARNING: All class config entries must end with _class!
[shipsimu.git] / inc / classes / main / template / class_TemplateEngine.php
index 6e09d8943f7ed32ee4e0b9259f9c37352a9a46fd..fad4cf4a3f5a956a63092319b477076d58f0586b 100644 (file)
@@ -3,11 +3,11 @@
  * The own template engine for loading caching and sending out the web pages
  * and emails.
  *
- * @author             Roland Haeder <webmaster@mxchange.org>
+ * @author             Roland Haeder <webmaster@ship-simu.org>
  * @version            0.0.0
  * @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
+ * @link               http://www.ship-simu.org
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -109,9 +109,9 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
        private $helpers = array();
 
        // Exception codes for the template engine
-       const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0xa00;
-       const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0xa01;
-       const EXCEPTION_INVALID_VIEW_HELPER           = 0xa02;
+       const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED   = 0x020;
+       const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x021;
+       const EXCEPTION_INVALID_VIEW_HELPER           = 0x022;
 
        /**
         * Protected constructor
@@ -123,10 +123,10 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                parent::__construct(__CLASS__);
 
                // Set part description
-               $this->setObjectDescription("Template-Engine");
+               $this->setObjectDescription("Web template engine");
 
                // Create unique ID number
-               $this->createUniqueID();
+               $this->generateUniqueId();
 
                // Clean up a little
                $this->removeNumberFormaters();
@@ -138,7 +138,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         *
         * @param       $basePath               The local base path for all templates
         * @param       $langInstance   An instance of LanguageSystem (default)
-        * @param       $ioInstance             An instance of FileIOHandler (default, middleware!)
+        * @param       $ioInstance             An instance of FileIoHandler (default, middleware!)
         * @return      $tplInstance    An instance of TemplateEngine
         * @throws      BasePathIsEmptyException                If the provided $basePath is empty
         * @throws      InvalidBasePathStringException  If $basePath is no string
@@ -147,7 +147,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         * @throws      BasePathReadProtectedException  If $basePath is
         *                                                                                      read-protected
         */
-       public final static function createTemplateEngine ($basePath, ManageableLanguage  $langInstance, FileIOHandler $ioInstance) {
+       public final static function createTemplateEngine ($basePath, ManageableLanguage  $langInstance, FileIoHandler $ioInstance) {
                // Get a new instance
                $tplInstance = new TemplateEngine();
 
@@ -167,7 +167,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                }
 
                // Get configuration instance
-               $cfgInstance = $tplInstance->getConfigInstance();
+               $cfgInstance = FrameworkConfiguration::getInstance();
 
                // Set the base path
                $tplInstance->setBasePath($basePath);
@@ -177,14 +177,14 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
 
                // Set the language and IO instances
                $tplInstance->setLanguageInstance($langInstance);
-               $tplInstance->setFileIOInstance($ioInstance);
+               $tplInstance->setFileIoInstance($ioInstance);
 
                // Set template extensions
-               $tplInstance->setRawTemplateExtension($cfgInstance->readConfig("raw_template_extension"));
-               $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig("code_template_extension"));
+               $tplInstance->setRawTemplateExtension($cfgInstance->readConfig('raw_template_extension'));
+               $tplInstance->setCodeTemplateExtension($cfgInstance->readConfig('code_template_extension'));
 
                // Absolute output path for compiled templates
-               $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig("compile_output_path"));
+               $tplInstance->setCompileOutputPath(PATH . $cfgInstance->readConfig('compile_output_path'));
 
                // Return the prepared instance
                return $tplInstance;
@@ -290,7 +290,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         * @return      void
         */
        public final function initVariableStack () {
-               $this->varStack = new FrameworkArrayObject();
+               $this->varStack = new FrameworkArrayObject("FakedVariableStack");
        }
 
        /**
@@ -518,7 +518,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                $ext = $this->getRawTemplateExtension();
 
                // If we shall load a code-template we need to switch the file extension
-               if ($this->getTemplateType() == $this->getConfigInstance()->readConfig("code_template_type")) {
+               if ($this->getTemplateType() == $this->getConfigInstance()->readConfig('code_template_type')) {
                        // Switch over to the code-template extension
                        $ext = $this->getCodeTemplateExtension();
                }
@@ -547,15 +547,8 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         *                                                              required method
         */
        private function loadRawTemplateData ($fqfn) {
-               // Debug message
-               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",
-                       $this->__toString(),
-                       $template,
-                       $this->getTemplateType()
-               ));
-
                // Get a input/output instance from the middleware
-               $ioInstance = $this->getFileIOInstance();
+               $ioInstance = $this->getFileIoInstance();
 
                // Validate the instance
                if (is_null($ioInstance)) {
@@ -572,12 +565,6 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                // Load the raw template
                $rawTemplateData = $ioInstance->loadFileContents($fqfn);
 
-               // Debug message
-               if ((defined('DEBUG_TEMPLATE')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] <strong>%s</strong> Byte Rohdaten geladen.<br />\n",
-                       $this->__toString(),
-                       strlen($rawTemplateData)
-               ));
-
                // Store the template's contents into this class
                $this->setRawTemplateData($rawTemplateData);
 
@@ -609,9 +596,6 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         *
         * @param       $rawData        The raw template data we shall analyze
         * @return      void
-        * @throws      InvalidTemplateVariableNameException    If a variable name
-        *                                                                                                      in a template is
-        *                                                                                                      invalid
         */
        private function extractVariablesFromRawData ($rawData) {
                // Cast to string
@@ -624,12 +608,6 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
                        // Initialize all missing variables
                        foreach ($variableMatches[3] as $key=>$var) {
-                               // Is the variable name valid?
-                               if (($variableMatches[1][$key] != $this->getConfigInstance()->readConfig("tpl_valid_var")) && ($variableMatches[1][$key] != "config")) {
-                                       // Invalid variable name
-                                       throw new InvalidTemplateVariableNameException(array($this, $this->getLastTemplate(), $variableMatches[1][$key], $this->getConfigInstance()), self::EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR);
-                               }
-
                                // Try to assign it, empty strings are being ignored
                                $this->assignTemplateVariable($variableMatches[1][$key], $var);
                        }
@@ -664,24 +642,24 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                        // RECURSIVE PROTECTION! BE CAREFUL HERE!
                        if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
 
-                               // Then try to search for code-templates first
-                               try {
-                                       // Load the code template and remember it's contents
-                                       $this->loadCodeTemplate($template);
-                                       $this->loadedRawData[$template] = $this->getRawTemplateData();
+                               // Template not found, but maybe variable assigned?
+                               if ($this->isVariableAlreadySet($template) !== false) {
+                                       // Use that content here
+                                       $this->loadedRawData[$template] = $this->readVariable($template);
 
-                                       // Remember this template for recursion detection
-                                       // RECURSIVE PROTECTION!
+                                       // Recursive protection:
                                        $this->loadedTemplates[] = $template;
-                               } catch (FilePointerNotOpenedException $e) {
-                                       // Template not found, but maybe variable assigned?
-                                       if ($this->isVariableAlreadySet($template) !== false) {
-                                               // Use that content here
-                                               $this->loadedRawData[$template] = $this->readVariable($template);
-
-                                               // Recursive protection:
+                               } else {
+                                       // Then try to search for code-templates
+                                       try {
+                                               // Load the code template and remember it's contents
+                                               $this->loadCodeTemplate($template);
+                                               $this->loadedRawData[$template] = $this->getRawTemplateData();
+
+                                               // Remember this template for recursion detection
+                                               // RECURSIVE PROTECTION!
                                                $this->loadedTemplates[] = $template;
-                                       } else {
+                                       } catch (FilePointerNotOpenedException $e) {
                                                // Even this is not done... :/
                                                $this->rawTemplates[] = $template;
                                        }
@@ -888,15 +866,14 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
 
                // Walk through all variables
                for ($idx = $this->varStack->getIterator(); $idx->valid(); $idx->next()) {
-
                        // Get current entry
                        $currEntry = $idx->current();
 
                        // Replace all [$var] or {?$var?} with the content
+                       //* DEBUG: */ echo "name=".$currEntry['name'].", value=<pre>".htmlentities($currEntry['value'])."</pre>\n";
                        $content = str_replace("\$content[".$currEntry['name']."]", $currEntry['value'], $content);
                        $content = str_replace("[".$currEntry['name']."]", $currEntry['value'], $content);
                        $content = str_replace("{?".$currEntry['name']."?}", $currEntry['value'], $content);
-
                } // END - for
 
                // Set the content back
@@ -928,7 +905,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         */
        public final function loadWebTemplate ($template) {
                // Set template type
-               $this->setTemplateType($this->getConfigInstance()->readConfig("web_template_type"));
+               $this->setTemplateType($this->getConfigInstance()->readConfig('web_template_type'));
 
                // Load the special template
                $this->loadTemplate($template);
@@ -943,7 +920,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         */
        public final function loadEmailTemplate ($template) {
                // Set template type
-               $this->setTemplateType($this->getConfigInstance()->readConfig("email_template_type"));
+               $this->setTemplateType($this->getConfigInstance()->readConfig('email_template_type'));
 
                // Load the special template
                $this->loadTemplate($template);
@@ -958,7 +935,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         */
        public final function loadCodeTemplate ($template) {
                // Set template type
-               $this->setTemplateType($this->getConfigInstance()->readConfig("code_template_type"));
+               $this->setTemplateType($this->getConfigInstance()->readConfig('code_template_type'));
 
                // Load the special template
                $this->loadTemplate($template);
@@ -971,7 +948,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         */
        public final function compileVariables () {
                // Initialize the $content array
-               $validVar = $this->getConfigInstance()->readConfig("tpl_valid_var");
+               $validVar = $this->getConfigInstance()->readConfig('tpl_valid_var');
                $dummy = array();
 
                // Iterate through all variables
@@ -981,6 +958,7 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                        $currVariable = $idx->current();
 
                        // 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
@@ -995,22 +973,67 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                unset($idx);
                unset($currVariable);
 
-               // Finalize the compilation of template variables
-               $this->finalizeVariableCompilation();
+               // Run the compilation twice to get content from helper classes in
+               $cnt = 0;
+               while ($cnt < 3) {
+                       // Finalize the compilation of template variables
+                       $this->finalizeVariableCompilation();
 
-               // Prepare the eval() command for comiling the template
-               $eval = sprintf("\$this->setCompiledData(\"%s\");",
-                       addslashes($this->getRawTemplateData())
-               );
+                       // Prepare the eval() command for comiling the template
+                       $eval = sprintf("\$result = \"%s\";",
+                               addslashes($this->getRawTemplateData())
+                       );
 
-               // Debug message
-               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",
-                       $this->__toString(),
-                       htmlentities($eval)
-               ));
+                       // This loop does remove the backslashes (\) in PHP parameters
+                       // @TODO Make this some nicer...
+                       while (strpos($eval, "<?") !== false) {
+                               // Get left part before "<?"
+                               $evalLeft = substr($eval, 0, strpos($eval, "<?"));
+
+                               // 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
+
+                               // Cut middle part out and remove escapes
+                               $evalMiddle = trim(substr($evalRight, 0, strpos($evalRight, "?>")));
+                               $evalMiddle = stripslashes($evalMiddle);
+
+                               // Remove the middle part from right one
+                               $evalRight = substr($evalRight, (strpos($evalRight, "?>") + 2));
+
+                               // And put all together
+                               $eval = sprintf("%s<%%php %s %%>%s", $evalLeft, $evalMiddle, $evalRight);
+                       } // END - while
+
+                       // Prepare PHP code for eval() command
+                       $eval = str_replace(
+                               "<%php", "\";",
+                               str_replace(
+                                       "%>", "\$result .= \"", $eval
+                               )
+                       );
+
+                       // Debug message
+                       if ((defined('DEBUG_EVAL')) && (is_object($this->getDebugInstance()))) $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
+                               $this->__toString(),
+                               htmlentities($eval)
+                       ));
+
+                       // Run the constructed command. This will "compile" all variables in
+                       eval($eval);
+
+                       // Set raw template data
+                       $this->setRawTemplateData($result);
+                       $cnt++;
+               }
 
-               // Run the constructed command. This will "compile" all variables in
-               eval($eval);
+               // Set the new content
+               $this->setCompiledData($result);
        }
 
        /**
@@ -1018,15 +1041,15 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
         *
         * @return      void
         * @throws      UnexpectedTemplateTypeException If the template type is
-        *                                                                              not "code"
+        *                                                                                      not "code"
         * @throws      InvalidArrayCountException              If an unexpected array
-        *                                                                              count has been found
+        *                                                                                      count has been found
         */
        public final function compileTemplate () {
                // We will only work with template type "code" from configuration
-               if ($this->getTemplateType() != $this->getConfigInstance()->readConfig("code_template_type")) {
+               if ($this->getTemplateType() != $this->getConfigInstance()->readConfig('code_template_type')) {
                        // Abort here
-                       throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig("code_template_type")), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
+                       throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->readConfig('code_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
                } // END - if
 
                // Get the raw data.
@@ -1168,6 +1191,23 @@ class TemplateEngine extends BaseFrameworkSystem implements CompileableTemplate
                // Get the content and set it in the response class
                $responseInstance->writeToBody($this->getCompiledData());
        }
+
+       /**
+        * Assigns all the application data with template variables
+        *
+        * @param       $appInstance    A manageable application instance
+        * @return      void
+        */
+       public function assignApplicationData (ManageableApplication $appInstance) {
+               // Get long name and assign it
+               $this->assignVariable("app_full_name" , $appInstance->getAppName());
+
+               // Get short name and assign it
+               $this->assignVariable("app_short_name", $appInstance->getAppShortName());
+
+               // Get version number and assign it
+               $this->assignVariable("app_version"   , $appInstance->getAppVersion());
+       }
 }
 
 // [EOF]