PageRenderTime 30ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/smarty/Smarty_Compiler.class.php

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