Source for file Compiler.php

Documentation is available at Compiler.php

  1. <?php
  2.  
  3. include dirname(__FILE__'/Compilation/Exception.php';
  4.  
  5. /**
  6.  * default dwoo compiler class, compiles dwoo templates into php
  7.  *
  8.  * This software is provided 'as-is', without any express or implied warranty.
  9.  * In no event will the authors be held liable for any damages arising from the use of this software.
  10.  *
  11.  * This file is released under the LGPL
  12.  * "GNU Lesser General Public License"
  13.  * More information can be found here:
  14.  * {@link http://www.gnu.org/copyleft/lesser.html}
  15.  *
  16.  * @author     Jordi Boggiano <j.boggiano@seld.be>
  17.  * @copyright  Copyright (c) 2008, Jordi Boggiano
  18.  * @license    http://www.gnu.org/copyleft/lesser.html  GNU Lesser General Public License
  19.  * @link       http://dwoo.org/
  20.  * @version    0.9.1
  21.  * @date       2008-05-30
  22.  * @package    Dwoo
  23.  */
  24. class Dwoo_Compiler implements Dwoo_ICompiler
  25. {
  26.     /**
  27.      * constant that represents a php opening tag
  28.      *
  29.      * use it in case it needs to be adjusted
  30.      *
  31.      * @var string 
  32.      */
  33.     const PHP_OPEN "<?php ";
  34.  
  35.     /**
  36.      * constant that represents a php closing tag
  37.      *
  38.      * use it in case it needs to be adjusted
  39.      *
  40.      * @var string 
  41.      */
  42.     const PHP_CLOSE "?>";
  43.  
  44.     /**
  45.      * boolean flag to enable or disable debugging output
  46.      *
  47.      * @var bool 
  48.      */
  49.     public $debug = false;
  50.  
  51.     /**
  52.      * left script delimiter
  53.      *
  54.      * @var string 
  55.      */
  56.     protected $ld = '{';
  57.  
  58.     /**
  59.      * left script delimiter with escaped regex meta characters
  60.      *
  61.      * @var string 
  62.      */
  63.     protected $ldr = '\\{';
  64.  
  65.     /**
  66.      * right script delimiter
  67.      *
  68.      * @var string 
  69.      */
  70.     protected $rd = '}';
  71.  
  72.     /**
  73.      * right script delimiter with escaped regex meta characters
  74.      *
  75.      * @var string 
  76.      */
  77.     protected $rdr = '\\}';
  78.  
  79.     /**
  80.      * defines whether opening and closing tags can contain spaces before valid data or not
  81.      *
  82.      * turn to true if you want to be sloppy with the syntax, but when set to false it allows
  83.      * to skip javascript and css tags as long as they are in the form "{ something", which is
  84.      * nice. default is false.
  85.      *
  86.      * @var bool 
  87.      */
  88.     protected $allowLooseOpenings = false;
  89.  
  90.     /**
  91.      * defines whether the compiler will automatically html-escape variables or not
  92.      *
  93.      * default is false
  94.      *
  95.      * @var bool 
  96.      */
  97.     protected $autoEscape = false;
  98.  
  99.     /**
  100.      * security policy object
  101.      *
  102.      * @var Dwoo_Security_Policy 
  103.      */
  104.     protected $securityPolicy;
  105.  
  106.     /**
  107.      * stores the custom plugins registered with this compiler
  108.      *
  109.      * @var array 
  110.      */
  111.     protected $customPlugins = array();
  112.  
  113.     /**
  114.      * stores the pre- and post-processors callbacks
  115.      *
  116.      * @var array 
  117.      */
  118.     protected $processors = array('pre'=>array()'post'=>array());
  119.  
  120.     /**
  121.      * stores a list of plugins that are used in the currently compiled
  122.      * template, and that are not compilable. these plugins will be loaded
  123.      * during the template's runtime if required.
  124.      *
  125.      * it is a 1D array formatted as key:pluginName value:pluginType
  126.      *
  127.      * @var array 
  128.      */
  129.     protected $usedPlugins;
  130.  
  131.     /**
  132.      * stores the template undergoing compilation
  133.      *
  134.      * @var string 
  135.      */
  136.     protected $template;
  137.  
  138.     /**
  139.      * stores the current pointer position inside the template
  140.      *
  141.      * @var int 
  142.      */
  143.     protected $pointer;
  144.  
  145.     /**
  146.      * stores the data within which the scope moves
  147.      *
  148.      * @var array 
  149.      */
  150.     protected $data;
  151.  
  152.     /**
  153.      * variable scope of the compiler, set to null if
  154.      * it can not be resolved to a static string (i.e. if some
  155.      * plugin defines a new scope based on a variable array key)
  156.      *
  157.      * @var mixed 
  158.      */
  159.     protected $scope;
  160.  
  161.     /**
  162.      * variable scope tree, that allows to rebuild the current
  163.      * scope if required, i.e. when going to a parent level
  164.      *
  165.      * @var array 
  166.      */
  167.     protected $scopeTree;
  168.  
  169.     /**
  170.      * block plugins stack, accessible through some methods
  171.      *
  172.      * @see findBlock
  173.      * @see getCurrentBlock
  174.      * @see addBlock
  175.      * @see addCustomBlock
  176.      * @see injectBlock
  177.      * @see removeBlock
  178.      * @see removeTopBlock
  179.      *
  180.      * @var array 
  181.      */
  182.     protected $stack = array();
  183.  
  184.     /**
  185.      * current block at the top of the block plugins stack,
  186.      * accessible through getCurrentBlock
  187.      *
  188.      * @see getCurrentBlock
  189.      *
  190.      * @var Dwoo_Block_Plugin 
  191.      */
  192.     protected $curBlock;
  193.  
  194.     /**
  195.      * current dwoo object that uses this compiler, or null
  196.      *
  197.      * @var Dwoo 
  198.      */
  199.     protected $dwoo;
  200.  
  201.     /**
  202.      * holds an instance of this class, used by getInstance when you don't
  203.      * provide a custom compiler in order to save resources
  204.      *
  205.      * @var Dwoo_Compiler 
  206.      */
  207.     protected static $instance;
  208.  
  209.     /**
  210.      * sets the delimiters to use in the templates
  211.      *
  212.      * delimiters can be multi-character strings but should not be one of those as they will
  213.      * make it very hard to work with templates or might even break the compiler entirely : "\", "$", "|", ":" and finally "#" only if you intend to use config-vars with the #var# syntax.
  214.      *
  215.      * @param string $left left delimiter
  216.      * @param string $right right delimiter
  217.      */
  218.     public function setDelimiters($left$right)
  219.     {
  220.         $this->ld = $left;
  221.         $this->rd = $right;
  222.         $this->ldr = preg_quote($left'/');
  223.         $this->rdr = preg_quote($right'/');
  224.     }
  225.  
  226.     /**
  227.      * returns the left and right template delimiters
  228.      *
  229.      * @return array containing the left and the right delimiters
  230.      */
  231.     public function getDelimiters()
  232.     {
  233.         return array($this->ld$this->rd);
  234.     }
  235.  
  236.     /**
  237.      * sets the tag openings handling strictness, if set to true, template tags can
  238.      * contain spaces before the first function/string/variable such as { $foo} is valid.
  239.      *
  240.      * if set to false (default setting), { $foo} is invalid but that is however a good thing
  241.      * as it allows css (i.e. #foo { color:red; }) to be parsed silently without triggering
  242.      * an error, same goes for javascript.
  243.      *
  244.      * @param bool $allow true to allow loose handling, false to restore default setting
  245.      */
  246.     public function setLooseOpeningHandling($allow false)
  247.     {
  248.         $this->allowLooseOpenings = (bool) $allow;
  249.     }
  250.  
  251.     /**
  252.      * returns the tag openings handling strictness setting
  253.      *
  254.      * @see setLooseOpeningHandling
  255.      * @return bool true if loose tags are allowed
  256.      */
  257.     public function getLooseOpeningHandling()
  258.     {
  259.         return $this->allowLooseOpenings;
  260.     }
  261.  
  262.     /**
  263.      * changes the auto escape setting
  264.      *
  265.      * if enabled, the compiler will automatically html-escape variables,
  266.      * unless they are passed through the safe function such as {$var|safe}
  267.      * or {safe $var}
  268.      *
  269.      * default setting is disabled/false
  270.      *
  271.      * @param bool $enabled set to true to enable, false to disable
  272.      */
  273.     public function setAutoEscape($enabled)
  274.     {
  275.         $this->autoEscape = $enabled;
  276.     }
  277.  
  278.     /**
  279.      * returns the auto escape setting
  280.      *
  281.      * default setting is disabled/false
  282.      *
  283.      * @return bool 
  284.      */
  285.     public function getAutoEscape()
  286.     {
  287.         return $this->autoEscape;
  288.     }
  289.  
  290.     /**
  291.      * adds a preprocessor to the compiler, it will be called
  292.      * before the template is compiled
  293.      *
  294.      * @param mixed $callback either a valid callback to the preprocessor or a simple name if the autoload is set to true
  295.      * @param bool $autoload if set to true, the preprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback
  296.      */
  297.     public function addPreProcessor($callback$autoload false)
  298.     {
  299.         if ($autoload{
  300.             $name str_replace('Dwoo_Processor_'''$callback);
  301.             $class 'Dwoo_Processor_'.$name;
  302.  
  303.             if (class_exists($classfalse)) {
  304.                 $callback array(new $class($this)'process');
  305.             elseif (function_exists($class)) {
  306.                 $callback $class;
  307.             else {
  308.                 $callback array('autoload'=>true'class'=>$class'name'=>$name);
  309.             }
  310.  
  311.             $this->processors['pre'][$callback;
  312.         else {
  313.             $this->processors['pre'][$callback;
  314.         }
  315.     }
  316.  
  317.     /**
  318.      * removes a preprocessor from the compiler
  319.      *
  320.      * @param mixed $callback either a valid callback to the preprocessor or a simple name if it was autoloaded
  321.      */
  322.     public function removePreProcessor($callback)
  323.     {
  324.         if (($index array_search($callback$this->processors['pre']true)) !== false{
  325.             unset($this->processors['pre'][$index]);
  326.         elseif (($index array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_'''$callback)$this->processors['pre']true)) !== false{
  327.             unset($this->processors['pre'][$index]);
  328.         else {
  329.             $class 'Dwoo_Processor_' str_replace('Dwoo_Processor_'''$callback);
  330.             foreach ($this->processors['pre'as $index=>$proc{
  331.                 if (is_array($proc&& ($proc[0instanceof $class|| (isset($proc['class']&& $proc['class'== $class)) {
  332.                     unset($this->processors['pre'][$index]);
  333.                     break;
  334.                 }
  335.             }
  336.         }
  337.     }
  338.  
  339.     /**
  340.      * adds a postprocessor to the compiler, it will be called
  341.      * before the template is compiled
  342.      *
  343.      * @param mixed $callback either a valid callback to the postprocessor or a simple name if the autoload is set to true
  344.      * @param bool $autoload if set to true, the postprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback
  345.      */
  346.     public function addPostProcessor($callback$autoload false)
  347.     {
  348.         if ($autoload{
  349.             $name str_replace('Dwoo_Processor_'''$callback);
  350.             $class 'Dwoo_Processor_'.$name;
  351.  
  352.             if (class_exists($classfalse)) {
  353.                 $callback array(new $class($this)'process');
  354.             elseif (function_exists($class)) {
  355.                 $callback $class;
  356.             else {
  357.                 $callback array('autoload'=>true'class'=>$class'name'=>$name);
  358.             }
  359.  
  360.             $this->processors['post'][$callback;
  361.         else {
  362.             $this->processors['post'][$callback;
  363.         }
  364.     }
  365.  
  366.     /**
  367.      * removes a postprocessor from the compiler
  368.      *
  369.      * @param mixed $callback either a valid callback to the postprocessor or a simple name if it was autoloaded
  370.      */
  371.     public function removePostProcessor($callback)
  372.     {
  373.         if (($index array_search($callback$this->processors['post']true)) !== false{
  374.             unset($this->processors['post'][$index]);
  375.         elseif (($index array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_'''$callback)$this->processors['post']true)) !== false{
  376.             unset($this->processors['post'][$index]);
  377.         else    {
  378.             $class 'Dwoo_Processor_' str_replace('Dwoo_Processor_'''$callback);
  379.             foreach ($this->processors['post'as $index=>$proc{
  380.                 if (is_array($proc&& ($proc[0instanceof $class|| (isset($proc['class']&& $proc['class'== $class)) {
  381.                     unset($this->processors['post'][$index]);
  382.                     break;
  383.                 }
  384.             }
  385.         }
  386.     }
  387.  
  388.     /**
  389.      * internal function to autoload processors at runtime if required
  390.      *
  391.      * @param string $class the class/function name
  392.      * @param string $name the plugin name (without Dwoo_Plugin_ prefix)
  393.      */
  394.     protected function loadProcessor($class$name)
  395.     {
  396.         if (!class_exists($classfalse&& !function_exists($class)) {
  397.             try {
  398.                 $this->dwoo->getLoader()->loadPlugin($name);
  399.             catch (Dwoo_Exception $e{
  400.                 throw new Dwoo_Exception('Processor '.$name.' could not be found in your plugin directories, please ensure it is in a file named '.$name.'.php in the plugin directory');
  401.             }
  402.         }
  403.  
  404.         if (class_exists($classfalse)) {
  405.             return array(new $class($this)'process');
  406.         }
  407.  
  408.         if (function_exists($class)) {
  409.             return $class;
  410.         }
  411.  
  412.         throw new Dwoo_Exception('Wrong processor name, when using autoload the processor must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Processor_name"');
  413.     }
  414.  
  415.     /**
  416.      * adds the custom plugins loaded into Dwoo to the compiler so it can load them
  417.      *
  418.      * @see Dwoo::addPlugin
  419.      * @param array $customPlugins an array of custom plugins
  420.      */
  421.     public function setCustomPlugins(array $customPlugins)
  422.     {
  423.         $this->customPlugins $customPlugins;
  424.     }
  425.  
  426.     /**
  427. /**
  428.      * sets the security policy object to enforce some php security settings
  429.      *
  430.      * use this if untrusted persons can modify templates,
  431.      * set it on the Dwoo object as it will be passed onto the compiler automatically
  432.      *
  433.      * @param Dwoo_Security_Policy $policy the security policy object
  434.      */
  435.     public function setSecurityPolicy(Dwoo_Security_Policy $policy null)
  436.     {
  437.         $this->securityPolicy = $policy;
  438.     }
  439.  
  440.     /**
  441.      * returns the current security policy object or null by default
  442.      *
  443.      * @return Dwoo_Security_Policy|nullthe security policy object if any
  444.      */
  445.     public function getSecurityPolicy()
  446.     {
  447.         return $this->securityPolicy;
  448.     }
  449.  
  450.     /**
  451.      * sets the pointer position
  452.      *
  453.      * @param int $position the new pointer position
  454.      * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position
  455.      */
  456.     public function setPointer($position$isOffset false)
  457.     {
  458.         if ($isOffset{
  459.             $this->pointer += $position;
  460.         else {
  461.             $this->pointer = $position;
  462.         }
  463.     }
  464.  
  465.     /**
  466.      * returns the current pointer position, only available during compilation of a template
  467.      *
  468.      * @return int 
  469.      */
  470.     public function getPointer()
  471.     {
  472.         return $this->pointer;
  473.     }
  474.  
  475.     /**
  476.      * sets the line number
  477.      *
  478.      * @param int $number the new line number
  479.      * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position
  480.      */
  481.     public function setLine($number$isOffset false)
  482.     {
  483.         if ($isOffset{
  484.             $this->line += $number;
  485.         else {
  486.             $this->line $number;
  487.         }
  488.     }
  489.  
  490.     /**
  491.      * returns the current line number, only available during compilation of a template
  492.      *
  493.      * @return int 
  494.      */
  495.     public function getLine()
  496.     {
  497.         return $this->line;
  498.     }
  499.  
  500.     /**
  501.      * returns the dwoo object that initiated this template compilation, only available during compilation of a template
  502.      *
  503.      * @return Dwoo 
  504.      */
  505.     public function getDwoo()
  506.     {
  507.         return $this->dwoo;
  508.     }
  509.  
  510.     /**
  511.      * overwrites the template that is being compiled
  512.      *
  513.      * @param string $newSource the template source that must replace the current one
  514.      * @param bool $fromPointer if set to true, only the source from the current pointer position is replaced
  515.      * @return string the template or partial template
  516.      */
  517.     public function setTemplateSource($newSource$fromPointer false)
  518.     {
  519.         if ($fromPointer === true{
  520.             $this->templateSource substr($this->templateSource0$this->pointer$newSource;
  521.         else {
  522.             $this->templateSource $newSource;
  523.         }
  524.     }
  525.  
  526.     /**
  527.      * returns the template that is being compiled
  528.      *
  529.      * @param mixed $fromPointer if set to true, only the source from the current pointer
  530.      *                                position is returned, if a number is given it overrides the current pointer
  531.      * @return string the template or partial template
  532.      */
  533.     public function getTemplateSource($fromPointer false)
  534.     {
  535.         if ($fromPointer === true{
  536.             return substr($this->templateSource$this->pointer);
  537.         elseif (is_numeric($fromPointer)) {
  538.             return substr($this->templateSource$fromPointer);
  539.         else {
  540.             return $this->templateSource;
  541.         }
  542.     }
  543.  
  544.     /**
  545.      * compiles the provided string down to php code
  546.      *
  547.      * @param string $tpl the template to compile
  548.      * @return string a compiled php string
  549.      */
  550.     public function compile(Dwoo $dwooDwoo_ITemplate $template)
  551.     {
  552.         // init vars
  553.         $tpl $template->getSource();
  554.         $ptr 0;
  555.         $this->dwoo = $dwoo;
  556.         $this->template = $template;
  557.         $this->templateSource =$tpl;
  558.         $this->pointer =$ptr;
  559.  
  560.         while (true{
  561.             // if pointer is at the beginning, reset everything, that allows a plugin to externally reset the compiler if everything must be reparsed
  562.             if ($ptr===0{
  563.                 // resets variables
  564.                 $this->usedPlugins = array();
  565.                 $this->data = array();
  566.                 $this->scope =$this->data;
  567.                 $this->scopeTree = array();
  568.                 $this->stack = array();
  569.                 $this->line 1;
  570.                 // add top level block
  571.                 $compiled $this->addBlock('topLevelBlock'array()0);
  572.                 $this->stack[0]['buffer''';
  573.  
  574.                 if ($this->debugecho 'COMPILER INIT<br />';
  575.  
  576.                 if ($this->debugecho 'PROCESSING PREPROCESSORS ('.count($this->processors['pre']).')<br>';
  577.  
  578.                 // runs preprocessors
  579.                 foreach ($this->processors['pre'as $preProc{
  580.                     if (is_array($preProc&& isset($preProc['autoload'])) {
  581.                         $preProc $this->loadProcessor($preProc['class']$preProc['name']);
  582.                     }
  583.                     if (is_array($preProc&& $preProc[0instanceof Dwoo_Processor{
  584.                         $tpl call_user_func($preProc$tpl);
  585.                     else {
  586.                         $tpl call_user_func($preProc$this$tpl);
  587.                     }
  588.                 }
  589.                 unset($preProc);
  590.  
  591.                 // show template source if debug
  592.                 if ($this->debugecho '<pre>'.print_r(htmlentities($tpl)true).'</pre><hr />';
  593.  
  594.                 // strips comments
  595.                 if (strstr($tpl$this->ld.'*'!== false{
  596.                     $tpl preg_replace('/'.$this->ldr.'\*.*?\*'.$this->rdr.'/s'''$tpl);
  597.                 }
  598.  
  599.                 // strips php tags if required by the security policy
  600.                 if ($this->securityPolicy !== null{
  601.                     $search array('{<\?php.*?\?>}');
  602.                     if (ini_get('short_open_tags')) {
  603.                         $search array('{<\?.*?\?>}''{<%.*?%>}');
  604.                     }
  605.                     switch($this->securityPolicy->getPhpHandling()) {
  606.  
  607.                     case Dwoo_Security_Policy::PHP_ALLOW:
  608.                         break;
  609.                     case Dwoo_Security_Policy::PHP_ENCODE:
  610.                         $tpl preg_replace_callback($searcharray($this'phpTagEncodingHelper')$tpl);
  611.                         break;
  612.                     case Dwoo_Security_Policy::PHP_REMOVE:
  613.                         $tpl preg_replace($search''$tpl);
  614.  
  615.                     }
  616.                 }
  617.             }
  618.  
  619.             $pos strpos($tpl$this->ld$ptr);
  620.  
  621.             if ($pos === false{
  622.                 $this->push(substr($tpl$ptr)0);
  623.                 break;
  624.             elseif (substr($tpl$pos-11=== '\\' && substr($tpl$pos-21!== '\\'{
  625.                 $this->push(substr($tpl$ptr$pos-$ptr-1$this->ld);
  626.                 $ptr $pos+strlen($this->ld);
  627.             elseif (preg_match('/^'.$this->ldr . ($this->allowLooseOpenings ? '\s*' '''literal' ($this->allowLooseOpenings ? '\s*' ''$this->rdr.'/s'substr($tpl$pos)$litOpen)) {
  628.                 if (!preg_match('/'.$this->ldr . ($this->allowLooseOpenings ? '\s*' '''\/literal' ($this->allowLooseOpenings ? '\s*' ''$this->rdr.'/s'$tpl$litClosePREG_OFFSET_CAPTURE$pos)) {
  629.                     throw new Dwoo_Compilation_Exception($this'The {literal} blocks must be closed explicitly with {/literal}');
  630.                 }
  631.                 $endpos $litClose[0][1];
  632.                 $this->push(substr($tpl$ptr$pos-$ptrsubstr($tpl$pos strlen($litOpen[0])$endpos-$pos-strlen($litOpen[0])));
  633.                 $ptr $endpos+strlen($litClose[0][0]);
  634.             else {
  635.                 if (substr($tpl$pos-21=== '\\' && substr($tpl$pos-11=== '\\'{
  636.                     $this->push(substr($tpl$ptr$pos-$ptr-1));
  637.                     $ptr $pos;
  638.                 }
  639.  
  640.                 $this->push(substr($tpl$ptr$pos-$ptr));
  641.                 $ptr $pos;
  642.  
  643.                 $pos += strlen($this->ld);
  644.                 if ($this->allowLooseOpenings{
  645.                     while (substr($tpl$pos1=== ' '{
  646.                         $pos+=1;
  647.                     }
  648.                 else {
  649.                     if (substr($tpl$pos1=== ' ' || substr($tpl$pos1=== "\r" || substr($tpl$pos1=== "\n" || substr($tpl$pos1=== "\t"{
  650.                         $ptr $pos;
  651.                         $this->push($this->ld);
  652.                         continue;
  653.                     }
  654.                 }
  655.  
  656.                 // check that there is an end tag present
  657.                 if (strpos($tpl$this->rd$pos=== false{
  658.                     throw new Dwoo_Compilation_Exception($this'A template tag was not closed, started with "'.substr($tpl$ptr30).'"');
  659.                 }
  660.  
  661.  
  662.                 $ptr += strlen($this->ld);
  663.                 $subptr $ptr;
  664.  
  665.                 while (true{
  666.                     $parsed $this->parse($tpl$subptrnullfalse'root'$subptr);
  667.  
  668.                     // reload loop if the compiler was reset
  669.                     if ($ptr === 0{
  670.                         continue 2;
  671.                     }
  672.  
  673.                     $len $subptr $ptr;
  674.                     $this->push($parsedsubstr_count(substr($tpl$ptr$len)"\n"));
  675.                     $ptr += $len;
  676.  
  677.                     if ($parsed === false{
  678.                         break;
  679.                     }
  680.                 }
  681.  
  682.                 $ptr += strlen($this->rd);
  683.                 $this->setLine(substr_count($this->rd"\n")true);
  684.  
  685.                 // adds additional line breaks between php closing and opening tags because the php parser removes those if there is just a single line break
  686.                 if (substr($this->curBlock['buffer']-2=== '?>' && preg_match('{^(([\r\n])([\r\n]?))}'substr($tpl$ptr3)$m)) {
  687.                     if ($m[3=== ''{
  688.                         $ptr+=1;
  689.                         $this->push($m[1].$m[1]1);
  690.                     else {
  691.                         $ptr+=2;
  692.                         $this->push($m[1]."\n"2);
  693.                     }
  694.                 }
  695.             }
  696.         }
  697.  
  698.         $compiled .= $this->removeBlock('topLevelBlock');
  699.  
  700.         if ($this->debugecho 'PROCESSING POSTPROCESSORS<br>';
  701.  
  702.         foreach ($this->processors['post'as $postProc{
  703.             if (is_array($postProc&& isset($postProc['autoload'])) {
  704.                 $postProc $this->loadProcessor($postProc['class']$postProc['name']);
  705.             }
  706.             if (is_array($postProc&& $postProc[0instanceof Dwoo_Processor{
  707.                 $compiled call_user_func($postProc$compiled);
  708.             else {
  709.                 $compiled call_user_func($postProc$this$compiled);
  710.             }
  711.         }
  712.         unset($postProc);
  713.  
  714.         if ($this->debugecho 'COMPILATION COMPLETE : MEM USAGE : '.memory_get_usage().'<br>';
  715.  
  716.         $output "<?php\n";
  717.  
  718.         // build plugin preloader
  719.         foreach ($this->usedPlugins as $plugin=>$type{
  720.             if (($type Dwoo::CUSTOM_PLUGIN|| ($type Dwoo::PROXY_PLUGIN)) {
  721.                 continue;
  722.             }
  723.  
  724.             switch($type{
  725.  
  726.             case Dwoo::BLOCK_PLUGIN:
  727.             case Dwoo::CLASS_PLUGIN:
  728.                 $output .= "if (class_exists('Dwoo_Plugin_$plugin', false)===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
  729.                 break;
  730.             case Dwoo::FUNC_PLUGIN:
  731.                 $output .= "if (function_exists('Dwoo_Plugin_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
  732.                 break;
  733.             case Dwoo::SMARTY_MODIFIER:
  734.                 $output .= "if (function_exists('smarty_modifier_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
  735.                 break;
  736.             case Dwoo::SMARTY_FUNCTION:
  737.                 $output .= "if (function_exists('smarty_function_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
  738.                 break;
  739.             case Dwoo::SMARTY_BLOCK:
  740.                 $output .= "if (function_exists('smarty_block_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
  741.                 break;
  742.             default:
  743.                 throw new Dwoo_Compilation_Exception($this'Type error for '.$plugin.' with type'.$type);
  744.  
  745.             }
  746.         }
  747.  
  748.         $output .= $compiled."\n?>";
  749.  
  750.         $output preg_replace('/(?<!;|\}|\*\/|\n|\{)(\s*'.preg_quote(self::PHP_CLOSE'/'preg_quote(self::PHP_OPEN'/').')/'";\n"$output);
  751.         $output str_replace(self::PHP_CLOSE self::PHP_OPEN"\n"$output);
  752.  
  753.         // handle <?xml tag at the beginning
  754.         $output preg_replace('#(/\* template body \*/ \?>\s*)<\?xml#is''$1<?php echo \'<?xml\'; ?>'$output);
  755.  
  756.         if ($this->debug{
  757.             echo '<hr><pre>';
  758.             $lines preg_split('{\r\n|\n|<br />}'highlight_string(($output)true));
  759.             array_shift($lines);
  760.             foreach ($lines as $i=>$line{
  761.                 echo ($i+1).'. '.$line."\r\n";
  762.             }
  763.         }
  764.         if ($this->debugecho '<hr></pre></pre>';
  765.  
  766.         $this->template = $this->dwoo = null;
  767.         $tpl null;
  768.  
  769.         return $output;
  770.     }
  771.  
  772.     /**
  773.      * adds compiled content to the current block
  774.      *
  775.      * @param string $content the content to push
  776.      * @param int $lineCount newlines count in content, optional
  777.      */
  778.     public function push($content$lineCount null)
  779.     {
  780.         if ($lineCount === null{
  781.             $lineCount substr_count($content"\n");
  782.         }
  783.  
  784.         if ($this->curBlock['buffer'=== null && count($this->stack1{
  785.             // buffer is not initialized yet (the block has just been created)
  786.             $this->stack[count($this->stack)-2]['buffer'.= (string) $content;
  787.             $this->curBlock['buffer''';
  788.         else {
  789.             if (!isset($this->curBlock['buffer'])) {
  790.                 throw new Dwoo_Compilation_Exception($this'The template has been closed too early, you probably have an extra block-closing tag somewhere');
  791.             }
  792.             // append current content to current block's buffer
  793.             $this->curBlock['buffer'.= (string) $content;
  794.         }
  795.         $this->line += $lineCount;
  796.     }
  797.  
  798.     /**
  799.      * sets the scope
  800.      *
  801.      * set to null if the scope becomes "unstable" (i.e. too variable or unknown) so that
  802.      * variables are compiled in a more evaluative way than just $this->scope['key']
  803.      *
  804.      * @param mixed $scope a string i.e. "level1.level2" or an array i.e. array("level1", "level2")
  805.      * @param bool $absolute if true, the scope is set from the top level scope and not from the current scope
  806.      * @return array the current scope tree
  807.      */
  808.     public function setScope($scope$absolute false)
  809.     {
  810.         $old $this->scopeTree;
  811.  
  812.         if ($scope===null{
  813.             unset($this->scope);
  814.             $this->scope = null;
  815.         }
  816.  
  817.         if (is_array($scope)===false{
  818.             $scope explode('.'$scope);
  819.         }
  820.  
  821.         if ($absolute===true{
  822.             $this->scope =$this->data;
  823.             $this->scopeTree = array();
  824.         }
  825.  
  826.         while (($bit array_shift($scope)) !== null{
  827.             if ($bit === '_parent' || $bit === '_'{
  828.                 array_pop($this->scopeTree);
  829.                 reset($this->scopeTree);
  830.                 $this->scope =$this->data;
  831.                 $cnt count($this->scopeTree);
  832.                 for ($i=0;$i<$cnt;$i++)
  833.                     $this->scope =$this->scope[$this->scopeTree[$i]];
  834.             elseif ($bit === '_root' || $bit === '__'{
  835.                 $this->scope =$this->data;
  836.                 $this->scopeTree = array();
  837.             elseif (isset($this->scope[$bit])) {
  838.                 $this->scope =$this->scope[$bit];
  839.                 $this->scopeTree[$bit;
  840.             else {
  841.                 $this->scope[$bitarray();
  842.                 $this->scope =$this->scope[$bit];
  843.                 $this->scopeTree[$bit;
  844.             }
  845.         }
  846.  
  847.         return $old;
  848.     }
  849.  
  850.     /**
  851.      * forces an absolute scope
  852.      *
  853.      * @deprecated
  854.      * @param mixed $scope a scope as a string or array
  855.      * @return array the current scope tree
  856.      */
  857.     public function forceScope($scope)
  858.     {
  859.         return $this->setScope($scopetrue);
  860.     }
  861.  
  862.     /**
  863.      * adds a block to the top of the block stack
  864.      *
  865.      * @param string $type block type (name)
  866.      * @param array $params the parameters array
  867.      * @param int $paramtype the parameters type (see mapParams), 0, 1 or 2
  868.      * @return string the preProcessing() method's output
  869.      */
  870.     public function addBlock($typearray $params$paramtype)
  871.     {
  872.         $class 'Dwoo_Plugin_'.$type;
  873.         if (class_exists($classfalse=== false{
  874.             $this->dwoo->getLoader()->loadPlugin($type);
  875.         }
  876.  
  877.         $params $this->mapParams($paramsarray($class'init')$paramtype);
  878.  
  879.         $this->stack[array('type' => $type'params' => $params'custom' => false'class' => $class'buffer' => null);
  880.         $this->curBlock =$this->stack[count($this->stack)-1];
  881.         return call_user_func(array($class,'preProcessing')$this$params''''$type);
  882.     }
  883.  
  884.     /**
  885.      * adds a custom block to the top of the block stack
  886.      *
  887.      * @param string $type block type (name)
  888.      * @param array $params the parameters array
  889.      * @param int $paramtype the parameters type (see mapParams), 0, 1 or 2
  890.      * @return string the preProcessing() method's output
  891.      */
  892.     public function addCustomBlock($typearray $params$paramtype)
  893.     {
  894.         $callback $this->customPlugins[$type]['callback'];
  895.         if (is_array($callback)) {
  896.             $class is_object($callback[0]get_class($callback[0]$callback[0];
  897.         else {
  898.             $class $callback;
  899.         }
  900.  
  901.         $params $this->mapParams($paramsarray($class'init')$paramtype);
  902.  
  903.         $this->stack[array('type' => $type'params' => $params'custom' => true'class' => $class'buffer' => null);
  904.         $this->curBlock =$this->stack[count($this->stack)-1];
  905.         return call_user_func(array($class,'preProcessing')$this$params''''$type);
  906.     }
  907.  
  908.     /**
  909.      * injects a block at the top of the plugin stack without calling its preProcessing method
  910.      *
  911.      * used by {else} blocks to re-add themselves after having closed everything up to their parent
  912.      *
  913.      * @param string $type block type (name)
  914.      * @param array $params parameters array
  915.      */
  916.     public function injectBlock($typearray $params)
  917.     {
  918.         $class 'Dwoo_Plugin_'.$type;
  919.         if (class_exists($classfalse=== false{
  920.             $this->dwoo->getLoader()->loadPlugin($type);
  921.         }
  922.         $this->stack[array('type' => $type'params' => $params'custom' => false'class' => $class'buffer' => null);
  923.         $this->curBlock =$this->stack[count($this->stack)-1];
  924.     }
  925.  
  926.     /**
  927.      * removes the closest-to-top block of the given type and all other
  928.      * blocks encountered while going down the block stack
  929.      *
  930.      * @param string $type block type (name)
  931.      * @return string the output of all postProcessing() method's return values of the closed blocks
  932.      */
  933.     public function removeBlock($type)
  934.     {
  935.         $output '';
  936.  
  937.         $pluginType $this->getPluginType($type);
  938.         if ($pluginType Dwoo::SMARTY_BLOCK{
  939.             $type 'smartyinterface';
  940.         }
  941.         while (true{
  942.             while ($top array_pop($this->stack)) {
  943.                 if ($top['custom']{
  944.                     $class $top['class'];
  945.                 else {
  946.                     $class 'Dwoo_Plugin_'.$top['type'];
  947.                 }
  948.                 if (count($this->stack)) {
  949.                     $this->curBlock =$this->stack[count($this->stack)-1];
  950.                     $this->push(call_user_func(array($class'postProcessing')$this$top['params']''''$top['buffer'])0);
  951.                 else {
  952.                     $null null;
  953.                     $this->curBlock =$null;
  954.                     $output call_user_func(array($class'postProcessing')$this$top['params']''''$top['buffer']);
  955.                 }
  956.  
  957.                 if ($top['type'=== $type{
  958.                     break 2;
  959.                 }
  960.             }
  961.  
  962.             throw new Dwoo_Compilation_Exception($this'Syntax malformation, a block of type "'.$type.'" was closed but was not opened');
  963.             break;
  964.         }
  965.  
  966.         return $output;
  967.     }
  968.  
  969.     /**
  970.      * returns a reference to the first block of the given type encountered and
  971.      * optionally closes all blocks until it finds it
  972.      *
  973.      * this is mainly used by {else} plugins to close everything that was opened
  974.      * between their parent and themselves
  975.      *
  976.      * @param string $type the block type (name)
  977.      * @param bool $closeAlong whether to close all blocks encountered while going down the block stack or not
  978.      * @return &array the array is as such: array('type'=>pluginName, 'params'=>parameter array,
  979.      *                    'custom'=>bool defining whether it's a custom plugin or not, for internal use)
  980.      */
  981.     public function &findBlock($type$closeAlong false)
  982.     {
  983.         if ($closeAlong===true{
  984.             while ($b end($this->stack)) {
  985.                 if ($b['type']===$type{
  986.                     return $this->stack[key($this->stack)];
  987.                 }
  988.                 $this->push($this->removeTopBlock()0);
  989.             }
  990.         else {
  991.             end($this->stack);
  992.             while ($b current($this->stack)) {
  993.                 if ($b['type']===$type{
  994.                     return $this->stack[key($this->stack)];
  995.                 }
  996.                 prev($this->stack);
  997.             }
  998.         }
  999.  
  1000.         throw new Dwoo_Compilation_Exception($this'A parent block of type "'.$type.'" is required and can not be found');
  1001.     }
  1002.  
  1003.     /**
  1004.      * returns a reference to the current block array
  1005.      *
  1006.      * @return &array the array is as such: array('type'=>pluginName, 'params'=>parameter array,
  1007.      *                    'custom'=>bool defining whether it's a custom plugin or not, for internal use)
  1008.      */
  1009.     public function &getCurrentBlock()
  1010.     {
  1011.         return $this->curBlock;
  1012.     }
  1013.  
  1014.     /**
  1015.      * removes the block at the top of the stack and calls its postProcessing() method
  1016.      *
  1017.      * @return string the postProcessing() method's output
  1018.      */
  1019.     public function removeTopBlock()
  1020.     {
  1021.         $o array_pop($this->stack);
  1022.         if ($o === null{
  1023.             throw new Dwoo_Compilation_Exception($this'Syntax malformation, a block of unknown type was closed but was not opened.');
  1024.         }
  1025.         if ($o['custom']{
  1026.             $class $o['class'];
  1027.         else {
  1028.             $class 'Dwoo_Plugin_'.$o['type'];
  1029.         }
  1030.  
  1031.         $this->curBlock =$this->stack[count($this->stack)-1];
  1032.  
  1033.         return call_user_func(array($class'postProcessing')$this$o['params']''''$o['buffer']);
  1034.     }
  1035.  
  1036.     /**
  1037.      * returns the compiled parameters (for example a variable's compiled parameter will be "$this->scope['key']") out of the given parameter array
  1038.      *
  1039.      * @param array $params parameter array
  1040.      * @return array filtered parameters
  1041.      */
  1042.     public function getCompiledParams(array $params)
  1043.     {
  1044.         foreach ($params as $k=>$p{
  1045.             if (is_array($p)) {
  1046.                 $params[$k$p[0];
  1047.             }
  1048.         }
  1049.         return $params;
  1050.     }
  1051.  
  1052.     /**
  1053.      * returns the real parameters (for example a variable's real parameter will be its key, etc) out of the given parameter array
  1054.      *
  1055.      * @param array $params parameter array
  1056.      * @return array filtered parameters
  1057.      */
  1058.     public function getRealParams(array $params)
  1059.     {
  1060.         foreach ($params as $k=>$p{
  1061.             if (is_array($p)) {
  1062.                 $params[$k$p[1];
  1063.             }
  1064.         }
  1065.         return $params;
  1066.     }
  1067.  
  1068.     /**
  1069.      * entry point of the parser, it redirects calls to other parse* functions
  1070.      *
  1071.      * @param string $in the string within which we must parse something
  1072.      * @param int $from the starting offset of the parsed area
  1073.      * @param int $to the ending offset of the parsed area
  1074.      * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
  1075.      * @param string $curBlock the current parser-block being processed
  1076.      * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default
  1077.      * @return string parsed values
  1078.      */
  1079.     protected function parse($in$from$to$parsingParams false$curBlock=''&$pointer null)
  1080.     {
  1081.         if ($to === null{
  1082.             $to strlen($in);
  1083.         }
  1084.         $first substr($in$from1);
  1085.  
  1086.         if ($first === false{
  1087.             throw new Dwoo_Compilation_Exception($this'Unexpected EOF, a template tag was not closed');
  1088.         }
  1089.  
  1090.         while ($first===" " || $first==="\n" || $first==="\t" || $first==="\r"{
  1091.             if ($curBlock === 'root' && substr($in$fromstrlen($this->rd)) === $this->rd{
  1092.                 // end template tag
  1093.                 if ($this->debugecho 'TEMPLATE PARSING ENDED<br />';
  1094.                 return false;
  1095.             }
  1096.             $from++;
  1097.             if ($pointer !== null{
  1098.                 $pointer++;
  1099.             }
  1100.             if ($from >= $to{
  1101.                 if (is_array($parsingParams)) {
  1102.                     return $parsingParams;
  1103.                 else {
  1104.                     return '';
  1105.                 }
  1106.             }
  1107.             $first $in[$from];
  1108.         }
  1109.  
  1110.         $substr substr($in$from$to-$from);
  1111.  
  1112.         if ($this->debugecho '<br />PARSE CALL : PARSING "<b>'.htmlentities(substr($in$frommin($to-$from50))).(($to-$from50 '...':'').'</b>" @ '.$from.':'.$to.' in '.$curBlock.' : pointer='.$pointer.'<br/>';
  1113.  
  1114.         if ($first==='$'{
  1115.             // var
  1116.             $out $this->parseVar($in$from$to$parsingParams$curBlock$pointer);
  1117.             $parsed 'var';
  1118.         elseif ($first==='%' && preg_match('#^%[a-z]#i'$substr)) {
  1119.             // const
  1120.             $out $this->parseConst($in$from$to$parsingParams$curBlock$pointer);
  1121.         elseif ($first==='"' || $first==="'"{
  1122.             // string
  1123.             $out $this->parseString($in$from$to$parsingParams$curBlock$pointer);
  1124.         elseif (preg_match('/^[a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)?('.(is_array($parsingParams)||$curBlock!='root'?'':'\s+[^(]|').'\s*\(|\s*'.$this->rdr.'|\s*;)/i'$substr)) {
  1125.             // func
  1126.             $out $this->parseFunction($in$from$to$parsingParams$curBlock$pointer);
  1127.             $parsed 'func';
  1128.         elseif ($first === ';'{
  1129.             // instruction end
  1130.             if ($this->debugecho 'END OF INSTRUCTION<br />';
  1131.             if ($pointer !== null{
  1132.                 $pointer++;
  1133.             }
  1134.             return $this->parse($in$from+1$tofalse'root'$pointer);
  1135.         elseif ($curBlock === 'root' && preg_match('#^/([a-z][a-z0-9_]*)?#i'$substr$match)) {
  1136.             // close block
  1137.             if (!empty($match[1]&& $match[1== 'else'{
  1138.                 throw new Dwoo_Compilation_Exception($this'Else blocks must not be closed explicitly, they are automatically closed when their parent block is closed');
  1139.             }
  1140.             if (!empty($match[1]&& $match[1== 'elseif'{
  1141.                 throw new Dwoo_Compilation_Exception($this'Elseif blocks must not be closed explicitly, they are automatically closed when their parent block is closed or a new else/elseif block is declared after them');
  1142.             }
  1143.             if ($pointer !== null{
  1144.                 $pointer += strlen($match[0]);
  1145.             }
  1146.             if (empty($match[1])) {
  1147.                 if ($this->curBlock['type'== 'else' || $this->curBlock['type'== 'elseif'{
  1148.                     $pointer -= strlen($match[0]);
  1149.                 }
  1150.                 if ($this->debugecho 'TOP BLOCK CLOSED<br />';
  1151.                 return $this->removeTopBlock();
  1152.             else {
  1153.                 if ($this->debugecho 'BLOCK OF TYPE '.$match[1].' CLOSED<br />';
  1154.                 return $this->removeBlock($match[1]);
  1155.             }
  1156.         elseif ($curBlock === 'root' && substr($substr0strlen($this->rd)) === $this->rd{
  1157.             // end template tag
  1158.             if ($this->debugecho 'TAG PARSING ENDED<br />';
  1159.             return false;
  1160.         elseif (is_array($parsingParams&& preg_match('#^([a-z0-9_]+\s*=)(?:\s+|[^=]).*#i'$substr$match)) {
  1161.             // named parameter
  1162.             if ($this->debugecho 'NAMED PARAM FOUND<br />';
  1163.             $len strlen($match[1]);
  1164.             while (substr($in$from+$len1)===' '{
  1165.                 $len++;
  1166.             }
  1167.             if ($pointer !== null{
  1168.                 $pointer += $len;
  1169.             }
  1170.  
  1171.             $output array(trim(substr(trim($match[1])0-1))$this->parse($in$from+$len$tofalse'namedparam'$pointer));
  1172.  
  1173.             $parsingParams[$output;
  1174.             return $parsingParams;
  1175.         elseif ($substr!=='' && (is_array($parsingParams|| $curBlock === 'namedparam' || $curBlock === 'condition')) {
  1176.             // unquoted string, bool or number
  1177.             $out $this->parseOthers($in$from$to$parsingParams$curBlock$pointer);
  1178.         else {
  1179.             // parse error
  1180.             throw new Dwoo_Compilation_Exception($this'Parse error in "'.substr($in$from$to-$from).'"');
  1181.         }
  1182.  
  1183.         if (empty($out)) {
  1184.             return '';
  1185.         }
  1186.  
  1187.         $substr substr($in$pointer$to-$pointer);
  1188.         if (isset($parsed&& $parsed==='var' && preg_match('#^\s*([/%+*-])\s*([0-9]|\$)#'$substr$match)) {
  1189.             $pointer += strlen($match[0]1;
  1190.             if (is_array($parsingParams)) {
  1191.                 if ($match[2== '$'{
  1192.                     $expr $this->parseVar($in$pointer$toarray()$curBlock$pointer);
  1193.                 else {
  1194.                     $expr $this->parseOthers($in$pointer$toarray()'expression'$pointer);
  1195.                 }
  1196.                 $out[count($out)-1][0.= $match[1$expr[0];
  1197.                 $out[count($out)-1][1.= $match[1$expr[1];
  1198.             else {
  1199.                 if ($match[2== '$'{
  1200.                     $out .= $match[1$this->parseVar($in$pointer$tofalse$curBlock$pointer);
  1201.                 else {
  1202.                     $out .= $match[1$this->parseOthers($in$pointer$tofalse'expression'$pointer);
  1203.                 }
  1204.             }
  1205.         }
  1206.  
  1207.         if (isset($parsed&& $parsed==='func' && preg_match('#^->[a-z0-9_]+(\s*\(.+)?#is'$substr$match)) {
  1208.             $ptr 0;
  1209.  
  1210.             if (is_array($parsingParams)) {
  1211.                 $output $this->parseMethodCall($out[count($out)-1][1]$match[0]$curBlock$ptr);
  1212.  
  1213.                 $out[count($out)-1][0.= substr($match[0]0$ptr);
  1214.                 $out[count($out)-1][1.= $output;
  1215.             else {
  1216.                 $out $this->parseMethodCall($out$match[0]$curBlock$ptr);
  1217.             }
  1218.  
  1219.             $pointer += $ptr;
  1220.         }
  1221.  
  1222.         if ($curBlock === 'root' && substr($out0strlen(self::PHP_OPEN)) !== self::PHP_OPEN{
  1223.             return self::PHP_OPEN .'echo '.$out.';'self::PHP_CLOSE;
  1224.         else {
  1225.             return $out;
  1226.         }
  1227.     }
  1228.  
  1229.     /**
  1230.      * parses a function call
  1231.      *
  1232.      * @param string $in the string within which we must parse something
  1233.      * @param int $from the starting offset of the parsed area
  1234.      * @param int $to the ending offset of the parsed area
  1235.      * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
  1236.      * @param string $curBlock the current parser-block being processed
  1237.      * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default
  1238.      * @return string parsed values
  1239.      */
  1240.     protected function parseFunction($in$from$to$parsingParams false$curBlock=''&$pointer null)
  1241.     {
  1242.         $cmdstr substr($in$from$to-$from);
  1243.         preg_match('/^([a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)?)(\s*'.$this->rdr.'|\s*;)?/i'$cmdstr$match);
  1244.  
  1245.         if (empty($match[1])) {
  1246.             throw new Dwoo_Compilation_Exception($this'Parse error, invalid function name : '.substr($cmdstr015));
  1247.         }
  1248.  
  1249.         $func $match[1];
  1250.  
  1251.         if (!empty($match[2])) {
  1252.             $cmdstr $match[1];
  1253.         }
  1254.  
  1255.         if ($this->debugecho 'FUNC FOUND ('.$func.')<br />';
  1256.  
  1257.         $paramsep '';
  1258.  
  1259.         if (is_array($parsingParams|| $curBlock != 'root'{
  1260.             $paramspos strpos($cmdstr'(');
  1261.             $paramsep ')';
  1262.         elseif(preg_match_all('#[a-z0-9_]+(\s*\(|\s+[^(])#'$cmdstr$matchPREG_OFFSET_CAPTURE)) {
  1263.             $paramspos $match[1][0][1];
  1264.             $paramsep substr($match[1][0][0]-1=== '(' ')':'';
  1265.             if($paramsep === ')'{
  1266.                 $paramspos += strlen($match[1][0][0]1;
  1267.                 if(substr($cmdstr02=== 'if' || substr($cmdstr06=== 'elseif'{
  1268.                     $paramsep '';
  1269.                     if(strlen($match[1][0][0]1{
  1270.                         $paramspos--;
  1271.                     }
  1272.                 }
  1273.             }
  1274.         else {
  1275.             $paramspos false;
  1276.         }
  1277.  
  1278.         $state 0;
  1279.  
  1280.         if ($paramspos === false{
  1281.             $params array();
  1282.  
  1283.             if ($curBlock !== 'root'{
  1284.                 return $this->parseOthers($in$from$to$parsingParams$curBlock$pointer);
  1285.             }
  1286.         else {
  1287.             $whitespace strlen(substr($cmdstrstrlen($func)$paramspos-strlen($func)));
  1288.             $paramstr substr($cmdstr$paramspos+1);
  1289.             if (substr($paramstr-11=== $paramsep{
  1290.                 $paramstr substr($paramstr0-1);
  1291.             }
  1292.  
  1293.             if (strlen($paramstr)===0{
  1294.                 $params array();
  1295.                 $paramstr '';
  1296.             else {
  1297.                 $ptr 0;
  1298.                 $params array();
  1299.                 if ($func === 'empty'{
  1300.                     $params $this->parseVar($paramstr$ptrstrlen($paramstr)$params'root'$ptr);
  1301.                 else {
  1302.                     while ($ptr strlen($paramstr)) {
  1303.                         while (true{
  1304.                             if ($ptr >= strlen($paramstr)) {
  1305.                                 break 2;
  1306.                             }
  1307.  
  1308.                             if ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr=== ')'{
  1309.                                 if ($this->debugecho 'PARAM PARSING ENDED, ")" FOUND, POINTER AT '.$ptr.'<br/>';
  1310.                                 break 2;
  1311.                             elseif ($paramstr[$ptr=== ';'{
  1312.                                 $ptr++;
  1313.                                 if ($this->debugecho 'PARAM PARSING ENDED, ";" FOUND, POINTER AT '.$ptr.'<br/>';
  1314.                                 break 2;
  1315.                             elseif ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr=== '/'{
  1316.                                 if ($this->debugecho 'PARAM PARSING ENDED, "/" FOUND, POINTER AT '.$ptr.'<br/>';
  1317.                                 break 2;
  1318.                             elseif (substr($paramstr$ptrstrlen($this->rd)) === $this->rd{
  1319.                                 if ($this->debugecho 'PARAM PARSING ENDED, RIGHT DELIMITER FOUND, POINTER AT '.$ptr.'<br/>';
  1320.                                 break 2;
  1321.                             }
  1322.  
  1323.                             if ($paramstr[$ptr=== ' ' || $paramstr[$ptr=== ',' || $paramstr[$ptr=== "\r" || $paramstr[$ptr=== "\n" || $paramstr[$ptr=== "\t"{
  1324.                                 $ptr++;
  1325.                             else {
  1326.                                 break;
  1327.                             }
  1328.                         }
  1329.  
  1330.                         if ($this->debugecho 'FUNC START PARAM PARSING WITH POINTER AT '.$ptr.'<br/>';
  1331.  
  1332.                         if ($func === 'if' || $func === 'elseif' || $func === 'tif'{
  1333.                             $params $this->parse($paramstr$ptrstrlen($paramstr)$params'condition'$ptr);
  1334.                         else {
  1335.                             $params $this->parse($paramstr$ptrstrlen($paramstr)$params'function'$ptr);
  1336.                         }
  1337.  
  1338.                         if ($this->debugecho 'PARAM PARSED, POINTER AT '.$ptr.' ('.substr($paramstr$ptr-13).')<br/>';
  1339.                     }
  1340.                 }
  1341.                 $paramstr substr($paramstr0$ptr);
  1342.                 $state 0;
  1343.                 foreach ($params as $k=>$p{
  1344.                     if (is_array($p&& is_array($p[1])) {
  1345.                         $state |= 2;
  1346.                     else {
  1347.                         if (($state 2&& preg_match('#^(["\'])(.+?)\1$#'$p[0]$m)) {
  1348.                             $params[$karray($m[2]array('true''true'));
  1349.                         else {
  1350.                             if ($state 2{
  1351.                                 throw new Dwoo_Compilation_Exception($this'You can not use an unnamed parameter after a named one');
  1352.                             }
  1353.                             $state |= 1;
  1354.                         }
  1355.                     }
  1356.                 }
  1357.             }
  1358.         }
  1359.  
  1360.         if ($pointer !== null{
  1361.             $pointer += (isset($paramstrstrlen($paramstr0(')' === $paramsep ($paramspos === false 1)) strlen($func(isset($whitespace$whitespace 0);
  1362.             if ($this->debugecho 'FUNC ADDS '.((isset($paramstrstrlen($paramstr0(')' === $paramsep ($paramspos === false 1)) strlen($func)).' TO POINTER<br/>';
  1363.         }
  1364.  
  1365.         if ($curBlock === 'method' || $func === 'do' || strstr($func'::'!== false{
  1366.             $pluginType Dwoo::NATIVE_PLUGIN;
  1367.         else {
  1368.             $pluginType $this->getPluginType($func);
  1369.         }
  1370.  
  1371.         // blocks
  1372.         if ($pluginType Dwoo::BLOCK_PLUGIN{
  1373.             if ($curBlock !== 'root' || is_array($parsingParams)) {
  1374.                 throw new Dwoo_Compilation_Exception($this'Block plugins can not be used as other plugin\'s arguments');
  1375.             }
  1376.             if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1377.                 return $this->addCustomBlock($func$params$state);
  1378.             else {
  1379.                 return $this->addBlock($func$params$state);
  1380.             }
  1381.         elseif ($pluginType Dwoo::SMARTY_BLOCK{
  1382.             if ($curBlock !== 'root' || is_array($parsingParams)) {
  1383.                 throw new Dwoo_Compilation_Exception($this'Block plugins can not be used as other plugin\'s arguments');
  1384.             }
  1385.  
  1386.             if ($state 2{
  1387.                 array_unshift($paramsarray('__functype'array($pluginType$pluginType)));
  1388.                 array_unshift($paramsarray('__funcname'array($func$func)));
  1389.             else {
  1390.                 array_unshift($paramsarray($pluginType$pluginType));
  1391.                 array_unshift($paramsarray($func$func));
  1392.             }
  1393.  
  1394.             return $this->addBlock('smartyinterface'$params$state);
  1395.         }
  1396.  
  1397.         // funcs
  1398.         if ($pluginType Dwoo::NATIVE_PLUGIN || $pluginType Dwoo::PROXY_PLUGIN || $pluginType Dwoo::SMARTY_FUNCTION || $pluginType Dwoo::SMARTY_BLOCK{
  1399.             $params $this->mapParams($paramsnull$state);
  1400.         elseif ($pluginType Dwoo::CLASS_PLUGIN{
  1401.             if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1402.                 $params $this->mapParams($paramsarray($this->customPlugins[$func]['class']$this->customPlugins[$func]['function'])$state);
  1403.             else {
  1404.                 $params $this->mapParams($paramsarray('Dwoo_Plugin_'.$func($pluginType Dwoo::COMPILABLE_PLUGIN'compile' 'process')$state);
  1405.             }
  1406.         elseif ($pluginType Dwoo::FUNC_PLUGIN{
  1407.             if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1408.                 $params $this->mapParams($params$this->customPlugins[$func]['callback']$state);
  1409.             else {
  1410.                 $params $this->mapParams($params'Dwoo_Plugin_'.$func.(($pluginType Dwoo::COMPILABLE_PLUGIN'_compile' '')$state);
  1411.             }
  1412.         elseif ($pluginType Dwoo::SMARTY_MODIFIER{
  1413.             $output 'smarty_modifier_'.$func.'('.implode(', '$params).')';
  1414.         }
  1415.  
  1416.         // only keep php-syntax-safe values for non-block plugins
  1417.         foreach ($params as &$p)
  1418.             $p $p[0];
  1419.         if ($pluginType Dwoo::NATIVE_PLUGIN{
  1420.             if ($func === 'do'{
  1421.                 if (isset($params['*'])) {
  1422.                     $output implode(';'$params['*']).';';
  1423.                 else {
  1424.                     $output '';
  1425.                 }
  1426.  
  1427.                 if (is_array($parsingParams|| $curBlock !== 'root'{
  1428.                     throw new Dwoo_Compilation_Exception($this'Do can not be used inside another function or block');
  1429.                 else {
  1430.                     return self::PHP_OPEN.$output.self::PHP_CLOSE;
  1431.                 }
  1432.             else {
  1433.                 if (isset($params['*'])) {
  1434.                     $output $func.'('.implode(', '$params['*']).')';
  1435.                 else {
  1436.                     $output $func.'()';
  1437.                 }
  1438.             }
  1439.         elseif ($pluginType Dwoo::FUNC_PLUGIN{
  1440.             if ($pluginType Dwoo::COMPILABLE_PLUGIN{
  1441.                 if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1442.                     $funcCompiler $this->customPlugins[$func]['callback'];
  1443.                 else {
  1444.                     $funcCompiler 'Dwoo_Plugin_'.$func.'_compile';
  1445.                 }
  1446.                 array_unshift($params$this);
  1447.                 $output call_user_func_array($funcCompiler$params);
  1448.             else {
  1449.                 array_unshift($params'$this');
  1450.                 $params self::implode_r($params);
  1451.  
  1452.                 if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1453.                     $callback $this->customPlugins[$func]['callback'];
  1454.                     $output 'call_user_func(\''.$callback.'\', '.$params.')';
  1455.                 else {
  1456.                     $output 'Dwoo_Plugin_'.$func.'('.$params.')';
  1457.                 }
  1458.             }
  1459.         elseif ($pluginType Dwoo::CLASS_PLUGIN{
  1460.             if ($pluginType Dwoo::COMPILABLE_PLUGIN{
  1461.                 if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1462.                     $callback $this->customPlugins[$func]['callback'];
  1463.                     if (!is_array($callback)) {
  1464.                         if (!method_exists($callback'compile')) {
  1465.                             throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use');
  1466.                         }
  1467.                         if (($ref new ReflectionMethod($callback'compile')) && $ref->isStatic()) {
  1468.                             $funcCompiler array($callback'compile');
  1469.                         else {
  1470.                             $funcCompiler array(new $callback'compile');
  1471.                         }
  1472.                     else {
  1473.                         $funcCompiler $callback;
  1474.                     }
  1475.                 else {
  1476.                     $funcCompiler array('Dwoo_Plugin_'.$func'compile');
  1477.                     array_unshift($params$this);
  1478.                 }
  1479.                 $output call_user_func_array($funcCompiler$params);
  1480.             else {
  1481.                 $params self::implode_r($params);
  1482.                 if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1483.                     $callback $this->customPlugins[$func]['callback'];
  1484.                     if (!is_array($callback)) {
  1485.                         if (!method_exists($callback'process')) {
  1486.                             throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "process" method to be usable, or you should provide a full callback to the method to use');
  1487.                         }
  1488.                         if (($ref new ReflectionMethod($callback'process')) && $ref->isStatic()) {
  1489.                             $output 'call_user_func(array(\''.$callback.'\', \'process\'), '.$params.')';
  1490.                         else {
  1491.                             $output 'call_user_func(array($this->getObjectPlugin(\''.$callback.'\'), \'process\'), '.$params.')';
  1492.                         }
  1493.                     elseif (is_object($callback[0])) {
  1494.                         $output 'call_user_func(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), '.$params.')';
  1495.                     elseif (($ref new ReflectionMethod($callback[0]$callback[1])) && $ref->isStatic()) {
  1496.                         $output 'call_user_func(array(\''.$callback[0].'\', \''.$callback[1].'\'), '.$params.')';
  1497.                     else {
  1498.                         $output 'call_user_func(array($this->getObjectPlugin(\''.$callback[0].'\'), \''.$callback[1].'\'), '.$params.')';
  1499.                     }
  1500.                     if (empty($params)) {
  1501.                         $output substr($output0-3).')';
  1502.                     }
  1503.                 else {
  1504.                     $output '$this->classCall(\''.$func.'\', array('.$params.'))';
  1505.                 }
  1506.             }
  1507.         elseif ($pluginType Dwoo::PROXY_PLUGIN{
  1508.             if (isset($params['*'])) {
  1509.                 $output call_user_func_array(array($this->dwoo->getPluginProxy()$func)$params['*']);
  1510.             else {
  1511.                 $output call_user_func(array($this->dwoo->getPluginProxy()$func));
  1512.             }
  1513.         elseif ($pluginType Dwoo::SMARTY_FUNCTION{
  1514.             if (isset($params['*'])) {
  1515.                 $params self::implode_r($params['*']true);
  1516.             else {
  1517.                 $params '';
  1518.             }
  1519.  
  1520.             if ($pluginType Dwoo::CUSTOM_PLUGIN{
  1521.                 $callback $this->customPlugins[$func]['callback'];
  1522.                 if (is_array($callback)) {
  1523.                     if (is_object($callback[0])) {
  1524.                         $output 'call_user_func_array(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array(array('.$params.'), $this))';
  1525.                     else {
  1526.                         $output 'call_user_func_array(array(\''.$callback[0].'\', \''.$callback[1].'\'), array(array('.$params.'), $this))';
  1527.                     }
  1528.                 else {
  1529.                     $output $callback.'(array('.$params.'), $this)';
  1530.                 }
  1531.             else {
  1532.                 $output 'smarty_function_'.$func.'(array('.$params.'), $this)';
  1533.             }
  1534.         }
  1535.  
  1536.         if (is_array($parsingParams)) {
  1537.             $parsingParams[array($output$output);
  1538.             return $parsingParams;
  1539.         elseif ($curBlock === 'namedparam'{
  1540.             return array($output$output);
  1541.         else {
  1542.             return $output;
  1543.         }
  1544.     }
  1545.  
  1546.     /**
  1547.      * parses a string
  1548.      *
  1549.      * @param string $in the string within which we must parse something
  1550.      * @param int $from the starting offset of the parsed area
  1551.      * @param int $to the ending offset of the parsed area
  1552.      * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
  1553.      * @param string $curBlock the current parser-block being processed
  1554.      * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default
  1555.      * @return string parsed values
  1556.      */
  1557.     protected function parseString($in$from$to$parsingParams false$curBlock=''&$pointer null)
  1558.     {
  1559.         $substr substr($in$from$to-$from);
  1560.         $first $substr[0];
  1561.  
  1562.         if ($this->debugecho 'STRING FOUND (in '.htmlentities(substr($in$frommin($to-$from50))).(($to-$from50 '...':'').')<br />';
  1563.         $strend false;
  1564.         $o $from+1;
  1565.         while ($strend === false{
  1566.             $strend strpos($in$first$o);
  1567.             if ($strend === false{
  1568.                 throw new Dwoo_Compilation_Exception($this'Unfinished string, started with '.substr($in$from$to-$from));
  1569.             }
  1570.             if (substr($in$strend-11=== '\\'{
  1571.                 $o $strend+1;
  1572.                 $strend false;
  1573.             }
  1574.         }
  1575.         if ($this->debugecho 'STRING DELIMITED: '.substr($in$from$strend+1-$from).'<br/>';
  1576.  
  1577.         $srcOutput substr($in$from$strend+1-$from);
  1578.  
  1579.         if ($pointer !== null{
  1580.             $pointer += strlen($srcOutput);
  1581.         }
  1582.  
  1583.         $output $this->replaceStringVars($srcOutput$first);
  1584.  
  1585.         // handle modifiers
  1586.         if ($curBlock !== 'modifier' && preg_match('#^((?:\|(?:@?[a-z0-9_]+(?::.*)*))+)#i'substr($substr$strend+1-$from)$match)) {
  1587.             $modstr $match[1];
  1588.  
  1589.             if ($curBlock === 'root' && substr($modstr-1=== '}'{
  1590.                 $modstr substr($modstr0-1);
  1591.             }
  1592.             $modstr str_replace('\\'.$first$first$modstr);
  1593.             $ptr 0;
  1594.             $output $this->replaceModifiers(array(nullnull$output$modstr)'string'$ptr);
  1595.  
  1596.             $strend += $ptr;
  1597.             if ($pointer !== null{
  1598.                 $pointer += $ptr;
  1599.             }
  1600.             $srcOutput .= substr($substr$strend+1-$from$ptr);
  1601.         }
  1602.  
  1603.         if (is_array($parsingParams)) {
  1604.             $parsingParams[array($outputsubstr($srcOutput1-1));
  1605.             return $parsingParams;
  1606.         elseif ($curBlock === 'namedparam'{
  1607.             return array($outputsubstr($srcOutput1-1));
  1608.         else {
  1609.             return $output;
  1610.         }
  1611.     }
  1612.  
  1613.     /**
  1614.      * parses a constant
  1615.      *
  1616.      * @param string $in the string within which we must parse something
  1617.      * @param int $from the starting offset of the parsed area
  1618.      * @param int $to the ending offset of the parsed area
  1619.      * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
  1620.      * @param string $curBlock the current parser-block being processed
  1621.      * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default
  1622.      * @return string parsed values
  1623.      */
  1624.     protected function parseConst($in$from$to$parsingParams false$curBlock=''&$pointer null)
  1625.     {
  1626.         $substr substr($in$from$to-$from);
  1627.  
  1628.         if ($this->debug{
  1629.             echo 'CONST FOUND : '.$substr.'<br />';
  1630.         }
  1631.  
  1632.         if (!preg_match('#^%([a-z0-9_:]+)#i'$substr$m)) {
  1633.             throw new Dwoo_Compilation_Exception($this'Invalid constant');
  1634.         }
  1635.  
  1636.         if ($pointer !== null{
  1637.             $pointer += strlen($m[0]);
  1638.         }
  1639.  
  1640.         $output $this->parseConstKey($m[1]$curBlock);
  1641.  
  1642.         if (is_array($parsingParams)) {
  1643.             $parsingParams[array($output$m[1]);
  1644.             return $parsingParams;
  1645.         elseif ($curBlock === 'namedparam'{
  1646.             return array($output$m[1]);
  1647.         else {
  1648.             return $output;
  1649.         }
  1650.     }
  1651.  
  1652.     /**
  1653.      * parses a constant
  1654.      *
  1655.      * @param string $key the constant to parse
  1656.      * @param string $curBlock the current parser-block being processed
  1657.      * @return string parsed constant
  1658.      */
  1659.     protected function parseConstKey($key$curBlock)
  1660.     {
  1661.         if ($this->securityPolicy !== null && $this->securityPolicy->getConstantHandling(=== Dwoo_Security_Policy::CONST_DISALLOW{
  1662.             return 'null';
  1663.         }
  1664.  
  1665.         if ($curBlock !== 'root'{
  1666.             $output '(defined("'.$key.'") ? '.$key.' : null)';
  1667.         else {
  1668.             $output $key;
  1669.         }
  1670.  
  1671.         return $output;
  1672.     }
  1673.  
  1674.     /**
  1675.      * parses a variable
  1676.      *
  1677.      * @param string $in the string within which we must parse something
  1678.      * @param int $from the starting offset of the parsed area
  1679.      * @param int $to the ending offset of the parsed area
  1680.      * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
  1681.      * @param string $curBlock the current parser-block being processed
  1682.      * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default
  1683.      * @return string parsed values
  1684.      */
  1685.     protected function parseVar($in$from$to$parsingParams false$curBlock=''&$pointer null)
  1686.     {
  1687.         $substr substr($in$from$to-$from);
  1688.  
  1689.         if (preg_match('#(\$?\.?[a-z0-9_:]*(?:(?:(?:\.|->)(?:[a-z0-9_:]+|(?R))|\[(?:[a-z0-9_:]+|(?R)|(["\'])[^\2]*\2)\]))*)' // var key
  1690.             ($curBlock==='root' || $curBlock==='function' || $curBlock==='namedparam' || $curBlock==='condition' || $curBlock==='variable' || $curBlock==='expression' '(\(.*)?' '()'// method call
  1691.             ($curBlock==='root' || $curBlock==='function' || $curBlock==='namedparam' || $curBlock==='condition' || $curBlock==='variable' || $curBlock==='delimited_string' '((?:(?:[+/*%=-])(?:(?<!=)=?-?[$%][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|(?<!=)=?-?[0-9.,]*|[+-]))*)':'()'// simple math expressions
  1692.             ($curBlock!=='modifier' '((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').*?\5|:[^`]*))*))+)?':'(())'// modifiers
  1693.             '#i'$substr$match)) {
  1694.             $key substr($match[1]1);
  1695.  
  1696.             $matchedLength strlen($match[0]);
  1697.             $hasModifiers !empty($match[5]);
  1698.             $hasExpression !empty($match[4]);
  1699.             $hasMethodCall !empty($match[3]);
  1700.  
  1701.             if ($hasMethodCall{
  1702.                 $matchedLength -= strlen($match[3]strlen(substr($match[1]strrpos($match[1]'->')));
  1703.                 $key substr($match[1]1strrpos($match[1]'->')-1);
  1704.                 $methodCall substr($match[1]strrpos($match[1]'->')) $match[3];
  1705.             }
  1706.  
  1707.             if ($hasModifiers{
  1708.                 $matchedLength -= strlen($match[5]);
  1709.             }
  1710.  
  1711.             if ($pointer !== null{
  1712.                 $pointer += $matchedLength;
  1713.             }
  1714.  
  1715.             // replace useless brackets by dot accessed vars
  1716.             $key preg_replace('#\[([^$%\[.>-]+)\]#''.$1'$key);
  1717.  
  1718.             // prevent $foo->$bar calls because it doesn't seem worth the trouble
  1719.             if (strpos($key'->$'!== false{
  1720.                 throw new Dwoo_Compilation_Exception($this'You can not access an object\'s property using a variable name.');
  1721.             }
  1722.  
  1723.             if ($this->debug{
  1724.                 if ($hasMethodCall{
  1725.                     echo 'METHOD CALL FOUND : $'.$key.substr($methodCall030).'<br />';
  1726.                 else {
  1727.                     echo 'VAR FOUND : $'.$key.'<br />';
  1728.                 }
  1729.             }
  1730.  
  1731.             $key str_replace('"''\\"'$key);
  1732.  
  1733.             $cnt=substr_count($key'$');
  1734.             if ($cnt 0{
  1735.                 $uid 0;
  1736.                 $parsed array($uid => '');
  1737.                 $current =$parsed;
  1738.                 $curTxt =$parsed[$uid++];
  1739.                 $tree array();
  1740.                 $chars str_split($key1);
  1741.                 $inSplittedVar false;
  1742.                 $bracketCount 0;
  1743.  
  1744.                 while (($char array_shift($chars)) !== null{
  1745.                     if ($char === '['{
  1746.                         if (count($tree0{
  1747.                             $bracketCount++;
  1748.                         else {
  1749.                             $tree[=$current;
  1750.                             $current[$uidarray($uid+=> '');
  1751.                             $current =$current[$uid++];
  1752.                             $curTxt =$current[$uid++];
  1753.                             continue;
  1754.                         }
  1755.                     elseif ($char === ']'{
  1756.                         if ($bracketCount 0{
  1757.                             $bracketCount--;
  1758.                         else {
  1759.                             $current =$tree[count($tree)-1];
  1760.                             array_pop($tree);
  1761.                             if (current($chars!== '[' && current($chars!== false && current($chars!== ']'{
  1762.                                 $current[$uid'';
  1763.                                 $curTxt =$current[$uid++];
  1764.                             }
  1765.                             continue;
  1766.                         }
  1767.                     elseif ($char === '$'{
  1768.                         if (count($tree== 0{
  1769.                             $curTxt =$current[$uid++];
  1770.                             $inSplittedVar true;
  1771.                         }
  1772.                     elseif (($char === '.' || $char === '-'&& count($tree== && $inSplittedVar{
  1773.                         $curTxt =$current[$uid++];
  1774.                         $inSplittedVar false;
  1775.                     }
  1776.  
  1777.                     $curTxt .= $char;
  1778.                 }
  1779.                 unset($uid$current$curTxt$tree$chars);
  1780.  
  1781.                 if ($this->debugecho 'RECURSIVE VAR REPLACEMENT : '.$key.'<br>';
  1782.  
  1783.                 $key $this->flattenVarTree($parsed);
  1784.  
  1785.                 if ($this->debugecho 'RECURSIVE VAR REPLACEMENT DONE : '.$key.'<br>';
  1786.  
  1787.                 $output preg_replace('#(^""\.|""\.|\.""$|(\()""\.|\.""(\)))#''$2$3''$this->readVar("'.$key.'")');
  1788.             else {
  1789.                 $output $this->parseVarKey($key$hasModifiers 'modifier' $curBlock);
  1790.             }
  1791.  
  1792.             // methods
  1793.             if ($hasMethodCall{
  1794.                 $ptr 0;
  1795.  
  1796.                 $output $this->parseMethodCall($output$methodCall$curBlock$ptr);
  1797.  
  1798.                 if ($pointer !== null{
  1799.                     $pointer += $ptr;
  1800.                 }
  1801.                 $matchedLength += $ptr;
  1802.             }
  1803.  
  1804.             if ($hasExpression{
  1805.                 // expressions
  1806.                 preg_match_all('#(?:([+/*%=-])(=?-?[%$][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|=?-?[0-9.,]+|\1))#i'$match[4]$expMatch);
  1807.  
  1808.                 foreach ($expMatch[1as $k=>$operator{
  1809.                     if (substr($expMatch[2][$k]01)==='='{
  1810.                         $assign true;
  1811.                         if ($operator === '='{
  1812.                             throw new Dwoo_Compilation_Exception($this'Invalid expression <em>'.$substr.'</em>, can not use "==" in expressions');
  1813.                         }
  1814.                         if ($curBlock !== 'root'{
  1815.                             throw new Dwoo_Compilation_Exception($this'Invalid expression <em>'.$substr.'</em>, "=" can only be used in pure expressions like {$foo+=3}, {$foo="bar"}');
  1816.                         }
  1817.                         $operator .= '=';
  1818.                         $expMatch[2][$ksubstr($expMatch[2][$k]1);
  1819.                     }
  1820.  
  1821.                     if (substr($expMatch[2][$k]01)==='-' && strlen($expMatch[2][$k]1{
  1822.                         $operator .= '-';
  1823.                         $expMatch[2][$ksubstr($expMatch[2][$k]1);
  1824.                     }
  1825.                     if (($operator==='+'||$operator==='-'&& $expMatch[2][$k]===$operator{
  1826.                         $output '('.$output.$operator.$operator.')';
  1827.                         break;
  1828.                     elseif (substr($expMatch[2][$k]01=== '$'{
  1829.                         $output '('.$output.' '.$operator.' '.$this->parseVar($expMatch[2][$k]0strlen($expMatch[2][$k])false'expression').')';
  1830.                     elseif (substr($expMatch[2][$k]01=== '%'{
  1831.                         $output '('.$output.' '.$operator.' '.$this->parseConst($expMatch[2][$k]0strlen($expMatch[2][$k])false'expression').')';
  1832.                     elseif (!empty($expMatch[2][$k])) {
  1833.                         $output '('.$output.' '.$operator.' '.str_replace(',''.'$expMatch[2][$k]).')';
  1834.                     else {
  1835.                         throw new Dwoo_Compilation_Exception($this'Unfinished expression <em>'.$substr.'</em>, missing var or number after math operator');
  1836.                     }
  1837.                 }
  1838.             elseif ($curBlock === 'root' && substr(trim(substr($substr$matchedLength))01=== '='{
  1839.                 // var assignment
  1840.                 $value trim(substr(trim(substr($substr$matchedLength))1));
  1841.  
  1842.                 if ($pointer !== null{
  1843.                     $pointer++;
  1844.                 }
  1845.                 $parts array();
  1846.                 $parts $this->parse($value0strlen($value)$parts'condition'$pointer);
  1847.  
  1848.                 // load if plugin
  1849.                 try {
  1850.                     $this->getPluginType('if');
  1851.                 catch (Dwoo_Exception $e{
  1852.                     throw new Dwoo_Compilation_Exception($this'Assignments require the "if" plugin to be accessible');
  1853.                 }
  1854.  
  1855.                 $parts $this->mapParams($partsarray('Dwoo_Plugin_if''init')1);
  1856.                 $parts $this->getCompiledParams($parts);
  1857.  
  1858.                 $value Dwoo_Plugin_if::replaceKeywords($parts['*']$this);
  1859.  
  1860.                 $output .= '='.implode(' '$value);
  1861.                 $assign true;
  1862.             }
  1863.  
  1864.             if ($this->autoEscape === true{
  1865.                 $output '(is_string($tmp='.$output.') ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)';
  1866.             }
  1867.  
  1868.             // handle modifiers
  1869.             if ($curBlock !== 'modifier' && $hasModifiers{
  1870.                 $ptr 0;
  1871.                 $output $this->replaceModifiers(array(nullnull$output$match[5])'var'$ptr);
  1872.                 if ($pointer !== null{
  1873.                     $pointer += $ptr;
  1874.                 }
  1875.                 $matchedLength += $ptr;
  1876.             }
  1877.  
  1878.             if (is_array($parsingParams)) {
  1879.                 $parsingParams[array($output$key);
  1880.                 return $parsingParams;
  1881.             elseif ($curBlock === 'namedparam'{
  1882.                 return array($output$key);
  1883.             elseif ($curBlock === 'string' || $curBlock === 'delimited_string'{
  1884.                 return array($matchedLength$output);
  1885.             elseif ($curBlock === 'expression' || $curBlock === 'variable'{
  1886.                 return $output;
  1887.             elseif (isset($assign)) {
  1888.                 return self::PHP_OPEN.$output.';'.self::PHP_CLOSE;
  1889.             else {
  1890.                 return $output;
  1891.             }
  1892.         else {
  1893.             if ($curBlock === 'string' || $curBlock === 'delimited_string'{
  1894.                 return array(0'');
  1895.             else {
  1896.                 throw new Dwoo_Compilation_Exception($this'Invalid variable name <em>'.$substr.'</em>');
  1897.             }
  1898.         }
  1899.     }
  1900.  
  1901.     /**
  1902.      * parses any number of chained method calls/property reads
  1903.      *
  1904.      * @param string $output the variable or whatever upon which the method are called
  1905.      * @param string $methodCall method call source, starting at "->"
  1906.      * @param string $curBlock the current parser-block being processed
  1907.      * @param int $pointer a reference to a pointer that will be increased by the amount of characters parsed
  1908.      * @return string parsed call(s)/read(s)
  1909.      */
  1910.     protected function parseMethodCall($output$methodCall$curBlock&$pointer)
  1911.     {
  1912.         $ptr 0;
  1913.         $len strlen($methodCall);
  1914.  
  1915.         while ($ptr $len{
  1916.             if (strpos($methodCall'->'$ptr=== $ptr{
  1917.                 $ptr += 2;
  1918.             }
  1919.  
  1920.             if (in_array($methodCall[$ptr]array(';''/'' '"\t""\r""\n"')''+''*''%''=''-')) || substr($methodCall$ptrstrlen($this->rd)) === $this->rd{
  1921.                 // break char found
  1922.                 break;
  1923.             }
  1924.  
  1925.             if(!preg_match('/^([a-z0-9_]+)(\(.*?\))?/i'substr($methodCall$ptr)$methMatch)) {
  1926.                 throw new Dwoo_Compilation_Exception($this'Invalid method name : '.substr($methodCall$ptr20));
  1927.             }
  1928.  
  1929.             if (empty($methMatch[2])) {
  1930.                 // property
  1931.                 if ($curBlock === 'root'{
  1932.                     $output .= '->'.$methMatch[1];
  1933.                 else {
  1934.                     $output '(($tmp = '.$output.') ? $tmp->'.$methMatch[1].' : null)';
  1935.                 }
  1936.                 $ptr += strlen($methMatch[1]);
  1937.             else {
  1938.                 // method
  1939.                 if (substr($methMatch[2]02=== '()'{
  1940.                     $parsedCall '->'.$methMatch[1].'()';
  1941.                     $ptr += strlen($methMatch[1]2;
  1942.                 else {
  1943.                     $parsedCall '->'.$this->parseFunction($methodCall$ptrstrlen($methodCall)false'method'$ptr);
  1944.                 }
  1945.                 if ($curBlock === 'root'{
  1946.                     $output .= $parsedCall;
  1947.                 else {
  1948.                     $output '(($tmp = '.$output.') ? $tmp'.$parsedCall.' : null)';
  1949.                 }
  1950.             }
  1951.         }
  1952.  
  1953.         $pointer += $ptr;
  1954.         return $output;
  1955.     }
  1956.  
  1957.     /**
  1958.      * parses a constant variable (a variable that doesn't contain another variable) and preprocesses it to save runtime processing time
  1959.      *
  1960.      * @param string $key the variable to parse
  1961.      * @param string $curBlock the current parser-block being processed
  1962.      * @return string parsed variable
  1963.      */
  1964.     protected function parseVarKey($key$curBlock)
  1965.     {
  1966.         if ($key === ''{
  1967.             return '$this->scope';
  1968.         }
  1969.         if (substr($key01=== '.'{
  1970.             $key 'dwoo'.$key;
  1971.         }
  1972.         if (preg_match('#dwoo\.(get|post|server|cookies|session|env|request)((?:\.[a-z0-9_-]+)+)#i'$key$m)) {
  1973.             $global strtoupper($m[1]);
  1974.             if ($global === 'COOKIES'{
  1975.                 $global 'COOKIE';
  1976.             }
  1977.             $key '$_'.$global;
  1978.             foreach (explode('.'ltrim($m[2]'.')) as $part)
  1979.                 $key .= '['.var_export($parttrue).']';
  1980.             if ($curBlock === 'root'{
  1981.                 $output $key;
  1982.             else {
  1983.                 $output '(isset('.$key.')?'.$key.':null)';
  1984.             }
  1985.         elseif (preg_match('#dwoo\.const\.([a-z0-9_:]+)#i'$key$m)) {
  1986.             return $this->parseConstKey($m[1]$curBlock);
  1987.         elseif ($this->scope !== null{
  1988.             if (strstr($key'.'=== false && strstr($key'['=== false && strstr($key'->'=== false{
  1989.                 if ($key === 'dwoo'{
  1990.                     $output '$this->globals';
  1991.                 elseif ($key === '_root' || $key === '__'{
  1992.                     $output '$this->data';
  1993.                 elseif ($key === '_parent' || $key === '_'{
  1994.                     $output '$this->readParentVar(1)';
  1995.                 elseif ($key === '_key'{
  1996.                     $output '$tmp_key';
  1997.                 else {
  1998.                     if ($curBlock === 'root'{
  1999.                         $output '$this->scope["'.$key.'"]';
  2000.                     else {
  2001.                         $output '(isset($this->scope["'.$key.'"]) ? $this->scope["'.$key.'"] : null)';
  2002.                     }
  2003.                 }
  2004.             else {
  2005.                 preg_match_all('#(\[|->|\.)?([a-z0-9_]+|(\\\?[\'"])[^\3]*\3)\]?#i'$key$m);
  2006.  
  2007.                 $i $m[2][0];
  2008.                 if ($i === '_parent' || $i === '_'{
  2009.                     $parentCnt 0;
  2010.  
  2011.                     while (true{
  2012.                         $parentCnt++;
  2013.                         array_shift($m[2]);
  2014.                         array_shift($m[1]);
  2015.                         if (current($m[2]=== '_parent'{
  2016.                             continue;
  2017.                         }
  2018.                         break;
  2019.                     }
  2020.  
  2021.                     $output '$this->readParentVar('.$parentCnt.')';
  2022.                 else {
  2023.                     if ($i === 'dwoo'{
  2024.                         $output '$this->globals';
  2025.                         array_shift($m[2]);
  2026.                         array_shift($m[1]);
  2027.                     elseif ($i === '_root' || $i === '__'{
  2028.                         $output '$this->data';
  2029.                         array_shift($m[2]);
  2030.                         array_shift($m[1]);
  2031.                     elseif ($i === '_key'{
  2032.                         $output '$tmp_key';
  2033.                     else {
  2034.                         $output '$this->scope';
  2035.                     }
  2036.  
  2037.                     while (count($m[1]&& $m[1][0!== '->'{
  2038.                         $m[2][0preg_replace('/(^\\\([\'"])|\\\([\'"])$)/x''$2$3'$m[2][0]);
  2039.                         if(substr($m[2][0]01== '"' || substr($m[2][0]01== "'"{
  2040.                             $output .= '['.$m[2][0].']';
  2041.                         else {
  2042.                             $output .= '["'.$m[2][0].'"]';
  2043.                         }
  2044.                         array_shift($m[2]);
  2045.                         array_shift($m[1]);
  2046.                     }
  2047.  
  2048.                     if ($curBlock !== 'root'{
  2049.                         $output '(isset('.$output.') ? '.$output.':null)';
  2050.                     }
  2051.                 }
  2052.  
  2053.                 if (count($m[2])) {
  2054.                     unset($m[0]);
  2055.                     $output '$this->readVarInto('.str_replace("\n"''var_export($mtrue)).', '.$output.')';
  2056.                 }
  2057.             }
  2058.         else {
  2059.             preg_match_all('#(\[|->|\.)?([a-z0-9_]+)\]?#i'$key$m);
  2060.             unset($m[0]);
  2061.             $output '$this->readVar('.str_replace("\n"''var_export($mtrue)).')';
  2062.         }
  2063.  
  2064.         return $output;
  2065.     }
  2066.  
  2067.     /**
  2068.      * flattens a variable tree, this helps in parsing very complex variables such as $var.foo[$foo.bar->baz].baz,
  2069.      * it computes the contents of the brackets first and works out from there
  2070.      *
  2071.      * @param array $tree the variable tree parsed by he parseVar() method that must be flattened
  2072.      * @param bool $recursed leave that to false by default, it is only for internal use
  2073.      * @return string flattened tree
  2074.      */
  2075.     protected function flattenVarTree(array $tree$recursed=false)
  2076.     {
  2077.         $out $recursed ?  '".$this->readVarInto(' '';
  2078.         foreach ($tree as $bit{
  2079.             if (is_array($bit)) {
  2080.                 $out.='.'.$this->flattenVarTree($bitfalse);
  2081.             else {
  2082.                 $key str_replace('"''\\"'$bit);
  2083.  
  2084.                 if (substr($key01)==='$'{
  2085.                     $out .= '".'.$this->parseVar($key0strlen($key)false'variable').'."';
  2086.                 else {
  2087.                     $cnt substr_count($key'$');
  2088.  
  2089.                     if ($this->debugecho 'PARSING SUBVARS IN : '.$key.'<br>';
  2090.                     if ($cnt 0{
  2091.                         while (--$cnt >= 0{
  2092.                             if (isset($last)) {
  2093.                                 $last strrpos($key'$'(strlen($key$last 1));
  2094.                             else {
  2095.                                 $last strrpos($key'$');
  2096.                             }
  2097.                             preg_match('#\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*'.
  2098.                                       '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i'substr($key$last)$submatch);
  2099.  
  2100.                             $len strlen($submatch[0]);
  2101.                             $key substr_replace(
  2102.                                 $key,
  2103.                                 preg_replace_callback(
  2104.                                     '#(\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*)'.
  2105.                                     '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i',
  2106.                                     array($this'replaceVarKeyHelper')substr($key$last$len)
  2107.                                 ),
  2108.                                 $last,
  2109.                                 $len
  2110.                             );
  2111.                             if ($this->debugecho 'RECURSIVE VAR REPLACEMENT DONE : '.$key.'<br>';
  2112.                         }
  2113.                         unset($last);
  2114.  
  2115.                         $out .= $key;
  2116.                     else {
  2117.                         $out .= $key;
  2118.                     }
  2119.                 }
  2120.             }
  2121.         }
  2122.         $out .= $recursed ')."' '';
  2123.         return $out;
  2124.     }
  2125.  
  2126.     /**
  2127.      * helper function that parses a variable
  2128.      *
  2129.      * @param array $match the matched variable, array(1=>"string match")
  2130.      * @return string parsed variable
  2131.      */
  2132.     protected function replaceVarKeyHelper($match)
  2133.     {
  2134.         return '".'.$this->parseVar($match[0]0strlen($match[0])false'variable').'."';
  2135.     }
  2136.  
  2137.     /**
  2138.      * parses various constants, operators or non-quoted strings
  2139.      *
  2140.      * @param string $in the string within which we must parse something
  2141.      * @param int $from the starting offset of the parsed area
  2142.      * @param int $to the ending offset of the parsed area
  2143.      * @param mixed $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
  2144.      * @param string $curBlock the current parser-block being processed
  2145.      * @param mixed $pointer a reference to a pointer that will be increased by the amount of characters parsed, or null by default
  2146.      * @return string parsed values
  2147.      */
  2148.     protected function parseOthers($in$from$to$parsingParams false$curBlock=''&$pointer null)
  2149.     {
  2150.         $first $in[$from];
  2151.         $substr substr($in$from$to-$from);
  2152.  
  2153.         $end strlen($substr);
  2154.  
  2155.         if ($curBlock === 'condition'{
  2156.             $breakChars array('('')'' ''||''&&''|''&''>=''<=''===''==''=''!==''!=''<<''<''>>''>''^''~'',''+''-''*''/''%''!''?'':'$this->rd';');
  2157.         elseif ($curBlock === 'modifier'{
  2158.             $breakChars array(' '','')'':''|'"\r""\n""\t"";"$this->rd);
  2159.         elseif ($curBlock === 'expression'{
  2160.             $breakChars array('/''%''+''-''*'' '','')'"\r""\n""\t"";"$this->rd);
  2161.         else {
  2162.             $breakChars array(' '','')'"\r""\n""\t"";"$this->rd);
  2163.         }
  2164.  
  2165.         $breaker false;
  2166.         while (list($k,$chareach($breakChars)) {
  2167.             $test strpos($substr$char);
  2168.             if ($test !== false && $test $end{
  2169.                 $end $test;
  2170.                 $breaker $k;
  2171.             }
  2172.         }
  2173.  
  2174.         if ($curBlock === 'condition'{
  2175.             if ($end === && $breaker !== false{
  2176.                 $end strlen($breakChars[$breaker]);
  2177.             }
  2178.         }
  2179.  
  2180.         if ($end !== false{
  2181.             $substr substr($substr0$end);
  2182.         }
  2183.  
  2184.         if ($pointer !== null{
  2185.             $pointer += strlen($substr);
  2186.         }
  2187.  
  2188.         $src $substr;
  2189.  
  2190.         if (strtolower($substr=== 'false' || strtolower($substr=== 'no' || strtolower($substr=== 'off'{
  2191.             if ($this->debugecho 'BOOLEAN(FALSE) PARSED<br />';
  2192.             $substr 'false';
  2193.         elseif (strtolower($substr=== 'true' || strtolower($substr=== 'yes' || strtolower($substr=== 'on'{
  2194.             if ($this->debugecho 'BOOLEAN(TRUE) PARSED<br />';
  2195.             $substr 'true';
  2196.         elseif ($substr === 'null' || $substr === 'NULL'{
  2197.             if ($this->debugecho 'NULL PARSED<br />';
  2198.             $substr 'null';
  2199.         elseif (is_numeric($substr)) {
  2200.             $substr = (float) $substr;
  2201.             if ((int) $substr == $substr{
  2202.                 $substr = (int) $substr;
  2203.             }
  2204.             if ($this->debugecho 'NUMBER ('.$substr.') PARSED<br />';
  2205.         elseif (preg_match('{^-?(\d+|\d*(\.\d+))\s*([/*%+-]\s*-?(\d+|\d*(\.\d+)))+$}'$substr)) {
  2206.             if ($this->debugecho 'SIMPLE MATH PARSED<br />';
  2207.             $substr '('.$substr.')';
  2208.         elseif ($curBlock === 'condition' && array_search($substr$breakCharstrue!== false{
  2209.             if ($this->debugecho 'BREAKCHAR ('.$substr.') PARSED<br />';
  2210.             //$substr = '"'.$substr.'"';
  2211.         else {
  2212.             $substr $this->replaceStringVars('\''.str_replace('\'''\\\''$substr).'\'''\''$curBlock);
  2213.  
  2214.             if ($this->debugecho 'BLABBER ('.$substr.') CASTED AS STRING<br />';
  2215.         }
  2216.  
  2217.         if (is_array($parsingParams)) {
  2218.             $parsingParams[array($substr$src);
  2219.             return $parsingParams;
  2220.         elseif ($curBlock === 'namedparam'{
  2221.             return array($substr$src);
  2222.         elseif ($curBlock === 'expression'{
  2223.             return $substr;
  2224.         else {
  2225.             throw new Exception('Something went wrong');
  2226.         }
  2227.     }
  2228.  
  2229.     /**
  2230.      * replaces variables within a parsed string
  2231.      *
  2232.      * @param string $string the parsed string
  2233.      * @param string $first the first character parsed in the string, which is the string delimiter (' or ")
  2234.      * @param string $curBlock the current parser-block being processed
  2235.      * @return string the original string with variables replaced
  2236.      */
  2237.     protected function replaceStringVars($string$first$curBlock='')
  2238.     {
  2239.         $pos 0;
  2240.         if ($this->debugecho 'STRING VAR REPLACEMENT : '.$string.'<br>';
  2241.         // replace vars
  2242.         while (($pos strpos($string'$'$pos)) !== false{
  2243.             $prev substr($string$pos-11);
  2244.             if ($prev === '\\'{
  2245.                 $pos++;
  2246.                 continue;
  2247.             }
  2248.  
  2249.             $var $this->parse($string$posnullfalse($curBlock === 'modifier' 'modifier' ($prev === '`' 'delimited_string':'string')));
  2250.             $len $var[0];
  2251.             $var $this->parse(str_replace('\\'.$first$first$string)$posnullfalse($curBlock === 'modifier' 'modifier' ($prev === '`' 'delimited_string':'string')));
  2252.  
  2253.             if ($prev === '`' && substr($string$pos+$len1=== '`'{
  2254.                 $string substr_replace($string$first.'.'.$var[1].'.'.$first$pos-1$len+2);
  2255.             else {
  2256.                 $string substr_replace($string$first.'.'.$var[1].'.'.$first$pos$len);
  2257.             }
  2258.             $pos += strlen($var[1]2;
  2259.             if ($this->debugecho 'STRING VAR REPLACEMENT DONE : '.$string.'<br>';
  2260.         }
  2261.  
  2262.         // handle modifiers
  2263.         // TODO Obsolete?
  2264.         $string preg_replace_callback('#("|\')\.(.+?)\.\1((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').+?\4|:[^`]*))*))+)#i'array($this'replaceModifiers')$string);
  2265.  
  2266.         // replace escaped dollar operators by unescaped ones if required
  2267.         if ($first==="'"{
  2268.             $string str_replace('\\$''$'$string);
  2269.         }
  2270.  
  2271.         return $string;
  2272.     }
  2273.  
  2274.     /**
  2275.      * replaces the modifiers applied to a string or a variable
  2276.      *
  2277.      * @param array $m the regex matches that must be array(1=>"double or single quotes enclosing a string, when applicable", 2=>"the string or var", 3=>"the modifiers matched")
  2278.      * @param string $curBlock the current parser-block being processed
  2279.      * @return string the input enclosed with various function calls according to the modifiers found
  2280.      */
  2281.     protected function replaceModifiers(array $m$curBlock null&$pointer null)
  2282.     {
  2283.         if ($this->debugecho 'PARSING MODIFIERS : '.$m[3].'<br />';
  2284.  
  2285.         if ($pointer !== null{
  2286.             $pointer += strlen($m[3]);
  2287.         }
  2288.         // remove first pipe
  2289.         $cmdstrsrc substr($m[3]1);
  2290.         // remove last quote if present
  2291.         if (substr($cmdstrsrc-11=== $m[1]{
  2292.             $cmdstrsrc substr($cmdstrsrc0-1);
  2293.             $add $m[1];
  2294.         }
  2295.  
  2296.         $output $m[2];
  2297.  
  2298.         $continue true;
  2299.         while (strlen($cmdstrsrc&& $continue{
  2300.             if ($cmdstrsrc[0=== '|'{
  2301.                 $cmdstrsrc substr($cmdstrsrc1);
  2302.                 continue;
  2303.             }
  2304.             if ($cmdstrsrc[0=== ' ' || $cmdstrsrc[0=== ';' || substr($cmdstrsrc0strlen($this->rd)) === $this->rd{
  2305.                 if ($this->debugecho 'MODIFIER PARSING ENDED, RIGHT DELIMITER or ";" FOUND<br/>';
  2306.                 $continue false;
  2307.                 if ($pointer !== null{
  2308.                     $pointer -= strlen($cmdstrsrc);
  2309.                 }
  2310.                 break;
  2311.             }
  2312.             $cmdstr $cmdstrsrc;
  2313.             $paramsep ':';
  2314.             if (!preg_match('/^(@{0,2}[a-z][a-z0-9_]*)(:)?/i'$cmdstr$match)) {
  2315.                 throw new Dwoo_Compilation_Exception($this'Invalid modifier name, started with : '.substr($cmdstr010));
  2316.             }
  2317.             $paramspos !empty($match[2]strlen($match[1]false;
  2318.             $func $match[1];
  2319.  
  2320.             $state 0;
  2321.             if ($paramspos === false{
  2322.                 $cmdstrsrc substr($cmdstrsrcstrlen($func));
  2323.                 $params array();
  2324.                 if ($this->debugecho 'MODIFIER ('.$func.') CALLED WITH NO PARAMS<br/>';
  2325.             else {
  2326.                 $paramstr substr($cmdstr$paramspos+1);
  2327.                 if (substr($paramstr-11=== $paramsep{
  2328.                     $paramstr substr($paramstr0-1);
  2329.                 }
  2330.  
  2331.                 $ptr 0;
  2332.                 $params array();
  2333.                 while ($ptr strlen($paramstr)) {
  2334.                     if ($this->debugecho 'MODIFIER ('.$func.') START PARAM PARSING WITH POINTER AT '.$ptr.'<br/>';
  2335.                     if ($this->debugecho $paramstr.'--'.$ptr.'--'.strlen($paramstr).'--modifier<br/>';
  2336.                     $params $this->parse($paramstr$ptrstrlen($paramstr)$params'modifier'$ptr);
  2337.                     if ($this->debugecho 'PARAM PARSED, POINTER AT '.$ptr.'<br/>';
  2338.  
  2339.                     if ($ptr >= strlen($paramstr)) {
  2340.                         if ($this->debugecho 'PARAM PARSING ENDED, PARAM STRING CONSUMED<br/>';
  2341.                         break;
  2342.                     }
  2343.  
  2344.                     if ($paramstr[$ptr=== ' ' || $paramstr[$ptr=== '|' || $paramstr[$ptr=== ';' || substr($paramstr$ptrstrlen($this->rd)) === $this->rd{
  2345.                         if ($this->debugecho 'PARAM PARSING ENDED, " ", "|", RIGHT DELIMITER or ";" FOUND, POINTER AT '.$ptr.'<br/>';
  2346.                         if ($paramstr[$ptr!== '|'{
  2347.                             $continue false;
  2348.                             if ($pointer !== null{
  2349.                                 $pointer -= strlen($paramstr$ptr;
  2350.                             }
  2351.                         }
  2352.                         $ptr++;
  2353.                         break;
  2354.                     }
  2355.                     if ($ptr strlen($paramstr&& $paramstr[$ptr=== ':'{
  2356.                         $ptr++;
  2357.                     }
  2358.                 }
  2359.                 $cmdstrsrc substr($cmdstrsrcstrlen($func)+1+$ptr);
  2360.                 $paramstr substr($paramstr0$ptr);
  2361.                 foreach ($params as $k=>$p{
  2362.                     if (is_array($p&& is_array($p[1])) {
  2363.                         $state |= 2;
  2364.                     else {
  2365.                         if (($state 2&& preg_match('#^(["\'])(.+?)\1$#'$p[0]$m)) {
  2366.                             $params[$karray($m[2]array('true''true'));
  2367.                         else {
  2368.                             if ($state 2{
  2369.                                 throw new Dwoo_Compilation_Exception($this'You can not use an unnamed parameter after a named one');
  2370.                             }
  2371.                             $state |= 1;
  2372.                         }
  2373.                     }
  2374.                 }
  2375.             }
  2376.  
  2377.             // check if we must use array_map with this plugin or not
  2378.             $mapped false;
  2379.             if (substr($func01=== '@'{
  2380.                 $func substr($func1);
  2381.                 $mapped true;
  2382.             }
  2383.  
  2384.             $pluginType $this->getPluginType($func);
  2385.  
  2386.             if ($state 2{
  2387.                 array_unshift($paramsarray('value'array($output$output)));
  2388.             else {
  2389.                 array_unshift($paramsarray($output$output));
  2390.             }
  2391.  
  2392.             if ($pluginType Dwoo::NATIVE_PLUGIN{
  2393.                 $params $this->mapParams($paramsnull$state);
  2394.  
  2395.                 $params $params['*'][0];
  2396.  
  2397.                 $params self::implode_r($params);
  2398.  
  2399.                 if ($mapped{
  2400.                     $output '$this->arrayMap(\''.$func.'\', array('.$params.'))';
  2401.                 else {
  2402.                     $output $func.'('.$params.')';
  2403.                 }
  2404.             elseif ($pluginType Dwoo::PROXY_PLUGIN{
  2405.                 $params $this->mapParams($paramsnull$state);
  2406.                 $params $params['*'][0];
  2407.                 $output call_user_func_array(array($this->dwoo->getPluginProxy()$func)$params);
  2408.             elseif ($pluginType Dwoo::SMARTY_MODIFIER{
  2409.                 $params $this->mapParams($paramsnull$state);
  2410.                 $params $params['*'][0];
  2411.  
  2412.                 $params self::implode_r($params);
  2413.  
  2414.                 if ($pluginType Dwoo::CUSTOM_PLUGIN{
  2415.                     $callback $this->customPlugins[$func]['callback'];
  2416.                     if (is_array($callback)) {
  2417.                         if (is_object($callback[0])) {
  2418.                             $output ($mapped '$this->arrayMap' 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))';
  2419.                         else {
  2420.                             $output ($mapped '$this->arrayMap' 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))';
  2421.                         }
  2422.                     elseif ($mapped{
  2423.                         $output '$this->arrayMap(\''.$callback.'\', array('.$params.'))';
  2424.                     else {
  2425.                         $output $callback.'('.$params.')';
  2426.                     }
  2427.                 elseif ($mapped{
  2428.                     $output '$this->arrayMap(\'smarty_modifier_'.$func.'\', array('.$params.'))';
  2429.                 else {
  2430.                     $output 'smarty_modifier_'.$func.'('.$params.')';
  2431.                 }
  2432.             else {
  2433.                 if ($pluginType Dwoo::CUSTOM_PLUGIN{
  2434.                     $callback $this->customPlugins[$func]['callback'];
  2435.                     $pluginName $callback;
  2436.                 else {
  2437.                     $pluginName 'Dwoo_Plugin_'.$func;
  2438.  
  2439.                     if ($pluginType Dwoo::CLASS_PLUGIN{
  2440.                         $callback array($pluginName($pluginType Dwoo::COMPILABLE_PLUGIN'compile' 'process');
  2441.                     else {
  2442.                         $callback $pluginName (($pluginType Dwoo::COMPILABLE_PLUGIN'_compile' '');
  2443.                     }
  2444.                 }
  2445.  
  2446.                 $params $this->mapParams($params$callback$state);
  2447.  
  2448.                 foreach ($params as &$p)
  2449.                     $p $p[0];
  2450.  
  2451.                 if ($pluginType Dwoo::FUNC_PLUGIN{
  2452.                     if ($pluginType Dwoo::COMPILABLE_PLUGIN{
  2453.                         if ($mapped{
  2454.                             throw new Dwoo_Compilation_Exception($this'The @ operator can not be used on compiled plugins.');
  2455.                         }
  2456.                         if ($pluginType Dwoo::CUSTOM_PLUGIN{
  2457.                             $funcCompiler $this->customPlugins[$func]['callback'];
  2458.                         else {
  2459.                             $funcCompiler 'Dwoo_Plugin_'.$func.'_compile';
  2460.                         }
  2461.                         array_unshift($params$this);
  2462.                         $output call_user_func_array($funcCompiler$params);
  2463.                     else {
  2464.                         array_unshift($params'$this');
  2465.  
  2466.                         $params self::implode_r($params);
  2467.                         if ($mapped{
  2468.                             $output '$this->arrayMap(\''.$pluginName.'\', array('.$params.'))';
  2469.                         else {
  2470.                             $output $pluginName.'('.$params.')';
  2471.                         }
  2472.                     }
  2473.                 else {
  2474.                     if ($pluginType Dwoo::COMPILABLE_PLUGIN{
  2475.                         if ($mapped{
  2476.                             throw new Dwoo_Compilation_Exception($this'The @ operator can not be used on compiled plugins.');
  2477.                         }
  2478.                         if ($pluginType Dwoo::CUSTOM_PLUGIN{
  2479.                             $callback $this->customPlugins[$func]['callback'];
  2480.                             if (!is_array($callback)) {
  2481.                                 if (!method_exists($callback'compile')) {
  2482.                                     throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use');
  2483.                                 }
  2484.                                 if (($ref new ReflectionMethod($callback'compile')) && $ref->isStatic()) {
  2485.                                     $funcCompiler array($callback'compile');
  2486.                                 else {
  2487.                                     $funcCompiler array(new $callback'compile');
  2488.                                 }
  2489.                             else {
  2490.                                 $funcCompiler $callback;
  2491.                             }
  2492.                         else {
  2493.                             $funcCompiler array('Dwoo_Plugin_'.$func'compile');
  2494.                             array_unshift($params$this);
  2495.                         }
  2496.                         $output call_user_func_array($funcCompiler$params);
  2497.                     else {
  2498.                         $params self::implode_r($params);
  2499.  
  2500.                         if ($pluginType Dwoo::CUSTOM_PLUGIN{
  2501.                             if (is_object($callback[0])) {
  2502.                                 $output ($mapped '$this->arrayMap' 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))';
  2503.                             else {
  2504.                                 $output ($mapped '$this->arrayMap' 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))';
  2505.                             }
  2506.                         elseif ($mapped{
  2507.                             $output '$this->arrayMap(array($this->getObjectPlugin(\'Dwoo_Plugin_'.$func.'\'), \'process\'), array('.$params.'))';
  2508.                         else {
  2509.                             $output '$this->classCall(\''.$func.'\', array('.$params.'))';
  2510.                         }
  2511.                     }
  2512.                 }
  2513.             }
  2514.         }
  2515.  
  2516.         if ($curBlock === 'var' || $m[1=== null{
  2517.             return $output;
  2518.         elseif ($curBlock === 'string' || $curBlock === 'root'{
  2519.             return $m[1].'.'.$output.'.'.$m[1].(isset($add)?$add:null);
  2520.         }
  2521.     }
  2522.  
  2523.     /**
  2524.      * recursively implodes an array in a similar manner as var_export() does but with some tweaks
  2525.      * to handle pre-compiled values and the fact that we do not need to enclose everything with
  2526.      * "array" and do not require top-level keys to be displayed
  2527.      *
  2528.      * @param array $params the array to implode
  2529.      * @param bool $recursiveCall if set to true, the function outputs key names for the top level
  2530.      * @return string the imploded array
  2531.      */
  2532.     public static function implode_r(array $params$recursiveCall false)
  2533.     {
  2534.         $out '';
  2535.         foreach ($params as $k=>$p{
  2536.             if (is_array($p)) {
  2537.                 $out2 'array(';
  2538.                 foreach ($p as $k2=>$v)
  2539.                     $out2 .= var_export($k2true).' => '.(is_array($v'array('.self::implode_r($vtrue).')' $v).', ';
  2540.                 $p rtrim($out2', ').')';
  2541.             }
  2542.             if ($recursiveCall{
  2543.                 $out .= var_export($ktrue).' => '.$p.', ';
  2544.             else {
  2545.                 $out .= $p.', ';
  2546.             }
  2547.         }
  2548.         return rtrim($out', ');
  2549.     }
  2550.  
  2551.     /**
  2552.      * returns the plugin type of a plugin and adds it to the used plugins array if required
  2553.      *
  2554.      * @param string $name plugin name, as found in the template
  2555.      * @return int type as a multi bit flag composed of the Dwoo plugin types constants
  2556.      */
  2557.     protected function getPluginType($name)
  2558.     {
  2559.         $pluginType = -1;
  2560.  
  2561.         if (($this->securityPolicy === null && (function_exists($name|| strtolower($name=== 'isset' || strtolower($name=== 'empty')) ||
  2562.             ($this->securityPolicy !== null && in_array(strtolower($name)$this->securityPolicy->getAllowedPhpFunctions()) !== false)) {
  2563.             $phpFunc true;
  2564.         }
  2565.  
  2566.         while ($pluginType <= 0{
  2567.             if (isset($this->customPlugins[$name])) {
  2568.                 $pluginType $this->customPlugins[$name]['type'Dwoo::CUSTOM_PLUGIN;
  2569.             elseif (class_exists('Dwoo_Plugin_'.$namefalse!== false{
  2570.                 if (is_subclass_of('Dwoo_Plugin_'.$name'Dwoo_Block_Plugin')) {
  2571.                     $pluginType Dwoo::BLOCK_PLUGIN;
  2572.                 else {
  2573.                     $pluginType Dwoo::CLASS_PLUGIN;
  2574.                 }
  2575.                 $interfaces class_implements('Dwoo_Plugin_'.$namefalse);
  2576.                 if (in_array('Dwoo_ICompilable'$interfaces!== false || in_array('Dwoo_ICompilable_Block'$interfaces!== false{
  2577.                     $pluginType |= Dwoo::COMPILABLE_PLUGIN;
  2578.                 }
  2579.             elseif (function_exists('Dwoo_Plugin_'.$name!== false{
  2580.                 $pluginType Dwoo::FUNC_PLUGIN;
  2581.             elseif (function_exists('Dwoo_Plugin_'.$name.'_compile')) {
  2582.                 $pluginType Dwoo::FUNC_PLUGIN Dwoo::COMPILABLE_PLUGIN;
  2583.             elseif (function_exists('smarty_modifier_'.$name!== false{
  2584.                 $pluginType Dwoo::SMARTY_MODIFIER;
  2585.             elseif (function_exists('smarty_function_'.$name!== false{
  2586.                 $pluginType Dwoo::SMARTY_FUNCTION;
  2587.             elseif (function_exists('smarty_block_'.$name!== false{
  2588.                 $pluginType Dwoo::SMARTY_BLOCK;
  2589.             else {
  2590.                 if ($pluginType===-1{
  2591.                     try {
  2592.                         $this->dwoo->getLoader()->loadPlugin($nameisset($phpFunc)===false);
  2593.                     catch (Exception $e{
  2594.                         if (isset($phpFunc)) {
  2595.                             $pluginType Dwoo::NATIVE_PLUGIN;
  2596.                         elseif (is_object($this->dwoo->getPluginProxy()) && $this->dwoo->getPluginProxy()->loadPlugin($name)) {
  2597.                             $pluginType Dwoo::PROXY_PLUGIN;
  2598.                             break;
  2599.                         else {
  2600.                             throw $e;
  2601.                         }
  2602.                     }
  2603.                 else {
  2604.                     throw new Dwoo_Exception('Plugin "'.$name.'" could not be found');
  2605.                 }
  2606.                 $pluginType++;
  2607.             }
  2608.         }
  2609.  
  2610.         if (($pluginType Dwoo::COMPILABLE_PLUGIN=== && ($pluginType Dwoo::NATIVE_PLUGIN=== && ($pluginType Dwoo::PROXY_PLUGIN=== 0{
  2611.             $this->usedPlugins[$name$pluginType;
  2612.         }
  2613.  
  2614.         return $pluginType;
  2615.     }
  2616.  
  2617.     /**
  2618.      * runs htmlentities over the matched <?php ?> blocks when the security policy enforces that
  2619.      *
  2620.      * @param array $match matched php block
  2621.      * @return string the htmlentities-converted string
  2622.      */
  2623.     protected function phpTagEncodingHelper($match)
  2624.     {
  2625.         return htmlspecialchars($match[0]);
  2626.     }
  2627.  
  2628.     /**
  2629.      * maps the parameters received from the template onto the parameters required by the given callback
  2630.      *
  2631.      * @param array $params the array of parameters
  2632.      * @param callback $callback the function or method to reflect on to find out the required parameters
  2633.      * @param int $callType the type of call in the template, 0 = no params, 1 = php-style call, 2 = named parameters call
  2634.      * @return array parameters sorted in the correct order with missing optional parameters filled
  2635.      */
  2636.     protected function mapParams(array $params$callback$callType=2)
  2637.     {
  2638.         $map $this->getParamMap($callback);
  2639.  
  2640.         $paramlist array();
  2641.  
  2642.         // transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values))
  2643.         $ps array();
  2644.         foreach ($params as $p{
  2645.             if (is_array($p[1])) {
  2646.                 $ps[$p[0]] $p[1];
  2647.             else {
  2648.                 $ps[$p;
  2649.             }
  2650.         }
  2651.  
  2652.         // loops over the param map and assigns values from the template or default value for unset optional params
  2653.         while (list($k,$veach($map)) {
  2654.             if ($v[0=== '*'{
  2655.                 // "rest" array parameter, fill every remaining params in it and then break
  2656.                 if (count($ps=== 0{
  2657.                     if ($v[1]===false{
  2658.                         throw new Dwoo_Compilation_Exception($this'Rest argument missing for '.str_replace(array('Dwoo_Plugin_''_compile')''(is_array($callback$callback[0$callback)));
  2659.                     else {
  2660.                         break;
  2661.                     }
  2662.                 }
  2663.                 $tmp array();
  2664.                 $tmp2 array();
  2665.                 foreach ($ps as $i=>$p{
  2666.                     $tmp[$i$p[0];
  2667.                     $tmp2[$i$p[1];
  2668.                 }
  2669.                 $paramlist[$v[0]] array($tmp$tmp2);
  2670.                 unset($tmp$tmp2$i$p);
  2671.                 break;
  2672.             elseif (isset($ps[$v[0]])) {
  2673.                 // parameter is defined as named param
  2674.                 $paramlist[$v[0]] $ps[$v[0]];
  2675.                 unset($ps[$v[0]]);
  2676.             elseif (isset($ps[$k])) {
  2677.                 // parameter is defined as ordered param
  2678.                 $paramlist[$v[0]] $ps[$k];
  2679.                 unset($ps[$k]);
  2680.             elseif ($v[1]===false{
  2681.                 // parameter is not defined and not optional, throw error
  2682.                 throw new Dwoo_Compilation_Exception($this'Argument '.$k.'/'.$v[0].' missing for '.str_replace(array('Dwoo_Plugin_''_compile')''(is_array($callback$callback[0$callback)));
  2683.             elseif ($v[2]===null{
  2684.                 // enforce lowercased null if default value is null (php outputs NULL with var export)
  2685.                 $paramlist[$v[0]] array('null'null);
  2686.             else {
  2687.                 // outputs default value with var_export
  2688.                 $paramlist[$v[0]] array(var_export($v[2]true)$v[2]);
  2689.             }
  2690.         }
  2691.  
  2692.         return $paramlist;
  2693.     }
  2694.  
  2695.     /**
  2696.      * returns the parameter map of the given callback, it filters out entries typed as Dwoo and Dwoo_Compiler and turns the rest parameter into a "*"
  2697.      *
  2698.      * @param callback $callback the function/method to reflect on
  2699.      * @return array processed parameter map
  2700.      */
  2701.     protected function getParamMap($callback)
  2702.     {
  2703.         if (is_null($callback)) {
  2704.             return array(array('*'true));
  2705.         }
  2706.         if (is_array($callback)) {
  2707.             $ref new ReflectionMethod($callback[0]$callback[1]);
  2708.         else {
  2709.             $ref new ReflectionFunction($callback);
  2710.         }
  2711.  
  2712.         $out array();
  2713.         foreach ($ref->getParameters(as $param{
  2714.             if (($class $param->getClass()) !== null && $class->name === 'Dwoo'{
  2715.                 continue;
  2716.             }
  2717.             if (($class $param->getClass()) !== null && $class->name === 'Dwoo_Compiler'{
  2718.                 continue;
  2719.             }
  2720.             if ($param->getName(=== 'rest' && $param->isArray(=== true{
  2721.                 $out[array('*'$param->isOptional()null);
  2722.             }
  2723.             $out[array($param->getName()$param->isOptional()$param->isOptional($param->getDefaultValue(null);
  2724.         }
  2725.  
  2726.         return $out;
  2727.     }
  2728.  
  2729.     /**
  2730.      * returns a default instance of this compiler, used by default by all Dwoo templates that do not have a
  2731.      * specific compiler assigned and when you do not override the default compiler factory function
  2732.      *
  2733.      * @see Dwoo::setDefaultCompilerFactory()
  2734.      * @return Dwoo_Compiler 
  2735.      */
  2736.     public static function compilerFactory()
  2737.     {
  2738.         if (self::$instance === null{
  2739.             self::$instance new self;
  2740.         }
  2741.         return self::$instance;
  2742.     }
  2743. }

Documentation generated on Sun, 07 Sep 2008 23:57:38 +0200 by phpDocumentor 1.4.0