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

Documentation generated on Sat, 18 Jul 2009 21:04:45 +0200 by phpDocumentor 1.4.0