PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/smarty/Smarty_Compiler.class.php

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