phpDocumentor Smarty
[ class tree: Smarty ] [ index: Smarty ] [ all elements ]

Source for file Smarty_Compiler.class.php

Documentation is available at Smarty_Compiler.class.php

  1. <?php
  2.  
  3. /**
  4.  * Project:     Smarty: the PHP compiling template engine
  5.  * File:        Smarty_Compiler.class.php
  6.  *
  7.  * This library is free software; you can redistribute it and/or
  8.  * modify it under the terms of the GNU Lesser General Public
  9.  * License as published by the Free Software Foundation; either
  10.  * version 2.1 of the License, or (at your option) any later version.
  11.  *
  12.  * This library is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15.  * Lesser General Public License for more details.
  16.  *
  17.  * You should have received a copy of the GNU Lesser General Public
  18.  * License along with this library; if not, write to the Free Software
  19.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  20.  *
  21.  * You may contact the authors of Smarty by e-mail at:
  22.  *
  23.  * Or, write to:
  24.  * Monte Ohrt
  25.  * Director of Technology, ispi
  26.  * 237 S. 70th suite 220
  27.  * Lincoln, NE 68510
  28.  *
  29.  * The latest version of Smarty can be obtained from:
  30.  * http://smarty.php.net/
  31.  *
  32.  * @link http://smarty.php.net/
  33.  * @author Monte Ohrt <[email protected]>
  34.  * @author Andrei Zmievski <[email protected]>
  35.  * @version 2.6.0
  36.  * @copyright 2001-2003 ispi of Lincoln, Inc.
  37.  * @package Smarty
  38.  */
  39.  
  40. /* $Id: Smarty_Compiler.class.php,v 1.1 2005/10/17 18:37:39 jeichorn Exp $ */
  41.  
  42. /**
  43.  * Template compiling class
  44.  * @package Smarty
  45.  */
  46. class Smarty_Compiler extends Smarty {
  47.  
  48.     // internal vars
  49.         /**#@+
  50.      * @access private
  51.      */
  52.     var $_sectionelse_stack     =   array();    // keeps track of whether section had 'else' part
  53.         var $_foreachelse_stack     =   array();    // keeps track of whether foreach had 'else' part
  54.         var $_literal_blocks        =   array();    // keeps literal template blocks
  55.         var $_php_blocks            =   array();    // keeps php code blocks
  56.         var $_current_file          =   null;       // the current template being compiled
  57.         var $_current_line_no       =   1;          // line number for error messages
  58.         var $_capture_stack         =   array();    // keeps track of nested capture buffers
  59.         var $_plugin_info           =   array();    // keeps track of plugins to load
  60.         var $_init_smarty_vars      =   false;
  61.     var $_permitted_tokens      =   array('true','false','yes','no','on','off','null');
  62.     var $_db_qstr_regexp        =   null;        // regexps are setup in the constructor
  63.         var $_si_qstr_regexp        =   null;
  64.     var $_qstr_regexp           =   null;
  65.     var $_func_regexp           =   null;
  66.     var $_var_bracket_regexp    =   null;
  67.     var $_dvar_guts_regexp      =   null;
  68.     var $_dvar_regexp           =   null;
  69.     var $_cvar_regexp           =   null;
  70.     var $_svar_regexp           =   null;
  71.     var $_avar_regexp           =   null;
  72.     var $_mod_regexp            =   null;
  73.     var $_var_regexp            =   null;
  74.     var $_parenth_param_regexp  =   null;
  75.     var $_func_call_regexp      =   null;
  76.     var $_obj_ext_regexp        =   null;
  77.     var $_obj_start_regexp      =   null;
  78.     var $_obj_params_regexp     =   null;
  79.     var $_obj_call_regexp       =   null;
  80.     var $_cacheable_state       =   0;
  81.     var $_cache_attrs_count     =   0;
  82.     var $_nocache_count         =   0;
  83.     var $_cache_serial          =   null;
  84.     var $_cache_include         =   null;
  85.  
  86.     var $_strip_depth           =   0;
  87.     var $_additional_newline    =   "\n";
  88.  
  89.     /**#@-*/
  90.     /**
  91.      * The class constructor.
  92.      */
  93.     function Smarty_Compiler()
  94.     {
  95.         // matches double quoted strings:
  96.         // "foobar"
  97.         // "foo\"bar"
  98.         $this->_db_qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  99.  
  100.         // matches single quoted strings:
  101.         // 'foobar'
  102.         // 'foo\'bar'
  103.         $this->_si_qstr_regexp = '\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
  104.  
  105.         // matches single or double quoted strings
  106.         $this->_qstr_regexp = '(?:' . $this->_db_qstr_regexp . '|' . $this->_si_qstr_regexp . ')';
  107.  
  108.         // matches bracket portion of vars
  109.         // [0]
  110.         // [foo]
  111.         // [$bar]
  112.         $this->_var_bracket_regexp = '\[\$?[\w\.]+\]';
  113.  
  114.         // matches $ vars (not objects):
  115.         // $foo
  116.         // $foo.bar
  117.         // $foo.bar.foobar
  118.         // $foo[0]
  119.         // $foo[$bar]
  120.         // $foo[5][blah]
  121.         // $foo[5].bar[$foobar][4]
  122.         $this->_dvar_math_regexp = '[\+\-\*\/\%]';
  123.         $this->_dvar_math_var_regexp = '[\$\w\.\+\-\*\/\%\d\>\[\]]';
  124.         $this->_dvar_num_var_regexp = '\-?\d+(?:\.\d+)?' . $this->_dvar_math_var_regexp;
  125.         $this->_dvar_guts_regexp = '\w+(?:' . $this->_var_bracket_regexp
  126.                 . ')*(?:\.\$?\w+(?:' . $this->_var_bracket_regexp . ')*)*(?:' . $this->_dvar_math_regexp . '(?:\-?\d+(?:\.\d+)?|' . $this->_dvar_math_var_regexp . ')*)?';
  127.         $this->_dvar_regexp = '\$' . $this->_dvar_guts_regexp;
  128.  
  129.         // matches config vars:
  130.         // #foo#
  131.         // #foobar123_foo#
  132.         $this->_cvar_regexp = '\#\w+\#';
  133.  
  134.         // matches section vars:
  135.         // %foo.bar%
  136.         $this->_svar_regexp = '\%\w+\.\w+\%';
  137.  
  138.         // matches all valid variables (no quotes, no modifiers)
  139.         $this->_avar_regexp = '(?:' . $this->_dvar_regexp . '|'
  140.            . $this->_cvar_regexp . '|' . $this->_svar_regexp . ')';
  141.  
  142.         // matches valid variable syntax:
  143.         // $foo
  144.         // $foo
  145.         // #foo#
  146.         // #foo#
  147.         // "text"
  148.         // "text"
  149.         $this->_var_regexp = '(?:' . $this->_avar_regexp . '|' . $this->_qstr_regexp . ')';
  150.  
  151.         // matches valid object call (no objects allowed in parameters):
  152.         // $foo->bar
  153.         // $foo->bar()
  154.         // $foo->bar("text")
  155.         // $foo->bar($foo, $bar, "text")
  156.         // $foo->bar($foo, "foo")
  157.         // $foo->bar->foo()
  158.         // $foo->bar->foo->bar()
  159.         $this->_obj_ext_regexp = '\->(?:\$?' . $this->_dvar_guts_regexp . ')';
  160.         $this->_obj_params_regexp = '\((?:\w+|'
  161.                 . $this->_var_regexp . '(?:\s*,\s*(?:(?:\w+|'
  162.                 . $this->_var_regexp . ')))*)?\)';
  163.         $this->_obj_start_regexp = '(?:' . $this->_dvar_regexp . '(?:' . $this->_obj_ext_regexp . ')+)';
  164.         $this->_obj_call_regexp = '(?:' . $this->_obj_start_regexp . '(?:' . $this->_obj_params_regexp . ')?)';
  165.  
  166.         // matches valid modifier syntax:
  167.         // |foo
  168.         // |@foo
  169.         // |foo:"bar"
  170.         // |foo:$bar
  171.         // |foo:"bar":$foobar
  172.         // |foo|bar
  173.         // |foo:$foo->bar
  174.         $this->_mod_regexp = '(?:\|@?\w+(?::(?>-?\w+|'
  175.            . $this->_obj_call_regexp . '|' . $this->_avar_regexp . '|' . $this->_qstr_regexp .'))*)';
  176.  
  177.         // matches valid function name:
  178.         // foo123
  179.         // _foo_bar
  180.         $this->_func_regexp = '[a-zA-Z_]\w*';
  181.  
  182.         // matches valid registered object:
  183.         // foo->bar
  184.         $this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*';
  185.  
  186.         // matches valid parameter values:
  187.         // true
  188.         // $foo
  189.         // $foo|bar
  190.         // #foo#
  191.         // #foo#|bar
  192.         // "text"
  193.         // "text"|bar
  194.         // $foo->bar
  195.         $this->_param_regexp = '(?:\s*(?:' . $this->_obj_call_regexp . '|'
  196.            . $this->_var_regexp  . '|\w+)(?>' . $this->_mod_regexp . '*)\s*)';
  197.  
  198.         // matches valid parenthesised function parameters:
  199.         //
  200.         // "text"
  201.         //    $foo, $bar, "text"
  202.         // $foo|bar, "foo"|bar, $foo->bar($foo)|bar
  203.         $this->_parenth_param_regexp = '(?:\((?:\w+|'
  204.                 . $this->_param_regexp . '(?:\s*,\s*(?:(?:\w+|'
  205.                 . $this->_param_regexp . ')))*)?\))';
  206.  
  207.         // matches valid function call:
  208.         // foo()
  209.         // foo_bar($foo)
  210.         // _foo_bar($foo,"bar")
  211.         // foo123($foo,$foo->bar(),"foo")
  212.         $this->_func_call_regexp = '(?:' . $this->_func_regexp . '\s*(?:'
  213.            . $this->_parenth_param_regexp . '))';
  214.     }
  215.  
  216.     /**
  217.      * compile a resource
  218.      *
  219.      * sets $compiled_content to the compiled source
  220.      * @param string $resource_name 
  221.      * @param string $source_content 
  222.      * @param string $compiled_content 
  223.      * @return true 
  224.      */
  225.     function _compile_file($resource_name, $source_content, &$compiled_content)
  226.     {
  227.  
  228.         if ($this->security) {
  229.             // do not allow php syntax to be executed unless specified
  230.             if ($this->php_handling == SMARTY_PHP_ALLOW &&
  231.                 !$this->security_settings['PHP_HANDLING']) {
  232.                 $this->php_handling = SMARTY_PHP_PASSTHRU;
  233.             }
  234.         }
  235.  
  236.         $this->_load_filters();
  237.  
  238.         $this->_current_file = $resource_name;
  239.         $this->_current_line_no = 1;
  240.         $ldq = preg_quote($this->left_delimiter, '!');
  241.         $rdq = preg_quote($this->right_delimiter, '!');
  242.  
  243.         // run template source through prefilter functions
  244.         if (count($this->_plugins['prefilter']) > 0) {
  245.             foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
  246.                 if ($prefilter === false) continue;
  247.                 if ($prefilter[3] || is_callable($prefilter[0])) {
  248.                     $source_content = call_user_func_array($prefilter[0],
  249.                                                             array($source_content, &$this));
  250.                     $this->_plugins['prefilter'][$filter_name][3] = true;
  251.                 } else {
  252.                     $this->_trigger_fatal_error("[plugin] prefilter '$filter_name' is not implemented");
  253.                 }
  254.             }
  255.         }
  256.  
  257.         /* Annihilate the comments. */
  258.         $source_content = preg_replace("!({$ldq})\*(.*?)\*({$rdq})!se",
  259.                                         "'\\1*'.str_repeat(\"\n\", substr_count('\\2', \"\n\")) .'*\\3'",
  260.                                         $source_content);
  261.  
  262.         /* Pull out the literal blocks. */
  263.         preg_match_all("!{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}!s", $source_content, $_match);
  264.         $this->_literal_blocks = $_match[1];
  265.         $source_content = preg_replace("!{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}!s",
  266.                                         $this->_quote_replace($this->left_delimiter.'literal'.$this->right_delimiter), $source_content);
  267.  
  268.         /* Pull out the php code blocks. */
  269.         preg_match_all("!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s", $source_content, $_match);
  270.         $this->_php_blocks = $_match[1];
  271.         $source_content = preg_replace("!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s",
  272.                                         $this->_quote_replace($this->left_delimiter.'php'.$this->right_delimiter), $source_content);
  273.  
  274.         /* Gather all template tags. */
  275.         preg_match_all("!{$ldq}\s*(.*?)\s*{$rdq}!s", $source_content, $_match);
  276.         $template_tags = $_match[1];
  277.         /* Split content by template tags to obtain non-template content. */
  278.         $text_blocks = preg_split("!{$ldq}.*?{$rdq}!s", $source_content);
  279.  
  280.         /* loop through text blocks */
  281.         for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) {
  282.             /* match anything resembling php tags */
  283.             if (preg_match_all('!(<\?(?:\w+|=)?|\?>|language\s*=\s*[\"\']?php[\"\']?)!is', $text_blocks[$curr_tb], $sp_match)) {
  284.                 /* replace tags with placeholders to prevent recursive replacements */
  285.                 $sp_match[1] = array_unique($sp_match[1]);
  286.                 usort($sp_match[1], '_smarty_sort_length');
  287.                 for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {
  288.                     $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],'%%%SMARTYSP'.$curr_sp.'%%%',$text_blocks[$curr_tb]);
  289.                 }
  290.                 /* process each one */
  291.                 for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {
  292.                     if ($this->php_handling == SMARTY_PHP_PASSTHRU) {
  293.                         /* echo php contents */
  294.                         $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '<?php echo \''.str_replace("'", "\'", $sp_match[1][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]);
  295.                     } else if ($this->php_handling == SMARTY_PHP_QUOTE) {
  296.                         /* quote php tags */
  297.                         $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]);
  298.                     } else if ($this->php_handling == SMARTY_PHP_REMOVE) {
  299.                         /* remove php tags */
  300.                         $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '', $text_blocks[$curr_tb]);
  301.                     } else {
  302.                         /* SMARTY_PHP_ALLOW, but echo non php starting tags */
  303.                         $sp_match[1][$curr_sp] = preg_replace('%(<\?(?!php|=|$))%i', '<?php echo \'\\1\'?>'."\n", $sp_match[1][$curr_sp]);
  304.                         $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]);
  305.                     }
  306.                 }
  307.             }
  308.         }
  309.  
  310.         /* Compile the template tags into PHP code. */
  311.         $compiled_tags = array();
  312.         for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) {
  313.             $this->_current_line_no += substr_count($text_blocks[$i], "\n");
  314.             $compiled_tags[] = $this->_compile_tag($template_tags[$i]);
  315.             $this->_current_line_no += substr_count($template_tags[$i], "\n");
  316.         }
  317.  
  318.         $compiled_content = '';
  319.  
  320.         /* Interleave the compiled contents and text blocks to get the final result. */
  321.         for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {
  322.             if ($compiled_tags[$i] == '') {
  323.                 // tag result empty, remove first newline from following text block
  324.                 $text_blocks[$i+1] = preg_replace('!^(\r\n|\r|\n)!', '', $text_blocks[$i+1]);
  325.             }
  326.             $compiled_content .= $text_blocks[$i].$compiled_tags[$i];
  327.         }
  328.         $compiled_content .= $text_blocks[$i];
  329.  
  330.         /* Reformat data between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */
  331.         if (preg_match_all("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s", $compiled_content, $_match)) {
  332.             $strip_tags = $_match[0];
  333.             $strip_tags_modified = preg_replace("!{$ldq}/?strip{$rdq}|[\t ]+$|^[\t ]+!m", '', $strip_tags);
  334.             $strip_tags_modified = preg_replace('![\r\n]+!m', '', $strip_tags_modified);
  335.             for ($i = 0, $for_max = count($strip_tags); $i < $for_max; $i++)
  336.                 $compiled_content = preg_replace("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s",
  337.                                                   $this->_quote_replace($strip_tags_modified[$i]),
  338.                                                   $compiled_content, 1);
  339.         }
  340.  
  341.         // remove \n from the end of the file, if any
  342.         if (($_len=strlen($compiled_content)) && ($compiled_content{$_len - 1} == "\n" )) {
  343.             $compiled_content = substr($compiled_content, 0, -1);
  344.         }
  345.  
  346.         if (!empty($this->_cache_serial)) {
  347.             $compiled_content = "<?php \$this->_cache_serials['".$this->_cache_include."'] = '".$this->_cache_serial."'; ?>" . $compiled_content;
  348.         }
  349.  
  350.         // remove unnecessary close/open tags
  351.         $compiled_content = preg_replace('!\?>\n?<\?php!', '', $compiled_content);
  352.  
  353.         // run compiled template through postfilter functions
  354.         if (count($this->_plugins['postfilter']) > 0) {
  355.             foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
  356.                 if ($postfilter === false) continue;
  357.                 if ($postfilter[3] || is_callable($postfilter[0])) {
  358.                     $compiled_content = call_user_func_array($postfilter[0],
  359.                                                               array($compiled_content, &$this));
  360.                     $this->_plugins['postfilter'][$filter_name][3] = true;
  361.                 } else {
  362.                     $this->_trigger_fatal_error("Smarty plugin error: postfilter '$filter_name' is not implemented");
  363.                 }
  364.             }
  365.         }
  366.  
  367.         // put header at the top of the compiled template
  368.         $template_header = "<?php /* Smarty version ".$this->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n";
  369.         $template_header .= "         compiled from ".strtr(urlencode($resource_name), array('%2F'=>'/', '%3A'=>':'))." */ ?>\n";
  370.  
  371.         /* Emit code to load needed plugins. */
  372.         $this->_plugins_code = '';
  373.         if (count($this->_plugin_info)) {
  374.             $_plugins_params = "array('plugins' => array(";
  375.             foreach ($this->_plugin_info as $plugin_type => $plugins) {
  376.                 foreach ($plugins as $plugin_name => $plugin_info) {
  377.                     $_plugins_params .= "array('$plugin_type', '$plugin_name', '$plugin_info[0]', $plugin_info[1], ";
  378.                     $_plugins_params .= $plugin_info[2] ? 'true),' : 'false),';
  379.                 }
  380.             }
  381.             $_plugins_params .= '))';
  382.             $plugins_code = "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');\nsmarty_core_load_plugins($_plugins_params, \$this); ?>\n";
  383.             $template_header .= $plugins_code;
  384.             $this->_plugin_info = array();
  385.             $this->_plugins_code = $plugins_code;
  386.         }
  387.  
  388.         if ($this->_init_smarty_vars) {
  389.             $template_header .= "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.assign_smarty_interface.php');\nsmarty_core_assign_smarty_interface(null, \$this); ?>\n";
  390.             $this->_init_smarty_vars = false;
  391.         }
  392.  
  393.         $compiled_content = $template_header . $compiled_content;
  394.  
  395.         return true;
  396.     }
  397.  
  398.     /**
  399.      * Compile a template tag
  400.      *
  401.      * @param string $template_tag 
  402.      * @return string 
  403.      */
  404.     function _compile_tag($template_tag)
  405.     {
  406.         /* Matched comment. */
  407.         if ($template_tag{0} == '*' && $template_tag{strlen($template_tag) - 1} == '*')
  408.             return '';
  409.  
  410.         /* Split tag into two three parts: command, command modifiers and the arguments. */
  411.         if(! preg_match('/^(?:(' . $this->_obj_call_regexp . '|' . $this->_var_regexp
  412.                 . '|\/?' . $this->_reg_obj_regexp . '|\/?' . $this->_func_regexp . ')(' . $this->_mod_regexp . '*))
  413.                       (?:\s+(.*))?$
  414.                     /xs', $template_tag, $match)) {
  415.             $this->_syntax_error("unrecognized tag: $template_tag", E_USER_ERROR, __FILE__, __LINE__);
  416.         }
  417.  
  418.         $tag_command = $match[1];
  419.         $tag_modifier = isset($match[2]) ? $match[2] : null;
  420.         $tag_args = isset($match[3]) ? $match[3] : null;
  421.  
  422.         if (preg_match('!^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '$!', $tag_command)) {
  423.             /* tag name is a variable or object */
  424.             $_return = $this->_parse_var_props($tag_command . $tag_modifier, $this->_parse_attrs($tag_args));
  425.             if(isset($_tag_attrs['assign'])) {
  426.                 return "<?php \$this->assign('" . $this->_dequote($_tag_attrs['assign']) . "', $_return ); ?>\n";
  427.             } else {
  428.                 return "<?php echo $_return; ?>" . $this->_additional_newline;
  429.             }
  430.         }
  431.  
  432.         /* If the tag name is a registered object, we process it. */
  433.         if (preg_match('!^\/?' . $this->_reg_obj_regexp . '$!', $tag_command)) {
  434.             return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier);
  435.         }
  436.  
  437.         switch ($tag_command) {
  438.             case 'include':
  439.                 return $this->_compile_include_tag($tag_args);
  440.  
  441.             case 'include_php':
  442.                 return $this->_compile_include_php_tag($tag_args);
  443.  
  444.             case 'if':
  445.                 return $this->_compile_if_tag($tag_args);
  446.  
  447.             case 'else':
  448.                 return '<?php else: ?>';
  449.  
  450.             case 'elseif':
  451.                 return $this->_compile_if_tag($tag_args, true);
  452.  
  453.             case '/if':
  454.                 return '<?php endif; ?>';
  455.  
  456.             case 'capture':
  457.                 return $this->_compile_capture_tag(true, $tag_args);
  458.  
  459.             case '/capture':
  460.                 return $this->_compile_capture_tag(false);
  461.  
  462.             case 'ldelim':
  463.                 return $this->left_delimiter;
  464.  
  465.             case 'rdelim':
  466.                 return $this->right_delimiter;
  467.  
  468.             case 'section':
  469.                 array_push($this->_sectionelse_stack, false);
  470.                 return $this->_compile_section_start($tag_args);
  471.  
  472.             case 'sectionelse':
  473.                 $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;
  474.                 return "<?php endfor; else: ?>";
  475.  
  476.             case '/section':
  477.                 if (array_pop($this->_sectionelse_stack))
  478.                     return "<?php endif; ?>";
  479.                 else
  480.                     return "<?php endfor; endif; ?>";
  481.  
  482.             case 'foreach':
  483.                 array_push($this->_foreachelse_stack, false);
  484.                 return $this->_compile_foreach_start($tag_args);
  485.                 break;
  486.  
  487.             case 'foreachelse':
  488.                 $this->_foreachelse_stack[count($this->_foreachelse_stack)-1] = true;
  489.                 return "<?php endforeach; unset(\$_from); else: ?>";
  490.  
  491.             case '/foreach':
  492.                 if (array_pop($this->_foreachelse_stack))
  493.                     return "<?php endif; ?>";
  494.                 else
  495.                     return "<?php endforeach; unset(\$_from); endif; ?>";
  496.  
  497.             case 'strip':
  498.             case '/strip':
  499.                 if ($tag_command{0}=='/') {
  500.                     if (--$this->_strip_depth==0) { /* outermost closing {/strip} */
  501.                         $this->_additional_newline = "\n";
  502.                         return $this->left_delimiter.$tag_command.$this->right_delimiter;
  503.                     }
  504.                 } else {
  505.                     if ($this->_strip_depth++==0) { /* outermost opening {strip} */
  506.                         $this->_additional_newline = "";
  507.                         return $this->left_delimiter.$tag_command.$this->right_delimiter;
  508.                     }
  509.                 }
  510.                 return '';
  511.  
  512.             case 'literal':
  513.                 list (,$literal_block) = each($this->_literal_blocks);
  514.                 $this->_current_line_no += substr_count($literal_block, "\n");
  515.                 return "<?php echo '".str_replace("'", "\'", str_replace("\\", "\\\\", $literal_block))."'; ?>" . $this->_additional_newline;
  516.  
  517.             case 'php':
  518.                 if ($this->security && !$this->security_settings['PHP_TAGS']) {
  519.                     $this->_syntax_error("(secure mode) php tags not permitted", E_USER_WARNING, __FILE__, __LINE__);
  520.                     return;
  521.                 }
  522.                 list (,$php_block) = each($this->_php_blocks);
  523.                 $this->_current_line_no += substr_count($php_block, "\n");
  524.                 return '<?php '.$php_block.' ?>';
  525.  
  526.             case 'insert':
  527.                 return $this->_compile_insert_tag($tag_args);
  528.  
  529.             default:
  530.                 if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) {
  531.                     return $output;
  532.                 } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) {
  533.                     return $output;
  534.                 } else {
  535.                     return $this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier);
  536.                 }
  537.         }
  538.     }
  539.  
  540.  
  541.     /**
  542.      * compile the custom compiler tag
  543.      *
  544.      * sets $output to the compiled custom compiler tag
  545.      * @param string $tag_command 
  546.      * @param string $tag_args 
  547.      * @param string $output 
  548.      * @return boolean 
  549.      */
  550.     function _compile_compiler_tag($tag_command, $tag_args, &$output)
  551.     {
  552.         $found = false;
  553.         $have_function = true;
  554.  
  555.         /*
  556.          * First we check if the compiler function has already been registered
  557.          * or loaded from a plugin file.
  558.          */
  559.         if (isset($this->_plugins['compiler'][$tag_command])) {
  560.             $found = true;
  561.             $plugin_func = $this->_plugins['compiler'][$tag_command][0];
  562.             if (!is_callable($plugin_func)) {
  563.                 $message = "compiler function '$tag_command' is not implemented";
  564.                 $have_function = false;
  565.             }
  566.         }
  567.         /*
  568.          * Otherwise we need to load plugin file and look for the function
  569.          * inside it.
  570.          */
  571.         else if ($plugin_file = $this->_get_plugin_filepath('compiler', $tag_command)) {
  572.             $found = true;
  573.  
  574.             include_once $plugin_file;
  575.  
  576.             $plugin_func = 'smarty_compiler_' . $tag_command;
  577.             if (!is_callable($plugin_func)) {
  578.                 $message = "plugin function $plugin_func() not found in $plugin_file\n";
  579.                 $have_function = false;
  580.             } else {
  581.                 $this->_plugins['compiler'][$tag_command] = array($plugin_func, null, null, null, true);
  582.             }
  583.         }
  584.  
  585.         /*
  586.          * True return value means that we either found a plugin or a
  587.          * dynamically registered function. False means that we didn't and the
  588.          * compiler should now emit code to load custom function plugin for this
  589.          * tag.
  590.          */
  591.         if ($found) {
  592.             if ($have_function) {
  593.                 $output = call_user_func_array($plugin_func, array($tag_args, &$this));
  594.                 if($output != '') {
  595.                 $output = '<?php ' . $this->_push_cacheable_state('compiler', $tag_command)
  596.                                    . $output
  597.                                    . $this->_pop_cacheable_state('compiler', $tag_command) . ' ?>';
  598.                 }
  599.             } else {
  600.                 $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
  601.             }
  602.             return true;
  603.         } else {
  604.             return false;
  605.         }
  606.     }
  607.  
  608.  
  609.     /**
  610.      * compile block function tag
  611.      *
  612.      * sets $output to compiled block function tag
  613.      * @param string $tag_command 
  614.      * @param string $tag_args 
  615.      * @param string $tag_modifier 
  616.      * @param string $output 
  617.      * @return boolean 
  618.      */
  619.     function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output)
  620.     {
  621.         if ($tag_command{0} == '/') {
  622.             $start_tag = false;
  623.             $tag_command = substr($tag_command, 1);
  624.         } else
  625.             $start_tag = true;
  626.  
  627.         $found = false;
  628.         $have_function = true;
  629.  
  630.         /*
  631.          * First we check if the block function has already been registered
  632.          * or loaded from a plugin file.
  633.          */
  634.         if (isset($this->_plugins['block'][$tag_command])) {
  635.             $found = true;
  636.             $plugin_func = $this->_plugins['block'][$tag_command][0];
  637.             if (!is_callable($plugin_func)) {
  638.                 $message = "block function '$tag_command' is not implemented";
  639.                 $have_function = false;
  640.             }
  641.         }
  642.         /*
  643.          * Otherwise we need to load plugin file and look for the function
  644.          * inside it.
  645.          */
  646.         else if ($plugin_file = $this->_get_plugin_filepath('block', $tag_command)) {
  647.             $found = true;
  648.  
  649.             include_once $plugin_file;
  650.  
  651.             $plugin_func = 'smarty_block_' . $tag_command;
  652.             if (!function_exists($plugin_func)) {
  653.                 $message = "plugin function $plugin_func() not found in $plugin_file\n";
  654.                 $have_function = false;
  655.             } else {
  656.                 $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);
  657.  
  658.             }
  659.         }
  660.  
  661.         if (!$found) {
  662.             return false;
  663.         } else if (!$have_function) {
  664.             $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
  665.             return true;
  666.         }
  667.  
  668.         /*
  669.          * Even though we've located the plugin function, compilation
  670.          * happens only once, so the plugin will still need to be loaded
  671.          * at runtime for future requests.
  672.          */
  673.         $this->_add_plugin('block', $tag_command);
  674.  
  675.         if ($start_tag) {
  676.             $output = '<?php ' . $this->_push_cacheable_state('block', $tag_command);
  677.             $attrs = $this->_parse_attrs($tag_args);
  678.             $arg_list = $this->_compile_arg_list('block', $tag_command, $attrs, $_cache_attrs='');
  679.             $output .= "$_cache_attrs\$_params = \$this->_tag_stack[] = array('$tag_command', array(".implode(',', $arg_list).')); ';
  680.             $output .= $this->_compile_plugin_call('block', $tag_command).'($_params[1], null, $this, $_block_repeat=true); unset($_params);';
  681.             $output .= 'while ($_block_repeat) { ob_start(); ?>';
  682.         } else {
  683.             $output = '<?php $this->_block_content = ob_get_contents(); ob_end_clean(); ';
  684.             $_out_tag_text = $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], $this->_block_content, $this, $_block_repeat=false)';
  685.             if ($tag_modifier != '') {
  686.                 $this->_parse_modifiers($_out_tag_text, $tag_modifier);
  687.             }
  688.             $output .= 'echo '.$_out_tag_text.'; } ';
  689.             $output .= " array_pop(\$this->_tag_stack); " . $this->_pop_cacheable_state('block', $tag_command) . '?>';
  690.         }
  691.  
  692.         return true;
  693.     }
  694.  
  695.  
  696.     /**
  697.      * compile custom function tag
  698.      *
  699.      * @param string $tag_command 
  700.      * @param string $tag_args 
  701.      * @param string $tag_modifier 
  702.      * @return string 
  703.      */
  704.     function _compile_custom_tag($tag_command, $tag_args, $tag_modifier)
  705.     {
  706.         $this->_add_plugin('function', $tag_command);
  707.  
  708.         $_cacheable_state = $this->_push_cacheable_state('function', $tag_command);
  709.         $attrs = $this->_parse_attrs($tag_args);
  710.         $arg_list = $this->_compile_arg_list('function', $tag_command, $attrs, $_cache_attrs='');
  711.  
  712.         $_return = $this->_compile_plugin_call('function', $tag_command).'(array('.implode(',', $arg_list)."), \$this)";
  713.         if($tag_modifier != '') {
  714.             $this->_parse_modifiers($_return, $tag_modifier);
  715.         }
  716.  
  717.         if($_return != '') {
  718.             $_return =  '<?php ' . $_cacheable_state . $_cache_attrs . 'echo ' . $_return . ';'
  719.                 . $this->_pop_cacheable_state('function', $tag_command) . "?>" . $this->_additional_newline;
  720.         }
  721.  
  722.         return $_return;
  723.     }
  724.  
  725.     /**
  726.      * compile a registered object tag
  727.      *
  728.      * @param string $tag_command 
  729.      * @param array $attrs 
  730.      * @param string $tag_modifier 
  731.      * @return string 
  732.      */
  733.     function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier)
  734.     {
  735.         if ($tag_command{0} == '/') {
  736.             $start_tag = false;
  737.             $tag_command = substr($tag_command, 1);
  738.         } else {
  739.             $start_tag = true;
  740.         }
  741.  
  742.         list($object, $obj_comp) = explode('->', $tag_command);
  743.  
  744.         $arg_list = array();
  745.         if(count($attrs)) {
  746.             $_assign_var = false;
  747.             foreach ($attrs as $arg_name => $arg_value) {
  748.                 if($arg_name == 'assign') {
  749.                     $_assign_var = $arg_value;
  750.                     unset($attrs['assign']);
  751.                     continue;
  752.                 }
  753.                 if (is_bool($arg_value))
  754.                     $arg_value = $arg_value ? 'true' : 'false';
  755.                 $arg_list[] = "'$arg_name' => $arg_value";
  756.             }
  757.         }
  758.  
  759.         if($this->_reg_objects[$object][2]) {
  760.             // smarty object argument format
  761.             $args = "array(".implode(',', (array)$arg_list)."), \$this";
  762.         } else {
  763.             // traditional argument format
  764.             $args = implode(',', array_values($attrs));
  765.             if (empty($args)) {
  766.                 $args = 'null';
  767.             }
  768.         }
  769.  
  770.         $prefix = '';
  771.         $postfix = '';
  772.         $newline = '';
  773.         if(!is_object($this->_reg_objects[$object][0])) {
  774.             $this->_trigger_fatal_error("registered '$object' is not an object");
  775.         } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) {
  776.             $this->_trigger_fatal_error("'$obj_comp' is not a registered component of object '$object'");
  777.         } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) {
  778.             // method
  779.             if(in_array($obj_comp, $this->_reg_objects[$object][3])) {
  780.                 // block method
  781.                 if ($start_tag) {
  782.                     $prefix = "\$this->_tag_stack[] = array('$obj_comp', $args); ";
  783.                     $prefix .= "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], null, \$this, \$_block_repeat=true); ";
  784.                     $prefix .= "while (\$_block_repeat) { ob_start();";
  785.                     $return = null;
  786.                     $postfix = '';
  787.             } else {
  788.                     $prefix = "\$this->_obj_block_content = ob_get_contents(); ob_end_clean(); ";
  789.                     $return = "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], \$this->_obj_block_content, \$this, \$_block_repeat=false)";
  790.                     $postfix = "} array_pop(\$this->_tag_stack);";
  791.                 }
  792.             } else {
  793.                 // non-block method
  794.                 $return = "\$this->_reg_objects['$object'][0]->$obj_comp($args)";
  795.             }
  796.         } else {
  797.             // property
  798.             $return = "\$this->_reg_objects['$object'][0]->$obj_comp";
  799.         }
  800.  
  801.         if($return != null) {
  802.             if($tag_modifier != '') {
  803.                 $this->_parse_modifiers($return, $tag_modifier);
  804.             }
  805.  
  806.             if(!empty($_assign_var)) {
  807.                 $output = "\$this->assign('" . $this->_dequote($_assign_var) ."',  $return);";
  808.             } else {
  809.                 $output = 'echo ' . $return . ';';
  810.                 $newline = $this->_additional_newline;
  811.             }
  812.         } else {
  813.             $output = '';
  814.         }
  815.  
  816.         return '<?php ' . $prefix . $output . $postfix . "?>" . $newline;
  817.     }
  818.  
  819.     /**
  820.      * Compile {insert ...} tag
  821.      *
  822.      * @param string $tag_args 
  823.      * @return string 
  824.      */
  825.     function _compile_insert_tag($tag_args)
  826.     {
  827.         $attrs = $this->_parse_attrs($tag_args);
  828.         $name = $this->_dequote($attrs['name']);
  829.  
  830.         if (empty($name)) {
  831.             $this->_syntax_error("missing insert name", E_USER_ERROR, __FILE__, __LINE__);
  832.         }
  833.  
  834.         if (!empty($attrs['script'])) {
  835.             $delayed_loading = true;
  836.         } else {
  837.             $delayed_loading = false;
  838.         }
  839.  
  840.         foreach ($attrs as $arg_name => $arg_value) {
  841.             if (is_bool($arg_value))
  842.                 $arg_value = $arg_value ? 'true' : 'false';
  843.             $arg_list[] = "'$arg_name' => $arg_value";
  844.         }
  845.  
  846.         $this->_add_plugin('insert', $name, $delayed_loading);
  847.  
  848.         $_params = "array('args' => array(".implode(', ', (array)$arg_list)."))";
  849.  
  850.         return "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.run_insert_handler.php');\necho smarty_core_run_insert_handler($_params, \$this); ?>" . $this->_additional_newline;
  851.     }
  852.  
  853.     /**
  854.      * Compile {include ...} tag
  855.      *
  856.      * @param string $tag_args 
  857.      * @return string 
  858.      */
  859.     function _compile_include_tag($tag_args)
  860.     {
  861.         $attrs = $this->_parse_attrs($tag_args);
  862.         $arg_list = array();
  863.  
  864.         if (empty($attrs['file'])) {
  865.             $this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__, __LINE__);
  866.         }
  867.  
  868.         foreach ($attrs as $arg_name => $arg_value) {
  869.             if ($arg_name == 'file') {
  870.                 $include_file = $arg_value;
  871.                 continue;
  872.             } else if ($arg_name == 'assign') {
  873.                 $assign_var = $arg_value;
  874.                 continue;
  875.             }
  876.             if (is_bool($arg_value))
  877.                 $arg_value = $arg_value ? 'true' : 'false';
  878.             $arg_list[] = "'$arg_name' => $arg_value";
  879.         }
  880.  
  881.         $output = '<?php ';
  882.  
  883.         if (isset($assign_var)) {
  884.             $output .= "ob_start();\n";
  885.         }
  886.  
  887.         $output .=
  888.             "\$_smarty_tpl_vars = \$this->_tpl_vars;\n";
  889.  
  890.  
  891.         $_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))";
  892.         $output .= "\$this->_smarty_include($_params);\n" .
  893.         "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" .
  894.         "unset(\$_smarty_tpl_vars);\n";
  895.  
  896.         if (isset($assign_var)) {
  897.             $output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n";
  898.         }
  899.  
  900.         $output .= ' ?>';
  901.  
  902.         return $output;
  903.  
  904.     }
  905.  
  906.     /**
  907.      * Compile {include ...} tag
  908.      *
  909.      * @param string $tag_args 
  910.      * @return string 
  911.      */
  912.     function _compile_include_php_tag($tag_args)
  913.     {
  914.         $attrs = $this->_parse_attrs($tag_args);
  915.  
  916.         if (empty($attrs['file'])) {
  917.             $this->_syntax_error("missing 'file' attribute in include_php tag", E_USER_ERROR, __FILE__, __LINE__);
  918.         }
  919.  
  920.         $assign_var = (empty($attrs['assign'])) ? '' : $this->_dequote($attrs['assign']);
  921.         $once_var = (empty($attrs['once']) || $attrs['once']=='false') ? 'false' : 'true';
  922.  
  923.         foreach($attrs as $arg_name => $arg_value) {
  924.             if($arg_name != 'file' AND $arg_name != 'once' AND $arg_name != 'assign') {
  925.                 if(is_bool($arg_value))
  926.                     $arg_value = $arg_value ? 'true' : 'false';
  927.                 $arg_list[] = "'$arg_name' => $arg_value";
  928.             }
  929.         }
  930.  
  931.         $_params = "array('smarty_file' => " . $attrs['file'] . ", 'smarty_assign' => '$assign_var', 'smarty_once' => $once_var, 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))";
  932.  
  933.         return "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.smarty_include_php.php');\nsmarty_core_smarty_include_php($_params, \$this); ?>" . $this->_additional_newline;
  934.     }
  935.  
  936.  
  937.     /**
  938.      * Compile {section ...} tag
  939.      *
  940.      * @param string $tag_args 
  941.      * @return string 
  942.      */
  943.     function _compile_section_start($tag_args)
  944.     {
  945.         $attrs = $this->_parse_attrs($tag_args);
  946.         $arg_list = array();
  947.  
  948.         $output = '<?php ';
  949.         $section_name = $attrs['name'];
  950.         if (empty($section_name)) {
  951.             $this->_syntax_error("missing section name", E_USER_ERROR, __FILE__, __LINE__);
  952.         }
  953.  
  954.         $output .= "if (isset(\$this->_sections[$section_name])) unset(\$this->_sections[$section_name]);\n";
  955.         $section_props = "\$this->_sections[$section_name]";
  956.  
  957.         foreach ($attrs as $attr_name => $attr_value) {
  958.             switch ($attr_name) {
  959.                 case 'loop':
  960.                     $output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int)\$_loop); unset(\$_loop);\n";
  961.                     break;
  962.  
  963.                 case 'show':
  964.                     if (is_bool($attr_value))
  965.                         $show_attr_value = $attr_value ? 'true' : 'false';
  966.                     else
  967.                         $show_attr_value = "(bool)$attr_value";
  968.                     $output .= "{$section_props}['show'] = $show_attr_value;\n";
  969.                     break;
  970.  
  971.                 case 'name':
  972.                     $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
  973.                     break;
  974.  
  975.                 case 'max':
  976.                 case 'start':
  977.                     $output .= "{$section_props}['$attr_name'] = (int)$attr_value;\n";
  978.                     break;
  979.  
  980.                 case 'step':
  981.                     $output .= "{$section_props}['$attr_name'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\n";
  982.                     break;
  983.  
  984.                 default:
  985.                     $this->_syntax_error("unknown section attribute - '$attr_name'", E_USER_ERROR, __FILE__, __LINE__);
  986.                     break;
  987.             }
  988.         }
  989.  
  990.         if (!isset($attrs['show']))
  991.             $output .= "{$section_props}['show'] = true;\n";
  992.  
  993.         if (!isset($attrs['loop']))
  994.             $output .= "{$section_props}['loop'] = 1;\n";
  995.  
  996.         if (!isset($attrs['max']))
  997.             $output .= "{$section_props}['max'] = {$section_props}['loop'];\n";
  998.         else
  999.             $output .= "if ({$section_props}['max'] < 0)\n" .
  1000.                        "    {$section_props}['max'] = {$section_props}['loop'];\n";
  1001.  
  1002.         if (!isset($attrs['step']))
  1003.             $output .= "{$section_props}['step'] = 1;\n";
  1004.  
  1005.         if (!isset($attrs['start']))
  1006.             $output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n";
  1007.         else {
  1008.             $output .= "if ({$section_props}['start'] < 0)\n" .
  1009.                        "    {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" .
  1010.                        "else\n" .
  1011.                        "    {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
  1012.         }
  1013.  
  1014.         $output .= "if ({$section_props}['show']) {\n";
  1015.         if (!isset($attrs['start']) && !isset($attrs['step']) && !isset($attrs['max'])) {
  1016.             $output .= "    {$section_props}['total'] = {$section_props}['loop'];\n";
  1017.         } else {
  1018.             $output .= "    {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n";
  1019.         }
  1020.         $output .= "    if ({$section_props}['total'] == 0)\n" .
  1021.                    "        {$section_props}['show'] = false;\n" .
  1022.                    "} else\n" .
  1023.                    "    {$section_props}['total'] = 0;\n";
  1024.  
  1025.         $output .= "if ({$section_props}['show']):\n";
  1026.         $output .= "
  1027.             for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
  1028.                  {$section_props}['iteration'] <= {$section_props}['total'];
  1029.                  {$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
  1030.         $output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n";
  1031.         $output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n";
  1032.         $output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n";
  1033.         $output .= "{$section_props}['first']      = ({$section_props}['iteration'] == 1);\n";
  1034.         $output .= "{$section_props}['last']       = ({$section_props}['iteration'] == {$section_props}['total']);\n";
  1035.  
  1036.         $output .= "?>";
  1037.  
  1038.         return $output;
  1039.     }
  1040.  
  1041.  
  1042.     /**
  1043.      * Compile {foreach ...} tag.
  1044.      *
  1045.      * @param string $tag_args 
  1046.      * @return string 
  1047.      */
  1048.     function _compile_foreach_start($tag_args)
  1049.     {
  1050.         $attrs = $this->_parse_attrs($tag_args);
  1051.         $arg_list = array();
  1052.  
  1053.         if (empty($attrs['from'])) {
  1054.             $this->_syntax_error("missing 'from' attribute", E_USER_ERROR, __FILE__, __LINE__);
  1055.         }
  1056.  
  1057.         if (empty($attrs['item'])) {
  1058.             $this->_syntax_error("missing 'item' attribute", E_USER_ERROR, __FILE__, __LINE__);
  1059.         }
  1060.  
  1061.         $from = $attrs['from'];
  1062.         $item = $this->_dequote($attrs['item']);
  1063.         if (isset($attrs['name']))
  1064.             $name = $attrs['name'];
  1065.  
  1066.         $output = '<?php ';
  1067.         if (isset($name)) {
  1068.             $output .= "if (isset(\$this->_foreach[$name])) unset(\$this->_foreach[$name]);\n";
  1069.             $foreach_props = "\$this->_foreach[$name]";
  1070.         }
  1071.  
  1072.         $key_part = '';
  1073.  
  1074.         foreach ($attrs as $attr_name => $attr_value) {
  1075.             switch ($attr_name) {
  1076.                 case 'key':
  1077.                     $key  = $this->_dequote($attrs['key']);
  1078.                     $key_part = "\$this->_tpl_vars['$key'] => ";
  1079.                     break;
  1080.  
  1081.                 case 'name':
  1082.                     $output .= "{$foreach_props}['$attr_name'] = $attr_value;\n";
  1083.                     break;
  1084.             }
  1085.         }
  1086.  
  1087.         if (isset($name)) {
  1088.             $output .= "{$foreach_props}['total'] = count(\$_from = (array)$from);\n";
  1089.             $output .= "{$foreach_props}['show'] = {$foreach_props}['total'] > 0;\n";
  1090.             $output .= "if ({$foreach_props}['show']):\n";
  1091.             $output .= "{$foreach_props}['iteration'] = 0;\n";
  1092.             $output .= "    foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
  1093.             $output .= "        {$foreach_props}['iteration']++;\n";
  1094.             $output .= "        {$foreach_props}['first'] = ({$foreach_props}['iteration'] == 1);\n";
  1095.             $output .= "        {$foreach_props}['last']  = ({$foreach_props}['iteration'] == {$foreach_props}['total']);\n";
  1096.         } else {
  1097.             $output .= "if (count(\$_from = (array)$from)):\n";
  1098.             $output .= "    foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
  1099.         }
  1100.         $output .= '?>';
  1101.  
  1102.         return $output;
  1103.     }
  1104.  
  1105.  
  1106.     /**
  1107.      * Compile {capture} .. {/capture} tags
  1108.      *
  1109.      * @param boolean $start true if this is the {capture} tag
  1110.      * @param string $tag_args 
  1111.      * @return string 
  1112.      */
  1113.  
  1114.     function _compile_capture_tag($start, $tag_args = '')
  1115.     {
  1116.         $attrs = $this->_parse_attrs($tag_args);
  1117.  
  1118.         if ($start) {
  1119.             if (isset($attrs['name']))
  1120.                 $buffer = $attrs['name'];
  1121.             else
  1122.                 $buffer = "'default'";
  1123.  
  1124.             if (isset($attrs['assign']))
  1125.                 $assign = $attrs['assign'];
  1126.             else
  1127.                 $assign = null;
  1128.             $output = "<?php ob_start(); ?>";
  1129.             $this->_capture_stack[] = array($buffer, $assign);
  1130.         } else {
  1131.             list($buffer, $assign) = array_pop($this->_capture_stack);
  1132.             $output = "<?php \$this->_smarty_vars['capture'][$buffer] = ob_get_contents(); ";
  1133.             if (isset($assign)) {
  1134.                 $output .= " \$this->assign($assign, ob_get_contents());";
  1135.             }
  1136.             $output .= "ob_end_clean(); ?>";
  1137.         }
  1138.  
  1139.         return $output;
  1140.     }
  1141.  
  1142.     /**
  1143.      * Compile {if ...} tag
  1144.      *
  1145.      * @param string $tag_args 
  1146.      * @param boolean $elseif if true, uses elseif instead of if
  1147.      * @return string 
  1148.      */
  1149.     function _compile_if_tag($tag_args, $elseif = false)
  1150.     {
  1151.  
  1152.         /* Tokenize args for 'if' tag. */
  1153.         preg_match_all('/(?>
  1154.                 ' . $this->_obj_call_regexp . '(?:' . $this->_mod_regexp . '*)? | # valid object call
  1155.                 ' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)?    | # var or quoted string
  1156.                 \-?0[xX][0-9a-fA-F]+|\-?\d+(?:\.\d+)?|\.\d+|!==|===|==|!=|<>|<<|>>|<=|>=|\&\&|\|\||\(|\)|,|\!|\^|=|\&|\~|<|>|\||\%|\+|\-|\/|\*|\@    | # valid non-word token
  1157.                 \b\w+\b                                                        | # valid word token
  1158.                 \S+                                                           # anything else
  1159.                 )/x', $tag_args, $match);
  1160.  
  1161.         $tokens = $match[0];
  1162.  
  1163.         // make sure we have balanced parenthesis
  1164.         $token_count = array_count_values($tokens);
  1165.         if(isset($token_count['(']) && $token_count['('] != $token_count[')']) {
  1166.             $this->_syntax_error("unbalanced parenthesis in if statement", E_USER_ERROR, __FILE__, __LINE__);
  1167.         }
  1168.  
  1169.         $is_arg_stack = array();
  1170.  
  1171.         for ($i = 0; $i < count($tokens); $i++) {
  1172.  
  1173.             $token = &$tokens[$i];
  1174.  
  1175.             switch (strtolower($token)) {
  1176.                 case '!':
  1177.                 case '%':
  1178.                 case '!==':
  1179.                 case '==':
  1180.                 case '===':
  1181.                 case '>':
  1182.                 case '<':
  1183.                 case '!=':
  1184.                 case '<>':
  1185.                 case '<<':
  1186.                 case '>>':
  1187.                 case '<=':
  1188.                 case '>=':
  1189.                 case '&&':
  1190.                 case '||':
  1191.                 case '|':
  1192.                 case '^':
  1193.                 case '&':
  1194.                 case '~':
  1195.                 case ')':
  1196.                 case ',':
  1197.                 case '+':
  1198.                 case '-':
  1199.                 case '*':
  1200.                 case '/':
  1201.                 case '@':
  1202.                     break;
  1203.  
  1204.                 case 'eq':
  1205.                     $token = '==';
  1206.                     break;
  1207.  
  1208.                 case 'ne':
  1209.                 case 'neq':
  1210.                     $token = '!=';
  1211.                     break;
  1212.  
  1213.                 case 'lt':
  1214.                     $token = '<';
  1215.                     break;
  1216.  
  1217.                 case 'le':
  1218.                 case 'lte':
  1219.                     $token = '<=';
  1220.                     break;
  1221.  
  1222.                 case 'gt':
  1223.                     $token = '>';
  1224.                     break;
  1225.  
  1226.                 case 'ge':
  1227.                 case 'gte':
  1228.                     $token = '>=';
  1229.                     break;
  1230.  
  1231.                 case 'and':
  1232.                     $token = '&&';
  1233.                     break;
  1234.  
  1235.                 case 'or':
  1236.                     $token = '||';
  1237.                     break;
  1238.  
  1239.                 case 'not':
  1240.                     $token = '!';
  1241.                     break;
  1242.  
  1243.                 case 'mod':
  1244.                     $token = '%';
  1245.                     break;
  1246.  
  1247.                 case '(':
  1248.                     array_push($is_arg_stack, $i);
  1249.                     break;
  1250.  
  1251.                 case 'is':
  1252.                     /* If last token was a ')', we operate on the parenthesized
  1253.                        expression. The start of the expression is on the stack.
  1254.                        Otherwise, we operate on the last encountered token. */
  1255.                     if ($tokens[$i-1] == ')')
  1256.                         $is_arg_start = array_pop($is_arg_stack);
  1257.                     else
  1258.                         $is_arg_start = $i-1;
  1259.                     /* Construct the argument for 'is' expression, so it knows
  1260.                        what to operate on. */
  1261.                     $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
  1262.  
  1263.                     /* Pass all tokens from next one until the end to the
  1264.                        'is' expression parsing function. The function will
  1265.                        return modified tokens, where the first one is the result
  1266.                        of the 'is' expression and the rest are the tokens it
  1267.                        didn't touch. */
  1268.                     $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
  1269.  
  1270.                     /* Replace the old tokens with the new ones. */
  1271.                     array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);
  1272.  
  1273.                     /* Adjust argument start so that it won't change from the
  1274.                        current position for the next iteration. */
  1275.                     $i = $is_arg_start;
  1276.                     break;
  1277.  
  1278.                 default:
  1279.                     if(preg_match('!^' . $this->_func_regexp . '$!', $token) ) {
  1280.                             // function call
  1281.                             if($this->security &&
  1282.                                !in_array($token, $this->security_settings['IF_FUNCS'])) {
  1283.                                 $this->_syntax_error("(secure mode) '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__);
  1284.                             }
  1285.                     } elseif(preg_match('!^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)$!', $token)) {
  1286.                         // object or variable
  1287.                         $token = $this->_parse_var_props($token);
  1288.                     } elseif(is_numeric($token)) {
  1289.                         // number, skip it
  1290.                     } else {
  1291.                         $this->_syntax_error("unidentified token '$token'", E_USER_ERROR, __FILE__, __LINE__);
  1292.                     }
  1293.                     break;
  1294.             }
  1295.         }
  1296.  
  1297.         if ($elseif)
  1298.             return '<?php elseif ('.implode(' ', $tokens).'): ?>';
  1299.         else
  1300.             return '<?php if ('.implode(' ', $tokens).'): ?>';
  1301.     }
  1302.  
  1303.  
  1304.     function _compile_arg_list($type, $name, $attrs, &$cache_code) {
  1305.         $arg_list = array();
  1306.  
  1307.         if (isset($type) && isset($name)
  1308.             && isset($this->_plugins[$type])
  1309.             && isset($this->_plugins[$type][$name])
  1310.             && empty($this->_plugins[$type][$name][4])
  1311.             && is_array($this->_plugins[$type][$name][5])
  1312.             ) {
  1313.             /* we have a list of parameters that should be cached */
  1314.             $_cache_attrs = $this->_plugins[$type][$name][5];
  1315.             $_count = $this->_cache_attrs_count++;
  1316.             $cache_code = "\$_cache_attrs =& \$this->_smarty_cache_attrs('$this->_cache_serial','$_count');";
  1317.  
  1318.         } else {
  1319.             /* no parameters are cached */
  1320.             $_cache_attrs = null;
  1321.         }
  1322.  
  1323.         foreach ($attrs as $arg_name => $arg_value) {
  1324.             if (is_bool($arg_value))
  1325.                 $arg_value = $arg_value ? 'true' : 'false';
  1326.             if (is_null($arg_value))
  1327.                 $arg_value = 'null';
  1328.             if ($_cache_attrs && in_array($arg_name, $_cache_attrs)) {
  1329.                 $arg_list[] = "'$arg_name' => (\$this->_cache_including) ? \$_cache_attrs['$arg_name'] : (\$_cache_attrs['$arg_name']=$arg_value)";
  1330.             } else {
  1331.                 $arg_list[] = "'$arg_name' => $arg_value";
  1332.             }
  1333.         }
  1334.         return $arg_list;
  1335.     }
  1336.  
  1337.     /**
  1338.      * Parse is expression
  1339.      *
  1340.      * @param string $is_arg 
  1341.      * @param array $tokens 
  1342.      * @return array 
  1343.      */
  1344.     function _parse_is_expr($is_arg, $tokens)
  1345.     {
  1346.         $expr_end = 0;
  1347.         $negate_expr = false;
  1348.  
  1349.         if (($first_token = array_shift($tokens)) == 'not') {
  1350.             $negate_expr = true;
  1351.             $expr_type = array_shift($tokens);
  1352.         } else
  1353.             $expr_type = $first_token;
  1354.  
  1355.         switch ($expr_type) {
  1356.             case 'even':
  1357.                 if (@$tokens[$expr_end] == 'by') {
  1358.                     $expr_end++;
  1359.                     $expr_arg = $tokens[$expr_end++];
  1360.                     $expr = "!(($is_arg / $expr_arg) % " . $this->_parse_var_props($expr_arg) . ")";
  1361.                 } else
  1362.                     $expr = "!($is_arg % 2)";
  1363.                 break;
  1364.  
  1365.             case 'odd':
  1366.                 if (@$tokens[$expr_end] == 'by') {
  1367.                     $expr_end++;
  1368.                     $expr_arg = $tokens[$expr_end++];
  1369.                     $expr = "(($is_arg / $expr_arg) % ". $this->_parse_var_props($expr_arg) . ")";
  1370.                 } else
  1371.                     $expr = "($is_arg % 2)";
  1372.                 break;
  1373.  
  1374.             case 'div':
  1375.                 if (@$tokens[$expr_end] == 'by') {
  1376.                     $expr_end++;
  1377.                     $expr_arg = $tokens[$expr_end++];
  1378.                     $expr = "!($is_arg % " . $this->_parse_var_props($expr_arg) . ")";
  1379.                 } else {
  1380.                     $this->_syntax_error("expecting 'by' after 'div'", E_USER_ERROR, __FILE__, __LINE__);
  1381.                 }
  1382.                 break;
  1383.  
  1384.             default:
  1385.                 $this->_syntax_error("unknown 'is' expression - '$expr_type'", E_USER_ERROR, __FILE__, __LINE__);
  1386.                 break;
  1387.         }
  1388.  
  1389.         if ($negate_expr) {
  1390.             $expr = "!($expr)";
  1391.         }
  1392.  
  1393.         array_splice($tokens, 0, $expr_end, $expr);
  1394.  
  1395.         return $tokens;
  1396.     }
  1397.  
  1398.  
  1399.     /**
  1400.      * Parse attribute string
  1401.      *
  1402.      * @param string $tag_args 
  1403.      * @return array 
  1404.      */
  1405.     function _parse_attrs($tag_args)
  1406.     {
  1407.  
  1408.         /* Tokenize tag attributes. */
  1409.         preg_match_all('/(?:' . $this->_obj_call_regexp . '|' . $this->_qstr_regexp . ' | (?>[^"\'=\s]+)
  1410.                          )+ |
  1411.                          [=]
  1412.                         /x', $tag_args, $match);
  1413.         $tokens       = $match[0];
  1414.  
  1415.         $attrs = array();
  1416.         /* Parse state:
  1417.             0 - expecting attribute name
  1418.             1 - expecting '='
  1419.             2 - expecting attribute value (not '=') */
  1420.         $state = 0;
  1421.  
  1422.         foreach ($tokens as $token) {
  1423.             switch ($state) {
  1424.                 case 0:
  1425.                     /* If the token is a valid identifier, we set attribute name
  1426.                        and go to state 1. */
  1427.                     if (preg_match('!^\w+$!', $token)) {
  1428.                         $attr_name = $token;
  1429.                         $state = 1;
  1430.                     } else
  1431.                         $this->_syntax_error("invalid attribute name: '$token'", E_USER_ERROR, __FILE__, __LINE__);
  1432.                     break;
  1433.  
  1434.                 case 1:
  1435.                     /* If the token is '=', then we go to state 2. */
  1436.                     if ($token == '=') {
  1437.                         $state = 2;
  1438.                     } else
  1439.                         $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__);
  1440.                     break;
  1441.  
  1442.                 case 2:
  1443.                     /* If token is not '=', we set the attribute value and go to
  1444.                        state 0. */
  1445.                     if ($token != '=') {
  1446.                         /* We booleanize the token if it's a non-quoted possible
  1447.                            boolean value. */
  1448.                         if (preg_match('!^(on|yes|true)$!', $token)) {
  1449.                             $token = 'true';
  1450.                         } else if (preg_match('!^(off|no|false)$!', $token)) {
  1451.                             $token = 'false';
  1452.                         } else if ($token == 'null') {
  1453.                             $token = 'null';
  1454.                         } else if (preg_match('!^-?([0-9]+|0[xX][0-9a-fA-F]+)$!', $token)) {
  1455.                             /* treat integer literally */
  1456.                         } else if (!preg_match('!^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . ')*$!', $token)) {
  1457.                             /* treat as a string, double-quote it escaping quotes */
  1458.                             $token = '"'.addslashes($token).'"';
  1459.                         }
  1460.  
  1461.                         $attrs[$attr_name] = $token;
  1462.                         $state = 0;
  1463.                     } else
  1464.                         $this->_syntax_error("'=' cannot be an attribute value", E_USER_ERROR, __FILE__, __LINE__);
  1465.                     break;
  1466.             }
  1467.             $last_token = $token;
  1468.         }
  1469.  
  1470.         if($state != 0) {
  1471.             if($state == 1) {
  1472.                 $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__);
  1473.             } else {
  1474.                 $this->_syntax_error("missing attribute value", E_USER_ERROR, __FILE__, __LINE__);
  1475.             }
  1476.         }
  1477.  
  1478.         $this->_parse_vars_props($attrs);
  1479.  
  1480.         return $attrs;
  1481.     }
  1482.  
  1483.     /**
  1484.      * compile multiple variables and section properties tokens into
  1485.      * PHP code
  1486.      *
  1487.      * @param array $tokens 
  1488.      */
  1489.     function _parse_vars_props(&$tokens)
  1490.     {
  1491.         foreach($tokens as $key => $val) {
  1492.             $tokens[$key] = $this->_parse_var_props($val);
  1493.         }
  1494.     }
  1495.  
  1496.     /**
  1497.      * compile single variable and section properties token into
  1498.      * PHP code
  1499.      *
  1500.      * @param string $val 
  1501.      * @param string $tag_attrs 
  1502.      * @return string 
  1503.      */
  1504.     function _parse_var_props($val)
  1505.     {
  1506.         $val = trim($val);
  1507.  
  1508.         if(preg_match('!^(' . $this->_obj_call_regexp . '|' . $this->_dvar_regexp . ')(' . $this->_mod_regexp . '*)$!', $val, $match)) {
  1509.                 // $ variable or object
  1510.                 $return = $this->_parse_var($match[1]);
  1511.                 if($match[2] != '') {
  1512.                     $this->_parse_modifiers($return, $match[2]);
  1513.                 }
  1514.                 return $return;
  1515.             }
  1516.         elseif(preg_match('!^' . $this->_db_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
  1517.                 // double quoted text
  1518.                 preg_match('!^(' . $this->_db_qstr_regexp . ')('. $this->_mod_regexp . '*)$!', $val, $match);
  1519.                 $return = $this->_expand_quoted_text($match[1]);
  1520.                 if($match[2] != '') {
  1521.                     $this->_parse_modifiers($return, $match[2]);
  1522.                 }
  1523.                 return $return;
  1524.             }
  1525.         elseif(preg_match('!^' . $this->_si_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
  1526.                 // single quoted text
  1527.                 preg_match('!^(' . $this->_si_qstr_regexp . ')('. $this->_mod_regexp . '*)$!', $val, $match);
  1528.                 if($match[2] != '') {
  1529.                     $this->_parse_modifiers($match[1], $match[2]);
  1530.                     return $match[1];
  1531.                 }
  1532.             }
  1533.         elseif(preg_match('!^' . $this->_cvar_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
  1534.                 // config var
  1535.                 return $this->_parse_conf_var($val);
  1536.             }
  1537.         elseif(preg_match('!^' . $this->_svar_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
  1538.                 // section var
  1539.                 return $this->_parse_section_prop($val);
  1540.             }
  1541.         elseif(!in_array($val, $this->_permitted_tokens) && !is_numeric($val)) {
  1542.             // literal string
  1543.             return $this->_expand_quoted_text('"' . $val .'"');
  1544.         }
  1545.         return $val;
  1546.     }
  1547.  
  1548.     /**
  1549.      * expand quoted text with embedded variables
  1550.      *
  1551.      * @param string $var_expr 
  1552.      * @return string 
  1553.      */
  1554.     function _expand_quoted_text($var_expr)
  1555.     {
  1556.         // if contains unescaped $, expand it
  1557.         if(preg_match_all('%(?:\`(?<!\\\\)\$' . $this->_dvar_guts_regexp . '\`)|(?:(?<!\\\\)\$\w+(\[[a-zA-Z0-9]+\])*)%', $var_expr, $_match)) {
  1558.             $_match = $_match[0];
  1559.             rsort($_match);
  1560.             reset($_match);
  1561.             foreach($_match as $_var) {
  1562.                 $var_expr = str_replace ($_var, '".(' . $this->_parse_var(str_replace('`','',$_var)) . ')."', $var_expr);
  1563.             }
  1564.             $_return = preg_replace('%\.""|(?<!\\\\)""\.%', '', $var_expr);
  1565.         } else {
  1566.             $_return = $var_expr;
  1567.         }
  1568.         // replace double quoted literal string with single quotes
  1569.         $_return = preg_replace('!^"([\s\w]+)"$!',"'\\1'",$_return);
  1570.         return $_return;
  1571.     }
  1572.  
  1573.     /**
  1574.      * parse variable expression into PHP code
  1575.      *
  1576.      * @param string $var_expr 
  1577.      * @param string $output 
  1578.      * @return string 
  1579.      */
  1580.     function _parse_var($var_expr)
  1581.     {
  1582.         $_has_math = false;
  1583.         $_math_vars = preg_split('!('.$this->_dvar_math_regexp.'|'.$this->_qstr_regexp.')!', $var_expr, -1, PREG_SPLIT_DELIM_CAPTURE);
  1584.  
  1585.         if(count($_math_vars) > 1) {
  1586.             $_first_var = "";
  1587.             $_complete_var = "";
  1588.             // simple check if there is any math, to stop recursion (due to modifiers with "xx % yy" as parameter)
  1589.             foreach($_math_vars as $_k => $_math_var) {
  1590.                 $_math_var = $_math_vars[$_k];
  1591.  
  1592.                 if(!empty($_math_var) || is_numeric($_math_var)) {
  1593.                     // hit a math operator, so process the stuff which came before it
  1594.                     if(preg_match('!^' . $this->_dvar_math_regexp . '$!', $_math_var)) {
  1595.                         $_has_math = true;
  1596.                         if(!empty($_complete_var) || is_numeric($_complete_var)) {
  1597.                             $_output .= $this->_parse_var($_complete_var);
  1598.                         }
  1599.  
  1600.                         // just output the math operator to php
  1601.                         $_output .= $_math_var;
  1602.  
  1603.                         if(empty($_first_var))
  1604.                             $_first_var = $_complete_var;
  1605.  
  1606.                         $_complete_var = "";
  1607.                     } else {
  1608.                         // fetch multiple -> (like $foo->bar->baz ) which wouldn't get fetched else, because it would only get $foo->bar and treat the ->baz as "-" ">baz" then
  1609.                         for($_i = $_k + 1; $_i <= count($_math_vars); $_i += 2) {
  1610.                             // fetch -> because it gets splitted at - and move it back together
  1611.                             if( /* prevent notice */ (isset($_math_vars[$_i]) && isset($_math_vars[$_i+1])) && ($_math_vars[$_i] === '-' && $_math_vars[$_i+1]{0} === '>')) {
  1612.                                 $_math_var .= $_math_vars[$_i].$_math_vars[$_i+1];
  1613.                                 $_math_vars[$_i] = $_math_vars[$_i+1] = '';
  1614.                             } else {
  1615.                                 break;
  1616.                             }
  1617.                         }
  1618.                         $_complete_var .= $_math_var;
  1619.                     }
  1620.                 }
  1621.             }
  1622.             if($_has_math) {
  1623.                 if(!empty($_complete_var) || is_numeric($_complete_var))
  1624.                     $_output .= $this->_parse_var($_complete_var, true);
  1625.  
  1626.                 // get the modifiers working (only the last var from math + modifier is left)
  1627.                 $var_expr = $_complete_var;
  1628.             }
  1629.         }
  1630.  
  1631.         // prevent cutting of first digit in the number (we _definitly_ got a number if the first char is a digit)
  1632.         if(is_numeric($var_expr{0}))
  1633.             $_var_ref = $var_expr;
  1634.         else
  1635.             $_var_ref = substr($var_expr, 1);
  1636.  
  1637.         if(!$_has_math) {
  1638.             // get [foo] and .foo and ->foo and (...) pieces
  1639.             preg_match_all('!(?:^\w+)|' . $this->_obj_params_regexp . '|(?:' . $this->_var_bracket_regexp . ')|->\$?\w+|\.\$?\w+|\S+!', $_var_ref, $match);
  1640.  
  1641.             $_indexes = $match[0];
  1642.             $_var_name = array_shift($_indexes);
  1643.  
  1644.             /* Handle $smarty.* variable references as a special case. */
  1645.             if ($_var_name == 'smarty') {
  1646.                 /*
  1647.                  * If the reference could be compiled, use the compiled output;
  1648.                  * otherwise, fall back on the $smarty variable generated at
  1649.                  * run-time.
  1650.                  */
  1651.                 if (($smarty_ref = $this->_compile_smarty_ref($_indexes)) !== null) {
  1652.                     $_output = $smarty_ref;
  1653.                 } else {
  1654.                     $_var_name = substr(array_shift($_indexes), 1);
  1655.                     $_output = "\$this->_smarty_vars['$_var_name']";
  1656.                 }
  1657.             } elseif(is_numeric($_var_name) && is_numeric($var_expr{0})) {
  1658.                 // because . is the operator for accessing arrays thru inidizes we need to put it together again for floating point numbers
  1659.                 if(count($_indexes) > 0)
  1660.                 {
  1661.                     $_var_name .= implode("", $_indexes);
  1662.                     $_indexes = array();
  1663.                 }
  1664.                 $_output = $_var_name;
  1665.             } else {
  1666.                 $_output = "\$this->_tpl_vars['$_var_name']";
  1667.             }
  1668.  
  1669.             foreach ($_indexes as $_index) {
  1670.                 if ($_index{0} == '[') {
  1671.                     $_index = substr($_index, 1, -1);
  1672.                     if (is_numeric($_index)) {
  1673.                         $_output .= "[$_index]";
  1674.                     } elseif ($_index{0} == '$') {
  1675.                         if (strpos($_index, '.') !== false) {
  1676.                             $_output .= '[' . $this->_parse_var($_index) . ']';
  1677.                         } else {
  1678.                             $_output .= "[\$this->_tpl_vars['" . substr($_index, 1) . "']]";
  1679.                         }
  1680.                     } else {
  1681.                         $_var_parts = explode('.', $_index);
  1682.                         $_var_section = $_var_parts[0];
  1683.                         $_var_section_prop = isset($_var_parts[1]) ? $_var_parts[1] : 'index';
  1684.                         $_output .= "[\$this->_sections['$_var_section']['$_var_section_prop']]";
  1685.                     }
  1686.                 } else if ($_index{0} == '.') {
  1687.                     if ($_index{1} == '$')
  1688.                         $_output .= "[\$this->_tpl_vars['" . substr($_index, 2) . "']]";
  1689.                     else
  1690.                         $_output .= "['" . substr($_index, 1) . "']";
  1691.                 } else if (substr($_index,0,2) == '->') {
  1692.                     if(substr($_index,2,2) == '__') {
  1693.                         $this->_syntax_error('call to internal object members is not allowed', E_USER_ERROR, __FILE__, __LINE__);
  1694.                     } elseif($this->security && substr($_index, 2, 1) == '_') {
  1695.                         $this->_syntax_error('(secure) call to private object member is not allowed', E_USER_ERROR, __FILE__, __LINE__);
  1696.                     } elseif ($_index{2} == '$') {
  1697.                         if ($this->security) {
  1698.                             $this->_syntax_error('(secure) call to dynamic object member is not allowed', E_USER_ERROR, __FILE__, __LINE__);
  1699.                         } else {
  1700.                             $_output .= '->{(($_var=$this->_tpl_vars[\''.substr($_index,3).'\']) && substr($_var,0,2)!=\'__\') ? $_var : $this->trigger_error("cannot access property \\"$_var\\"")}';
  1701.                         }
  1702.                     } else {
  1703.                         $_output .= $_index;
  1704.                     }
  1705.                 } elseif ($_index{0} == '(') {
  1706.                     $_index = $this->_parse_parenth_args($_index);
  1707.                     $_output .= $_index;
  1708.                 } else {
  1709.                     $_output .= $_index;
  1710.                 }
  1711.             }
  1712.         }
  1713.  
  1714.         return $_output;
  1715.     }
  1716.  
  1717.     /**
  1718.      * parse arguments in function call parenthesis
  1719.      *
  1720.      * @param string $parenth_args 
  1721.      * @return string 
  1722.      */
  1723.     function _parse_parenth_args($parenth_args)
  1724.     {
  1725.         preg_match_all('!' . $this->_param_regexp . '!',$parenth_args, $match);
  1726.         $match = $match[0];
  1727.         rsort($match);
  1728.         reset($match);
  1729.         $orig_vals = $match;
  1730.         $this->_parse_vars_props($match);
  1731.         return str_replace($orig_vals, $match, $parenth_args);
  1732.     }
  1733.  
  1734.     /**
  1735.      * parse configuration variable expression into PHP code
  1736.      *
  1737.      * @param string $conf_var_expr 
  1738.      */
  1739.     function _parse_conf_var($conf_var_expr)
  1740.     {
  1741.         $parts = explode('|', $conf_var_expr, 2);
  1742.         $var_ref = $parts[0];
  1743.         $modifiers = isset($parts[1]) ? $parts[1] : '';
  1744.  
  1745.         $var_name = substr($var_ref, 1, -1);
  1746.  
  1747.         $output = "\$this->_config[0]['vars']['$var_name']";
  1748.  
  1749.         $this->_parse_modifiers($output, $modifiers);
  1750.  
  1751.         return $output;
  1752.     }
  1753.  
  1754.     /**
  1755.      * parse section property expression into PHP code
  1756.      *
  1757.      * @param string $section_prop_expr 
  1758.      * @return string 
  1759.      */
  1760.     function _parse_section_prop($section_prop_expr)
  1761.     {
  1762.         $parts = explode('|', $section_prop_expr, 2);
  1763.         $var_ref = $parts[0];
  1764.         $modifiers = isset($parts[1]) ? $parts[1] : '';
  1765.  
  1766.         preg_match('!%(\w+)\.(\w+)%!', $var_ref, $match);
  1767.         $section_name = $match[1];
  1768.         $prop_name = $match[2];
  1769.  
  1770.         $output = "\$this->_sections['$section_name']['$prop_name']";
  1771.  
  1772.         $this->_parse_modifiers($output, $modifiers);
  1773.  
  1774.         return $output;
  1775.     }
  1776.  
  1777.  
  1778.     /**
  1779.      * parse modifier chain into PHP code
  1780.      *
  1781.      * sets $output to parsed modified chain
  1782.      * @param string $output 
  1783.      * @param string $modifier_string 
  1784.      */
  1785.     function _parse_modifiers(&$output, $modifier_string)
  1786.     {
  1787.         preg_match_all('!\|(@?\w+)((?>:(?:'. $this->_qstr_regexp . '|[^|]+))*)!', '|' . $modifier_string, $_match);
  1788.         list(, $_modifiers, $modifier_arg_strings) = $_match;
  1789.  
  1790.         for ($_i = 0, $_for_max = count($_modifiers); $_i < $_for_max; $_i++) {
  1791.             $_modifier_name = $_modifiers[$_i];
  1792.  
  1793.             if($_modifier_name == 'smarty') {
  1794.                 // skip smarty modifier
  1795.                 continue;
  1796.             }
  1797.  
  1798.             preg_match_all('!:(' . $this->_qstr_regexp . '|[^:]+)!', $modifier_arg_strings[$_i], $_match);
  1799.             $_modifier_args = $_match[1];
  1800.  
  1801.             if ($_modifier_name{0} == '@') {
  1802.                 $_map_array = false;
  1803.                 $_modifier_name = substr($_modifier_name, 1);
  1804.             } else {
  1805.                 $_map_array = true;
  1806.             }
  1807.  
  1808.             $this->_add_plugin('modifier', $_modifier_name);
  1809.             if (empty($this->_plugins['modifier'][$_modifier_name])
  1810.                 && !$this->_get_plugin_filepath('modifier', $_modifier_name)
  1811.                 && function_exists($_modifier_name)) {
  1812.                 if ($this->security && !in_array($_modifier_name, $this->security_settings['MODIFIER_FUNCS'])) {
  1813.                     $this->_trigger_fatal_error("[plugin] (secure mode) modifier '$_modifier_name' is not allowed" , $_tpl_file, $_tpl_line, __FILE__, __LINE__);
  1814.                 } else {
  1815.                     $this->_plugins['modifier'][$_modifier_name] = array($_modifier_name,  null, null, false);
  1816.                 }
  1817.             }
  1818.  
  1819.             $this->_parse_vars_props($_modifier_args);
  1820.  
  1821.             if($_modifier_name == 'default') {
  1822.                 // supress notifications of default modifier vars and args
  1823.                 if($output{0} == '$') {
  1824.                     $output = '@' . $output;
  1825.                 }
  1826.                 if(isset($_modifier_args[0]) && $_modifier_args[0]{0} == '$') {
  1827.                     $_modifier_args[0] = '@' . $_modifier_args[0];
  1828.                 }
  1829.             }
  1830.             if (count($_modifier_args) > 0)
  1831.                 $_modifier_args = ', '.implode(', ', $_modifier_args);
  1832.             else
  1833.                 $_modifier_args = '';
  1834.  
  1835.             if ($_map_array) {
  1836.                 $output = "((is_array(\$_tmp=$output)) ? \$this->_run_mod_handler('$_modifier_name', true, \$_tmp$_modifier_args) : " . $this->_compile_plugin_call('modifier', $_modifier_name) . "(\$_tmp$_modifier_args))";
  1837.  
  1838.             } else {
  1839.  
  1840.                 $output = $this->_compile_plugin_call('modifier', $_modifier_name)."($output$_modifier_args)";
  1841.  
  1842.             }
  1843.         }
  1844.     }
  1845.  
  1846.  
  1847.     /**
  1848.      * add plugin
  1849.      *
  1850.      * @param string $type 
  1851.      * @param string $name 
  1852.      * @param boolean? $delayed_loading 
  1853.      */
  1854.     function _add_plugin($type, $name, $delayed_loading = null)
  1855.     {
  1856.         if (!isset($this->_plugin_info[$type])) {
  1857.             $this->_plugin_info[$type] = array();
  1858.         }
  1859.         if (!isset($this->_plugin_info[$type][$name])) {
  1860.             $this->_plugin_info[$type][$name] = array($this->_current_file,
  1861.                                                       $this->_current_line_no,
  1862.                                                       $delayed_loading);
  1863.         }
  1864.     }
  1865.  
  1866.  
  1867.     /**
  1868.      * Compiles references of type $smarty.foo
  1869.      *
  1870.      * @param string $indexes 
  1871.      * @return string 
  1872.      */
  1873.     function _compile_smarty_ref(&$indexes)
  1874.     {
  1875.         /* Extract the reference name. */
  1876.         $_ref = substr($indexes[0], 1);
  1877.         foreach($indexes as $_index_no=>$_index) {
  1878.             if ($_index{0} != '.' && $_index_no<2 || !preg_match('!^(\.|\[|->)!', $_index)) {
  1879.                 $this->_syntax_error('$smarty' . implode('', array_slice($indexes, 0, 2)) . ' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__);
  1880.             }
  1881.         }
  1882.  
  1883.         switch ($_ref) {
  1884.             case 'now':
  1885.                 $compiled_ref = 'time()';
  1886.                 $_max_index = 1;
  1887.                 break;
  1888.  
  1889.             case 'foreach':
  1890.             case 'section':
  1891.                 array_shift($indexes);
  1892.                 $_var = $this->_parse_var_props(substr($indexes[0], 1));
  1893.                 if ($_ref == 'foreach')
  1894.                     $compiled_ref = "\$this->_foreach[$_var]";
  1895.                 else
  1896.                     $compiled_ref = "\$this->_sections[$_var]";
  1897.                 break;
  1898.  
  1899.             case 'get':
  1900.                 $compiled_ref = ($this->request_use_auto_globals) ? '$_GET' : "\$GLOBALS['HTTP_GET_VARS']";
  1901.                 break;
  1902.  
  1903.             case 'post':
  1904.                 $compiled_ref = ($this->request_use_auto_globals) ? '$_POST' : "\$GLOBALS['HTTP_POST_VARS']";
  1905.                 break;
  1906.  
  1907.             case 'cookies':
  1908.                 $compiled_ref = ($this->request_use_auto_globals) ? '$_COOKIE' : "\$GLOBALS['HTTP_COOKIE_VARS']";
  1909.                 break;
  1910.  
  1911.             case 'env':
  1912.                 $compiled_ref = ($this->request_use_auto_globals) ? '$_ENV' : "\$GLOBALS['HTTP_ENV_VARS']";
  1913.                 break;
  1914.  
  1915.             case 'server':
  1916.                 $compiled_ref = ($this->request_use_auto_globals) ? '$_SERVER' : "\$GLOBALS['HTTP_SERVER_VARS']";
  1917.                 break;
  1918.  
  1919.             case 'session':
  1920.                 $compiled_ref = ($this->request_use_auto_globals) ? '$_SESSION' : "\$GLOBALS['HTTP_SESSION_VARS']";
  1921.                 break;
  1922.  
  1923.             /*
  1924.              * These cases are handled either at run-time or elsewhere in the
  1925.              * compiler.
  1926.              */
  1927.             case 'request':
  1928.                 if ($this->request_use_auto_globals) {
  1929.                     $compiled_ref = '$_REQUEST';
  1930.                     break;
  1931.                 } else {
  1932.                     $this->_init_smarty_vars = true;
  1933.                 }
  1934.                 return null;
  1935.  
  1936.             case 'capture':
  1937.                 return null;
  1938.  
  1939.             case 'template':
  1940.                 $compiled_ref = "'$this->_current_file'";
  1941.                 $_max_index = 1;
  1942.                 break;
  1943.  
  1944.             case 'version':
  1945.                 $compiled_ref = "'$this->_version'";
  1946.                 $_max_index = 1;
  1947.                 break;
  1948.  
  1949.             case 'const':
  1950.                 array_shift($indexes);
  1951.                 $_val = $this->_parse_var_props(substr($indexes[0],1));
  1952.                 $compiled_ref = '@constant(' . $_val . ')';
  1953.                 $_max_index = 1;
  1954.                 break;
  1955.  
  1956.             case 'config':
  1957.                 $compiled_ref = "\$this->_config[0]['vars']";
  1958.                 $_max_index = 2;
  1959.                 break;
  1960.  
  1961.             default:
  1962.                 $this->_syntax_error('$smarty.' . $_ref . ' is an unknown reference', E_USER_ERROR, __FILE__, __LINE__);
  1963.                 break;
  1964.         }
  1965.  
  1966.         if (isset($_max_index) && count($indexes) > $_max_index) {
  1967.             $this->_syntax_error('$smarty' . implode('', $indexes) .' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__);
  1968.         }
  1969.  
  1970.         array_shift($indexes);
  1971.         return $compiled_ref;
  1972.     }
  1973.  
  1974.     /**
  1975.      * compiles call to plugin of type $type with name $name
  1976.      * returns a string containing the function-name or method call
  1977.      * without the paramter-list that would have follow to make the
  1978.      * call valid php-syntax
  1979.      *
  1980.      * @param string $type 
  1981.      * @param string $name 
  1982.      * @return string 
  1983.      */
  1984.     function _compile_plugin_call($type, $name) {
  1985.         if (isset($this->_plugins[$type][$name])) {
  1986.             /* plugin loaded */
  1987.             if (is_array($this->_plugins[$type][$name][0])) {
  1988.                 return ((is_object($this->_plugins[$type][$name][0][0])) ?
  1989.                         "\$this->_plugins['$type']['$name'][0][0]->"    /* method callback */
  1990.                         : (string)($this->_plugins[$type][$name][0][0]).'::'    /* class callback */
  1991.                        ). $this->_plugins[$type][$name][0][1];
  1992.  
  1993.             } else {
  1994.                 /* function callback */
  1995.                 return $this->_plugins[$type][$name][0];
  1996.  
  1997.             }
  1998.         } else {
  1999.             /* plugin not loaded -> auto-loadable-plugin */
  2000.             return 'smarty_'.$type.'_'.$name;
  2001.  
  2002.         }
  2003.     }
  2004.  
  2005.     /**
  2006.      * load pre- and post-filters
  2007.      */
  2008.     function _load_filters()
  2009.     {
  2010.         if (count($this->_plugins['prefilter']) > 0) {
  2011.             foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
  2012.                 if ($prefilter === false) {
  2013.                     unset($this->_plugins['prefilter'][$filter_name]);
  2014.                     $_params = array('plugins' => array(array('prefilter', $filter_name, null, null, false)));
  2015.                     require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');
  2016.                     smarty_core_load_plugins($_params, $this);
  2017.                 }
  2018.             }
  2019.         }
  2020.         if (count($this->_plugins['postfilter']) > 0) {
  2021.             foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
  2022.                 if ($postfilter === false) {
  2023.                     unset($this->_plugins['postfilter'][$filter_name]);
  2024.                     $_params = array('plugins' => array(array('postfilter', $filter_name, null, null, false)));
  2025.                     require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');
  2026.                     smarty_core_load_plugins($_params, $this);
  2027.                 }
  2028.             }
  2029.         }
  2030.     }
  2031.  
  2032.  
  2033.     /**
  2034.      * Quote subpattern references
  2035.      *
  2036.      * @param string $string 
  2037.      * @return string 
  2038.      */
  2039.     function _quote_replace($string)
  2040.     {
  2041.         return preg_replace('![\\$]\d!', '\\\\\\0', $string);
  2042.     }
  2043.  
  2044.     /**
  2045.      * display Smarty syntax error
  2046.      *
  2047.      * @param string $error_msg 
  2048.      * @param integer $error_type 
  2049.      * @param string $file 
  2050.      * @param integer $line 
  2051.      */
  2052.     function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file=null, $line=null)
  2053.     {
  2054.         if(isset($file) && isset($line)) {
  2055.             $info = ' ('.basename($file).", line $line)";
  2056.         } else {
  2057.             $info = null;
  2058.         }
  2059.         trigger_error('Smarty: [in ' . $this->_current_file . ' line ' .
  2060.                       $this->_current_line_no . "]: syntax error: $error_msg$info", $error_type);
  2061.     }
  2062.  
  2063.  
  2064.     /**
  2065.      * check if the compilation changes from cacheable to
  2066.      * non-cacheable state with the beginning of the current
  2067.      * plugin. return php-code to reflect the transition.
  2068.      * @return string 
  2069.      */
  2070.     function _push_cacheable_state($type, $name) {
  2071.         $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4];
  2072.         if ($_cacheable
  2073.             || 0<$this->_cacheable_state++) return '';
  2074.         if (!isset($this->_cache_serial)) $this->_cache_serial = md5(uniqid('Smarty'));
  2075.         $_ret = 'if ($this->caching) { echo \'{nocache:'
  2076.             . $this->_cache_serial . '#' . $this->_nocache_count
  2077.             . '}\';}';
  2078.         return $_ret;
  2079.     }
  2080.  
  2081.  
  2082.     /**
  2083.      * check if the compilation changes from non-cacheable to
  2084.      * cacheable state with the end of the current plugin return
  2085.      * php-code to reflect the transition.
  2086.      * @return string 
  2087.      */
  2088.     function _pop_cacheable_state($type, $name) {
  2089.         $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4];
  2090.         if ($_cacheable
  2091.             || --$this->_cacheable_state>0) return '';
  2092.         return 'if ($this->caching) { echo \'{/nocache:'
  2093.             . $this->_cache_serial . '#' . ($this->_nocache_count++)
  2094.             . '}\';}';
  2095.     }
  2096.  
  2097. }
  2098.  
  2099. /**
  2100.  * compare to values by their string length
  2101.  *
  2102.  * @access private
  2103.  * @param string $a 
  2104.  * @param string $b 
  2105.  * @return 0|-1|1
  2106.  */
  2107. function _smarty_sort_length($a, $b)
  2108. {
  2109.     if($a == $b)
  2110.         return 0;
  2111.  
  2112.     if(strlen($a) == strlen($b))
  2113.         return ($a > $b) ? -1 : 1;
  2114.  
  2115.     return (strlen($a) > strlen($b)) ? -1 : 1;
  2116. }
  2117.  
  2118.  
  2119. /* vim: set et: */
  2120.  
  2121. ?>

Documentation generated on Tue, 24 Oct 2006 09:26:24 -0500 by phpDocumentor 1.3.1