Subversion-Projekte lars-tiefland.php_share

Revision

Blame | Letzte Änderung | Log anzeigen | RSS feed

<?php
/* $Id: Easy_Templates.class.php 8 2007-04-24 14:17:50Z markus $ */

/**
 * Easy Templates parsing engine.
 * 
 * With this class you easily could handle template files
 * and parse the contents in it. A detailed documentation
 * you will find in the comments. Or in this DocBlock.
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Web_Contents
 * @package    Easy_Templates
 * @author     Markus Niewerth <markus@weban.de>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @since      File available since Release 1.0.1
 */
 
        /*
                Implementation von Klassen-basierter Programmierung. 
                Die neu Klasse Weban_Shop wird im späteren Verlauf mit 
                den Funktionen aus dem alten Shop Modul gefüllt, Somit 
                können alle Funktionen nach und nach ausgetauscht werden. 
                
                Zur Information: Es existieren noch keine extended Klassen, 
                alle benötigten Klassen eines Moduls werden in der Hauptklasse 
                instanziert und können dann auch über das $Weban_Shop Object 
                angesprochen werden.
        */
        
// {{{ constants
define("__CONSTRUCT_ERROR__",   "Can't load Template file: <strong>%s</strong>");
define("__ERROR_MESSAGE__",     "Keine ID bergeben, %s");
define("__RETURN_TEMPLATES__",  false);
// }}}
// {{{ GLOBALS
 
 // -------------------
 // IF any put in here!
 // -------------------
 
// }}}
// {{{ Easy_Templates

/**
 * Easy Templates parsing engine.
 * 
 * With this class you easily could handle template files
 * and parse the contents in it. A detailed documentation
 * you will find in the comments. Or in this DocBlock.
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Web_Contents
 * @package    Easy_Templates
 * @author     Markus Niewerth <markus@weban.de>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @since      File available since Release 1.0.1
 */
 
class Easy_Templates {

        // {{{ properties
        
        /**
        * @var   int   $SiteID
        * Seiten oder Status ID
        */
        var $SiteID;
        
        /**
        * @var   res   $fp
        * Resource fr den filestream
        */
        var $fp           =   '';
        
        /**
        * @var   array   $uncompiled
        * @var   array   $compiled
        * Eingabe und Ausgabe arrays
        */  
        var $uncompiled   =   array();
        var $compiled     =   array();
        
        /**
        * @var   int   $i                       Template zaehler, gibt die geladenen 
        * @var   int   $loaded          Zaehler array   
        * Uebertraegt den aktuellen Zaehler als einen Schluessel 
        */  
        var $i;
        var $loaded = array();
        
        /**
        * @var   int   $extension       
        * Template extension (sucht nach diesen endungen)       
        */    
        var $extension;
        
        /**
        * @var array $ctcscript
        * Beinhaltet template scripts, die
        * dynamisch zur Laufzeit ausgefhrt werden.
        * 
        */
        var $ctcscript = array();
        
        /**
        * @var string $parsed
        * Zu parsende CTC Script parts
        */
        var $parsed = "";
        
        /**
        * @var array $_cache         Cached templates
        * @var array $_evalcache     Parsed cached templates
        * 
        */
        var $_cache       = array();
        var $_evalcache   = array();
        
        /**
        * @var array $_cache
        * Cached templates
        */
        var $_loadtimes = array();
        
        // }}}
        // {{{ Easy_Templates()
        
        /**
        * Easy_Templates::Easy_Templates
        * C o n s t r u c t o r 
        * @param   $SiteID     Aktuelle Seite oder Kontext ID
        * @param   $extension  Die Template extension (zb. .tpl, .html usw.)
        */  
        function Easy_Templates($SiteID=0, $extension='.html')
        {
                if (empty($SiteID)) {
                        sprintf("Easy_Templates::Easy_Templates(".__ERROR_MESSAGE__.")", $extension);
                }
                $this->SiteID=$SiteID;
                $this->i=0; // templates loaded   
                $this->extension = $extension;
                
                $_loadtimes['start']    = array();
                $_loadtimes['end']      = array();
                
                // Definiert eine Methode und gleichzeitig auch die Funktion
                if (!function_exists('pre'))  {
                        function pre($arr) 
                        {
                                print("<pre>\n");
                                print_r($arr);
                                print("</pre>\n");
                        }   
                }
                if (!function_exists('microtime_float'))  {
                        function microtime_float() 
                        {
                                list($usec, $sec) = explode(" ", microtime());
                                return ((float)$usec + (float)$sec); 
                        }
                }  
                // {GLOBALS}[loaded]
        
        }
        
        // }}}
        // {{{ parse()  
        
        /**
        * @name parse
        * This Function uses a simple 
        * routine for executing small 
        * IF commands.
        * 
        * @param String $content  [The template file]
        * @param Bool   $fallback [not active atm]
        * @param Array  $args     [variables for the template execution]
        */
        function parse($content, $fallback=NULL, $args, $showPart=NULL, $delima = "{", $delimb = "}", $return=__RETURN_TEMPLATES__) 
        {
                global $loaded, $loadtime;
                
                $this->_loadtimes['start'][$this->i] = microtime_float();
                $__tmplpart = $showPart;
                
                extract($args, EXTR_OVERWRITE );
                        
                $this->parsed           = NULL;
                $this->cache            = NULL;
                $this->ctcscript        = NULL;
                $this->uncompiled       = NULL;
                $this->compiled         = NULL;
                
                /**
                 * Open the File Stream, to get 
                 * the template contents.
                 * We use @, cause we wanna have
                 * a clean template parser.
                 */
                $this->fp = @fopen($content. $this->extension, 'r');
                if (!$this->fp) {
                        $this->fp = @fopen($tplDir.$fallback.$this->extension, 'r');
                }
                if (!$this->fp) {
                        $show                   = "E_MESSAGE";
                        $E_MESSAGE              = sprintf(__CONSTRUCT_ERROR__,$content . $this->extension);
                        $this->cache    = "\n<!-- IF [show] 'E_MESSAGE' -->\n".$delima."E_MESSAGE".$delimb."\n<!-- ENDIF -->\n";
                }
                
                if ($this->fp) {
                        array_push ($this->loaded, $this->i);
                        /**
                         * Read the template contents
                         */             
                        $this->cache = fread($this->fp, filesize($content . $this->extension));
                        fclose($this->fp);
                }       
                
                /**
                 * Parse internal Functions
                 * called CTC Script.
                 * Its a simple IF construct.
                 * Example:
                 * <!-- IF [variable] 'value' -->
                 * TEMPLATE CONTENTS GOES HERE
                 * <!-- ENDIF -->
                 * NOTE: 
                 * The parser is not tested
                 * with normal HTML Comments.
                 * 
                 */
                
                /**
                 * @variable String $pcre 
                 * The Regular Expression to get 
                 * the template script executed.
                 * It cost me several hours for
                 * testing and executing. 
                 * Dieser Teil steuert die If Bedingungen in Kommentaren
                 * Siehe Kommentar weiter oben.
                 */
                $pcre = "/<!--[\s]{1,}IF[\s]{1,}\[([a-zA-Z0-9_]{1,})\][\s]{1,}\'([a-zA-Z0-9_]{1,})\'[\s]{1,}-->(.*)<!--[\s]{1,}ENDIF[\s]{1,}-->/sU";
                //$case = "/<!--[\s]{1,}CASE[\s]{1,}\[([a-zA-Z0-9]{1,})\][\s]{1,}\'([a-zA-Z0-9]{1,})\'[\s]{1,}-->(.*)<!--[\s]{1,}ENDCASE[\s]{1,}-->/sU";
                /**
                 * Execute the Regular Expression to
                 * handle CTC Template Script.
                 */             
                
                preg_match_all($pcre, $this->cache, $this->ctcscript);
                
                /**
                 * [1] => variables
                 * [2] => values
                 * [3] => html contents
                 */
                
                if (is_array($this->ctcscript[1])) {
                        foreach(array_keys($this->ctcscript[1]) AS $elem) {
                                $var = $this->ctcscript[1][$elem];
                                if ($$var==$this->ctcscript[2][$elem]) {
                                        $this->parsed .= $this->ctcscript[3][$elem];
                                }
                        }
                }
                
                        
                //      preg_match_all($case, $this->cache, $this->ctcscript);
                        
                        /**
                        * [1] => variables
                        * [2] => values
                        * [3] => html contents
                        */
                        
                //      if(is_array($this->ctcscript[1])) {
                //              foreach(array_keys($this->ctcscript[1]) AS $elem) {
                //                      $var = $this->ctcscript[1][$elem];
                //                      if($$var==$this->ctcscript[2][$elem]) {
                //                              $cases[] = $this->ctcscript[3][$elem];
                //                      }
                //              }
                //      }
                //pre($cases);
                
                
                
                $this->setTemplatesLoaded();
                // durch $delima und $delimb einstellbar
                // Standard Template Marker: { }
                $this->uncompiled = preg_replace("/($delima)(.*)($delimb)/U","$\\2", $this->parsed);                    
                
                // Standard String verarbeitung
                $this->compiled = addslashes($this->uncompiled);
                $this->compiled = "echo \"".trim($this->compiled)."\"";
                // entfernt ### durch '
                // ist fr die Ausgabe von Arrays zust�dig          
                $this->compiled = str_replace("###","'",$this->compiled);
                // Dieser Teil ist fr die Ausgabe von Arrays.
                // Syntax: %%.{arrayName}[0][key_x].%%
                $this->compiled = str_replace("%%.","\".",$this->compiled);
                $this->compiled = str_replace(".%%",".\"",$this->compiled);
                $this->_cache[] = $this->compiled;
                   
                ob_start();
                {
                        eval($this->compiled.";");
                                $ret_eval           = ob_get_contents();
                                $this->_evalcache[] = $ret_eval;
                        ob_end_clean();
                }
                
                $this->_loadtimes['end'][$this->i]      = microtime_float();
                $this->i++;
                $GLOBALS['loadtime']                            = $this->getLoadTimes();
        
                if ($return) {
                        return $ret_eval;
                } else {
                        print ($ret_eval);
                }
        }
        
        // }}}
        // {{{ parseFromCache() 
        
        function parseFromCache($part, $args) 
        {
                // Extract 
                extract ($args, EXTR_OVERWRITE);
                return  eval($this->_cache[$part].";");
        }
        
        // }}}
        // {{{ getLoadTimes()   
        
        function getLoadTimes()
        {
                $returnTime = null;
                if (count($this->_loadtimes['start']) == 0) {
                        return false;
                } else {
                        foreach(array_keys($this->_loadtimes['start']) AS $elem) {
                                $returnTime += $this->_loadtimes['end'][$elem] - $this->_loadtimes['start'][$elem];
                        }
                }
                $GLOBALS['loadtime'] = round($returnTime*100,4);
                return round($returnTime*100,4);
        }
        
        // }}}
        // {{{ setTemplatesLoaded()     
        
        function setTemplatesLoaded()
        {
                $GLOBALS['loaded'] = count($this->loaded);
        }
        
        // }}}
        // {{{ pre()
                
        function pre($array) 
        {
                print("<pre>");
                print_r($array);
                print("</pre>");
        }
        // }}}
}
// }}}
?>