PageRenderTime 30ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/project/library/Oxy/View/Smarty/Compiler.php

http://oxybase.googlecode.com/
PHP | 1582 lines | 1145 code | 158 blank | 279 comment | 183 complexity | 2ea3e90dcde6b0c07c8858fe53208bfa 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://smarty.php.net/
  21. * @author Monte Ohrt <monte at ohrt dot com>
  22. * @author Andrei Zmievski <andrei@php.net>
  23. * @version 2.6.18
  24. * @copyright 2001-2005 New Digital Group, Inc.
  25. * @package Smarty
  26. */
  27. /* $Id: Smarty_Compiler.class.php 3184 2007-12-06 12:25:08Z iwan $ */
  28. /**
  29. * Template compiling class
  30. * @package Smarty
  31. */
  32. class Oxy_View_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 __construct()
  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 regexp was changed to allow using dereferencing methods or chaining methods or nested methods
  149. $this->_obj_call_regexp = '(?:' . $this->_dvar_regexp . '(?:(?:' . $this->_obj_ext_regexp . ')+' . '(?:' . $this->_obj_params_regexp . ')?)*)';
  150. // matches valid modifier syntax:
  151. // |foo
  152. // |@foo
  153. // |foo:"bar"
  154. // |foo:$bar
  155. // |foo:"bar":$foobar
  156. // |foo|bar
  157. // |foo:$foo->bar
  158. $this->_mod_regexp = '(?:\|@?\w+(?::(?:\w+|' . $this->_num_const_regexp . '|'
  159. . $this->_obj_call_regexp . '|' . $this->_avar_regexp . '|' . $this->_qstr_regexp .'))*)';
  160. // matches valid function name:
  161. // foo123
  162. // _foo_bar
  163. $this->_func_regexp = '[a-zA-Z_]\w*';
  164. // matches valid registered object:
  165. // foo->bar
  166. $this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*';
  167. // matches valid parameter values:
  168. // true
  169. // $foo
  170. // $foo|bar
  171. // #foo#
  172. // #foo#|bar
  173. // "text"
  174. // "text"|bar
  175. // $foo->bar
  176. $this->_param_regexp = '(?:\s*(?:' . $this->_obj_call_regexp . '|'
  177. . $this->_var_regexp . '|' . $this->_num_const_regexp . '|\w+)(?>' . $this->_mod_regexp . '*)\s*)';
  178. // matches valid parenthesised function parameters:
  179. //
  180. // "text"
  181. // $foo, $bar, "text"
  182. // $foo|bar, "foo"|bar, $foo->bar($foo)|bar
  183. $this->_parenth_param_regexp = '(?:\((?:\w+|'
  184. . $this->_param_regexp . '(?:\s*,\s*(?:(?:\w+|'
  185. . $this->_param_regexp . ')))*)?\))';
  186. // matches valid function call:
  187. // foo()
  188. // foo_bar($foo)
  189. // _foo_bar($foo,"bar")
  190. // foo123($foo,$foo->bar(),"foo")
  191. $this->_func_call_regexp = '(?:' . $this->_func_regexp . '\s*(?:'
  192. . $this->_parenth_param_regexp . '))';
  193. }
  194. /**
  195. * compile a resource
  196. *
  197. * sets $compiled_content to the compiled source
  198. * @param string $resource_name
  199. * @param string $source_content
  200. * @param string $compiled_content
  201. * @return true
  202. */
  203. function _compile_file($resource_name, $source_content, &$compiled_content)
  204. {
  205. if ($this->security) {
  206. // do not allow php syntax to be executed unless specified
  207. if ($this->php_handling == SMARTY_PHP_ALLOW &&
  208. !$this->security_settings['PHP_HANDLING']) {
  209. $this->php_handling = SMARTY_PHP_PASSTHRU;
  210. }
  211. }
  212. $this->_load_filters();
  213. $this->_current_file = $resource_name;
  214. $this->_current_line_no = 1;
  215. $ldq = preg_quote($this->left_delimiter, '~');
  216. $rdq = preg_quote($this->right_delimiter, '~');
  217. // run template source through prefilter functions
  218. if (count($this->_plugins['prefilter']) > 0) {
  219. foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
  220. if ($prefilter === false) continue;
  221. if ($prefilter[3] || is_callable($prefilter[0])) {
  222. $source_content = call_user_func_array($prefilter[0],
  223. array($source_content, &$this));
  224. $this->_plugins['prefilter'][$filter_name][3] = true;
  225. } else {
  226. $this->_trigger_fatal_error("[plugin] prefilter '$filter_name' is not implemented");
  227. }
  228. }
  229. }
  230. /* fetch all special blocks */
  231. $search = "~{$ldq}\*(.*?)\*{$rdq}|{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}|{$ldq}\s*php\s*{$rdq}(.*?){$ldq}\s*/php\s*{$rdq}~s";
  232. preg_match_all($search, $source_content, $match, PREG_SET_ORDER);
  233. $this->_folded_blocks = $match;
  234. reset($this->_folded_blocks);
  235. /* replace special blocks by "{php}" */
  236. $source_content = preg_replace($search.'e', "'"
  237. . $this->_quote_replace($this->left_delimiter) . 'php'
  238. . "' . str_repeat(\"\n\", substr_count('\\0', \"\n\")) .'"
  239. . $this->_quote_replace($this->right_delimiter)
  240. . "'"
  241. , $source_content);
  242. /* Gather all template tags. */
  243. preg_match_all("~{$ldq}\s*(.*?)\s*{$rdq}~s", $source_content, $_match);
  244. $template_tags = $_match[1];
  245. /* Split content by template tags to obtain non-template content. */
  246. $text_blocks = preg_split("~{$ldq}.*?{$rdq}~s", $source_content);
  247. /* loop through text blocks */
  248. for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) {
  249. /* match anything resembling php tags */
  250. if (preg_match_all('~(<\?(?:\w+|=)?|\?>|language\s*=\s*[\"\']?\s*php\s*[\"\']?)~is', $text_blocks[$curr_tb], $sp_match)) {
  251. /* replace tags with placeholders to prevent recursive replacements */
  252. $sp_match[1] = array_unique($sp_match[1]);
  253. usort($sp_match[1], '_smarty_sort_length');
  254. for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {
  255. $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],'%%%SMARTYSP'.$curr_sp.'%%%',$text_blocks[$curr_tb]);
  256. }
  257. /* process each one */
  258. for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {
  259. if ($this->php_handling == SMARTY_PHP_PASSTHRU) {
  260. /* echo php contents */
  261. $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '<?php echo \''.str_replace("'", "\'", $sp_match[1][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]);
  262. } else if ($this->php_handling == SMARTY_PHP_QUOTE) {
  263. /* quote php tags */
  264. $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]);
  265. } else if ($this->php_handling == SMARTY_PHP_REMOVE) {
  266. /* remove php tags */
  267. $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '', $text_blocks[$curr_tb]);
  268. } else {
  269. /* SMARTY_PHP_ALLOW, but echo non php starting tags */
  270. $sp_match[1][$curr_sp] = preg_replace('~(<\?(?!php|=|$))~i', '<?php echo \'\\1\'?>'."\n", $sp_match[1][$curr_sp]);
  271. $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]);
  272. }
  273. }
  274. }
  275. }
  276. /* Compile the template tags into PHP code. */
  277. $compiled_tags = array();
  278. for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) {
  279. $this->_current_line_no += substr_count($text_blocks[$i], "\n");
  280. $compiled_tags[] = $this->_compile_tag($template_tags[$i]);
  281. $this->_current_line_no += substr_count($template_tags[$i], "\n");
  282. }
  283. if (count($this->_tag_stack)>0) {
  284. list($_open_tag, $_line_no) = end($this->_tag_stack);
  285. $this->_syntax_error("unclosed tag \{$_open_tag} (opened line $_line_no).", E_USER_ERROR, __FILE__, __LINE__);
  286. return;
  287. }
  288. /* Reformat $text_blocks between 'strip' and '/strip' tags,
  289. removing spaces, tabs and newlines. */
  290. $strip = false;
  291. for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {
  292. if ($compiled_tags[$i] == '{strip}') {
  293. $compiled_tags[$i] = '';
  294. $strip = true;
  295. /* remove leading whitespaces */
  296. $text_blocks[$i + 1] = ltrim($text_blocks[$i + 1]);
  297. }
  298. if ($strip) {
  299. /* strip all $text_blocks before the next '/strip' */
  300. for ($j = $i + 1; $j < $for_max; $j++) {
  301. /* remove leading and trailing whitespaces of each line */
  302. $text_blocks[$j] = preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $text_blocks[$j]);
  303. if ($compiled_tags[$j] == '{/strip}') {
  304. /* remove trailing whitespaces from the last text_block */
  305. $text_blocks[$j] = rtrim($text_blocks[$j]);
  306. }
  307. $text_blocks[$j] = "<?php echo '" . strtr($text_blocks[$j], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>";
  308. if ($compiled_tags[$j] == '{/strip}') {
  309. $compiled_tags[$j] = "\n"; /* slurped by php, but necessary
  310. if a newline is following the closing strip-tag */
  311. $strip = false;
  312. $i = $j;
  313. break;
  314. }
  315. }
  316. }
  317. }
  318. $compiled_content = '';
  319. $tag_guard = '%%%SMARTYOTG' . md5(uniqid(rand(), true)) . '%%%';
  320. /* Interleave the compiled contents and text blocks to get the final result. */
  321. for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {
  322. if ($compiled_tags[$i] == '') {
  323. // tag result empty, remove first newline from following text block
  324. $text_blocks[$i+1] = preg_replace('~^(\r\n|\r|\n)~', '', $text_blocks[$i+1]);
  325. }
  326. // replace legit PHP tags with placeholder
  327. $text_blocks[$i] = str_replace('<?', $tag_guard, $text_blocks[$i]);
  328. $compiled_tags[$i] = str_replace('<?', $tag_guard, $compiled_tags[$i]);
  329. $compiled_content .= $text_blocks[$i] . $compiled_tags[$i];
  330. }
  331. $compiled_content .= str_replace('<?', $tag_guard, $text_blocks[$i]);
  332. // escape php tags created by interleaving
  333. $compiled_content = str_replace('<?', "<?php echo '<?' ?>\n", $compiled_content);
  334. $compiled_content = preg_replace("~(?<!')language\s*=\s*[\"\']?\s*php\s*[\"\']?~", "<?php echo 'language=php' ?>\n", $compiled_content);
  335. // recover legit tags
  336. $compiled_content = str_replace($tag_guard, '<?', $compiled_content);
  337. // remove \n from the end of the file, if any
  338. if (strlen($compiled_content) && (substr($compiled_content, -1) == "\n") ) {
  339. $compiled_content = substr($compiled_content, 0, -1);
  340. }
  341. if (!empty($this->_cache_serial)) {
  342. $compiled_content = "<?php \$this->_cache_serials['".$this->_cache_include."'] = '".$this->_cache_serial."'; ?>" . $compiled_content;
  343. }
  344. // run compiled template through postfilter functions
  345. if (count($this->_plugins['postfilter']) > 0) {
  346. foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
  347. if ($postfilter === false) continue;
  348. if ($postfilter[3] || is_callable($postfilter[0])) {
  349. $compiled_content = call_user_func_array($postfilter[0],
  350. array($compiled_content, &$this));
  351. $this->_plugins['postfilter'][$filter_name][3] = true;
  352. } else {
  353. $this->_trigger_fatal_error("Smarty plugin error: postfilter '$filter_name' is not implemented");
  354. }
  355. }
  356. }
  357. // put header at the top of the compiled template
  358. $template_header = "<?php /* Smarty version ".$this->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n";
  359. $template_header .= " compiled from ".strtr(urlencode($resource_name), array('%2F'=>'/', '%3A'=>':'))." */ ?>\n";
  360. /* Emit code to load needed plugins. */
  361. $this->_plugins_code = '';
  362. if (count($this->_plugin_info)) {
  363. $_plugins_params = "array('plugins' => array(";
  364. foreach ($this->_plugin_info as $plugin_type => $plugins) {
  365. foreach ($plugins as $plugin_name => $plugin_info) {
  366. $_plugins_params .= "array('$plugin_type', '$plugin_name', '" . strtr($plugin_info[0], array("'" => "\\'", "\\" => "\\\\")) . "', $plugin_info[1], ";
  367. $_plugins_params .= $plugin_info[2] ? 'true),' : 'false),';
  368. }
  369. }
  370. $_plugins_params .= '))';
  371. $plugins_code = "<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');\nsmarty_core_load_plugins($_plugins_params, \$this); ?>\n";
  372. $template_header .= $plugins_code;
  373. $this->_plugin_info = array();
  374. $this->_plugins_code = $plugins_code;
  375. }
  376. if ($this->_init_smarty_vars) {
  377. $template_header .= "<?php require_once(SMARTY_CORE_DIR . 'core.assign_smarty_interface.php');\nsmarty_core_assign_smarty_interface(null, \$this); ?>\n";
  378. $this->_init_smarty_vars = false;
  379. }
  380. $compiled_content = $template_header . $compiled_content;
  381. return true;
  382. }
  383. /**
  384. * Compile a template tag
  385. *
  386. * @param string $template_tag
  387. * @return string
  388. */
  389. function _compile_tag($template_tag)
  390. {
  391. /* Matched comment. */
  392. if (substr($template_tag, 0, 1) == '*' && substr($template_tag, -1) == '*')
  393. return '';
  394. /* Split tag into two three parts: command, command modifiers and the arguments. */
  395. if(! preg_match('~^(?:(' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp
  396. . '|\/?' . $this->_reg_obj_regexp . '|\/?' . $this->_func_regexp . ')(' . $this->_mod_regexp . '*))
  397. (?:\s+(.*))?$
  398. ~xs', $template_tag, $match)) {
  399. $this->_syntax_error("unrecognized tag: $template_tag", E_USER_ERROR, __FILE__, __LINE__);
  400. }
  401. $tag_command = $match[1];
  402. $tag_modifier = isset($match[2]) ? $match[2] : null;
  403. $tag_args = isset($match[3]) ? $match[3] : null;
  404. if (preg_match('~^' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '$~', $tag_command)) {
  405. /* tag name is a variable or object */
  406. $_return = $this->_parse_var_props($tag_command . $tag_modifier);
  407. return "<?php echo $_return; ?>" . $this->_additional_newline;
  408. }
  409. /* If the tag name is a registered object, we process it. */
  410. if (preg_match('~^\/?' . $this->_reg_obj_regexp . '$~', $tag_command)) {
  411. return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier);
  412. }
  413. switch ($tag_command) {
  414. case 'include':
  415. return $this->_compile_include_tag($tag_args);
  416. case 'include_php':
  417. return $this->_compile_include_php_tag($tag_args);
  418. case 'if':
  419. $this->_push_tag('if');
  420. return $this->_compile_if_tag($tag_args);
  421. case 'else':
  422. list($_open_tag) = end($this->_tag_stack);
  423. if ($_open_tag != 'if' && $_open_tag != 'elseif')
  424. $this->_syntax_error('unexpected {else}', E_USER_ERROR, __FILE__, __LINE__);
  425. else
  426. $this->_push_tag('else');
  427. return '<?php else: ?>';
  428. case 'elseif':
  429. list($_open_tag) = end($this->_tag_stack);
  430. if ($_open_tag != 'if' && $_open_tag != 'elseif')
  431. $this->_syntax_error('unexpected {elseif}', E_USER_ERROR, __FILE__, __LINE__);
  432. if ($_open_tag == 'if')
  433. $this->_push_tag('elseif');
  434. return $this->_compile_if_tag($tag_args, true);
  435. case '/if':
  436. $this->_pop_tag('if');
  437. return '<?php endif; ?>';
  438. case 'capture':
  439. return $this->_compile_capture_tag(true, $tag_args);
  440. case '/capture':
  441. return $this->_compile_capture_tag(false);
  442. case 'ldelim':
  443. return $this->left_delimiter;
  444. case 'rdelim':
  445. return $this->right_delimiter;
  446. case 'section':
  447. $this->_push_tag('section');
  448. return $this->_compile_section_start($tag_args);
  449. case 'sectionelse':
  450. $this->_push_tag('sectionelse');
  451. return "<?php endfor; else: ?>";
  452. break;
  453. case '/section':
  454. $_open_tag = $this->_pop_tag('section');
  455. if ($_open_tag == 'sectionelse')
  456. return "<?php endif; ?>";
  457. else
  458. return "<?php endfor; endif; ?>";
  459. case 'foreach':
  460. $this->_push_tag('foreach');
  461. return $this->_compile_foreach_start($tag_args);
  462. break;
  463. case 'foreachelse':
  464. $this->_push_tag('foreachelse');
  465. return "<?php endforeach; else: ?>";
  466. case '/foreach':
  467. $_open_tag = $this->_pop_tag('foreach');
  468. if ($_open_tag == 'foreachelse')
  469. return "<?php endif; unset(\$_from); ?>";
  470. else
  471. return "<?php endforeach; endif; unset(\$_from); ?>";
  472. break;
  473. case 'strip':
  474. case '/strip':
  475. if (substr($tag_command, 0, 1)=='/') {
  476. $this->_pop_tag('strip');
  477. if (--$this->_strip_depth==0) { /* outermost closing {/strip} */
  478. $this->_additional_newline = "\n";
  479. return '{' . $tag_command . '}';
  480. }
  481. } else {
  482. $this->_push_tag('strip');
  483. if ($this->_strip_depth++==0) { /* outermost opening {strip} */
  484. $this->_additional_newline = "";
  485. return '{' . $tag_command . '}';
  486. }
  487. }
  488. return '';
  489. case 'php':
  490. /* handle folded tags replaced by {php} */
  491. list(, $block) = each($this->_folded_blocks);
  492. $this->_current_line_no += substr_count($block[0], "\n");
  493. /* the number of matched elements in the regexp in _compile_file()
  494. determins the type of folded tag that was found */
  495. switch (count($block)) {
  496. case 2: /* comment */
  497. return '';
  498. case 3: /* literal */
  499. return "<?php echo '" . strtr($block[2], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>" . $this->_additional_newline;
  500. case 4: /* php */
  501. if ($this->security && !$this->security_settings['PHP_TAGS']) {
  502. $this->_syntax_error("(secure mode) php tags not permitted", E_USER_WARNING, __FILE__, __LINE__);
  503. return;
  504. }
  505. return '<?php ' . $block[3] .' ?>';
  506. }
  507. break;
  508. case 'insert':
  509. return $this->_compile_insert_tag($tag_args);
  510. default:
  511. if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) {
  512. return $output;
  513. } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) {
  514. return $output;
  515. } else if ($this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier, $output)) {
  516. return $output;
  517. } else {
  518. $this->_syntax_error("unrecognized tag '$tag_command'", E_USER_ERROR, __FILE__, __LINE__);
  519. }
  520. }
  521. }
  522. /**
  523. * compile the custom compiler tag
  524. *
  525. * sets $output to the compiled custom compiler tag
  526. * @param string $tag_command
  527. * @param string $tag_args
  528. * @param string $output
  529. * @return boolean
  530. */
  531. function _compile_compiler_tag($tag_command, $tag_args, &$output)
  532. {
  533. $found = false;
  534. $have_function = true;
  535. /*
  536. * First we check if the compiler function has already been registered
  537. * or loaded from a plugin file.
  538. */
  539. if (isset($this->_plugins['compiler'][$tag_command])) {
  540. $found = true;
  541. $plugin_func = $this->_plugins['compiler'][$tag_command][0];
  542. if (!is_callable($plugin_func)) {
  543. $message = "compiler function '$tag_command' is not implemented";
  544. $have_function = false;
  545. }
  546. }
  547. /*
  548. * Otherwise we need to load plugin file and look for the function
  549. * inside it.
  550. */
  551. else if ($plugin_file = $this->_get_plugin_filepath('compiler', $tag_command)) {
  552. $found = true;
  553. include_once $plugin_file;
  554. $plugin_func = 'smarty_compiler_' . $tag_command;
  555. if (!is_callable($plugin_func)) {
  556. $message = "plugin function $plugin_func() not found in $plugin_file\n";
  557. $have_function = false;
  558. } else {
  559. $this->_plugins['compiler'][$tag_command] = array($plugin_func, null, null, null, true);
  560. }
  561. }
  562. /*
  563. * True return value means that we either found a plugin or a
  564. * dynamically registered function. False means that we didn't and the
  565. * compiler should now emit code to load custom function plugin for this
  566. * tag.
  567. */
  568. if ($found) {
  569. if ($have_function) {
  570. $output = call_user_func_array($plugin_func, array($tag_args, &$this));
  571. if($output != '') {
  572. $output = '<?php ' . $this->_push_cacheable_state('compiler', $tag_command)
  573. . $output
  574. . $this->_pop_cacheable_state('compiler', $tag_command) . ' ?>';
  575. }
  576. } else {
  577. $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
  578. }
  579. return true;
  580. } else {
  581. return false;
  582. }
  583. }
  584. /**
  585. * compile block function tag
  586. *
  587. * sets $output to compiled block function tag
  588. * @param string $tag_command
  589. * @param string $tag_args
  590. * @param string $tag_modifier
  591. * @param string $output
  592. * @return boolean
  593. */
  594. function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output)
  595. {
  596. if (substr($tag_command, 0, 1) == '/') {
  597. $start_tag = false;
  598. $tag_command = substr($tag_command, 1);
  599. } else
  600. $start_tag = true;
  601. $found = false;
  602. $have_function = true;
  603. /*
  604. * First we check if the block function has already been registered
  605. * or loaded from a plugin file.
  606. */
  607. if (isset($this->_plugins['block'][$tag_command])) {
  608. $found = true;
  609. $plugin_func = $this->_plugins['block'][$tag_command][0];
  610. if (!is_callable($plugin_func)) {
  611. $message = "block function '$tag_command' is not implemented";
  612. $have_function = false;
  613. }
  614. }
  615. /*
  616. * Otherwise we need to load plugin file and look for the function
  617. * inside it.
  618. */
  619. else if ($plugin_file = $this->_get_plugin_filepath('block', $tag_command)) {
  620. $found = true;
  621. include_once $plugin_file;
  622. $plugin_func = 'smarty_block_' . $tag_command;
  623. if (!function_exists($plugin_func)) {
  624. $message = "plugin function $plugin_func() not found in $plugin_file\n";
  625. $have_function = false;
  626. } else {
  627. $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);
  628. }
  629. }
  630. if (!$found) {
  631. return false;
  632. } else if (!$have_function) {
  633. $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
  634. return true;
  635. }
  636. /*
  637. * Even though we've located the plugin function, compilation
  638. * happens only once, so the plugin will still need to be loaded
  639. * at runtime for future requests.
  640. */
  641. $this->_add_plugin('block', $tag_command);
  642. if ($start_tag)
  643. $this->_push_tag($tag_command);
  644. else
  645. $this->_pop_tag($tag_command);
  646. if ($start_tag) {
  647. $output = '<?php ' . $this->_push_cacheable_state('block', $tag_command);
  648. $attrs = $this->_parse_attrs($tag_args);
  649. $_cache_attrs='';
  650. $arg_list = $this->_compile_arg_list('block', $tag_command, $attrs, $_cache_attrs);
  651. $output .= "$_cache_attrs\$this->_tag_stack[] = array('$tag_command', array(".implode(',', $arg_list).')); ';
  652. $output .= '$_block_repeat=true;' . $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);';
  653. $output .= 'while ($_block_repeat) { ob_start(); ?>';
  654. } else {
  655. $output = '<?php $_block_content = ob_get_contents(); ob_end_clean(); ';
  656. $_out_tag_text = $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat)';
  657. if ($tag_modifier != '') {
  658. $this->_parse_modifiers($_out_tag_text, $tag_modifier);
  659. }
  660. $output .= '$_block_repeat=false;echo ' . $_out_tag_text . '; } ';
  661. $output .= " array_pop(\$this->_tag_stack); " . $this->_pop_cacheable_state('block', $tag_command) . '?>';
  662. }
  663. return true;
  664. }
  665. /**
  666. * compile custom function tag
  667. *
  668. * @param string $tag_command
  669. * @param string $tag_args
  670. * @param string $tag_modifier
  671. * @return string
  672. */
  673. function _compile_custom_tag($tag_command, $tag_args, $tag_modifier, &$output)
  674. {
  675. $found = false;
  676. $have_function = true;
  677. /*
  678. * First we check if the custom function has already been registered
  679. * or loaded from a plugin file.
  680. */
  681. if (isset($this->_plugins['function'][$tag_command])) {
  682. $found = true;
  683. $plugin_func = $this->_plugins['function'][$tag_command][0];
  684. if (!is_callable($plugin_func)) {
  685. $message = "custom function '$tag_command' is not implemented";
  686. $have_function = false;
  687. }
  688. }
  689. /*
  690. * Otherwise we need to load plugin file and look for the function
  691. * inside it.
  692. */
  693. else if ($plugin_file = $this->_get_plugin_filepath('function', $tag_command)) {
  694. $found = true;
  695. include_once $plugin_file;
  696. $plugin_func = 'smarty_function_' . $tag_command;
  697. if (!function_exists($plugin_func)) {
  698. $message = "plugin function $plugin_func() not found in $plugin_file\n";
  699. $have_function = false;
  700. } else {
  701. $this->_plugins['function'][$tag_command] = array($plugin_func, null, null, null, true);
  702. }
  703. }
  704. if (!$found) {
  705. return false;
  706. } else if (!$have_function) {
  707. $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
  708. return true;
  709. }
  710. /* declare plugin to be loaded on display of the template that
  711. we compile right now */
  712. $this->_add_plugin('function', $tag_command);
  713. $_cacheable_state = $this->_push_cacheable_state('function', $tag_command);
  714. $attrs = $this->_parse_attrs($tag_args);
  715. $_cache_attrs = '';
  716. $arg_list = $this->_compile_arg_list('function', $tag_command, $attrs, $_cache_attrs);
  717. $output = $this->_compile_plugin_call('function', $tag_command).'(array('.implode(',', $arg_list)."), \$this)";
  718. if($tag_modifier != '') {
  719. $this->_parse_modifiers($output, $tag_modifier);
  720. }
  721. if($output != '') {
  722. $output = '<?php ' . $_cacheable_state . $_cache_attrs . 'echo ' . $output . ';'
  723. . $this->_pop_cacheable_state('function', $tag_command) . "?>" . $this->_additional_newline;
  724. }
  725. return true;
  726. }
  727. /**
  728. * compile a registered object tag
  729. *
  730. * @param string $tag_command
  731. * @param array $attrs
  732. * @param string $tag_modifier
  733. * @return string
  734. */
  735. function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier)
  736. {
  737. if (substr($tag_command, 0, 1) == '/') {
  738. $start_tag = false;
  739. $tag_command = substr($tag_command, 1);
  740. } else {
  741. $start_tag = true;
  742. }
  743. list($object, $obj_comp) = explode('->', $tag_command);
  744. $arg_list = array();
  745. if(count($attrs)) {
  746. $_assign_var = false;
  747. foreach ($attrs as $arg_name => $arg_value) {
  748. if($arg_name == 'assign') {
  749. $_assign_var = $arg_value;
  750. unset($attrs['assign']);
  751. continue;
  752. }
  753. if (is_bool($arg_value))
  754. $arg_value = $arg_value ? 'true' : 'false';
  755. $arg_list[] = "'$arg_name' => $arg_value";
  756. }
  757. }
  758. if($this->_reg_objects[$object][2]) {
  759. // smarty object argument format
  760. $args = "array(".implode(',', (array)$arg_list)."), \$this";
  761. } else {
  762. // traditional argument format
  763. $args = implode(',', array_values($attrs));
  764. if (empty($args)) {
  765. $args = 'null';
  766. }
  767. }
  768. $prefix = '';
  769. $postfix = '';
  770. $newline = '';
  771. if(!is_object($this->_reg_objects[$object][0])) {
  772. $this->_trigger_fatal_error("registered '$object' is not an object" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__);
  773. } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) {
  774. $this->_trigger_fatal_error("'$obj_comp' is not a registered component of object '$object'", $this->_current_file, $this->_current_line_no, __FILE__, __LINE__);
  775. } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) {
  776. // method
  777. if(in_array($obj_comp, $this->_reg_objects[$object][3])) {
  778. // block method
  779. if ($start_tag) {
  780. $prefix = "\$this->_tag_stack[] = array('$obj_comp', $args); ";
  781. $prefix .= "\$_block_repeat=true; \$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], null, \$this, \$_block_repeat); ";
  782. $prefix .= "while (\$_block_repeat) { ob_start();";
  783. $return = null;
  784. $postfix = '';
  785. } else {
  786. $prefix = "\$_obj_block_content = ob_get_contents(); ob_end_clean(); \$_block_repeat=false;";
  787. $return = "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], \$_obj_block_content, \$this, \$_block_repeat)";
  788. $postfix = "} array_pop(\$this->_tag_stack);";
  789. }
  790. } else {
  791. // non-block method
  792. $return = "\$this->_reg_objects['$object'][0]->$obj_comp($args)";
  793. }
  794. } else {
  795. // property
  796. $return = "\$this->_reg_objects['$object'][0]->$obj_comp";
  797. }
  798. if($return != null) {
  799. if($tag_modifier != '') {
  800. $this->_parse_modifiers($return, $tag_modifier);
  801. }
  802. if(!empty($_assign_var)) {
  803. $output = "\$this->assign('" . $this->_dequote($_assign_var) ."', $return);";
  804. } else {
  805. $output = 'echo ' . $return . ';';
  806. $newline = $this->_additional_newline;
  807. }
  808. } else {
  809. $output = '';
  810. }
  811. return '<?php ' . $prefix . $output . $postfix . "?>" . $newline;
  812. }
  813. /**
  814. * Compile {insert ...} tag
  815. *
  816. * @param string $tag_args
  817. * @return string
  818. */
  819. function _compile_insert_tag($tag_args)
  820. {
  821. $attrs = $this->_parse_attrs($tag_args);
  822. $name = $this->_dequote($attrs['name']);
  823. if (empty($name)) {
  824. return $this->_syntax_error("missing insert name", E_USER_ERROR, __FILE__, __LINE__);
  825. }
  826. if (!preg_match('~^\w+$~', $name)) {
  827. return $this->_syntax_error("'insert: 'name' must be an insert function name", E_USER_ERROR, __FILE__, __LINE__);
  828. }
  829. if (!empty($attrs['script'])) {
  830. $delayed_loading = true;
  831. } else {
  832. $delayed_loading = false;
  833. }
  834. foreach ($attrs as $arg_name => $arg_value) {
  835. if (is_bool($arg_value))
  836. $arg_value = $arg_value ? 'true' : 'false';
  837. $arg_list[] = "'$arg_name' => $arg_value";
  838. }
  839. $this->_add_plugin('insert', $name, $delayed_loading);
  840. $_params = "array('args' => array(".implode(', ', (array)$arg_list)."))";
  841. return "<?php require_once(SMARTY_CORE_DIR . 'core.run_insert_handler.php');\necho smarty_core_run_insert_handler($_params, \$this); ?>" . $this->_additional_newline;
  842. }
  843. /**
  844. * Compile {include ...} tag
  845. *
  846. * @param string $tag_args
  847. * @return string
  848. */
  849. function _compile_include_tag($tag_args)
  850. {
  851. $attrs = $this->_parse_attrs($tag_args);
  852. $arg_list = array();
  853. if (empty($attrs['file'])) {
  854. $this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__, __LINE__);
  855. }
  856. foreach ($attrs as $arg_name => $arg_value) {
  857. if ($arg_name == 'file') {
  858. $include_file = $arg_value;
  859. continue;
  860. } else if ($arg_name == 'assign') {
  861. $assign_var = $arg_value;
  862. continue;
  863. }
  864. if (is_bool($arg_value))
  865. $arg_value = $arg_value ? 'true' : 'false';
  866. $arg_list[] = "'$arg_name' => $arg_value";
  867. }
  868. $output = '<?php ';
  869. if (isset($assign_var)) {
  870. $output .= "ob_start();\n";
  871. }
  872. $output .=
  873. "\$_smarty_tpl_vars = \$this->_tpl_vars;\n";
  874. $_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))";
  875. $output .= "\$this->_smarty_include($_params);\n" .
  876. "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" .
  877. "unset(\$_smarty_tpl_vars);\n";
  878. if (isset($assign_var)) {
  879. $output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n";
  880. }
  881. $output .= ' ?>';
  882. return $output;
  883. }
  884. /**
  885. * Compile {include ...} tag
  886. *
  887. * @param string $tag_args
  888. * @return string
  889. */
  890. function _compile_include_php_tag($tag_args)
  891. {
  892. $attrs = $this->_parse_attrs($tag_args);
  893. if (empty($attrs['file'])) {
  894. $this->_syntax_error("missing 'file' attribute in include_php tag", E_USER_ERROR, __FILE__, __LINE__);
  895. }
  896. $assign_var = (empty($attrs['assign'])) ? '' : $this->_dequote($attrs['assign']);
  897. $once_var = (empty($attrs['once']) || $attrs['once']=='false') ? 'false' : 'true';
  898. $arg_list = array();
  899. foreach($attrs as $arg_name => $arg_value) {
  900. if($arg_name != 'file' AND $arg_name != 'once' AND $arg_name != 'assign') {
  901. if(is_bool($arg_value))
  902. $arg_value = $arg_value ? 'true' : 'false';
  903. $arg_list[] = "'$arg_name' => $arg_value";
  904. }
  905. }
  906. $_params = "array('smarty_file' => " . $attrs['file'] . ", 'smarty_assign' => '$assign_var', 'smarty_once' => $once_var, 'smarty_include_vars' => array(".implode(',', $arg_list)."))";
  907. return "<?php require_once(SMARTY_CORE_DIR . 'core.smarty_include_php.php');\nsmarty_core_smarty_include_php($_params, \$this); ?>" . $this->_additional_newline;
  908. }
  909. /**
  910. * Compile {section ...} tag
  911. *
  912. * @param string $tag_args
  913. * @return string
  914. */
  915. function _compile_section_start($tag_args)
  916. {
  917. $attrs = $this->_parse_attrs($tag_args);
  918. $arg_list = array();
  919. $output = '<?php ';
  920. $section_name = $attrs['name'];
  921. if (empty($section_name)) {
  922. $this->_syntax_error("missing section name", E_USER_ERROR, __FILE__, __LINE__);
  923. }
  924. $output .= "unset(\$this->_sections[$section_name]);\n";
  925. $section_props = "\$this->_sections[$section_name]";
  926. foreach ($attrs as $attr_name => $attr_value) {
  927. switch ($attr_name) {
  928. case 'loop':
  929. $output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int)\$_loop); unset(\$_loop);\n";
  930. break;
  931. case 'show':
  932. if (is_bool($attr_value))
  933. $show_attr_value = $attr_value ? 'true' : 'false';
  934. else
  935. $show_attr_value = "(bool)$attr_value";
  936. $output .= "{$section_props}['show'] = $show_attr_value;\n";
  937. break;
  938. case 'name':
  939. $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
  940. break;
  941. case 'max':
  942. case 'start':
  943. $output .= "{$section_props}['$attr_name'] = (int)$attr_value;\n";
  944. break;
  945. case 'step':
  946. $output .= "{$section_props}['$attr_name'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\n";
  947. break;
  948. default:
  949. $this->_syntax_error("unknown section attribute - '$attr_name'", E_USER_ERROR, __FILE__, __LINE__);
  950. break;
  951. }
  952. }
  953. if (!isset($attrs['show']))
  954. $output .= "{$section_props}['show'] = true;\n";
  955. if (!isset($attrs['loop']))
  956. $output .= "{$section_props}['loop'] = 1;\n";
  957. if (!isset($attrs['max']))
  958. $output .= "{$section_props}['max'] = {$section_props}['loop'];\n";
  959. else
  960. $output .= "if ({$section_props}['max'] < 0)\n" .
  961. " {$section_props}['max'] = {$section_props}['loop'];\n";
  962. if (!isset($attrs['step']))
  963. $output .= "{$section_props}['step'] = 1;\n";
  964. if (!isset($attrs['start']))
  965. $output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n";
  966. else {
  967. $output .= "if ({$section_props}['start'] < 0)\n" .
  968. " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" .
  969. "else\n" .
  970. " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
  971. }
  972. $output .= "if ({$section_props}['show']) {\n";
  973. if (!isset($attrs['start']) && !isset($attrs['step']) && !isset($attrs['max'])) {
  974. $output .= " {$section_props}['total'] = {$section_props}['loop'];\n";
  975. } else {
  976. $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";
  977. }
  978. $output .= " if ({$section_props}['total'] == 0)\n" .
  979. " {$section_props}['show'] = false;\n" .
  980. "} else\n" .
  981. " {$section_props}['total'] = 0;\n";
  982. $output .= "if ({$section_props}['show']):\n";
  983. $output .= "
  984. for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
  985. {$section_props}['iteration'] <= {$section_props}['total'];
  986. {$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
  987. $output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n";
  988. $output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n";
  989. $output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n";
  990. $output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n";
  991. $output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n";
  992. $output .= "?>";
  993. return $output;
  994. }
  995. /**
  996. * Compile {foreach ...} tag.
  997. *
  998. * @param string $tag_args
  999. * @return string
  1000. */
  1001. function _compile_foreach_start($tag_args)
  1002. {
  1003. $attrs = $this->_parse_attrs($tag_args);
  1004. $arg_list = array();
  1005. if (empty($attrs['from'])) {
  1006. return $this->_syntax_error("foreach: missing 'from' attribute", E_USER_ERROR, __FILE__, __LINE__);
  1007. }
  1008. $from = $attrs['from'];
  1009. if (empty($attrs['item'])) {
  1010. return $this->_syntax_error("foreach: missing 'item' attribute", E_USER_ERROR, __FILE__, __LINE__);
  1011. }
  1012. $item = $this->_dequote($attrs['item']);
  1013. if (!preg_match('~^\w+$~', $item)) {
  1014. return $this->_syntax_error("'foreach: 'item' must be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__);
  1015. }
  1016. if (isset($attrs['key'])) {
  1017. $key = $this->_dequote($attrs['key']);
  1018. if (!preg_match('~^\w+$~', $key)) {
  1019. return $this->_syntax_error("foreach: 'key' must to be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__);
  1020. }
  1021. $key_part = "\$this->_tpl_vars['$key'] => ";
  1022. } else {
  1023. $key = null;
  1024. $key_part = '';
  1025. }
  1026. if (isset($attrs['name'])) {
  1027. $name = $attrs['name'];
  1028. } else {
  1029. $name = null;
  1030. }
  1031. $output = '<?php ';
  1032. $output .= "\$_from = $from; if (!is_array(\$_from) && !is_object(\$_from)) { settype(\$_from, 'array'); }";
  1033. if (isset($name)) {
  1034. $foreach_props = "\$this->_foreach[$name]";
  1035. $output .= "{$foreach_props} = array('total' => count(\$_from), 'iteration' => 0);\n";
  1036. $output .= "if ({$foreach_props}['total'] > 0):\n";
  1037. $output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
  1038. $output .= " {$foreach_props}['iteration']++;\n";
  1039. } else {
  1040. $output .= "if (count(\$_from)):\n";
  1041. $output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
  1042. }
  1043. $output .= '?>';
  1044. return $output;
  1045. }
  1046. /**
  1047. * Compile {capture} .. {/capture} tags
  1048. *
  1049. * @param boolean $start true if this is the {capture} tag
  1050. * @param string $tag_args
  1051. * @return string
  1052. */
  1053. function _compile_capture_tag($start, $tag_args = '')
  1054. {
  1055. $attrs = $this->_parse_attrs($tag_args);
  1056. if ($start) {
  1057. if (isset($attrs['name']))
  1058. $buffer = $attrs['name'];
  1059. else
  1060. $buffer = "'default'";
  1061. if (isset($attrs['assign']))
  1062. $assign = $attrs['assign'];
  1063. else
  1064. $assign = null;
  1065. $output = "<?php ob_start(); ?>";
  1066. $this->_capture_stack[] = array($buffer, $assign);
  1067. } else {
  1068. list($buffer, $assign) = array_pop($this->_capture_stack);
  1069. $output = "<?php \$this->_smarty_vars['capture'][$buffer] = ob_get_contents(); ";
  1070. if (isset($assign)) {
  1071. $output .= " \$this->assign($assign, ob_get_contents());";
  1072. }
  1073. $output .= "ob_end_clean(); ?>";
  1074. }
  1075. return $output;
  1076. }
  1077. /**
  1078. * Compile {if ...} tag
  1079. *
  1080. * @param string $tag_args
  1081. * @param boolean $elseif if true, uses elseif instead of if
  1082. * @return string
  1083. */
  1084. function _compile_if_tag($tag_args, $elseif = false)
  1085. {
  1086. /* Tokenize args for 'if' tag. */
  1087. preg_match_all('~(?>
  1088. ' . $this->_obj_call_regexp . '(?:' . $this->_mod_regexp . '*)? | # valid object call
  1089. ' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)? | # var or quoted string
  1090. \-?0[xX][0-9a-fA-F]+|\-?\d+(?:\.\d+)?|\.\d+|!==|===|==|!=|<>|<<|>>|<=|>=|\&\&|\|\||\(|\)|,|\!|\^|=|\&|\~|<|>|\||\%|\+|\-|\/|\*|\@ | # valid non-word token
  1091. \b\w+\b | # valid word token
  1092. \S+ # anything else
  1093. )~x', $tag_args, $match);
  1094. $tokens = $match[0];
  1095. if(empty($tokens)) {
  1096. $_error_msg = $elseif ? "'elseif'" : "'if'";
  1097. $_error_msg .= ' statement requires arguments';
  1098. $this->_syntax_error($_error_msg, E_USER_ERROR, __FILE__, __LINE__);
  1099. }
  1100. // make sure we have balanced parenthesis
  1101. $token_count = array_count_values($tokens);
  1102. if(isset($token_count['(']) && $token_count['('] != $token_count[')']) {
  1103. $this->_syntax_error("unbalanced parenthesis in if statement", E_USER_ERROR, __FILE__, __LINE__);
  1104. }
  1105. $is_arg_stack = array();
  1106. for ($i = 0; $i < count($tokens); $i++) {
  1107. $token = &$tokens[$i];
  1108. switch (strtolower($token)) {
  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. case '@':
  1135. break;
  1136. case 'eq':
  1137. $token = '==';
  1138. break;
  1139. case 'ne':
  1140. case 'neq':
  1141. $token = '!=';
  1142. break;
  1143. case 'lt':
  1144. $token = '<';
  1145. break;
  1146. case 'le':
  1147. case 'lte':
  1148. $token = '<=';
  1149. break;
  1150. case 'gt':
  1151. $token = '>';
  1152. break;
  1153. case 'ge':
  1154. case 'gte':
  1155. $token = '>=';
  1156. break;
  1157. case 'and':
  1158. $token = '&&';
  1159. break;
  1160. case 'or':
  1161. $token = '||';
  1162. break;
  1163. case 'not':
  1164. $token = '!';
  1165. break;
  1166. case 'mod':
  1167. $token = '%';
  1168. break;
  1169. case '(':
  1170. array_push($is_arg_stack, $i);
  1171. break;
  1172. case 'is':
  1173. /* If last token was a ')', we operate on the parenthesized
  1174. expression. The start of the expression is on the stack.
  1175. Otherwise, we operate on the last encountered token. */
  1176. if ($tokens[$i-1] == ')')
  1177. $is_arg_start = array_pop($is_arg_stack);
  1178. else
  1179. $is_arg_start = $i-1;
  1180. /* Construct the argument for 'is' expression, so it knows
  1181. what to operate on. */
  1182. $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
  1183. /* Pass all tokens from next one until the end to the
  1184. 'is' expression parsing function. The function will
  1185. return modified tokens, where the first one is the result
  1186. of the 'is' expression and the rest are the tokens it
  1187. didn't touch. */
  1188. $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
  1189. /* Replace the old tokens with the new ones. */
  1190. array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);
  1191. /* Adjust argument start so that it won't change from the
  1192. current position for the next iteration. */
  1193. $i = $is_arg_start;
  1194. break;
  1195. default:
  1196. if(preg_match('~^' . $this->_func_regexp . '$~', $token) ) {
  1197. // function call
  1198. if($this->security &&
  1199. !in_array($token, $this->security_settings['IF_FUNCS'])) {
  1200. $this->_syntax_error("(secure mode) '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__);
  1201. }
  1202. } elseif(preg_match('~^' . $this->_var_regexp . '$~', $token) && (strpos('+-*/^%&|', substr($token, -1)) === false) && isset($tokens[$i+1]) && $tokens[$i+1] == '(') {
  1203. // variable function call
  1204. $this->_syntax_error("variable function call '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__);
  1205. } elseif(preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)$~', $token)) {
  1206. // object or variable
  1207. $token = $this->_parse_var_props($token);
  1208. } elseif(is_numeric($token)) {
  1209. // number, skip it
  1210. } else {
  1211. $this->_syntax_error("unidentified token '$token'", E_USER_ERROR, __FILE__, __LINE__);
  1212. }
  1213. break;
  1214. }
  1215. }
  1216. if ($elseif)
  1217. return '<?php elseif ('.implode(' ', $tokens).'): ?>';
  1218. else
  1219. return '<?php if ('.implode(' ', $tokens).'): ?>';
  1220. }
  1221. function _compile_arg_list($type, $name, $attrs, &$cache_code) {
  1222. $arg_list = array();
  1223. if (isset($type) && isset($name)
  1224. && isset($this->_plugins[$type])
  1225. && isset($this->_plugins[$type][$name])
  1226. && empty($this->_plugins[$type][$name][4])
  1227. && is_array($this->_plugins[$type][$name][5])
  1228. ) {
  1229. /* we have a list of parameters that should be cached */
  1230. $_cache_attrs = $this->_plugins[$type][$name][5];
  1231. $_count = $this->_cache_attrs_count++;
  1232. $cache_code = "\$_cache_attrs =& \$this->_smarty_cache_attrs('$this->_cache_serial','$_count');";
  1233. } else {
  1234. /* no parameters are cached */
  1235. $_cache_attrs = null;
  1236. }
  1237. foreach ($attrs as $arg_name => $arg_value) {
  1238. if (is_bool($arg_value))
  1239. $arg_value = $arg_value ? 'true' : 'false';
  1240. if (is_null($arg_value))
  1241. $arg_value = 'null';
  1242. if ($_cache_attrs && in_array($arg_name, $_cache_attrs)) {
  1243. $arg_list[] = "'$arg_name' => (\$this->_cache_including) ? \$_cache_attrs['$arg_name'] : (\$_cache_attrs['$arg_name']=$arg_value)";
  1244. } else {
  1245. $arg_list[] = "'$arg_name' => $arg_value";
  1246. }
  1247. }
  1248. return $arg_list;
  1249. }
  1250. /**
  1251. * Parse is expression
  1252. *
  1253. * @param string $is_arg
  1254. * @param array $tokens
  1255. * @return array
  1256. */
  1257. function _parse_is_expr($is_arg, $tokens)
  1258. {
  1259. $expr_end = 0;
  1260. $negate_expr = false;
  1261. if (($first_token = array_shift($tokens)) == 'not') {
  1262. $negate_expr = true;
  1263. $expr_type = array_shift($tokens);
  1264. } else
  1265. $expr_type = $first_token;
  1266. switch ($expr_type) {
  1267. case 'even':
  1268. if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') {
  1269. $expr_end++;
  1270. $expr_arg = $tokens[$expr_end++];
  1271. $expr = "!(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))";
  1272. } else
  1273. $expr = "!(1 & $is_arg)";
  1274. break;
  1275. case 'odd':
  1276. if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') {
  1277. $expr_end++;
  1278. $expr_arg = $tokens[$expr_end++];
  1279. $expr = "(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))";
  1280. } else
  1281. $expr = "(1 & $is_arg)";
  1282. break;
  1283. case 'div':
  1284. if (@$tokens[$expr_end] == 'by') {
  1285. $expr_end++;
  1286. $expr_arg = $tokens[$expr_end++];
  1287. $expr = "!($is_arg % " . $this->_parse_var_props($expr_arg) . ")";
  1288. } else {
  1289. $this->_syntax_error("expecting 'by' after 'div'", E_USER_ERROR, __FILE__, __LINE__);
  1290. }
  1291. break;
  1292. default:
  1293. $this->_syntax_error("unknown 'is' expression - '$expr_type'", E_USER_ERROR, __FILE__, __LINE__);
  1294. break;
  1295. }
  1296. if ($negate_expr) {
  1297. $expr = "!($expr)";
  1298. }
  1299. array_splice($tokens, 0, $expr_end, $expr);
  1300. return $tokens;
  1301. }
  1302. /**
  1303. * Parse attribute string
  1304. *
  1305. * @param string $tag_args
  1306. * @return array
  1307. */
  1308. function _parse_attrs($tag_args)
  1309. {
  1310. /* Tokenize tag attributes. */
  1311. preg_match_all('~(?:' . $this->_obj_call_regexp . '|' . $this->_qstr_regexp . ' | (?>[^"\'=\s]+)
  1312. )+ |
  1313. [=]
  1314. ~x', $tag_args, $match);
  1315. $tokens = $match[0];
  1316. $attrs = array();
  1317. /* Parse state:
  1318. 0 - expecting attribute name
  1319. 1 - expecting '='
  1320. 2 - expecting attribute value (not '=') */
  1321. $state = 0;
  1322. foreach ($tokens as $token) {
  1323. switch ($state) {
  1324. case 0:
  1325. /* If the token is a valid identifier, we set attribute name
  1326. and go to state 1. */
  1327. if (preg_match('~^\w+$~', $token)) {
  1328. $attr_name = $token;
  1329. $state = 1;
  1330. } else
  1331. $this->_syntax_error("invalid attribute name: '$token'", E_USER_ERROR, __FILE__, __LINE__);
  1332. break;
  1333. case 1:
  1334. /* If the token is '=', then we go to state 2. */
  1335. if ($token == '=') {
  1336. $state = 2;
  1337. } else
  1338. $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__);
  1339. break;
  1340. case 2:
  1341. /* If token is not '=', we set the attribute value and go to
  1342. state 0. */
  1343. if ($token != '=') {
  1344. /* We booleanize the token if it's a non-quoted possible
  1345. boolean value. */
  1346. if (preg_match('~^(on|yes|true)$~', $token)) {
  1347. $token = 'true';
  1348. } else if (preg_match('~^(off|no|false)$~', $token)) {
  1349. $token = 'false';
  1350. } else if ($token == 'null') {
  1351. $token = 'null';
  1352. } else if (preg_match('~^' . $this->_num_const_regexp . '|0[xX][0-9a-fA-F]+$~', $token)) {
  1353. /* treat integer literally */
  1354. } else if (!preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . ')*$~', $token)) {
  1355. /* treat as a string, double-quote it escaping quotes */
  1356. $token = '"'.addslashes($token).'"';
  1357. }
  1358. $attrs[$attr_name] = $token;
  1359. $state = 0;
  1360. } else