HTML_Template_IT
[ class tree: HTML_Template_IT ] [ index: HTML_Template_IT ] [ all elements ]

Source for file IT.php

Documentation is available at IT.php

  1. <?php
  2. //
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group                                |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license,      |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available at through the world-wide-web at                           |
  11. // | http://www.php.net/license/2_02.txt.                                 |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Author: Ulf Wendel <ulf.wendel@phpdoc.de>                            |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: IT.php,v 1.9 2005/08/14 18:27:03 pajoye Exp $
  20. //
  21.  
  22. require_once('PEAR.php');
  23.  
  24. define("IT_OK",                         1);
  25. define("IT_ERROR",                     -1);
  26. define("IT_TPL_NOT_FOUND",             -2);
  27. define("IT_BLOCK_NOT_FOUND",           -3);
  28. define("IT_BLOCK_DUPLICATE",           -4);
  29. define('IT_UNKNOWN_OPTION',            -6);
  30. /**
  31.  * Integrated Template - IT
  32.  *
  33.  * Well there's not much to say about it. I needed a template class that
  34.  * supports a single template file with multiple (nested) blocks inside and
  35.  * a simple block API.
  36.  *
  37.  * The Isotemplate API is somewhat tricky for a beginner although it is the best
  38.  * one you can build. template::parse() [phplib template = Isotemplate] requests
  39.  * you to name a source and a target where the current block gets parsed into.
  40.  * Source and target can be block names or even handler names. This API gives you
  41.  * a maximum of fexibility but you always have to know what you do which is
  42.  * quite unusual for php skripter like me.
  43.  *
  44.  * I noticed that I do not any control on which block gets parsed into which one.
  45.  * If all blocks are within one file, the script knows how they are nested and in
  46.  * which way you have to parse them. IT knows that inner1 is a child of block2, there's
  47.  * no need to tell him about this.
  48.  *
  49.  * <table border>
  50.  *   <tr>
  51.  *     <td colspan=2>
  52.  *       __global__
  53.  *       <p>
  54.  *       (hidden and automatically added)
  55.  *     </td>
  56.  *   </tr>
  57.  *   <tr>
  58.  *     <td>block1</td>
  59.  *     <td>
  60.  *       <table border>
  61.  *         <tr>
  62.  *           <td colspan=2>block2</td>
  63.  *         </tr>
  64.  *         <tr>
  65.  *           <td>inner1</td>
  66.  *           <td>inner2</td>
  67.  *         </tr>
  68.  *       </table>
  69.  *     </td>
  70.  *   </tr>
  71.  * </table>
  72.  *
  73.  * To add content to block1 you simply type:
  74.  * <code>$tpl->setCurrentBlock("block1");</code>
  75.  * and repeat this as often as needed:
  76.  * <code>
  77.  *   $tpl->setVariable(...);
  78.  *   $tpl->parseCurrentBlock();
  79.  * </code>
  80.  *
  81.  * To add content to block2 you would type something like:
  82.  * <code>
  83.  * $tpl->setCurrentBlock("inner1");
  84.  * $tpl->setVariable(...);
  85.  * $tpl->parseCurrentBlock();
  86.  *
  87.  * $tpl->setVariable(...);
  88.  * $tpl->parseCurrentBlock();
  89.  *
  90.  * $tpl->parse("block1");
  91.  * </code>
  92.  *
  93.  * This will result in one repition of block1 which contains two repitions
  94.  * of inner1. inner2 will be removed if $removeEmptyBlock is set to true which is the default.
  95.  *
  96.  * Usage:
  97.  * <code>
  98.  * $tpl = new HTML_Template_IT( [string filerootdir] );
  99.  *
  100.  * // load a template or set it with setTemplate()
  101.  * $tpl->loadTemplatefile( string filename [, boolean removeUnknownVariables, boolean removeEmptyBlocks] )
  102.  *
  103.  * // set "global" Variables meaning variables not beeing within a (inner) block
  104.  * $tpl->setVariable( string variablename, mixed value );
  105.  *
  106.  * // like with the Isotemplates there's a second way to use setVariable()
  107.  * $tpl->setVariable( array ( string varname => mixed value ) );
  108.  *
  109.  * // Let's use any block, even a deeply nested one
  110.  * $tpl->setCurrentBlock( string blockname );
  111.  *
  112.  * // repeat this as often as you need it.
  113.  * $tpl->setVariable( array ( string varname => mixed value ) );
  114.  * $tpl->parseCurrentBlock();
  115.  *
  116.  * // get the parsed template or print it: $tpl->show()
  117.  * $tpl->get();
  118.  * </code>
  119.  *
  120.  * @author   Ulf Wendel <uw@netuse.de>
  121.  * @version  $Id: IT.php,v 1.9 2005/08/14 18:27:03 pajoye Exp $
  122.  * @access   public
  123.  * @package  HTML_Template_IT
  124.  */
  125.  
  126.     /**
  127.      * Contains the error objects
  128.      * @var      array 
  129.      * @access   public
  130.      * @see      halt(), $printError, $haltOnError
  131.      */
  132.     var $err = array();
  133.  
  134.     /**
  135.      * Clear cache on get()?
  136.      * @var      boolean 
  137.      */
  138.     var $clearCache = false;
  139.  
  140.     /**
  141.      * First character of a variable placeholder ( _{_VARIABLE} ).
  142.      * @var      string 
  143.      * @access   public
  144.      * @see      $closingDelimiter, $blocknameRegExp, $variablenameRegExp
  145.      */
  146.     var $openingDelimiter = "{";
  147.  
  148.     /**
  149.      * Last character of a variable placeholder ( {VARIABLE_}_ ).
  150.      * @var      string 
  151.      * @access   public
  152.      * @see      $openingDelimiter, $blocknameRegExp, $variablenameRegExp
  153.      */
  154.     var $closingDelimiter     = "}";
  155.  
  156.     /**
  157.      * RegExp matching a block in the template.
  158.      * Per default "sm" is used as the regexp modifier, "i" is missing.
  159.      * That means a case sensitive search is done.
  160.      * @var      string 
  161.      * @access   public
  162.      * @see      $variablenameRegExp, $openingDelimiter, $closingDelimiter
  163.      */
  164.     var $blocknameRegExp    = "[0-9A-Za-z_-]+";
  165.  
  166.     /**
  167.      * RegExp matching a variable placeholder in the template.
  168.      * Per default "sm" is used as the regexp modifier, "i" is missing.
  169.      * That means a case sensitive search is done.
  170.      * @var      string 
  171.      * @access   public
  172.      * @see      $blocknameRegExp, $openingDelimiter, $closingDelimiter
  173.      */
  174.     var $variablenameRegExp    = "[0-9A-Za-z_-]+";
  175.  
  176.     /**
  177.      * RegExp used to find variable placeholder, filled by the constructor.
  178.      * @var      string    Looks somewhat like @(delimiter varname delimiter)@
  179.      * @access   public
  180.      * @see      IntegratedTemplate()
  181.      */
  182.     var $variablesRegExp = "";
  183.  
  184.     /**
  185.      * RegExp used to strip unused variable placeholder.
  186.      * @brother  $variablesRegExp
  187.      */
  188.     var $removeVariablesRegExp = "";
  189.  
  190.     /**
  191.      * Controls the handling of unknown variables, default is remove.
  192.      * @var      boolean 
  193.      * @access   public
  194.      */
  195.     var $removeUnknownVariables = true;
  196.  
  197.     /**
  198.      * Controls the handling of empty blocks, default is remove.
  199.      * @var      boolean 
  200.      * @access   public
  201.      */
  202.     var $removeEmptyBlocks = true;
  203.  
  204.     /**
  205.      * RegExp used to find blocks an their content, filled by the constructor.
  206.      * @var      string 
  207.      * @see      IntegratedTemplate()
  208.      */
  209.     var $blockRegExp = "";
  210.  
  211.     /**
  212.      * Name of the current block.
  213.      * @var      string 
  214.      */
  215.     var $currentBlock = "__global__";
  216.  
  217.     /**
  218.      * Content of the template.
  219.      * @var      string 
  220.      */
  221.     var $template = "";
  222.  
  223.     /**
  224.      * Array of all blocks and their content.
  225.      *
  226.      * @var      array 
  227.      * @see      findBlocks()
  228.      */
  229.     var $blocklist = array();
  230.  
  231.     /**
  232.      * Array with the parsed content of a block.
  233.      *
  234.      * @var      array 
  235.      */
  236.     var $blockdata = array();
  237.  
  238.     /**
  239.      * Array of variables in a block.
  240.      * @var      array 
  241.      */
  242.     var $blockvariables = array();
  243.  
  244.     /**
  245.      * Array of inner blocks of a block.
  246.      * @var      array 
  247.      */
  248.     var $blockinner         = array();
  249.  
  250.     /**
  251.      * List of blocks to preverse even if they are "empty".
  252.      *
  253.      * This is something special. Sometimes you have blocks that
  254.      * should be preserved although they are empty (no placeholder replaced).
  255.      * Think of a shopping basket. If it's empty you have to drop a message to
  256.      * the user. If it's filled you have to show the contents of
  257.      * the shopping baseket. Now where do you place the message that the basket
  258.      * is empty? It's no good idea to place it in you applications as customers
  259.      * tend to like unecessary minor text changes. Having another template file
  260.      * for an empty basket means that it's very likely that one fine day
  261.      * the filled and empty basket templates have different layout. I decided
  262.      * to introduce blocks that to not contain any placeholder but only
  263.      * text such as the message "Your shopping basked is empty".
  264.      *
  265.      * Now if there is no replacement done in such a block the block will
  266.      * be recognized as "empty" and by default ($removeEmptyBlocks = true) be
  267.      * stripped off. To avoid thisyou can now call touchBlock() to avoid this.
  268.      *
  269.      * The array $touchedBlocks stores a list of touched block which must not
  270.      * be removed even if they are empty.
  271.      *
  272.      * @var  array    $touchedBlocks 
  273.      * @see  touchBlock(), $removeEmptyBlocks
  274.      */
  275.      var $touchedBlocks = array();
  276.  
  277.     /**
  278.      * List of blocks which should not be shown even if not "empty"
  279.      * @var  array    $_hiddenBlocks 
  280.      * @see  hideBlock(), $removeEmptyBlocks
  281.      */
  282.     var $_hiddenBlocks = array();
  283.  
  284.     /**
  285.      * Variable cache.
  286.      *
  287.      * Variables get cached before any replacement is done.
  288.      * Advantage: empty blocks can be removed automatically.
  289.      * Disadvantage: might take some more memory
  290.      *
  291.      * @var    array 
  292.      * @see    setVariable(), $clearCacheOnParse
  293.      */
  294.     var $variableCache = array();
  295.  
  296.     /**
  297.      * Clear the variable cache on parse?
  298.      *
  299.      * If you're not an expert just leave the default false.
  300.      * True reduces memory consumption somewhat if you tend to
  301.      * add lots of values for unknown placeholder.
  302.      *
  303.      * @var    boolean 
  304.      */
  305.     var $clearCacheOnParse = false;
  306.  
  307.     /**
  308.      * Root directory for all file operations.
  309.      * The string gets prefixed to all filenames given.
  310.      * @var    string 
  311.      * @see    HTML_Template_IT(), setRoot()
  312.      */
  313.     var $fileRoot = "";
  314.  
  315.     /**
  316.      * Internal flag indicating that a blockname was used multiple times.
  317.      * @var    boolean 
  318.      */
  319.     var $flagBlocktrouble = false;
  320.  
  321.     /**
  322.      * Flag indicating that the global block was parsed.
  323.      * @var    boolean 
  324.      */
  325.     var $flagGlobalParsed = false;
  326.  
  327.     /**
  328.      * EXPERIMENTAL! FIXME!
  329.      * Flag indication that a template gets cached.
  330.      *
  331.      * Complex templates require some times to be preparsed
  332.      * before the replacement can take place. Often I use
  333.      * one template file over and over again but I don't know
  334.      * before that I will use the same template file again.
  335.      * Now IT could notice this and skip the preparse.
  336.      *
  337.      * @var    boolean 
  338.      */
  339.     var $flagCacheTemplatefile = true;
  340.  
  341.     /**
  342.      * EXPERIMENTAL! FIXME!
  343.      */
  344.     var $lastTemplatefile = "";
  345.  
  346.     /**
  347.      * $_options['preserve_data'] Whether to substitute variables and remove
  348.      * empty placeholders in data passed through setVariable
  349.      * (see also bugs #20199, #21951).
  350.      * $_options['use_preg'] Whether to use preg_replace instead of
  351.      * str_replace in parse()
  352.      * (this is a backwards compatibility feature, see also bugs #21951, #20392)
  353.      */
  354.     var $_options = array(
  355.         'preserve_data' => false,
  356.         'use_preg'      => true
  357.     );
  358.  
  359.  
  360.     /**
  361.      * Builds some complex regular expressions and optinally sets the
  362.      * file root directory.
  363.      *
  364.      * Make sure that you call this constructor if you derive your template
  365.      * class from this one.
  366.      *
  367.      * @param    string    File root directory, prefix for all filenames
  368.      *                      given to the object.
  369.      * @see      setRoot()
  370.      */
  371.     function HTML_Template_IT($root ""$options=null{
  372.         if(!is_null($options)){
  373.             $this->setOptions($options);
  374.         }
  375.         $this->variablesRegExp = "@" $this->openingDelimiter .
  376.                                  "(" $this->variablenameRegExp . ")" .
  377.                                  $this->closingDelimiter . "@sm";
  378.         $this->removeVariablesRegExp = "@" $this->openingDelimiter .
  379.                                        "\s*(" $this->variablenameRegExp .
  380.                                        ")\s*" $this->closingDelimiter ."@sm";
  381.  
  382.         $this->blockRegExp = '@<!--\s+BEGIN\s+(' $this->blocknameRegExp .
  383.                              ')\s+-->(.*)<!--\s+END\s+\1\s+-->@sm';
  384.  
  385.         $this->setRoot($root);
  386.     // end constructor
  387.  
  388.  
  389.     /**
  390.      * Sets the option for the template class
  391.      *
  392.      * @access public
  393.      * @param  string  option name
  394.      * @param  mixed   option value
  395.      * @return mixed   IT_OK on success, error object on failure
  396.      */
  397.     function setOption($option$value)
  398.     {
  399.         if (isset($this->_options[$option])) {
  400.             $this->_options[$option$value;
  401.             return IT_OK;
  402.         }
  403.         return PEAR::raiseError(
  404.                 $this->errorMessage(IT_UNKNOWN_OPTION. ": '{$option}'",
  405.                 IT_UNKNOWN_OPTION
  406.             );
  407.     }
  408.  
  409.     /**
  410.      * Sets the options for the template class
  411.      *
  412.      * @access public
  413.      * @param  string  options array of options
  414.      *                  default value:
  415.      *                    'preserve_data' => false,
  416.      *                    'use_preg'      => true
  417.      * @param  mixed   option value
  418.      * @return mixed   IT_OK on success, error object on failure
  419.      * @see $options
  420.      */
  421.     function setOptions($options)
  422.     {
  423.         foreach($options as $option=>$value){
  424.             ifPEAR::isError($error=$this->setOption($option$value)) ){
  425.                 return $error;
  426.             }
  427.         }
  428.         return IT_OK;
  429.     }
  430.  
  431.     /**
  432.      * Print a certain block with all replacements done.
  433.      * @brother get()
  434.      */
  435.     function show($block "__global__"{
  436.         print $this->get($block);
  437.     // end func show
  438.  
  439.     /**
  440.      * Returns a block with all replacements done.
  441.      *
  442.      * @param    string     name of the block
  443.      * @return   string 
  444.      * @throws   PEAR_Error
  445.      * @access   public
  446.      * @see      show()
  447.      */
  448.     function get($block "__global__"{
  449.  
  450.         if ("__global__" == $block && !$this->flagGlobalParsed)
  451.             $this->parse("__global__");
  452.  
  453.         if (!isset($this->blocklist[$block])) {
  454.             $this->err[= PEAR::raiseError(
  455.                             $this->errorMessageIT_BLOCK_NOT_FOUND .
  456.                             '"' $block "'",
  457.                             IT_BLOCK_NOT_FOUND
  458.                         );
  459.             return "";
  460.         }
  461.  
  462.         if (!isset($this->blockdata[$block])) {
  463.             return '';
  464.  
  465.         else {
  466.             $ret $this->blockdata[$block];
  467.             if ($this->clearCache{
  468.                 unset($this->blockdata[$block]);
  469.             }
  470.             if ($this->_options['preserve_data']{
  471.                 $ret str_replace(
  472.                         $this->openingDelimiter .
  473.                         '%preserved%' $this->closingDelimiter,
  474.                         $this->openingDelimiter,
  475.                         $ret
  476.                     );
  477.             }
  478.             return $ret;
  479.         }
  480.     // end func get()
  481.  
  482.     /**
  483.      * Parses the given block.
  484.      *
  485.      * @param    string    name of the block to be parsed
  486.      * @access   public
  487.      * @see      parseCurrentBlock()
  488.      * @throws   PEAR_Error
  489.      */
  490.     function parse($block "__global__"$flag_recursion = false)
  491.     {
  492.         static $regs$values;
  493.  
  494.         if (!isset($this->blocklist[$block])) {
  495.             return PEAR::raiseError(
  496.                 $this->errorMessageIT_BLOCK_NOT_FOUND '"' $block "'",
  497.                         IT_BLOCK_NOT_FOUND
  498.                 );
  499.         }
  500.  
  501.         if ("__global__" == $block{
  502.             $this->flagGlobalParsed = true;
  503.         }
  504.  
  505.         if (!$flag_recursion{
  506.             $regs   = array();
  507.             $values = array();
  508.         }
  509.         $outer $this->blocklist[$block];
  510.         $empty = true;
  511.  
  512.         if ($this->clearCacheOnParse{
  513.  
  514.             foreach ($this->variableCache as $name => $value{
  515.                 $regs[$this->openingDelimiter .
  516.                           $name $this->closingDelimiter;
  517.                 $values[$value;
  518.                 $empty = false;
  519.             }
  520.             $this->variableCache = array();
  521.  
  522.         else {
  523.  
  524.             foreach ($this->blockvariables[$blockas $allowedvar => $v{
  525.  
  526.                 if (isset($this->variableCache[$allowedvar])) {
  527.                    $regs[]   $this->openingDelimiter .
  528.                                $allowedvar $this->closingDelimiter;
  529.                    $values[$this->variableCache[$allowedvar];
  530.                    unset($this->variableCache[$allowedvar]);
  531.                    $empty = false;
  532.                 }
  533.  
  534.             }
  535.  
  536.         }
  537.  
  538.         if (isset($this->blockinner[$block])) {
  539.  
  540.             foreach ($this->blockinner[$blockas $k => $innerblock{
  541.  
  542.                 $this->parse($innerblocktrue);
  543.                 if ("" != $this->blockdata[$innerblock]{
  544.                     $empty = false;
  545.                 }
  546.  
  547.                 $placeholder $this->openingDelimiter . "__" .
  548.                                 $innerblock "__" $this->closingDelimiter;
  549.                 $outer str_replace(
  550.                                     $placeholder,
  551.                                     $this->blockdata[$innerblock]$outer
  552.                         );
  553.                 $this->blockdata[$innerblock"";
  554.             }
  555.  
  556.         }
  557.  
  558.         if (!$flag_recursion && 0 != count($values)) {
  559.             if ($this->_options['use_preg']{
  560.                 $regs        array_map(array(
  561.                                     &$this'_addPregDelimiters'),
  562.                                     $regs
  563.                                 );
  564.                 $funcReplace 'preg_replace';
  565.             else {
  566.                 $funcReplace 'str_replace';
  567.             }
  568.             if ($this->_options['preserve_data']{
  569.                 $values array_map(
  570.                             array(&$this'_preserveOpeningDelimiter')$values
  571.                         );
  572.             }
  573.  
  574.             $outer $funcReplace($regs$values$outer);
  575.  
  576.             if ($this->removeUnknownVariables{
  577.                 $outer preg_replace($this->removeVariablesRegExp""$outer);
  578.             }
  579.         }
  580.         if ($empty{
  581.  
  582.             if (!$this->removeEmptyBlocks{
  583.  
  584.                 $this->blockdata[$block ].= $outer;
  585.  
  586.             else {
  587.  
  588.                 if (isset($this->touchedBlocks[$block])) {
  589.                     $this->blockdata[$block.= $outer;
  590.                     unset($this->touchedBlocks[$block]);
  591.                 }
  592.  
  593.             }
  594.  
  595.         else {
  596.  
  597.             $this->blockdata[$block.= $outer;
  598.  
  599.         }
  600.  
  601.         return $empty;
  602.     // end func parse
  603.  
  604.     /**
  605.      * Parses the current block
  606.      * @see      parse(), setCurrentBlock(), $currentBlock
  607.      * @access   public
  608.      */
  609.     function parseCurrentBlock({
  610.         return $this->parse($this->currentBlock);
  611.     // end func parseCurrentBlock
  612.  
  613.     /**
  614.      * Sets a variable value.
  615.      *
  616.      * The function can be used eighter like setVariable( "varname", "value")
  617.      * or with one array $variables["varname"] = "value"
  618.      * given setVariable($variables) quite like phplib templates set_var().
  619.      *
  620.      * @param    mixed     string with the variable name or an array
  621.      *                      %variables["varname"] = "value"
  622.      * @param    string    value of the variable or empty if $variable
  623.      *                      is an array.
  624.      * @param    string    prefix for variable names
  625.      * @access   public
  626.      */
  627.     function setVariable($variable$value ""{
  628.  
  629.         if (is_array($variable)) {
  630.  
  631.             $this->variableCache = array_merge(
  632.                                             $this->variableCache$variable
  633.                                     );
  634.  
  635.         else {
  636.  
  637.             $this->variableCache[$variable$value;
  638.  
  639.         }
  640.  
  641.     // end func setVariable
  642.  
  643.     /**
  644.      * Sets the name of the current block that is the block where variables
  645.      * are added.
  646.      *
  647.      * @param    string      name of the block
  648.      * @return   boolean     false on failure, otherwise true
  649.      * @throws   PEAR_Error
  650.      * @access   public
  651.      */
  652.     function setCurrentBlock($block "__global__"{
  653.  
  654.         if (!isset($this->blocklist[$block])) {
  655.             return PEAR::raiseError(
  656.                 $this->errorMessageIT_BLOCK_NOT_FOUND .
  657.                 '"' $block "'"IT_BLOCK_NOT_FOUND
  658.             );
  659.         }
  660.  
  661.         $this->currentBlock = $block;
  662.  
  663.         return true;
  664.     // end func setCurrentBlock
  665.  
  666.     /**
  667.      * Preserves an empty block even if removeEmptyBlocks is true.
  668.      *
  669.      * @param    string      name of the block
  670.      * @return   boolean     false on false, otherwise true
  671.      * @throws   PEAR_Error
  672.      * @access   public
  673.      * @see      $removeEmptyBlocks
  674.      */
  675.     function touchBlock($block{
  676.  
  677.         if (!isset($this->blocklist[$block])) {
  678.             return PEAR::raiseError(
  679.                 $this->errorMessageIT_BLOCK_NOT_FOUND .
  680.                 '"' $block "'"IT_BLOCK_NOT_FOUND  );
  681.         }
  682.  
  683.         $this->touchedBlocks[$block= true;
  684.  
  685.         return true;
  686.     // end func touchBlock
  687.  
  688.     /**
  689.      * Clears all datafields of the object and rebuild the internal blocklist
  690.      *
  691.      * LoadTemplatefile() and setTemplate() automatically call this function
  692.      * when a new template is given. Don't use this function
  693.      * unless you know what you're doing.
  694.      *
  695.      * @access   public
  696.      * @see      free()
  697.      */
  698.     function init({
  699.  
  700.         $this->free();
  701.         $this->findBlocks($this->template);
  702.         // we don't need it any more
  703.         $this->template = '';
  704.         $this->buildBlockvariablelist();
  705.  
  706.     // end func init
  707.  
  708.     /**
  709.      * Clears all datafields of the object.
  710.      *
  711.      * Don't use this function unless you know what you're doing.
  712.      *
  713.      * @access   public
  714.      * @see      init()
  715.      */
  716.     function free({
  717.  
  718.         $this->err = array();
  719.  
  720.         $this->currentBlock = "__global__";
  721.  
  722.         $this->variableCache    = array();
  723.         $this->blocklookup      = array();
  724.         $this->touchedBlocks    = array();
  725.  
  726.         $this->flagBlocktrouble = false;
  727.         $this->flagGlobalParsed = false;
  728.  
  729.     // end func free
  730.  
  731.     /**
  732.      * Sets the template.
  733.      *
  734.      * You can eighter load a template file from disk with
  735.      * LoadTemplatefile() or set the template manually using this function.
  736.      *
  737.      * @param        string      template content
  738.      * @param        boolean     remove unknown/unused variables?
  739.      * @param        boolean     remove empty blocks?
  740.      * @see          LoadTemplatefile(), $template
  741.      * @access       public
  742.      */
  743.     function setTemplate$template$removeUnknownVariables = true,
  744.                           $removeEmptyBlocks = true
  745.     {
  746.  
  747.         $this->removeUnknownVariables = $removeUnknownVariables;
  748.         $this->removeEmptyBlocks = $removeEmptyBlocks;
  749.  
  750.         if ("" == $template && $this->flagCacheTemplatefile{
  751.  
  752.             $this->variableCache = array();
  753.             $this->blockdata = array();
  754.             $this->touchedBlocks = array();
  755.             $this->currentBlock = "__global__";
  756.  
  757.         else {
  758.  
  759.             $this->template = '<!-- BEGIN __global__ -->' $template .
  760.                               '<!-- END __global__ -->';
  761.             $this->init();
  762.  
  763.         }
  764.  
  765.         if ($this->flagBlocktrouble)
  766.             return false;
  767.  
  768.         return true;
  769.     // end func setTemplate
  770.  
  771.     /**
  772.      * Reads a template file from the disk.
  773.      *
  774.      * @param    string      name of the template file
  775.      * @param    bool        how to handle unknown variables.
  776.      * @param    bool        how to handle empty blocks.
  777.      * @access   public
  778.      * @return   boolean    false on failure, otherwise true
  779.      * @see      $template, setTemplate(), $removeUnknownVariables,
  780.      *            $removeEmptyBlocks
  781.      */
  782.     function loadTemplatefile$filename,
  783.                                $removeUnknownVariables = true,
  784.                                $removeEmptyBlocks = true {
  785.  
  786.         $template "";
  787.         if (!$this->flagCacheTemplatefile ||
  788.             $this->lastTemplatefile != $filename
  789.         ){
  790.             $template $this->getFile($filename);
  791.         }
  792.         $this->lastTemplatefile = $filename;
  793.  
  794.         return $template!=""?
  795.                 $this->setTemplate(
  796.                         $template,$removeUnknownVariables$removeEmptyBlocks
  797.                     ):false;
  798.     // end func LoadTemplatefile
  799.  
  800.     /**
  801.      * Sets the file root. The file root gets prefixed to all filenames passed
  802.      * to the object.
  803.      *
  804.      * Make sure that you override this function when using the class
  805.      * on windows.
  806.      *
  807.      * @param    string 
  808.      * @see      IntegratedTemplate()
  809.      * @access   public
  810.      */
  811.     function setRoot($root{
  812.  
  813.         if ("" != $root && "/" != substr($root-1))
  814.             $root .= "/";
  815.  
  816.         $this->fileRoot = $root;
  817.  
  818.     // end func setRoot
  819.  
  820.     /**
  821.      * Build a list of all variables within of a block
  822.      */
  823.     function buildBlockvariablelist({
  824.  
  825.         foreach ($this->blocklist as $name => $content{
  826.             preg_match_all$this->variablesRegExp$content$regs );
  827.  
  828.             if (0 != count($regs[1])) {
  829.  
  830.                 foreach ($regs[1as $k => $var)
  831.                     $this->blockvariables[$name][$var= true;
  832.  
  833.             else {
  834.  
  835.                 $this->blockvariables[$name= array();
  836.  
  837.             }
  838.  
  839.         }
  840.  
  841.     // end func buildBlockvariablelist
  842.  
  843.     /**
  844.      * Returns a list of all global variables
  845.      */
  846.     function getGlobalvariables({
  847.  
  848.         $regs   = array();
  849.         $values = array();
  850.  
  851.         foreach ($this->blockvariables["__global__"as $allowedvar => $v{
  852.  
  853.             if (isset($this->variableCache[$allowedvar])) {
  854.                 $regs[]   "@" $this->openingDelimiter .
  855.                             $allowedvar $this->closingDelimiter."@";
  856.                 $values[$this->variableCache[$allowedvar];
  857.                 unset($this->variableCache[$allowedvar]);
  858.             }
  859.  
  860.         }
  861.  
  862.         return array($regs$values);
  863.     // end func getGlobalvariables
  864.  
  865.     /**
  866.      * Recusively builds a list of all blocks within the template.
  867.      *
  868.      * @param    string    string that gets scanned
  869.      * @see      $blocklist
  870.      */
  871.     function findBlocks($string{
  872.  
  873.         $blocklist = array();
  874.  
  875.         if (
  876.             preg_match_all($this->blockRegExp$string$regsPREG_SET_ORDER)
  877.         {
  878.  
  879.             foreach ($regs as $k => $match{
  880.  
  881.                 $blockname         $match[1];
  882.                 $blockcontent $match[2];
  883.  
  884.                 if (isset($this->blocklist[$blockname])) {
  885.                     $this->err[= PEAR::raiseError(
  886.                                             $this->errorMessage(
  887.                                             IT_BLOCK_DUPLICATE '"' .
  888.                                             $blockname "'",
  889.                                             IT_BLOCK_DUPLICATE
  890.                                     );
  891.                     $this->flagBlocktrouble = true;
  892.                 }
  893.  
  894.                 $this->blocklist[$blockname$blockcontent;
  895.                 $this->blockdata[$blockname"";
  896.  
  897.                 $blocklist[$blockname;
  898.  
  899.                 $inner $this->findBlocks($blockcontent);
  900.                 foreach ($inner as $k => $name{
  901.  
  902.                     $pattern sprintf(
  903.                         '@<!--\s+BEGIN\s+%s\s+-->(.*)<!--\s+END\s+%s\s+-->@sm',
  904.                         $name,
  905.                         $name
  906.                     );
  907.  
  908.                     $this->blocklist[$blocknamepreg_replace(
  909.                                         $pattern,
  910.                                         $this->openingDelimiter .
  911.                                         "__" $name "__" .
  912.                                         $this->closingDelimiter,
  913.                                         $this->blocklist[$blockname]
  914.                                );
  915.                     $this->blockinner[$blockname][$name;
  916.                     $this->blockparents[$name$blockname;
  917.  
  918.                 }
  919.  
  920.             }
  921.  
  922.         }
  923.  
  924.         return $blocklist;
  925.     // end func findBlocks
  926.  
  927.     /**
  928.      * Reads a file from disk and returns its content.
  929.      * @param    string    Filename
  930.      * @return   string    Filecontent
  931.      */
  932.     function getFile($filename{
  933.  
  934.         if ("/" == $filename{0&& "/" == substr($this->fileRoot-1))
  935.             $filename substr($filename1);
  936.  
  937.         $filename $this->fileRoot . $filename;
  938.  
  939.         if (!($fh @fopen($filename"r"))) {
  940.             $this->err[= PEAR::raiseError(
  941.                         $this->errorMessage(IT_TPL_NOT_FOUND.
  942.                         ': "' .$filename .'"',
  943.                         IT_TPL_NOT_FOUND
  944.                     );
  945.             return "";
  946.         }
  947.  
  948.         $content fread($fhfilesize($filename));
  949.         fclose($fh);
  950.  
  951.         return preg_replace(
  952.             "#<!-- INCLUDE (.*) -->#ime""\$this->getFile('\\1')"$content
  953.         );
  954.     // end func getFile
  955.  
  956.  
  957.     /**
  958.      * Adds delimiters to a string, so it can be used as a pattern
  959.      * in preg_* functions
  960.      *
  961.      * @param string 
  962.      * @return string 
  963.      */
  964.     function _addPregDelimiters($str)
  965.     {
  966.         return '@' $str '@';
  967.     }
  968.  
  969.  
  970.    /**
  971.     * Replaces an opening delimiter by a special string
  972.     *
  973.     * @param string 
  974.     * @return string 
  975.     */
  976.     function _preserveOpeningDelimiter($str)
  977.     {
  978.         return (false === strpos($str$this->openingDelimiter))?
  979.                 $str:
  980.                 str_replace(
  981.                     $this->openingDelimiter,
  982.                     $this->openingDelimiter .
  983.                     '%preserved%' $this->closingDelimiter,
  984.                     $str
  985.                 );
  986.     }
  987.  
  988.     /**
  989.      * Return a textual error message for a IT error code
  990.      *
  991.      * @param integer $value error code
  992.      *
  993.      * @return string error message, or false if the error code was
  994.      *  not recognized
  995.      */
  996.     function errorMessage($value)
  997.     {
  998.         static $errorMessages;
  999.         if (!isset($errorMessages)) {
  1000.             $errorMessages = array(
  1001.                 IT_OK                       => '',
  1002.                 IT_ERROR                    => 'unknown error',
  1003.                 IT_TPL_NOT_FOUND            => 'Cannot read the template file',
  1004.                 IT_BLOCK_NOT_FOUND          => 'Cannot find this block',
  1005.                 IT_BLOCK_DUPLICATE          => 'The name of a block must be'.
  1006.                                                ' uniquewithin a template.'.
  1007.                                                ' Found "' $blockname '" twice.'.
  1008.                                                'Unpredictable results '.
  1009.                                                'may appear.',
  1010.                 IT_UNKNOWN_OPTION           => 'Unknown option'
  1011.             );
  1012.         }
  1013.  
  1014.         if (PEAR::isError($value)) {
  1015.             $value $value->getCode();
  1016.         }
  1017.  
  1018.         return isset($errorMessages[$value]?
  1019.                 $errorMessages[$value$errorMessages[IT_ERROR];
  1020.     }
  1021. // end class IntegratedTemplate
  1022. ?>

Documentation generated on Mon, 11 Mar 2019 14:16:57 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.