Source for file Smarty_Compiler.class.php
Documentation is available at Smarty_Compiler.class.php
* Project: Smarty: the PHP compiling template engine
* File: Smarty_Compiler.class.php
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* You may contact the authors of Smarty by e-mail at:
* Director of Technology, ispi
* The latest version of Smarty can be obtained from:
* @link http://smarty.php.net/
* @copyright 2001-2003 ispi of Lincoln, Inc.
/* $Id: Smarty_Compiler.class.php,v 1.1 2005/10/17 18:37:39 jeichorn Exp $ */
* Template compiling class
var $_sectionelse_stack = array(); // keeps track of whether section had 'else' part
var $_foreachelse_stack = array(); // keeps track of whether foreach had 'else' part
var $_literal_blocks = array(); // keeps literal template blocks
var $_php_blocks = array(); // keeps php code blocks
var $_current_file = null; // the current template being compiled
var $_current_line_no = 1; // line number for error messages
var $_capture_stack = array(); // keeps track of nested capture buffers
var $_plugin_info = array(); // keeps track of plugins to load
var $_init_smarty_vars = false;
var $_permitted_tokens = array('true','false','yes','no','on','off','null');
var $_db_qstr_regexp = null; // regexps are setup in the constructor
var $_si_qstr_regexp = null;
var $_qstr_regexp = null;
var $_func_regexp = null;
var $_var_bracket_regexp = null;
var $_dvar_guts_regexp = null;
var $_dvar_regexp = null;
var $_cvar_regexp = null;
var $_svar_regexp = null;
var $_avar_regexp = null;
var $_parenth_param_regexp = null;
var $_func_call_regexp = null;
var $_obj_ext_regexp = null;
var $_obj_start_regexp = null;
var $_obj_params_regexp = null;
var $_obj_call_regexp = null;
var $_cacheable_state = 0;
var $_cache_attrs_count = 0;
var $_cache_serial = null;
var $_cache_include = null;
var $_additional_newline = "\n";
// matches double quoted strings:
$this->_db_qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
// matches single quoted strings:
$this->_si_qstr_regexp = '\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
// matches single or double quoted strings
$this->_qstr_regexp = '(?:' . $this->_db_qstr_regexp . '|' . $this->_si_qstr_regexp . ')';
// matches bracket portion of vars
$this->_var_bracket_regexp = '\[\$?[\w\.]+\]';
// matches $ vars (not objects):
// $foo[5].bar[$foobar][4]
$this->_dvar_math_regexp = '[\+\-\*\/\%]';
$this->_dvar_math_var_regexp = '[\$\w\.\+\-\*\/\%\d\>\[\]]';
$this->_dvar_num_var_regexp = '\-?\d+(?:\.\d+)?' . $this->_dvar_math_var_regexp;
$this->_dvar_guts_regexp = '\w+(?:' . $this->_var_bracket_regexp
. ')*(?:\.\$?\w+(?:' . $this->_var_bracket_regexp . ')*)*(?:' . $this->_dvar_math_regexp . '(?:\-?\d+(?:\.\d+)?|' . $this->_dvar_math_var_regexp . ')*)?';
$this->_dvar_regexp = '\$' . $this->_dvar_guts_regexp;
$this->_cvar_regexp = '\#\w+\#';
$this->_svar_regexp = '\%\w+\.\w+\%';
// matches all valid variables (no quotes, no modifiers)
$this->_avar_regexp = '(?:' . $this->_dvar_regexp . '|'
. $this->_cvar_regexp . '|' . $this->_svar_regexp . ')';
// matches valid variable syntax:
$this->_var_regexp = '(?:' . $this->_avar_regexp . '|' . $this->_qstr_regexp . ')';
// matches valid object call (no objects allowed in parameters):
// $foo->bar($foo, $bar, "text")
// $foo->bar($foo, "foo")
$this->_obj_ext_regexp = '\->(?:\$?' . $this->_dvar_guts_regexp . ')';
$this->_obj_params_regexp = '\((?:\w+|'
. $this->_var_regexp . '(?:\s*,\s*(?:(?:\w+|'
. $this->_var_regexp . ')))*)?\)';
$this->_obj_start_regexp = '(?:' . $this->_dvar_regexp . '(?:' . $this->_obj_ext_regexp . ')+)';
$this->_obj_call_regexp = '(?:' . $this->_obj_start_regexp . '(?:' . $this->_obj_params_regexp . ')?)';
// matches valid modifier syntax:
$this->_mod_regexp = '(?:\|@?\w+(?::(?>-?\w+|'
. $this->_obj_call_regexp . '|' . $this->_avar_regexp . '|' . $this->_qstr_regexp . '))*)';
// matches valid function name:
$this->_func_regexp = '[a-zA-Z_]\w*';
// matches valid registered object:
$this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*';
// matches valid parameter values:
$this->_param_regexp = '(?:\s*(?:' . $this->_obj_call_regexp . '|'
. $this->_var_regexp . '|\w+)(?>' . $this->_mod_regexp . '*)\s*)';
// matches valid parenthesised function parameters:
// $foo|bar, "foo"|bar, $foo->bar($foo)|bar
$this->_parenth_param_regexp = '(?:\((?:\w+|'
. $this->_param_regexp . '(?:\s*,\s*(?:(?:\w+|'
. $this->_param_regexp . ')))*)?\))';
// matches valid function call:
// foo123($foo,$foo->bar(),"foo")
$this->_func_call_regexp = '(?:' . $this->_func_regexp . '\s*(?:'
. $this->_parenth_param_regexp . '))';
* sets $compiled_content to the compiled source
* @param string $resource_name
* @param string $source_content
* @param string $compiled_content
function _compile_file($resource_name, $source_content, &$compiled_content)
// do not allow php syntax to be executed unless specified
$this->_current_file = $resource_name;
$this->_current_line_no = 1;
// run template source through prefilter functions
if (count($this->_plugins['prefilter']) > 0) {
foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
if ($prefilter === false) continue;
array($source_content, &$this));
$this->_plugins['prefilter'][$filter_name][3] = true;
/* Annihilate the comments. */
$source_content = preg_replace("!({$ldq})\*(.*?)\*({$rdq})!se",
"'\\1*'.str_repeat(\"\n\", substr_count('\\2', \"\n\")) .'*\\3'",
/* Pull out the literal blocks. */
preg_match_all("!{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}!s", $source_content, $_match);
$this->_literal_blocks = $_match[1];
$source_content = preg_replace("!{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}!s",
/* Pull out the php code blocks. */
preg_match_all("!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s", $source_content, $_match);
$this->_php_blocks = $_match[1];
$source_content = preg_replace("!{$ldq}php{$rdq}(.*?){$ldq}/php{$rdq}!s",
/* Gather all template tags. */
preg_match_all("!{$ldq}\s*(.*?)\s*{$rdq}!s", $source_content, $_match);
$template_tags = $_match[1];
/* Split content by template tags to obtain non-template content. */
$text_blocks = preg_split("!{$ldq}.*?{$rdq}!s", $source_content);
/* loop through text blocks */
for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++ ) {
/* match anything resembling php tags */
if (preg_match_all('!(<\?(?:\w+|=)?|\?>|language\s*=\s*[\"\']?php[\"\']?)!is', $text_blocks[$curr_tb], $sp_match)) {
/* replace tags with placeholders to prevent recursive replacements */
usort($sp_match[1], '_smarty_sort_length');
for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++ ) {
$text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],'%%%SMARTYSP'. $curr_sp. '%%%',$text_blocks[$curr_tb]);
for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++ ) {
$text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'. $curr_sp. '%%%', '<?php echo \''. str_replace("'", "\'", $sp_match[1][$curr_sp]). '\'; ?>'. "\n", $text_blocks[$curr_tb]);
$text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'. $curr_sp. '%%%', '', $text_blocks[$curr_tb]);
/* SMARTY_PHP_ALLOW, but echo non php starting tags */
$sp_match[1][$curr_sp] = preg_replace('%(<\?(?!php|=|$))%i', '<?php echo \'\\1\'?>'. "\n", $sp_match[1][$curr_sp]);
$text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'. $curr_sp. '%%%', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]);
/* Compile the template tags into PHP code. */
$compiled_tags = array();
for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++ ) {
$this->_current_line_no += substr_count($text_blocks[$i], "\n");
$this->_current_line_no += substr_count($template_tags[$i], "\n");
/* Interleave the compiled contents and text blocks to get the final result. */
for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++ ) {
if ($compiled_tags[$i] == '') {
// tag result empty, remove first newline from following text block
$text_blocks[$i+ 1] = preg_replace('!^(\r\n|\r|\n)!', '', $text_blocks[$i+ 1]);
$compiled_content .= $text_blocks[$i]. $compiled_tags[$i];
$compiled_content .= $text_blocks[$i];
/* Reformat data between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */
if (preg_match_all("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s", $compiled_content, $_match)) {
$strip_tags = $_match[0];
$strip_tags_modified = preg_replace("!{$ldq}/?strip{$rdq}|[\t ]+$|^[\t ]+!m", '', $strip_tags);
$strip_tags_modified = preg_replace('![\r\n]+!m', '', $strip_tags_modified);
for ($i = 0, $for_max = count($strip_tags); $i < $for_max; $i++ )
$compiled_content = preg_replace("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s",
// remove \n from the end of the file, if any
if (($_len= strlen($compiled_content)) && ($compiled_content{$_len - 1} == "\n" )) {
$compiled_content = substr($compiled_content, 0, - 1);
if (!empty($this->_cache_serial)) {
$compiled_content = "<?php \$this->_cache_serials['". $this->_cache_include. "'] = '". $this->_cache_serial. "'; ?>" . $compiled_content;
// remove unnecessary close/open tags
$compiled_content = preg_replace('!\?>\n?<\?php!', '', $compiled_content);
// run compiled template through postfilter functions
if (count($this->_plugins['postfilter']) > 0) {
foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
if ($postfilter === false) continue;
array($compiled_content, &$this));
$this->_plugins['postfilter'][$filter_name][3] = true;
// put header at the top of the compiled template
$template_header = "<?php /* Smarty version ". $this->_version. ", created on ". strftime("%Y-%m-%d %H:%M:%S"). "\n";
$template_header .= " compiled from ". strtr(urlencode($resource_name), array('%2F'=> '/', '%3A'=> ':')). " */ ?>\n";
/* Emit code to load needed plugins. */
$this->_plugins_code = '';
if (count($this->_plugin_info)) {
$_plugins_params = "array('plugins' => array(";
foreach ($this->_plugin_info as $plugin_type => $plugins) {
foreach ($plugins as $plugin_name => $plugin_info) {
$_plugins_params .= "array('$plugin_type', '$plugin_name', '$plugin_info[0]', $plugin_info[1], ";
$_plugins_params .= $plugin_info[2] ? 'true),' : 'false),';
$_plugins_params .= '))';
$plugins_code = "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');\nsmarty_core_load_plugins($_plugins_params, \$this); ?>\n";
$template_header .= $plugins_code;
$this->_plugin_info = array();
$this->_plugins_code = $plugins_code;
if ($this->_init_smarty_vars) {
$template_header .= "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.assign_smarty_interface.php');\nsmarty_core_assign_smarty_interface(null, \$this); ?>\n";
$this->_init_smarty_vars = false;
$compiled_content = $template_header . $compiled_content;
* @param string $template_tag
if ($template_tag{0} == '*' && $template_tag{strlen($template_tag) - 1} == '*')
/* Split tag into two three parts: command, command modifiers and the arguments. */
if(! preg_match('/^(?:(' . $this->_obj_call_regexp . '|' . $this->_var_regexp
. '|\/?' . $this->_reg_obj_regexp . '|\/?' . $this->_func_regexp . ')(' . $this->_mod_regexp . '*))
/xs', $template_tag, $match)) {
$this->_syntax_error("unrecognized tag: $template_tag", E_USER_ERROR, __FILE__ , __LINE__ );
$tag_command = $match[1];
$tag_modifier = isset ($match[2]) ? $match[2] : null;
$tag_args = isset ($match[3]) ? $match[3] : null;
if (preg_match('!^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '$!', $tag_command)) {
/* tag name is a variable or object */
if(isset ($_tag_attrs['assign'])) {
return "<?php \$this->assign('" . $this->_dequote($_tag_attrs['assign']) . "', $_return ); ?>\n";
return "<?php echo $_return; ?>" . $this->_additional_newline;
/* If the tag name is a registered object, we process it. */
if (preg_match('!^\/?' . $this->_reg_obj_regexp . '$!', $tag_command)) {
return '<?php endif; ?>';
$this->_sectionelse_stack[count($this->_sectionelse_stack)- 1] = true;
return "<?php endfor; else: ?>";
return "<?php endif; ?>";
return "<?php endfor; endif; ?>";
$this->_foreachelse_stack[count($this->_foreachelse_stack)- 1] = true;
return "<?php endforeach; unset(\$_from); else: ?>";
return "<?php endif; ?>";
return "<?php endforeach; unset(\$_from); endif; ?>";
if ($tag_command{0}== '/') {
if (-- $this->_strip_depth== 0) { /* outermost closing {/strip} */
$this->_additional_newline = "\n";
if ($this->_strip_depth++== 0) { /* outermost opening {strip} */
$this->_additional_newline = "";
list (,$literal_block) = each($this->_literal_blocks);
$this->_current_line_no += substr_count($literal_block, "\n");
return "<?php echo '". str_replace("'", "\'", str_replace("\\", "\\\\", $literal_block)). "'; ?>" . $this->_additional_newline;
$this->_syntax_error("(secure mode) php tags not permitted", E_USER_WARNING, __FILE__ , __LINE__ );
list (,$php_block) = each($this->_php_blocks);
return '<?php '. $php_block. ' ?>';
* compile the custom compiler tag
* sets $output to the compiled custom compiler tag
* @param string $tag_command
* @param string $tag_args
* First we check if the compiler function has already been registered
* or loaded from a plugin file.
if (isset ($this->_plugins['compiler'][$tag_command])) {
$plugin_func = $this->_plugins['compiler'][$tag_command][0];
$message = "compiler function '$tag_command' is not implemented";
* Otherwise we need to load plugin file and look for the function
include_once $plugin_file;
$plugin_func = 'smarty_compiler_' . $tag_command;
$message = "plugin function $plugin_func() not found in $plugin_file\n";
$this->_plugins['compiler'][$tag_command] = array($plugin_func, null, null, null, true);
* True return value means that we either found a plugin or a
* dynamically registered function. False means that we didn't and the
* compiler should now emit code to load custom function plugin for this
$this->_syntax_error($message, E_USER_WARNING, __FILE__ , __LINE__ );
* compile block function tag
* sets $output to compiled block function tag
* @param string $tag_command
* @param string $tag_args
* @param string $tag_modifier
if ($tag_command{0} == '/') {
$tag_command = substr($tag_command, 1);
* First we check if the block function has already been registered
* or loaded from a plugin file.
if (isset ($this->_plugins['block'][$tag_command])) {
$plugin_func = $this->_plugins['block'][$tag_command][0];
$message = "block function '$tag_command' is not implemented";
* Otherwise we need to load plugin file and look for the function
include_once $plugin_file;
$plugin_func = 'smarty_block_' . $tag_command;
$message = "plugin function $plugin_func() not found in $plugin_file\n";
$this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);
} else if (!$have_function) {
$this->_syntax_error($message, E_USER_WARNING, __FILE__ , __LINE__ );
* Even though we've located the plugin function, compilation
* happens only once, so the plugin will still need to be loaded
* at runtime for future requests.
$arg_list = $this->_compile_arg_list('block', $tag_command, $attrs, $_cache_attrs= '');
$output .= "$_cache_attrs\$_params = \$this->_tag_stack[] = array('$tag_command', array(". implode(',', $arg_list). ')); ';
$output .= $this->_compile_plugin_call('block', $tag_command). '($_params[1], null, $this, $_block_repeat=true); unset($_params);';
$output .= 'while ($_block_repeat) { ob_start(); ?>';
$output = '<?php $this->_block_content = ob_get_contents(); ob_end_clean(); ';
$_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)';
if ($tag_modifier != '') {
$output .= 'echo '. $_out_tag_text. '; } ';
$output .= " array_pop(\$this->_tag_stack); " . $this->_pop_cacheable_state('block', $tag_command) . '?>';
* compile custom function tag
* @param string $tag_command
* @param string $tag_args
* @param string $tag_modifier
$arg_list = $this->_compile_arg_list('function', $tag_command, $attrs, $_cache_attrs= '');
if($tag_modifier != '') {
$_return = '<?php ' . $_cacheable_state . $_cache_attrs . 'echo ' . $_return . ';'
* compile a registered object tag
* @param string $tag_command
* @param string $tag_modifier
if ($tag_command{0} == '/') {
$tag_command = substr($tag_command, 1);
list ($object, $obj_comp) = explode('->', $tag_command);
foreach ($attrs as $arg_name => $arg_value) {
if($arg_name == 'assign') {
$_assign_var = $arg_value;
$arg_value = $arg_value ? 'true' : 'false';
$arg_list[] = "'$arg_name' => $arg_value";
if($this->_reg_objects[$object][2]) {
// smarty object argument format
$args = "array(". implode(',', (array) $arg_list). "), \$this";
// traditional argument format
if(!is_object($this->_reg_objects[$object][0])) {
} elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) {
} elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) {
if(in_array($obj_comp, $this->_reg_objects[$object][3])) {
$prefix = "\$this->_tag_stack[] = array('$obj_comp', $args); ";
$prefix .= "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], null, \$this, \$_block_repeat=true); ";
$prefix .= "while (\$_block_repeat) { ob_start();";
$prefix = "\$this->_obj_block_content = ob_get_contents(); ob_end_clean(); ";
$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)";
$postfix = "} array_pop(\$this->_tag_stack);";
$return = "\$this->_reg_objects['$object'][0]->$obj_comp($args)";
$return = "\$this->_reg_objects['$object'][0]->$obj_comp";
if($tag_modifier != '') {
if(!empty($_assign_var)) {
$output = "\$this->assign('" . $this->_dequote($_assign_var) . "', $return);";
$output = 'echo ' . $return . ';';
$newline = $this->_additional_newline;
return '<?php ' . $prefix . $output . $postfix . "?>" . $newline;
* Compile {insert ...} tag
* @param string $tag_args
$name = $this->_dequote($attrs['name']);
$this->_syntax_error("missing insert name", E_USER_ERROR, __FILE__ , __LINE__ );
if (!empty($attrs['script'])) {
$delayed_loading = false;
foreach ($attrs as $arg_name => $arg_value) {
$arg_value = $arg_value ? 'true' : 'false';
$arg_list[] = "'$arg_name' => $arg_value";
$_params = "array('args' => array(". implode(', ', (array) $arg_list). "))";
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;
* Compile {include ...} tag
* @param string $tag_args
if (empty($attrs['file'])) {
$this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__ , __LINE__ );
foreach ($attrs as $arg_name => $arg_value) {
if ($arg_name == 'file') {
$include_file = $arg_value;
} else if ($arg_name == 'assign') {
$assign_var = $arg_value;
$arg_value = $arg_value ? 'true' : 'false';
$arg_list[] = "'$arg_name' => $arg_value";
if (isset ($assign_var)) {
$output .= "ob_start();\n";
"\$_smarty_tpl_vars = \$this->_tpl_vars;\n";
$_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(". implode(',', (array) $arg_list). "))";
$output .= "\$this->_smarty_include($_params);\n" .
"\$this->_tpl_vars = \$_smarty_tpl_vars;\n" .
"unset(\$_smarty_tpl_vars);\n";
if (isset ($assign_var)) {
$output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n";
* Compile {include ...} tag
* @param string $tag_args
if (empty($attrs['file'])) {
$this->_syntax_error("missing 'file' attribute in include_php tag", E_USER_ERROR, __FILE__ , __LINE__ );
$assign_var = (empty($attrs['assign'])) ? '' : $this->_dequote($attrs['assign']);
$once_var = (empty($attrs['once']) || $attrs['once']== 'false') ? 'false' : 'true';
foreach($attrs as $arg_name => $arg_value) {
if($arg_name != 'file' AND $arg_name != 'once' AND $arg_name != 'assign') {
$arg_value = $arg_value ? 'true' : 'false';
$arg_list[] = "'$arg_name' => $arg_value";
$_params = "array('smarty_file' => " . $attrs['file'] . ", 'smarty_assign' => '$assign_var', 'smarty_once' => $once_var, 'smarty_include_vars' => array(". implode(',', (array) $arg_list). "))";
return "<?php require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.smarty_include_php.php');\nsmarty_core_smarty_include_php($_params, \$this); ?>" . $this->_additional_newline;
* Compile {section ...} tag
* @param string $tag_args
$section_name = $attrs['name'];
if (empty($section_name)) {
$this->_syntax_error("missing section name", E_USER_ERROR, __FILE__ , __LINE__ );
$output .= "if (isset(\$this->_sections[$section_name])) unset(\$this->_sections[$section_name]);\n";
$section_props = "\$this->_sections[$section_name]";
foreach ($attrs as $attr_name => $attr_value) {
$output .= "{ $section_props}[' loop' ] = is_array(\$ _loop= $attr_value) ? count(\$ _loop) : max(0, ( int)\$ _loop); unset(\$ _loop);\n ";
$show_attr_value = $attr_value ? 'true' : 'false';
$show_attr_value = "(bool)$attr_value";
$output .= "{ $section_props}[' show' ] = $show_attr_value;\n ";
$output .= "{ $section_props}[' $attr_name' ] = $attr_value;\n ";
$output .= "{ $section_props}[' $attr_name' ] = ( int) $attr_value;\n ";
$output .= "{ $section_props}[' $attr_name' ] = (( int) $attr_value) == 0 ? 1 : ( int) $attr_value;\n ";
$this->_syntax_error("unknown section attribute - '$attr_name'", E_USER_ERROR, __FILE__ , __LINE__ );
if (!isset ($attrs['show']))
$output .= "{ $section_props}[' show' ] = true;\n ";
if (!isset ($attrs['loop']))
$output .= "{ $section_props}[' loop' ] = 1;\n ";
if (!isset ($attrs['max']))
$output .= "{ $section_props}[' max' ] = { $section_props}[' loop' ];\n ";
$output .= "if ({$section_props}['max'] < 0)\n" .
" {$section_props}['max'] = {$section_props}['loop'];\n";
if (!isset ($attrs['step']))
$output .= "{ $section_props}[' step' ] = 1;\n ";
if (!isset ($attrs['start']))
$output .= "{ $section_props}[' start' ] = { $section_props}[' step' ] > 0 ? 0 : { $section_props}[' loop' ]-1;\n ";
$output .= "if ({$section_props}['start'] < 0)\n" .
" {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" .
" {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
$output .= "if ({$section_props}['show']) {\n";
if (!isset ($attrs['start']) && !isset ($attrs['step']) && !isset ($attrs['max'])) {
$output .= " {$section_props}['total'] = {$section_props}['loop'];\n";
$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";
$output .= " if ({$section_props}['total'] == 0)\n" .
" {$section_props}['show'] = false;\n" .
" {$section_props}['total'] = 0;\n";
$output .= "if ({$section_props}['show']):\n";
for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
{$section_props}['iteration'] <= {$section_props}['total'];
{$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
$output .= "{ $section_props}[' rownum' ] = { $section_props}[' iteration' ];\n ";
$output .= "{ $section_props}[' index_prev' ] = { $section_props}[' index' ] - { $section_props}[' step' ];\n ";
$output .= "{ $section_props}[' index_next' ] = { $section_props}[' index' ] + { $section_props}[' step' ];\n ";
$output .= "{ $section_props}[' first' ] = ({ $section_props}[' iteration' ] == 1);\n ";
$output .= "{ $section_props}[' last' ] = ({ $section_props}[' iteration' ] == { $section_props}[' total' ]);\n ";
* Compile {foreach ...} tag.
* @param string $tag_args
if (empty($attrs['from'])) {
$this->_syntax_error("missing 'from' attribute", E_USER_ERROR, __FILE__ , __LINE__ );
if (empty($attrs['item'])) {
$this->_syntax_error("missing 'item' attribute", E_USER_ERROR, __FILE__ , __LINE__ );
$item = $this->_dequote($attrs['item']);
if (isset ($attrs['name']))
$output .= "if (isset(\$this->_foreach[$name])) unset(\$this->_foreach[$name]);\n";
$foreach_props = "\$this->_foreach[$name]";
foreach ($attrs as $attr_name => $attr_value) {
$key_part = "\$this->_tpl_vars['$key'] => ";
$output .= "{ $foreach_props}[' $attr_name' ] = $attr_value;\n ";
$output .= "{ $foreach_props}[' total' ] = count(\$ _from = ( array) $from);\n ";
$output .= "{ $foreach_props}[' show' ] = { $foreach_props}[' total' ] > 0;\n ";
$output .= "if ({$foreach_props}['show']):\n";
$output .= "{ $foreach_props}[' iteration' ] = 0;\n ";
$output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
$output .= " {$foreach_props}['iteration']++;\n";
$output .= " {$foreach_props}['first'] = ({$foreach_props}['iteration'] == 1);\n";
$output .= " {$foreach_props}['last'] = ({$foreach_props}['iteration'] == {$foreach_props}['total']);\n";
$output .= "if (count(\$_from = (array)$from)):\n";
$output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
* Compile {capture} .. {/capture} tags
* @param boolean $start true if this is the {capture} tag
* @param string $tag_args
if (isset ($attrs['name']))
$buffer = $attrs['name'];
if (isset ($attrs['assign']))
$assign = $attrs['assign'];
$output = "<?php ob_start(); ?>";
$this->_capture_stack[] = array($buffer, $assign);
list ($buffer, $assign) = array_pop($this->_capture_stack);
$output = "<?php \$this->_smarty_vars['capture'][$buffer] = ob_get_contents(); ";
$output .= " \$this->assign($assign, ob_get_contents());";
$output .= "ob_end_clean(); ?>";
* @param string $tag_args
* @param boolean $elseif if true, uses elseif instead of if
/* Tokenize args for 'if' tag. */
' . $this->_obj_call_regexp . '(?:' . $this->_mod_regexp . '*)? | # valid object call
' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)? | # var or quoted string
\-?0[xX][0-9a-fA-F]+|\-?\d+(?:\.\d+)?|\.\d+|!==|===|==|!=|<>|<<|>>|<=|>=|\&\&|\|\||\(|\)|,|\!|\^|=|\&|\~|<|>|\||\%|\+|\-|\/|\*|\@ | # valid non-word token
\b\w+\b | # valid word token
)/x', $tag_args, $match);
// make sure we have balanced parenthesis
if(isset ($token_count['(']) && $token_count['('] != $token_count[')']) {
$this->_syntax_error("unbalanced parenthesis in if statement", E_USER_ERROR, __FILE__ , __LINE__ );
for ($i = 0; $i < count($tokens); $i++ ) {
/* If last token was a ')', we operate on the parenthesized
expression. The start of the expression is on the stack.
Otherwise, we operate on the last encountered token. */
if ($tokens[$i- 1] == ')')
/* Construct the argument for 'is' expression, so it knows
/* Pass all tokens from next one until the end to the
'is' expression parsing function. The function will
return modified tokens, where the first one is the result
of the 'is' expression and the rest are the tokens it
/* Replace the old tokens with the new ones. */
/* Adjust argument start so that it won't change from the
current position for the next iteration. */
if(preg_match('!^' . $this->_func_regexp . '$!', $token) ) {
$this->_syntax_error("(secure mode) '$token' not allowed in if statement", E_USER_ERROR, __FILE__ , __LINE__ );
} elseif(preg_match('!^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)$!', $token)) {
$this->_syntax_error("unidentified token '$token'", E_USER_ERROR, __FILE__ , __LINE__ );
return '<?php elseif ('. implode(' ', $tokens). '): ?>';
return '<?php if ('. implode(' ', $tokens). '): ?>';
if (isset ($type) && isset ($name)
&& isset ($this->_plugins[$type])
&& isset ($this->_plugins[$type][$name])
&& empty($this->_plugins[$type][$name][4])
&& is_array($this->_plugins[$type][$name][5])
/* we have a list of parameters that should be cached */
$_cache_attrs = $this->_plugins[$type][$name][5];
$_count = $this->_cache_attrs_count++ ;
$cache_code = "\$_cache_attrs =& \$this->_smarty_cache_attrs('$this->_cache_serial','$_count');";
/* no parameters are cached */
foreach ($attrs as $arg_name => $arg_value) {
$arg_value = $arg_value ? 'true' : 'false';
if ($_cache_attrs && in_array($arg_name, $_cache_attrs)) {
$arg_list[] = "'$arg_name' => (\$this->_cache_including) ? \$_cache_attrs['$arg_name'] : (\$_cache_attrs['$arg_name']=$arg_value)";
$arg_list[] = "'$arg_name' => $arg_value";
$expr_type = $first_token;
if (@$tokens[$expr_end] == 'by') {
$expr_arg = $tokens[$expr_end++ ];
$expr = "!(($is_arg / $expr_arg) % " . $this->_parse_var_props($expr_arg) . ")";
$expr = "!($is_arg % 2)";
if (@$tokens[$expr_end] == 'by') {
$expr_arg = $tokens[$expr_end++ ];
if (@$tokens[$expr_end] == 'by') {
$expr_arg = $tokens[$expr_end++ ];
$this->_syntax_error("expecting 'by' after 'div'", E_USER_ERROR, __FILE__ , __LINE__ );
$this->_syntax_error("unknown 'is' expression - '$expr_type'", E_USER_ERROR, __FILE__ , __LINE__ );
* @param string $tag_args
/* Tokenize tag attributes. */
preg_match_all('/(?:' . $this->_obj_call_regexp . '|' . $this->_qstr_regexp . ' | (?>[^"\'=\s]+)
0 - expecting attribute name
2 - expecting attribute value (not '=') */
foreach ($tokens as $token) {
/* If the token is a valid identifier, we set attribute name
$this->_syntax_error("invalid attribute name: '$token'", E_USER_ERROR, __FILE__ , __LINE__ );
/* If the token is '=', then we go to state 2. */
$this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__ , __LINE__ );
/* If token is not '=', we set the attribute value and go to
/* We booleanize the token if it's a non-quoted possible
} else if (preg_match('!^(off|no|false)$!', $token)) {
} else if ($token == 'null') {
} else if (preg_match('!^-?([0-9]+|0[xX][0-9a-fA-F]+)$!', $token)) {
/* treat integer literally */
} else if (!preg_match('!^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . ')*$!', $token)) {
/* treat as a string, double-quote it escaping quotes */
$attrs[$attr_name] = $token;
$this->_syntax_error("'=' cannot be an attribute value", E_USER_ERROR, __FILE__ , __LINE__ );
$this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__ , __LINE__ );
$this->_syntax_error("missing attribute value", E_USER_ERROR, __FILE__ , __LINE__ );
* compile multiple variables and section properties tokens into
foreach($tokens as $key => $val) {
* compile single variable and section properties token into
* @param string $tag_attrs
if(preg_match('!^(' . $this->_obj_call_regexp . '|' . $this->_dvar_regexp . ')(' . $this->_mod_regexp . '*)$!', $val, $match)) {
elseif(preg_match('!^' . $this->_db_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
preg_match('!^(' . $this->_db_qstr_regexp . ')('. $this->_mod_regexp . '*)$!', $val, $match);
elseif(preg_match('!^' . $this->_si_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
preg_match('!^(' . $this->_si_qstr_regexp . ')('. $this->_mod_regexp . '*)$!', $val, $match);
elseif(preg_match('!^' . $this->_cvar_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
elseif(preg_match('!^' . $this->_svar_regexp . '(?:' . $this->_mod_regexp . '*)$!', $val)) {
* expand quoted text with embedded variables
* @param string $var_expr
// if contains unescaped $, expand it
if(preg_match_all('%(?:\`(?<!\\\\)\$' . $this->_dvar_guts_regexp . '\`)|(?:(?<!\\\\)\$\w+(\[[a-zA-Z0-9]+\])*)%', $var_expr, $_match)) {
foreach($_match as $_var) {
$_return = preg_replace('%\.""|(?<!\\\\)""\.%', '', $var_expr);
// replace double quoted literal string with single quotes
$_return = preg_replace('!^"([\s\w]+)"$!',"'\\1'",$_return);
* parse variable expression into PHP code
* @param string $var_expr
$_math_vars = preg_split('!('. $this->_dvar_math_regexp. '|'. $this->_qstr_regexp. ')!', $var_expr, - 1, PREG_SPLIT_DELIM_CAPTURE);
if(count($_math_vars) > 1) {
// simple check if there is any math, to stop recursion (due to modifiers with "xx % yy" as parameter)
foreach($_math_vars as $_k => $_math_var) {
$_math_var = $_math_vars[$_k];
if(!empty($_math_var) || is_numeric($_math_var)) {
// hit a math operator, so process the stuff which came before it
if(preg_match('!^' . $this->_dvar_math_regexp . '$!', $_math_var)) {
if(!empty($_complete_var) || is_numeric($_complete_var)) {
// just output the math operator to php
$_first_var = $_complete_var;
// 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
for($_i = $_k + 1; $_i <= count($_math_vars); $_i += 2) {
// fetch -> because it gets splitted at - and move it back together
if( /* prevent notice */ (isset ($_math_vars[$_i]) && isset ($_math_vars[$_i+ 1])) && ($_math_vars[$_i] === '-' && $_math_vars[$_i+ 1]{0} === '>')) {
$_math_var .= $_math_vars[$_i]. $_math_vars[$_i+ 1];
$_math_vars[$_i] = $_math_vars[$_i+ 1] = '';
$_complete_var .= $_math_var;
if(!empty($_complete_var) || is_numeric($_complete_var))
$_output .= $this->_parse_var($_complete_var, true);
// get the modifiers working (only the last var from math + modifier is left)
$var_expr = $_complete_var;
// prevent cutting of first digit in the number (we _definitly_ got a number if the first char is a digit)
$_var_ref = substr($var_expr, 1);
// get [foo] and .foo and ->foo and (...) pieces
preg_match_all('!(?:^\w+)|' . $this->_obj_params_regexp . '|(?:' . $this->_var_bracket_regexp . ')|->\$?\w+|\.\$?\w+|\S+!', $_var_ref, $match);
/* Handle $smarty.* variable references as a special case. */
if ($_var_name == 'smarty') {
* If the reference could be compiled, use the compiled output;
* otherwise, fall back on the $smarty variable generated at
$_output = "\$this->_smarty_vars['$_var_name']";
// because . is the operator for accessing arrays thru inidizes we need to put it together again for floating point numbers
$_var_name .= implode("", $_indexes);
$_output = "\$this->_tpl_vars['$_var_name']";
foreach ($_indexes as $_index) {
$_index = substr($_index, 1, - 1);
} elseif ($_index{0} == '$') {
if (strpos($_index, '.') !== false) {
$_output .= '[' . $this->_parse_var($_index) . ']';
$_output .= "[\$this->_tpl_vars['" . substr($_index, 1) . "']]";
$_var_parts = explode('.', $_index);
$_var_section = $_var_parts[0];
$_var_section_prop = isset ($_var_parts[1]) ? $_var_parts[1] : 'index';
$_output .= "[\$this->_sections['$_var_section']['$_var_section_prop']]";
} else if ($_index{0} == '.') {
$_output .= "[\$this->_tpl_vars['" . substr($_index, 2) . "']]";
$_output .= "['" . substr($_index, 1) . "']";
} else if (substr($_index,0,2) == '->') {
if(substr($_index,2,2) == '__') {
$this->_syntax_error('call to internal object members is not allowed', E_USER_ERROR, __FILE__ , __LINE__ );
$this->_syntax_error('(secure) call to private object member is not allowed', E_USER_ERROR, __FILE__ , __LINE__ );
} elseif ($_index{2} == '$') {
$this->_syntax_error('(secure) call to dynamic object member is not allowed', E_USER_ERROR, __FILE__ , __LINE__ );
$_output .= '->{(($_var=$this->_tpl_vars[\''. substr($_index,3). '\']) && substr($_var,0,2)!=\'__\') ? $_var : $this->trigger_error("cannot access property \\"$_var\\"")}';
} elseif ($_index{0} == '(') {
* parse arguments in function call parenthesis
* @param string $parenth_args
preg_match_all('!' . $this->_param_regexp . '!',$parenth_args, $match);
* parse configuration variable expression into PHP code
* @param string $conf_var_expr
$parts = explode('|', $conf_var_expr, 2);
$modifiers = isset ($parts[1]) ? $parts[1] : '';
$var_name = substr($var_ref, 1, - 1);
$output = "\$this->_config[0]['vars']['$var_name']";
* parse section property expression into PHP code
* @param string $section_prop_expr
$parts = explode('|', $section_prop_expr, 2);
$modifiers = isset ($parts[1]) ? $parts[1] : '';
$section_name = $match[1];
$output = "\$this->_sections['$section_name']['$prop_name']";
* parse modifier chain into PHP code
* sets $output to parsed modified chain
* @param string $modifier_string
preg_match_all('!\|(@?\w+)((?>:(?:'. $this->_qstr_regexp . '|[^|]+))*)!', '|' . $modifier_string, $_match);
list (, $_modifiers, $modifier_arg_strings) = $_match;
for ($_i = 0, $_for_max = count($_modifiers); $_i < $_for_max; $_i++ ) {
$_modifier_name = $_modifiers[$_i];
if($_modifier_name == 'smarty') {
preg_match_all('!:(' . $this->_qstr_regexp . '|[^:]+)!', $modifier_arg_strings[$_i], $_match);
$_modifier_args = $_match[1];
if ($_modifier_name{0} == '@') {
$_modifier_name = substr($_modifier_name, 1);
if (empty($this->_plugins['modifier'][$_modifier_name])
$this->_trigger_fatal_error("[plugin] (secure mode) modifier '$_modifier_name' is not allowed" , $_tpl_file, $_tpl_line, __FILE__ , __LINE__ );
$this->_plugins['modifier'][$_modifier_name] = array($_modifier_name, null, null, false);
if($_modifier_name == 'default') {
// supress notifications of default modifier vars and args
if(isset ($_modifier_args[0]) && $_modifier_args[0]{0} == '$') {
$_modifier_args[0] = '@' . $_modifier_args[0];
if (count($_modifier_args) > 0)
$_modifier_args = ', '. implode(', ', $_modifier_args);
$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))";
* @param boolean? $delayed_loading
function _add_plugin($type, $name, $delayed_loading = null)
if (!isset ($this->_plugin_info[$type])) {
$this->_plugin_info[$type] = array();
if (!isset ($this->_plugin_info[$type][$name])) {
$this->_plugin_info[$type][$name] = array($this->_current_file,
* Compiles references of type $smarty.foo
/* Extract the reference name. */
$_ref = substr($indexes[0], 1);
foreach($indexes as $_index_no=> $_index) {
if ($_index{0} != '.' && $_index_no< 2 || !preg_match('!^(\.|\[|->)!', $_index)) {
$compiled_ref = 'time()';
$compiled_ref = "\$this->_foreach[$_var]";
$compiled_ref = "\$this->_sections[$_var]";
* These cases are handled either at run-time or elsewhere in the
$compiled_ref = '$_REQUEST';
$this->_init_smarty_vars = true;
$compiled_ref = "'$this->_current_file'";
$compiled_ref = "'$this->_version'";
$compiled_ref = '@constant(' . $_val . ')';
$compiled_ref = "\$this->_config[0]['vars']";
$this->_syntax_error('$smarty.' . $_ref . ' is an unknown reference', E_USER_ERROR, __FILE__ , __LINE__ );
if (isset ($_max_index) && count($indexes) > $_max_index) {
$this->_syntax_error('$smarty' . implode('', $indexes) . ' is an invalid reference', E_USER_ERROR, __FILE__ , __LINE__ );
* compiles call to plugin of type $type with name $name
* returns a string containing the function-name or method call
* without the paramter-list that would have follow to make the
if (isset ($this->_plugins[$type][$name])) {
if (is_array($this->_plugins[$type][$name][0])) {
return ((is_object($this->_plugins[$type][$name][0][0])) ?
"\$this->_plugins['$type']['$name'][0][0]->" /* method callback */
: (string) ($this->_plugins[$type][$name][0][0]). '::' /* class callback */
). $this->_plugins[$type][$name][0][1];
return $this->_plugins[$type][$name][0];
/* plugin not loaded -> auto-loadable-plugin */
return 'smarty_'. $type. '_'. $name;
* load pre- and post-filters
if (count($this->_plugins['prefilter']) > 0) {
foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
if ($prefilter === false) {
unset ($this->_plugins['prefilter'][$filter_name]);
$_params = array('plugins' => array(array('prefilter', $filter_name, null, null, false)));
require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');
if (count($this->_plugins['postfilter']) > 0) {
foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
if ($postfilter === false) {
unset ($this->_plugins['postfilter'][$filter_name]);
$_params = array('plugins' => array(array('postfilter', $filter_name, null, null, false)));
require_once(SMARTY_DIR . 'core' . DIRECTORY_SEPARATOR . 'core.load_plugins.php');
* Quote subpattern references
* display Smarty syntax error
* @param string $error_msg
* @param integer $error_type
function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file= null, $line= null)
if(isset ($file) && isset ($line)) {
$info = ' ('. basename($file). ", line $line)";
$this->_current_line_no . "]: syntax error: $error_msg$info", $error_type);
* check if the compilation changes from cacheable to
* non-cacheable state with the beginning of the current
* plugin. return php-code to reflect the transition.
$_cacheable = !isset ($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4];
|| 0< $this->_cacheable_state++ ) return '';
if (!isset ($this->_cache_serial)) $this->_cache_serial = md5(uniqid('Smarty'));
$_ret = 'if ($this->caching) { echo \'{nocache:'
. $this->_cache_serial . '#' . $this->_nocache_count
* check if the compilation changes from non-cacheable to
* cacheable state with the end of the current plugin return
* php-code to reflect the transition.
$_cacheable = !isset ($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4];
|| -- $this->_cacheable_state> 0) return '';
return 'if ($this->caching) { echo \'{/nocache:'
. $this->_cache_serial . '#' . ($this->_nocache_count++ )
* compare to values by their string length
function _smarty_sort_length($a, $b)
return ($a > $b) ? - 1 : 1;
|