cvs: pear /HTML_Template_IT IT.php ITX.php IT_Error.php package.xml

From: Date: Sun, 28 Apr 2002 07:16:05 +0000
Subject: cvs: pear /HTML_Template_IT IT.php ITX.php IT_Error.php package.xml
Groups: php.pear.cvs 
Request: Send a blank email to pear-cvs+get-3594@lists.php.net to get a copy of this message
sebastian Sun Apr 28 03:16:05 2002 EDT Added files: /pear/HTML_Template_IT IT.php ITX.php IT_Error.php package.xml Log: Move IT[X] to /pear.

Index: pear/HTML_Template_IT/IT.php +++ pear/HTML_Template_IT/IT.php <?php // // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2002 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Ulf Wendel <ulf.wendel@phpdoc.de> | // +----------------------------------------------------------------------+ // // $Id: IT.php,v 1.1 2002/04/28 07:16:05 sebastian Exp $ // require_once('HTML/IT_Error.php'); /** * Integrated Template - IT * * Well there's not much to say about it. I needed a template class that * supports a single template file with multiple (nested) blocks inside and * a simple block API. * * The Isotemplate API is somewhat tricky for a beginner although it is the best * one you can build. template::parse() [phplib template = Isotemplate] requests * you to name a source and a target where the current block gets parsed into. * Source and target can be block names or even handler names. This API gives you * a maximum of fexibility but you always have to know what you do which is * quite unusual for php skripter like me. * * I noticed that I do not any control on which block gets parsed into which one. * If all blocks are within one file, the script knows how they are nested and in * which way you have to parse them. IT knows that inner1 is a child of block2, there's * no need to tell him about this. * * <table border> * <tr> * <td colspan=2> * __global__ * <p> * (hidden and automatically added) * </td> * </tr> * <tr> * <td>block1</td> * <td> * <table border> * <tr> * <td colspan=2>block2</td> * </tr> * <tr> * <td>inner1</td> * <td>inner2</td> * </tr> * </table> * </td> * </tr> * </table> * * To add content to block1 you simply type: * <code>$tpl->setCurrentBlock("block1");</code> * and repeat this as often as needed: * <code> * $tpl->setVariable(...); * $tpl->parseCurrentBlock(); * </code> * * To add content to block2 you would type something like: * <code> * $tpl->setCurrentBlock("inner1"); * $tpl->setVariable(...); * $tpl->parseCurrentBlock(); * * $tpl->setVariable(...); * $tpl->parseCurrentBlock(); * * $tpl->parse("block1"); * </code> * * This will result in one repition of block1 which contains two repitions * of inner1. inner2 will be removed if $removeEmptyBlock is set to true which is the default. * * Usage: * <code> * $tpl = new IntegratedTemplate( [string filerootdir] ); * * // load a template or set it with setTemplate() * $tpl->loadTemplatefile( string filename [, boolean removeUnknownVariables, boolean removeEmptyBlocks] ) * * // set "global" Variables meaning variables not beeing within a (inner) block * $tpl->setVariable( string variablename, mixed value ); * * // like with the Isotemplates there's a second way to use setVariable() * $tpl->setVariable( array ( string varname => mixed value ) ); * * // Let's use any block, even a deeply nested one * $tpl->setCurrentBlock( string blockname ); * * // repeat this as often as you need it. * $tpl->setVariable( array ( string varname => mixed value ) ); * $tpl->parseCurrentBlock(); * * // get the parsed template or print it: $tpl->show() * $tpl->get(); * </code> * * @author Ulf Wendel <uw@netuse.de> * @version $Id: IT.php,v 1.1 2002/04/28 07:16:05 sebastian Exp $ * @access public * @package IX[X] */ class IntegratedTemplate { /** * Contains the error objects * @var array * @access public * @see halt(), $printError, $haltOnError */ var $err = array(); /** * Clear cache on get()? * @var boolean */ var $clearCache = false; /** * First character of a variable placeholder ( _{_VARIABLE} ). * @var string * @access public * @see $closingDelimiter, $blocknameRegExp, $variablenameRegExp */ var $openingDelimiter = "{"; /** * Last character of a variable placeholder ( {VARIABLE_}_ ). * @var string * @access public * @see $openingDelimiter, $blocknameRegExp, $variablenameRegExp */ var $closingDelimiter = "}"; /** * RegExp matching a block in the template. * Per default "sm" is used as the regexp modifier, "i" is missing. * That means a case sensitive search is done. * @var string * @access public * @see $variablenameRegExp, $openingDelimiter, $closingDelimiter */ var $blocknameRegExp = "[0-9A-Za-z_-]+"; /** * RegExp matching a variable placeholder in the template. * Per default "sm" is used as the regexp modifier, "i" is missing. * That means a case sensitive search is done. * @var string * @access public * @see $blocknameRegExp, $openingDelimiter, $closingDelimiter */ var $variablenameRegExp = "[0-9A-Za-z_-]+"; /** * RegExp used to find variable placeholder, filled by the constructor. * @var string Looks somewhat like @(delimiter varname delimiter)@ * @access public * @see IntegratedTemplate() */ var $variablesRegExp = ""; /** * RegExp used to strip unused variable placeholder. * @brother $variablesRegExp */ var $removeVariablesRegExp = ""; /** * Controls the handling of unknown variables, default is remove. * @var boolean * @access public */ var $removeUnknownVariables = true; /** * Controls the handling of empty blocks, default is remove. * @var boolean * @access public */ var $removeEmptyBlocks = true; /** * RegExp used to find blocks an their content, filled by the constructor. * @var string * @see IntegratedTemplate() */ var $blockRegExp = ""; /** * Name of the current block. * @var string */ var $currentBlock = "__global__"; /** * Content of the template. * @var string */ var $template = ""; /** * Array of all blocks and their content. * * @var array * @see findBlocks() */ var $blocklist = array(); /** * Array with the parsed content of a block. * * @var array */ var $blockdata = array(); /** * Array of variables in a block. * @var array */ var $blockvariables = array(); /** * Array of inner blocks of a block. * @var array */ var $blockinner = array(); /** * List of blocks to preverse even if they are "empty". * * This is something special. Sometimes you have blocks that * should be preserved although they are empty (no placeholder replaced). * Think of a shopping basket. If it's empty you have to drop a message to * the user. If it's filled you have to show the contents of the shopping baseket. * Now where do you place the message that the basket is empty? It's no good * idea to place it in you applications as customers tend to like unecessary minor * text changes. Having another template file for an empty basket means that it's * very likely that one fine day the filled and empty basket templates have different * layout. I decided to introduce blocks that to not contain any placeholder but only * text such as the message "Your shopping basked is empty". * * Now if there is no replacement done in such a block the block will be recognized * as "empty" and by default ($removeEmptyBlocks = true) be stripped off. To avoid this * you can now call touchBlock() to avoid this. * * The array $touchedBlocks stores a list of touched block which must not be removed even * if they are empty. * * @var array $touchedBlocks * @see touchBlock(), $removeEmptyBlocks */ var $touchedBlocks = array(); /** * Variable cache. * * Variables get cached before any replacement is done. * Advantage: empty blocks can be removed automatically. * Disadvantage: might take some more memory * * @var array * @see setVariable(), $clearCacheOnParse */ var $variableCache = array(); /** * Clear the variable cache on parse? * * If you're not an expert just leave the default false. * True reduces memory consumption somewhat if you tend to * add lots of values for unknown placeholder. * * @var boolean */ var $clearCacheOnParse = false; /** * Root directory for all file operations. * The string gets prefixed to all filenames given. * @var string * @see IntegratedTemplate(), setRoot() */ var $fileRoot = ""; /** * Internal flag indicating that a blockname was used multiple times. * @var boolean */ var $flagBlocktrouble = false; /** * Flag indicating that the global block was parsed. * @var boolean */ var $flagGlobalParsed = false; /** * EXPERIMENTAL! FIXME! * Flag indication that a template gets cached. * * Complex templates require some times to be preparsed * before the replacement can take place. Often I use * one template file over and over again but I don't know * before that I will use the same template file again. * Now IT could notice this and skip the preparse. * * @var boolean */ var $flagCacheTemplatefile = true; /** * EXPERIMENTAL! FIXME! */ var $lastTemplatefile = ""; /** * Builds some complex regular expressions and optinally sets the file root directory. * * Make sure that you call this constructor if you derive your template * class from this one. * * @param string File root directory, prefix for all filenames given to the object. * @see setRoot() */ function IntegratedTemplate($root = "") { $this->variablesRegExp = "@" . $this->openingDelimiter . "(" . $this->variablenameRegExp . ")" . $this->closingDelimiter . "@sm"; $this->removeVariablesRegExp = "@" . $this->openingDelimiter . "\s*(" . $this->variablenameRegExp . ")\s*" . $this->closingDelimiter . "@sm"; $this->blockRegExp = '@<!--\s+BEGIN\s+(' . $this->blocknameRegExp . ')\s+-->(.*)<!--\s+END\s+\1\s+-->@sm'; $this->setRoot($root); } // end constructor /** * Print a certain block with all replacements done. * @brother get() */ function show($block = "__global__") { print $this->get($block); } // end func show /** * Returns a block with all replacements done. * * @param string name of the block * @return string * @throws IT_Error * @access public * @see show() */ function get($block = "__global__") { if ("__global__" == $block && !$this->flagGlobalParsed) $this->parse("__global__"); if (!isset($this->blocklist[$block])) { new IT_Error("The block '$block' was not found in the template.", __FILE__, __LINE__); return ""; } if ($this->clearCache) { $data = (isset($this->blockdata[$block])) ? $this->blockdata[$block] : ""; unset($this->blockdata[$block]); return $data; } else { return (isset($this->blockdata[$block])) ? $this->blockdata[$block] : ""; } } // end func get() /** * Parses the given block. * * @param string name of the block to be parsed * @access public * @see parseCurrentBlock() * @throws IT_Error */ function parse($block = "__global__", $flag_recursion = false) { if (!isset($this->blocklist[$block])) { return new IT_Error("The block '$block' was not found in the template.", __FILE__, __LINE__); return false; } if ("__global__" == $block) $this->flagGlobalParsed = true; $regs = array(); $values = array(); if ($this->clearCacheOnParse) { foreach ($this->variableCache as $name => $value) { $regs[] = "@" . $this->openingDelimiter . $name . $this->closingDelimiter . "@"; $values[] = $value; } $this->variableCache = array(); } else { foreach ($this->blockvariables[$block] as $allowedvar => $v) { if (isset($this->variableCache[$allowedvar])) { $regs[] = "@".$this->openingDelimiter . $allowedvar . $this->closingDelimiter . "@"; $values[] = $this->variableCache[$allowedvar]; unset($this->variableCache[$allowedvar]); } } } $outer = (0 == count($regs)) ? $this->blocklist[$block] : preg_replace($regs, $values, $this->blocklist[$block]); $empty = (0 == count($values)) ? true : false; if (isset($this->blockinner[$block])) { foreach ($this->blockinner[$block] as $k => $innerblock) { $this->parse($innerblock, true); if ("" != $this->blockdata[$innerblock]) $empty = false; $placeholder = $this->openingDelimiter . "__" . $innerblock . "__" . $this->closingDelimiter; $outer = str_replace($placeholder, $this->blockdata[$innerblock], $outer); $this->blockdata[$innerblock] = ""; } } if ($this->removeUnknownVariables) $outer = preg_replace($this->removeVariablesRegExp, "", $outer); if ($empty) { if (!$this->removeEmptyBlocks) { $this->blockdata[$block ].= $outer; } else { if (isset($this->touchedBlocks[$block])) { $this->blockdata[$block] .= $outer; unset($this->touchedBlocks[$block]); } } } else { $this->blockdata[$block] .= $outer; } return $empty; } // end func parse /** * Parses the current block * @see parse(), setCurrentBlock(), $currentBlock * @access public */ function parseCurrentBlock() { return $this->parse($this->currentBlock); } // end func parseCurrentBlock /** * Sets a variable value. * * The function can be used eighter like setVariable( "varname", "value") * or with one array $variables["varname"] = "value" given setVariable($variables) * quite like phplib templates set_var(). * * @param mixed string with the variable name or an array %variables["varname"] = "value" * @param string value of the variable or empty if $variable is an array. * @param string prefix for variable names * @access public */ function setVariable($variable, $value = "") { if (is_array($variable)) { $this->variableCache = array_merge($this->variableCache, $variable); } else { $this->variableCache[$variable] = $value; } } // end func setVariable /** * Sets the name of the current block that is the block where variables are added. * * @param string name of the block * @return boolean false on failure, otherwise true * @throws IT_Error * @access public */ function setCurrentBlock($block = "__global__") { if (!isset($this->blocklist[$block])) return new IT_Error("Can't find the block '$block' in the template.", __FILE__, __LINE__); $this->currentBlock = $block; return true; } // end func setCurrentBlock /** * Preserves an empty block even if removeEmptyBlocks is true. * * @param string name of the block * @return boolean false on false, otherwise true * @throws IT_Error * @access public * @see $removeEmptyBlocks */ function touchBlock($block) { if (!isset($this->blocklist[$block])) return new IT_Error("Can't find the block '$block' in the template.", __FILE__, __LINE__); $this->touchedBlocks[$block] = true; return true; } // end func touchBlock /** * Clears all datafields of the object and rebuild the internal blocklist * * LoadTemplatefile() and setTemplate() automatically call this function * when a new template is given. Don't use this function * unless you know what you're doing. * * @access public * @see free() */ function init() { $this->free(); $this->findBlocks($this->template); // we don't need it any more $this->template = ''; $this->buildBlockvariablelist(); } // end func init /** * Clears all datafields of the object. * * Don't use this function unless you know what you're doing. * * @access public * @see init() */ function free() { $this->err = array(); $this->currentBlock = "__global__"; $this->variableCache = array(); $this->blocklookup = array(); $this->touchedBlocks = array(); $this->flagBlocktrouble = false; $this->flagGlobalParsed = false; } // end func free /** * Sets the template. * * You can eighter load a template file from disk with LoadTemplatefile() or set the * template manually using this function. * * @param string template content * @param boolean remove unknown/unused variables? * @param boolean remove empty blocks? * @see LoadTemplatefile(), $template * @access public */ function setTemplate($template, $removeUnknownVariables = true, $removeEmptyBlocks = true) { $this->removeUnknownVariables = $removeUnknownVariables; $this->removeEmptyBlocks = $removeEmptyBlocks; if ("" == $template && $this->flagCacheTemplatefile) { $this->variableCache = array(); $this->blockdata = array(); $this->touchedBlocks = array(); $this->currentBlock = "__global__"; } else { $this->template = '<!-- BEGIN __global__ -->' . $template . '<!-- END __global__ -->'; $this->init(); } if ($this->flagBlocktrouble) return false; return true; } // end func setTemplate /** * Reads a template file from the disk. * * @param string name of the template file * @param bool how to handle unknown variables. * @param bool how to handle empty blocks. * @access public * @return boolean false on failure, otherwise true * @see $template, setTemplate(), $removeUnknownVariables, $removeEmptyBlocks */ function loadTemplatefile($filename, $removeUnknownVariables = true, $removeEmptyBlocks = true) { $template = ""; if (!$this->flagCacheTemplatefile || $this->lastTemplatefile != $filename) $template = $this->getfile($filename); $this->lastTemplatefile = $filename; return $this->setTemplate($template, $removeUnknownVariables, $removeEmptyBlocks); } // end func LoadTemplatefile /** * Sets the file root. The file root gets prefixed to all filenames passed to the object. * * Make sure that you override this function when using the class * on windows. * * @param string * @see IntegratedTemplate() * @access public */ function setRoot($root) { if ("" != $root && "/" != substr($root, -1)) $root .= "/"; $this->fileRoot = $root; } // end func setRoot /** * Build a list of all variables within of a block */ function buildBlockvariablelist() { foreach ($this->blocklist as $name => $content) { preg_match_all( $this->variablesRegExp, $content, $regs ); if (0 != count($regs[1])) { foreach ($regs[1] as $k => $var) $this->blockvariables[$name][$var] = true; } else { $this->blockvariables[$name] = array(); } } } // end func buildBlockvariablelist /** * Returns a list of all */ function getGlobalvariables() { $regs = array(); $values = array(); foreach ($this->blockvariables["__global__"] as $allowedvar => $v) { if (isset($this->variableCache[$allowedvar])) { $regs[] = "@" . $this->openingDelimiter . $allowedvar . $this->closingDelimiter."@"; $values[] = $this->variableCache[$allowedvar]; unset($this->variableCache[$allowedvar]); } } return array($regs, $values); } // end func getGlobalvariables /** * Recusively builds a list of all blocks within the template. * * @param string string that gets scanned * @see $blocklist */ function findBlocks($string) { $blocklist = array(); if (preg_match_all($this->blockRegExp, $string, $regs, PREG_SET_ORDER)) { foreach ($regs as $k => $match) { $blockname = $match[1]; $blockcontent = $match[2]; if (isset($this->blocklist[$blockname])) { new IT_Error("The name of a block must be unique within a template. Found '$blockname' twice. Unpredictable results may appear.", __FILE__, __LINE__); $this->flagBlocktrouble = true; } $this->blocklist[$blockname] = $blockcontent; $this->blockdata[$blockname] = ""; $blocklist[] = $blockname; $inner = $this->findBlocks($blockcontent); foreach ($inner as $k => $name) { $pattern = sprintf('@<!--\s+BEGIN\s+%s\s+-->(.*)<!--\s+END\s+%s\s+-->@sm', $name, $name ); $this->blocklist[$blockname] = preg_replace( $pattern, $this->openingDelimiter . "__" . $name . "__" . $this->closingDelimiter, $this->blocklist[$blockname] ); $this->blockinner[$blockname][] = $name; $this->blockparents[$name] = $blockname; } } } return $blocklist; } // end func findBlocks /** * Reads a file from disk and returns its content. * @param string Filename * @return string Filecontent */ function getFile($filename) { if ("/" == $filename{0} && "/" == substr($this->fileRoot, -1)) $filename = substr($filename, 1); $filename = $this->fileRoot . $filename; if (!($fh = @fopen($filename, "r"))) { new IT_Error("Can't read '$filename'.", __FILE__, __LINE__); return ""; } $content = fread($fh, filesize($filename)); fclose($fh); return preg_replace("#<!-- INCLUDE (.*) -->#ime", "\$this->getFile('\\1')", $content); } // end func getFile } // end class IntegratedTemplate ?> Index: pear/HTML_Template_IT/ITX.php +++ pear/HTML_Template_IT/ITX.php <?php // // +----------------------------------------------------------------------+ // | PHP version 4.0 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2001 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Ulf Wendel <ulf.wendel@phpdoc.de> | // +----------------------------------------------------------------------+ // // $Id: ITX.php,v 1.1 2002/04/28 07:16:05 sebastian Exp $ // require_once('HTML/IT.php'); /** * Integrated Template Extension - ITX * * With this class you get the full power of the phplib template class. * You may have one file with blocks in it but you have as well one main file * and multiple files one for each block. This is quite usefull when you have * user configurable websites. Using blocks not in the main template allows * you to modify some parts of your layout easily. * * Note that you can replace an existing block and add new blocks at runtime. * Adding new blocks means changing a variable placeholder to a block. * * @author Ulf Wendel <uw@netuse.de> * @access public * @version $Id: ITX.php,v 1.1 2002/04/28 07:16:05 sebastian Exp $ * @package IT[X] */ class IntegratedTemplateExtension extends IntegratedTemplate { /** * Array with all warnings. * @var array * @access public * @see $printWarning, $haltOnWarning, warning() */ var $warn = array(); /** * Print warnings? * @var array * @access public * @see $haltOnWarning, $warn, warning() */ var $printWarning = false; /** * Call die() on warning? * @var boolean * @access public * @see $warn, $printWarning, warning() */ var $haltOnWarning = false; /** * RegExp used to test for a valid blockname. * @var string */ var $checkblocknameRegExp = ''; /** * Functionnameprefix used when searching function calls in the template. * @var string */ var $functionPrefix = 'func_'; /** * Functionname RegExp. * @var string */ var $functionnameRegExp = '[_a-zA-Z]+[A-Za-z_0-9]*'; /** * RegExp used to grep function calls in the template. * * The variable gets set by the constructor. * * @var string * @see IntegratedTemplateExtension() */ var $functionRegExp = ''; /** * List of functions found in the template. * * @var array */ var $functions = array(); /** * List of callback functions specified by the user. * * @var array */ var $callback = array(); /** * Builds some complex regexps and calls the constructor of the parent class. * * Make sure that you call this constructor if you derive your own * template class from this one. * * @see IntegratedTemplate() */ function IntegratedTemplateExtension($root = '') { $this->checkblocknameRegExp = '@' . $this->blocknameRegExp . '@'; $this->functionRegExp = '@' . $this->functionPrefix . '(' . $this->functionnameRegExp . ')\s*\(@sm'; $this->IntegratedTemplate($root); } // end func constructor function init() { $this->free(); $this->buildFunctionlist(); $this->findBlocks($this->template); // we don't need it any more $this->template = ''; $this->buildBlockvariablelist(); } // end func init /** * Replaces an existing block with new content. * * This function will replace a block of the template and all blocks contained in * the replaced block and add a new block insted, means you can dynamically change your * template. * * Note that changing the template structure violates one of the IT[X] development * goals. I've tried to write a simple to use template engine supporting blocks. * In contrast to other systems IT[X] analyses the way you've nested blocks and knows * which block belongs into another block. The nesting information helps to make the API * short and simple. Replacing blocks does not only mean that IT[X] has to update * the nesting information (relatively time consumpting task) but you have to * make sure that you do not get confused due to the template change itself. * * @param string Blockname * @param string Blockcontent * @param boolean true if the new block inherits the content of the old block * @return boolean * @throws IT_Error * @see replaceBlockfile(), addBlock(), addBlockfile() * @access public */ function replaceBlock($block, $template, $keep_content = false) { if (!isset($this->blocklist[$block])) return new IT_Error("The block '$block' does not exist in the template and thus it can't be replaced.", __FILE__, __LINE__); if ('' == $template) return new IT_Error('No block content given.', __FILE__, __LINE__); if ($keep_content) $blockdata = $this->blockdata[$block]; // remove all kinds of links to the block / data of the block $this->removeBlockData($block); $template = "<!-- BEGIN $block -->" . $template . "<!-- END $block -->"; $parents = $this->blockparents[$block]; $this->findBlocks($template); $this->blockparents[$block] = $parents; // KLUDGE: rebuild the list for all block - could be done faster $this->buildBlockvariablelist(); if ($keep_content) $this->blockdata[$block] = $blockdata; // old TODO - I'm not sure if we need this // update caches return true; } // end func replaceBlock /** * Replaces an existing block with new content from a file. Warning: not implemented yet. * @brother replaceBlock() * @param string Blockname * @param string Name of the file that contains the blockcontent * @param boolean true if the new block inherits the content of the old block */ function replaceBlockfile($block, $filename, $keep_content = false) { return $this->replaceBlock($block, $this->getFile($filename)); } // end func replaceBlockfile /** * Adds a block to the template changing a variable placeholder to a block placeholder. * * Add means "replace a variable placeholder by a new block". * This is different to PHPLibs templates. The function loads a * block, creates a handle for it and assigns it to a certain * variable placeholder. To to the same with PHPLibs templates you would * call set_file() to create the handle and parse() to assign the * parsed block to a variable. By this PHPLibs templates assume that you tend * to assign a block to more than one one placeholder. To assign a parsed block * to more than only the placeholder you specify in this function you have * to use a combination of getBlock() and setVariable(). * * As no updates to cached data is necessary addBlock() and addBlockfile() * are rather "cheap" meaning quick operations. * * The block content must not start with <!-- BEGIN blockname --> and end with * <!-- END blockname --> this would cause overhead and produce an error. * * @param string Name of the variable placeholder, the name must be unique within the template. * @param string Name of the block to be added * @param string Content of the block * @return boolean * @throws IT_Error * @see addBlockfile() * @access public */ function addBlock($placeholder, $blockname, $template) { // Don't trust any user even if it's a programmer or yourself... if ('' == $placeholder) { return new IT_Error('No variable placeholder given.', __FILE__, __LINE__); } else if ('' == $blockname || !preg_match($this->checkblocknameRegExp, $blockname) ) { return new IT_Error("No or invalid blockname '$blockname' given.", __FILE__, __LINE__); } else if ('' == $template) { return new IT_Error('No block content given.', __FILE__, __LINE__); } else if (isset($this->blocklist[$blockname])) { return new IT_Error('The block already exists.', __FILE__, __LINE__); } // find out where to insert the new block $parents = $this->findPlaceholderBlocks($placeholder); if (0 == count($parents)) { return new IT_Error("The variable placeholder '$placeholder' was not found in the template.", __FILE__, __LINE__); } else if ( count($parents) > 1 ) { reset($parents); while (list($k, $parent) = each($parents)) $msg .= "$parent, "; $msg = substr($parent, -2); return new IT_Error("The variable placeholder '$placeholder' must be unique, found in multiple blocks '$msg'.", __FILE__, __LINE__); } $template = "<!-- BEGIN $blockname -->" . $template . "<!-- END $blockname -->"; $this->findBlocks($template); if ($this->flagBlocktrouble) return false; // findBlocks() already throws an exception $this->blockinner[$parents[0]][] = $blockname; $this->blocklist[$parents[0]] = preg_replace('@' . $this->openingDelimiter . $placeholder . $this->closingDelimiter . '@', $this->openingDelimiter . '__' . $blockname . '__' . $this->closingDelimiter, $this->blocklist[$parents[0]] ); $this->deleteFromBlockvariablelist($parents[0], $placeholder); $this->updateBlockvariablelist($blockname); /* // check if any inner blocks were found if(is_array($this->blockinner[$blockname]) and count($this->blockinner[$blockname]) > 0) { // loop through inner blocks, registering the variable placeholders in each foreach($this->blockinner[$blockname] as $childBlock) { $this->updateBlockvariablelist($childBlock); } } */ return true; } // end func addBlock /** * Adds a block taken from a file to the template changing a variable placeholder to a block placeholder. * * @param string Name of the variable placeholder to be converted * @param string Name of the block to be added * @param string File that contains the block * @brother addBlock() */ function addBlockfile($placeholder, $blockname, $filename) { return $this->addBlock($placeholder, $blockname, $this->getFile($filename)); } // end func addBlockfile /** * Returns the name of the (first) block that contains the specified placeholder. * * @param string Name of the placeholder you're searching * @param string Name of the block to scan. If left out (default) all blocks are scanned. * @return string Name of the (first) block that contains the specified placeholder. * If the placeholder was not found or an error occured an empty string is returned. * @throws IT_Error * @access public */ function placeholderExists($placeholder, $block = '') { if ('' == $placeholder) { new IT_Error('No placeholder name given.', __FILE__, __LINE__); return ''; } if ('' != $block && !isset($this->blocklist[$block])) { new IT_Error("Unknown block '$block'.", __FILE__, __LINE__); return ''; } // name of the block where the given placeholder was found $found = ''; if ('' != $block) { if (is_array($variables = $this->blockvariables[$block])) { // search the value in the list of blockvariables reset($variables); while (list($k, $variable) = each($variables)) if ($variable == $placeholder) { $found = $block; break; } } } else { // search all blocks and return the name of the first block that // contains the placeholder reset($this->blockvariables); while (list($blockname, $variables) = each($this->blockvariables)) { reset($variables); while (list($k, $variable) = each($variables)) if ($variable == $placeholder) { $found = $blockname; break 2; } } } return $found; } // end func placeholderExists /** * Checks the list of function calls in the template and calls their callback function. * * @access public */ function performCallback() { reset($this->functions); while (list($func_id, $function) = each($this->functions)) { if (isset($this->callback[$function['name']])) { if ('' != $this->callback[$function['name']]['object']) { $this->variableCache['__function' . $func_id . '__'] = call_user_method( $this->callback[$function['name']]['function'], $GLOBALS[$this->callback[$function['name']]['object']], $function['args'] ); } else { $this->variableCache['__function' . $func_id . '__'] = call_user_func( $this->callback[$function['name']]['function'], $function['args'] ); } } } } // end func performCallback /** * Returns a list of all function calls in the current template. * * @return array * @access public */ function getFunctioncalls() { return $this->functions; } // end func getFunctioncalls /** * Replaces a function call with the given replacement. * * @param int Function ID * @param string Replacement * @deprec */ function setFunctioncontent($functionID, $replacement) { $this->variableCache['__function' . $functionID . '__'] = $replacement; } // end func setFunctioncontent /** * Sets a callback function. * * IT[X] templates (note the X) can contain simple function calls. * "function call" means that the editor of the template can add * special placeholder to the template like 'func_h1("embedded in h1")'. * IT[X] will grab this function calls and allow you to define a callback * function for them. * * This is an absolutely evil feature. If your application makes heavy * use of such callbacks and you're even implementing if-then etc. on * the level of a template engine you're reiventing the wheel... - that's * actually how PHP came into life. Anyway, sometimes it's handy. * * Consider also using XML/XSLT or native PHP. And please do not push * IT[X] any further into this direction of adding logics to the template * engine. * * For those of you ready for the X in IT[X]: * * <?php * ... * function h_one($args) { * return sprintf('<h1>%s</h1>', $args[0]); * } * * ... * $itx = new IntegratedTemplateExtension( ... ); * ... * $itx->setCallbackFunction('h1', 'h_one'); * $itx->performCallback(); * ?> * * template: * func_h1('H1 Headline'); * * @param string Function name in the template * @param string Name of the callback function * @param string Name of the callback object * @return boolean False on failure. * @throws IT_Error * @access public */ function setCallbackFunction($tplfunction, $callbackfunction, $callbackobject = '') { if ('' == $tplfunction || '' == $callbackfunction) return new IT_Error("No template function ('$tplfunction') and/or no callback function ('$callback') given.", __FILE__, __LINE__); $this->callback[$tplfunction] = array( "function" => $callbackfunction, "object" => $callbackobject ); return true; } // end func setCallbackFunction /** * Sets the Callback function lookup table * * @param array function table - array[templatefunction] = array( "function" => userfunction, "object" => userobject ) * @access public */ function setCallbackFuntiontable($functions) { $this->callback = $functions; } // end func setCallbackFunctiontable /** * Recursively removes all data assiciated with a block, including all inner blocks * * @param string block to be removed */ function removeBlockData($block) { if (isset($this->blockinner[$block])) { foreach ($this->blockinner[$block] as $k => $inner) $this->removeBlockData($inner); unset($this->blockinner[$block]); } unset($this->blocklist[$block]); unset($this->blockdata[$block]); unset($this->blockvariables[$block]); unset($this->touchedBlocks[$block]); } // end func removeBlockinner /** * Returns a list of blocknames in the template. * * @return array [blockname => blockname] * @access public * @see blockExists() */ function getBlocklist() { $blocklist = array(); foreach ($this->blocklist as $block => $content) $blocklist[$block] = $block; return $blocklist; } // end func getBlocklist /** * Checks wheter a block exists. * * @param string * @return boolean * @access public * @see getBlocklist() */ function blockExists($blockname) { return isset($this->blocklist[$blockname]); } // end func blockExists /** * Returns a list of variables of a block. * * @param string Blockname * @return array [varname => varname] * @access public * @see BlockvariableExists() */ function getBlockvariables($block) { if (!isset($this->blockvariables[$block])) return array(); $variables = array(); foreach ($this->blockvariables[$block] as $variable => $v) { $variables[$variable] = $variable; } return $variables; } // end func getBlockvariables /** * Checks wheter a block variable exists. * * @param string Blockname * @param string Variablename * @return boolean * @access public * @see getBlockvariables() */ function BlockvariableExists($block, $variable) { return isset($this->blockvariables[$block][$variable]); } // end func BlockvariableExists /** * Builds a functionlist from the template. */ function buildFunctionlist() { $this->functions = array(); $template = $this->template; $num = 0; while (preg_match($this->functionRegExp, $template, $regs)) { $pos = strpos($template, $regs[0]); $template = substr($template, $pos + strlen($regs[0])); $head = $this->getValue($template, ')'); $args = array(); $this->template = str_replace($regs[0] . $head . ')', '{__function' . $num . '__}', $this->template); $template = str_replace($regs[0] . $head . ')', '{__function' . $num . '__}', $template); while ('' != $head && $arg = $this->getValue($head, ',')) { $arg2 = trim($args2); $args[] = ('"' == $arg2{0} || "'" == $arg2{0}) ? substr($arg2, 1, -1) : $arg2; if ($arg == $head) break; $head = substr($head, strlen($arg) + 1); } $this->functions[$num++] = array( 'name' => $regs[1], 'args' => $args ); } } // end func buildFunctionlist function getValue($code, $delimiter) { if ('' == $code) return ''; if (!is_array($delimiter)) $delimiter = array( $delimiter => true ); $len = strlen($code); $enclosed = false; $enclosed_by = ''; if (isset($delimiter[$code[0]])) { $i = 1; } else { for ($i = 0; $i < $len; ++$i) { $char = $code[$i]; if (('"' == $char || "'" == $char) && ($char == $enclosed_by || '' == $enclosed_by) && (0 == $i || ($i > 0 && '\\' != $code[$i - 1]))) { if (!$enclosed) $enclosed_by = $char; else $enclosed_by = ""; $enclosed = !$enclosed; } if (!$enclosed && isset($delimiter[$char])) break; } } return substr($code, 0, $i); } // end func getValue /** * Deletes one or many variables from the block variable list. * * @param string Blockname * @param mixed Name of one variable or array of variables ( array ( name => true ) ) to be stripped. */ function deleteFromBlockvariablelist($block, $variables) { if (!is_array($variables)) $variables = array($variables => true); reset($this->blockvariables[$block]); while (list($varname, $val) = each($this->blockvariables[$block])) if (isset($variables[$varname])) unset($this->blockvariables[$block][$varname]); } // end deleteFromBlockvariablelist /** * Updates the variable list of a block. * * @param string Blockname */ function updateBlockvariablelist($block) { preg_match_all( $this->variablesRegExp, $this->blocklist[$block], $regs ); if (0 != count($regs[1])) { foreach ($regs[1] as $k => $var) { $this->blockvariables[$block][$var] = true; } } else { $this->blockvariables[$block] = array(); } // check if any inner blocks were found if (isset($this->blockinner[$block]) and is_array($this->blockinner[$block]) and count($this->blockinner[$block]) > 0) { // loop through inner blocks, registering the variable placeholders in each foreach($this->blockinner[$block] as $childBlock) { $this->updateBlockvariablelist($childBlock); } } } // end func updateBlockvariablelist /** * Returns an array of blocknames where the given variable placeholder is used. * * @param string Variable placeholder * @return array $parents parents[0..n] = blockname */ function findPlaceholderBlocks($variable) { $parents = array(); reset($this->blocklist); while (list($blockname, $content) = each($this->blocklist)) { reset($this->blockvariables[$blockname]); while (list($varname, $val) = each($this->blockvariables[$blockname])) { if ($variable == $varname) { $parents[] = $blockname; } } } return $parents; } // end func findPlaceholderBlocks /** * Handles warnings, saves them to $warn and prints them or calls die() depending on the flags * @param string Warning * @param string File where the warning occured * @param int Linenumber where the warning occured * @see $warn, $printWarning, $haltOnWarning */ function warning($message, $file = '', $line = 0) { $message = sprintf('IntegratedTemplateExtension Warning: %s [File: %s, Line: %d]', $message, $file, $line ); $this->warn[] = $message; if ($this->printWarning) print $message; if ($this->haltOnError) die($message); } // end func warning } // end class IntegratedTemplateExtension ?> Index: pear/HTML_Template_IT/IT_Error.php +++ pear/HTML_Template_IT/IT_Error.php <?php // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.0 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Ulf Wendel <ulf.wendel@phpdoc.de> | // +----------------------------------------------------------------------+ // // $Id: IT_Error.php,v 1.1 2002/04/28 07:16:05 sebastian Exp $ require_once "PEAR.php"; /** * IT[X] Error class * * @package IT[X] */ class IT_Error extends PEAR_Error { /** * Prefix of all error messages. * * @var string */ var $error_message_prefix = "IntegratedTemplate Error: "; /** * Creates an cache error object. * * @param string error message * @param string file where the error occured * @param string linenumber where the error occured */ function IT_Error($msg, $file = __FILE__, $line = __LINE__) { $this->PEAR_Error(sprintf("%s [%s on line %d].", $msg, $file, $line)); } // end func IT_Error } // end class IT_Error ?> Index: pear/HTML_Template_IT/package.xml +++ pear/HTML_Template_IT/package.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE package SYSTEM "../package.dtd"> <package version="1.0"> <name>HTML_Template_IT</name> <summary>Integrated Templates</summary> <description> ... </description> <maintainers> <maintainer> <user>uw</user> <role>lead</role> <name>Ulf Wendel</name> <email>ulf.wendel@phpdoc.de</email> </maintainer> </maintainers> <license>PHP License</license> <release> <version>0.1</version> <state>stable</state> <date>2002-04-28</date> <notes> Initial independent PEAR release. </notes> <filelist> <dir name="/" baseinstalldir="HTML/Template"> <file role="php" name="IT.php"/> <file role="php" name="ITX.php"/> <file role="php" name="IT_Error.php"/> </dir> </filelist> </release> </package>
« previous php.pear.cvs (#3594) next »