You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1042 lines
39 KiB

  1. <?php
  2. /**
  3. * RainTPL
  4. * -------
  5. * Realized by Federico Ulfo & maintained by the Rain Team
  6. * Distributed under GNU/LGPL 3 License
  7. *
  8. * @version 2.7.2
  9. */
  10. class RainTPL{
  11. // -------------------------
  12. // CONFIGURATION
  13. // -------------------------
  14. /**
  15. * Template directory
  16. *
  17. * @var string
  18. */
  19. private $tpl_dir = "tpl/";
  20. /**
  21. * Cache directory. Is the directory where RainTPL will compile the template and save the cache
  22. *
  23. * @var string
  24. */
  25. private $cache_dir = "tmp/";
  26. /**
  27. * Template base URL. RainTPL will add this URL to the relative paths of element selected in $path_replace_list.
  28. *
  29. * @var string
  30. */
  31. private $base_url = null;
  32. /**
  33. * Template extension.
  34. *
  35. * @var string
  36. */
  37. private $tpl_ext = "html";
  38. /**
  39. * Path replace is a cool features that replace all relative paths of images (<img src="...">), stylesheet (<link href="...">), script (<script src="...">) and link (<a href="...">)
  40. * Set true to enable the path replace.
  41. *
  42. * @var unknown_type
  43. */
  44. private $path_replace = false;
  45. /**
  46. * You can set what the path_replace method will replace.
  47. * Avaible options: a, img, link, script, input
  48. *
  49. * @var array
  50. */
  51. private $path_replace_list = array( 'a', 'img', 'link', 'script', 'input' );
  52. /**
  53. * You can define in the black list what string are disabled into the template tags
  54. *
  55. * @var unknown_type
  56. */
  57. private $black_list = array( '\$this', 'raintpl::', 'self::', '_SESSION', '_SERVER', '_ENV', 'eval', 'exec', 'unlink', 'rmdir' );
  58. /**
  59. * Check template.
  60. * true: checks template update time, if changed it compile them
  61. * false: loads the compiled template. Set false if server doesn't have write permission for cache_directory.
  62. *
  63. */
  64. private $check_template_update = true;
  65. /**
  66. * PHP tags <? ?>
  67. * True: php tags are enabled into the template
  68. * False: php tags are disabled into the template and rendered as html
  69. *
  70. * @var bool
  71. */
  72. private $php_enabled = false;
  73. /**
  74. * Debug mode flag.
  75. * True: debug mode is used, syntax errors are displayed directly in template. Execution of script is not terminated.
  76. * False: exception is thrown on found error.
  77. *
  78. * @var bool
  79. */
  80. private $debug = false;
  81. // -------------------------
  82. // -------------------------
  83. // RAINTPL VARIABLES
  84. // -------------------------
  85. /**
  86. * Is the array where RainTPL keep the variables assigned
  87. *
  88. * @var array
  89. */
  90. public $var = array();
  91. protected $tpl = array(), // variables to keep the template directories and info
  92. $cache = false, // static cache enabled / disabled
  93. $cache_id = null; // identify only one cache
  94. protected $config_name_sum = array(); // takes all the config to create the md5 of the file
  95. // -------------------------
  96. const CACHE_EXPIRE_TIME = 3600; // default cache expire time = hour
  97. /**
  98. * Assign variable
  99. * eg. $t->assign('name','mickey');
  100. *
  101. * @param mixed $variable_name Name of template variable or associative array name/value
  102. * @param mixed $value value assigned to this variable. Not set if variable_name is an associative array
  103. */
  104. function assign( $variable, $value = null ){
  105. if( is_array( $variable ) )
  106. $this->var += $variable;
  107. else
  108. $this->var[ $variable ] = $value;
  109. }
  110. /**
  111. * Draw the template
  112. * eg. $html = $tpl->draw( 'demo', TRUE ); // return template in string
  113. * or $tpl->draw( $tpl_name ); // echo the template
  114. *
  115. * @param string $tpl_name template to load
  116. * @param boolean $return_string true=return a string, false=echo the template
  117. * @return string
  118. */
  119. function draw( $tpl_name, $return_string = false ){
  120. try {
  121. // compile the template if necessary and set the template filepath
  122. $this->check_template( $tpl_name );
  123. } catch (RainTpl_Exception $e) {
  124. $output = $this->printDebug($e);
  125. die($output);
  126. }
  127. // Cache is off and, return_string is false
  128. // Rain just echo the template
  129. if( !$this->cache && !$return_string ){
  130. extract( $this->var );
  131. include $this->tpl['compiled_filename'];
  132. unset( $this->tpl );
  133. }
  134. // cache or return_string are enabled
  135. // rain get the output buffer to save the output in the cache or to return it as string
  136. else{
  137. //----------------------
  138. // get the output buffer
  139. //----------------------
  140. ob_start();
  141. extract( $this->var );
  142. include $this->tpl['compiled_filename'];
  143. $raintpl_contents = ob_get_clean();
  144. //----------------------
  145. // save the output in the cache
  146. if( $this->cache )
  147. file_put_contents( $this->tpl['cache_filename'], "<?php if(!class_exists('raintpl')){exit;}?>" . $raintpl_contents );
  148. // free memory
  149. unset( $this->tpl );
  150. // return or print the template
  151. if( $return_string ) return $raintpl_contents; else echo $raintpl_contents;
  152. }
  153. }
  154. /**
  155. * If exists a valid cache for this template it returns the cache
  156. *
  157. * @param string $tpl_name Name of template (set the same of draw)
  158. * @param int $expiration_time Set after how many seconds the cache expire and must be regenerated
  159. * @return string it return the HTML or null if the cache must be recreated
  160. */
  161. function cache( $tpl_name, $expire_time = self::CACHE_EXPIRE_TIME, $cache_id = null ){
  162. // set the cache_id
  163. $this->cache_id = $cache_id;
  164. if( !$this->check_template( $tpl_name ) && file_exists( $this->tpl['cache_filename'] ) && ( time() - filemtime( $this->tpl['cache_filename'] ) < $expire_time ) )
  165. return substr( file_get_contents( $this->tpl['cache_filename'] ), 43 );
  166. else{
  167. //delete the cache of the selected template
  168. if (file_exists($this->tpl['cache_filename']))
  169. unlink($this->tpl['cache_filename'] );
  170. $this->cache = true;
  171. }
  172. }
  173. /**
  174. * Configure the settings of RainTPL
  175. *
  176. */
  177. public function configure( $setting, $value = null ){
  178. if( is_array( $setting ) )
  179. foreach( $setting as $key => $value )
  180. $this->configure( $key, $value );
  181. else if( property_exists( __CLASS__, $setting ) ){
  182. $this->$setting = $value;
  183. $this->config_name_sum[ $setting ] = $value; // take trace of all config
  184. }
  185. }
  186. // check if has to compile the template
  187. // return true if the template has changed
  188. protected function check_template( $tpl_name ){
  189. if( !isset($this->tpl['checked']) ){
  190. $tpl_basename = basename( $tpl_name ); // template basename
  191. $tpl_basedir = strpos($tpl_name,"/") ? dirname($tpl_name) . '/' : null; // template basedirectory
  192. $tpl_dir = $this->tpl_dir . $tpl_basedir; // template directory
  193. $this->tpl['tpl_filename'] = $tpl_dir . $tpl_basename . '.' . $this->tpl_ext; // template filename
  194. $temp_compiled_filename = $this->cache_dir . $tpl_basename . "." . md5( $tpl_dir . serialize($this->config_name_sum));
  195. $this->tpl['compiled_filename'] = $temp_compiled_filename . '.rtpl.php'; // cache filename
  196. $this->tpl['cache_filename'] = $temp_compiled_filename . '.s_' . $this->cache_id . '.rtpl.php'; // static cache filename
  197. // if the template doesn't exsist throw an error
  198. if( $this->check_template_update && !file_exists( $this->tpl['tpl_filename'] ) ){
  199. $e = new RainTpl_NotFoundException( 'Template '. $tpl_basename .' not found!' );
  200. throw $e->setTemplateFile($this->tpl['tpl_filename']);
  201. }
  202. // file doesn't exsist, or the template was updated, Rain will compile the template
  203. if( !file_exists( $this->tpl['compiled_filename'] ) || ( $this->check_template_update && filemtime($this->tpl['compiled_filename']) < filemtime( $this->tpl['tpl_filename'] ) ) ){
  204. $this->compileFile( $tpl_basename, $tpl_basedir, $this->tpl['tpl_filename'], $this->cache_dir, $this->tpl['compiled_filename'] );
  205. return true;
  206. }
  207. $this->tpl['checked'] = true;
  208. }
  209. }
  210. /**
  211. * execute stripslaches() on the xml block. Invoqued by preg_replace_callback function below
  212. * @access protected
  213. */
  214. protected function xml_reSubstitution($capture) {
  215. return "<?php echo '<?xml ".stripslashes($capture[1])." ?>'; ?>";
  216. }
  217. /**
  218. * Compile and write the compiled template file
  219. * @access protected
  220. */
  221. protected function compileFile( $tpl_basename, $tpl_basedir, $tpl_filename, $cache_dir, $compiled_filename ){
  222. //read template file
  223. $this->tpl['source'] = $template_code = file_get_contents( $tpl_filename );
  224. //xml substitution
  225. $template_code = preg_replace( "/<\?xml(.*?)\?>/s", "##XML\\1XML##", $template_code );
  226. //disable php tag
  227. if( !$this->php_enabled )
  228. $template_code = str_replace( array("<?","?>"), array("&lt;?","?&gt;"), $template_code );
  229. //xml re-substitution
  230. $template_code = preg_replace_callback ( "/##XML(.*?)XML##/s", array($this, 'xml_reSubstitution'), $template_code );
  231. //compile template
  232. $template_compiled = "<?php if(!class_exists('raintpl')){exit;}?>" . $this->compileTemplate( $template_code, $tpl_basedir );
  233. // fix the php-eating-newline-after-closing-tag-problem
  234. $template_compiled = str_replace( "?>\n", "?>\n\n", $template_compiled );
  235. // create directories
  236. if( !is_dir( $cache_dir ) )
  237. mkdir( $cache_dir, 0755, true );
  238. if( !is_writable( $cache_dir ) )
  239. throw new RainTpl_Exception ('Cache directory ' . $cache_dir . 'doesn\'t have write permission. Set write permission or set RAINTPL_CHECK_TEMPLATE_UPDATE to false. More details on http://www.raintpl.com/Documentation/Documentation-for-PHP-developers/Configuration/');
  240. //write compiled file
  241. file_put_contents( $compiled_filename, $template_compiled );
  242. }
  243. /**
  244. * Compile template
  245. * @access protected
  246. */
  247. protected function compileTemplate( $template_code, $tpl_basedir ){
  248. //tag list
  249. $tag_regexp = array( 'loop' => '(\{loop(?: name){0,1}="\${0,1}[^"]*"\})',
  250. 'loop_close' => '(\{\/loop\})',
  251. 'if' => '(\{if(?: condition){0,1}="[^"]*"\})',
  252. 'elseif' => '(\{elseif(?: condition){0,1}="[^"]*"\})',
  253. 'else' => '(\{else\})',
  254. 'if_close' => '(\{\/if\})',
  255. 'function' => '(\{function="[^"]*"\})',
  256. 'noparse' => '(\{noparse\})',
  257. 'noparse_close'=> '(\{\/noparse\})',
  258. 'ignore' => '(\{ignore\}|\{\*)',
  259. 'ignore_close' => '(\{\/ignore\}|\*\})',
  260. 'include' => '(\{include="[^"]*"(?: cache="[^"]*")?\})',
  261. 'template_info'=> '(\{\$template_info\})',
  262. 'function' => '(\{function="(\w*?)(?:.*?)"\})'
  263. );
  264. $tag_regexp = "/" . join( "|", $tag_regexp ) . "/";
  265. //split the code with the tags regexp
  266. $template_code = preg_split ( $tag_regexp, $template_code, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
  267. //path replace (src of img, background and href of link)
  268. $template_code = $this->path_replace( $template_code, $tpl_basedir );
  269. //compile the code
  270. $compiled_code = $this->compileCode( $template_code );
  271. //return the compiled code
  272. return $compiled_code;
  273. }
  274. /**
  275. * Compile the code
  276. * @access protected
  277. */
  278. protected function compileCode( $parsed_code ){
  279. //variables initialization
  280. $compiled_code = $open_if = $comment_is_open = $ignore_is_open = null;
  281. $loop_level = 0;
  282. //read all parsed code
  283. while( $html = array_shift( $parsed_code ) ){
  284. //close ignore tag
  285. if( !$comment_is_open && ( strpos( $html, '{/ignore}' ) !== FALSE || strpos( $html, '*}' ) !== FALSE ) )
  286. $ignore_is_open = false;
  287. //code between tag ignore id deleted
  288. elseif( $ignore_is_open ){
  289. //ignore the code
  290. }
  291. //close no parse tag
  292. elseif( strpos( $html, '{/noparse}' ) !== FALSE )
  293. $comment_is_open = false;
  294. //code between tag noparse is not compiled
  295. elseif( $comment_is_open )
  296. $compiled_code .= $html;
  297. //ignore
  298. elseif( strpos( $html, '{ignore}' ) !== FALSE || strpos( $html, '{*' ) !== FALSE )
  299. $ignore_is_open = true;
  300. //noparse
  301. elseif( strpos( $html, '{noparse}' ) !== FALSE )
  302. $comment_is_open = true;
  303. //include tag
  304. elseif( preg_match( '/\{include="([^"]*)"(?: cache="([^"]*)"){0,1}\}/', $html, $code ) ){
  305. //variables substitution
  306. $include_var = $this->var_replace( $code[ 1 ], $left_delimiter = null, $right_delimiter = null, $php_left_delimiter = '".' , $php_right_delimiter = '."', $loop_level );
  307. // if the cache is active
  308. if( isset($code[ 2 ]) ){
  309. //dynamic include
  310. $compiled_code .= '<?php $tpl = new '.get_class($this).';' .
  311. 'if( $cache = $tpl->cache( $template = basename("'.$include_var.'") ) )' .
  312. ' echo $cache;' .
  313. 'else{' .
  314. ' $tpl_dir_temp = $this->tpl_dir;' .
  315. ' $tpl->assign( $this->var );' .
  316. ( !$loop_level ? null : '$tpl->assign( "key", $key'.$loop_level.' ); $tpl->assign( "value", $value'.$loop_level.' );' ).
  317. ' $tpl->draw( dirname("'.$include_var.'") . ( substr("'.$include_var.'",-1,1) != "/" ? "/" : "" ) . basename("'.$include_var.'") );'.
  318. '} ?>';
  319. }
  320. else{
  321. //dynamic include
  322. $compiled_code .= '<?php $tpl = new '.get_class($this).';' .
  323. '$tpl_dir_temp = $this->tpl_dir;' .
  324. '$tpl->assign( $this->var );' .
  325. ( !$loop_level ? null : '$tpl->assign( "key", $key'.$loop_level.' ); $tpl->assign( "value", $value'.$loop_level.' );' ).
  326. '$tpl->draw( dirname("'.$include_var.'") . ( substr("'.$include_var.'",-1,1) != "/" ? "/" : "" ) . basename("'.$include_var.'") );'.
  327. '?>';
  328. }
  329. }
  330. //loop
  331. elseif( preg_match( '/\{loop(?: name){0,1}="\${0,1}([^"]*)"\}/', $html, $code ) ){
  332. //increase the loop counter
  333. $loop_level++;
  334. //replace the variable in the loop
  335. $var = $this->var_replace( '$' . $code[ 1 ], $tag_left_delimiter=null, $tag_right_delimiter=null, $php_left_delimiter=null, $php_right_delimiter=null, $loop_level-1 );
  336. //loop variables
  337. $counter = "\$counter$loop_level"; // count iteration
  338. $key = "\$key$loop_level"; // key
  339. $value = "\$value$loop_level"; // value
  340. //loop code
  341. $compiled_code .= "<?php $counter=-1; if( isset($var) && is_array($var) && sizeof($var) ) foreach( $var as $key => $value ){ $counter++; ?>";
  342. }
  343. //close loop tag
  344. elseif( strpos( $html, '{/loop}' ) !== FALSE ) {
  345. //iterator
  346. $counter = "\$counter$loop_level";
  347. //decrease the loop counter
  348. $loop_level--;
  349. //close loop code
  350. $compiled_code .= "<?php } ?>";
  351. }
  352. //if
  353. elseif( preg_match( '/\{if(?: condition){0,1}="([^"]*)"\}/', $html, $code ) ){
  354. //increase open if counter (for intendation)
  355. $open_if++;
  356. //tag
  357. $tag = $code[ 0 ];
  358. //condition attribute
  359. $condition = $code[ 1 ];
  360. // check if there's any function disabled by black_list
  361. $this->function_check( $tag );
  362. //variable substitution into condition (no delimiter into the condition)
  363. $parsed_condition = $this->var_replace( $condition, $tag_left_delimiter = null, $tag_right_delimiter = null, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level );
  364. //if code
  365. $compiled_code .= "<?php if( $parsed_condition ){ ?>";
  366. }
  367. //elseif
  368. elseif( preg_match( '/\{elseif(?: condition){0,1}="([^"]*)"\}/', $html, $code ) ){
  369. //tag
  370. $tag = $code[ 0 ];
  371. //condition attribute
  372. $condition = $code[ 1 ];
  373. //variable substitution into condition (no delimiter into the condition)
  374. $parsed_condition = $this->var_replace( $condition, $tag_left_delimiter = null, $tag_right_delimiter = null, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level );
  375. //elseif code
  376. $compiled_code .= "<?php }elseif( $parsed_condition ){ ?>";
  377. }
  378. //else
  379. elseif( strpos( $html, '{else}' ) !== FALSE ) {
  380. //else code
  381. $compiled_code .= '<?php }else{ ?>';
  382. }
  383. //close if tag
  384. elseif( strpos( $html, '{/if}' ) !== FALSE ) {
  385. //decrease if counter
  386. $open_if--;
  387. // close if code
  388. $compiled_code .= '<?php } ?>';
  389. }
  390. //function
  391. elseif( preg_match( '/\{function="(\w*)(.*?)"\}/', $html, $code ) ){
  392. //tag
  393. $tag = $code[ 0 ];
  394. //function
  395. $function = $code[ 1 ];
  396. // check if there's any function disabled by black_list
  397. $this->function_check( $tag );
  398. if( empty( $code[ 2 ] ) )
  399. $parsed_function = $function . "()";
  400. else
  401. // parse the function
  402. $parsed_function = $function . $this->var_replace( $code[ 2 ], $tag_left_delimiter = null, $tag_right_delimiter = null, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level );
  403. //if code
  404. $compiled_code .= "<?php echo $parsed_function; ?>";
  405. }
  406. // show all vars
  407. elseif ( strpos( $html, '{$template_info}' ) !== FALSE ) {
  408. //tag
  409. $tag = '{$template_info}';
  410. //if code
  411. $compiled_code .= '<?php echo "<pre>"; print_r( $this->var ); echo "</pre>"; ?>';
  412. }
  413. //all html code
  414. else{
  415. //variables substitution (es. {$title})
  416. $html = $this->var_replace( $html, $left_delimiter = '\{', $right_delimiter = '\}', $php_left_delimiter = '<?php ', $php_right_delimiter = ';?>', $loop_level, $echo = true );
  417. //const substitution (es. {#CONST#})
  418. $html = $this->const_replace( $html, $left_delimiter = '\{', $right_delimiter = '\}', $php_left_delimiter = '<?php ', $php_right_delimiter = ';?>', $loop_level, $echo = true );
  419. //functions substitution (es. {"string"|functions})
  420. $compiled_code .= $this->func_replace( $html, $left_delimiter = '\{', $right_delimiter = '\}', $php_left_delimiter = '<?php ', $php_right_delimiter = ';?>', $loop_level, $echo = true );
  421. }
  422. }
  423. if( $open_if > 0 ) {
  424. $e = new RainTpl_SyntaxException('Error! You need to close an {if} tag in ' . $this->tpl['tpl_filename'] . ' template');
  425. throw $e->setTemplateFile($this->tpl['tpl_filename']);
  426. }
  427. return $compiled_code;
  428. }
  429. /**
  430. * Reduce a path, eg. www/library/../filepath//file => www/filepath/file
  431. * @param type $path
  432. * @return type
  433. */
  434. protected function reduce_path( $path ){
  435. $path = str_replace( "://", "@not_replace@", $path );
  436. $path = str_replace( "//", "/", $path );
  437. $path = str_replace( "@not_replace@", "://", $path );
  438. return preg_replace('/\w+\/\.\.\//', '', $path );
  439. }
  440. /**
  441. * replace the path of image src, link href and a href.
  442. * url => template_dir/url
  443. * url# => url
  444. * http://url => http://url
  445. *
  446. * @param string $html
  447. * @return string html sostituito
  448. */
  449. protected function path_replace( $html, $tpl_basedir ){
  450. if( $this->path_replace ){
  451. $tpl_dir = $this->base_url . $this->tpl_dir . $tpl_basedir;
  452. // reduce the path
  453. $path = $this->reduce_path($tpl_dir);
  454. $exp = $sub = array();
  455. if( in_array( "img", $this->path_replace_list ) ){
  456. $exp = array( '/<img(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<img(.*?)src=(?:")([^"]+?)#(?:")/i', '/<img(.*?)src="(.*?)"/', '/<img(.*?)src=(?:\@)([^"]+?)(?:\@)/i' );
  457. $sub = array( '<img$1src=@$2://$3@', '<img$1src=@$2@', '<img$1src="' . $path . '$2"', '<img$1src="$2"' );
  458. }
  459. if( in_array( "script", $this->path_replace_list ) ){
  460. $exp = array_merge( $exp , array( '/<script(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<script(.*?)src=(?:")([^"]+?)#(?:")/i', '/<script(.*?)src="(.*?)"/', '/<script(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
  461. $sub = array_merge( $sub , array( '<script$1src=@$2://$3@', '<script$1src=@$2@', '<script$1src="' . $path . '$2"', '<script$1src="$2"' ) );
  462. }
  463. if( in_array( "link", $this->path_replace_list ) ){
  464. $exp = array_merge( $exp , array( '/<link(.*?)href=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<link(.*?)href=(?:")([^"]+?)#(?:")/i', '/<link(.*?)href="(.*?)"/', '/<link(.*?)href=(?:\@)([^"]+?)(?:\@)/i' ) );
  465. $sub = array_merge( $sub , array( '<link$1href=@$2://$3@', '<link$1href=@$2@' , '<link$1href="' . $path . '$2"', '<link$1href="$2"' ) );
  466. }
  467. if( in_array( "a", $this->path_replace_list ) ){
  468. $exp = array_merge( $exp , array( '/<a(.*?)href=(?:")(http\:\/\/|https\:\/\/|javascript:)([^"]+?)(?:")/i', '/<a(.*?)href="(.*?)"/', '/<a(.*?)href=(?:\@)([^"]+?)(?:\@)/i' ) );
  469. $sub = array_merge( $sub , array( '<a$1href=@$2$3@', '<a$1href="' . $this->base_url . '$2"', '<a$1href="$2"' ) );
  470. }
  471. if( in_array( "input", $this->path_replace_list ) ){
  472. $exp = array_merge( $exp , array( '/<input(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<input(.*?)src=(?:")([^"]+?)#(?:")/i', '/<input(.*?)src="(.*?)"/', '/<input(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
  473. $sub = array_merge( $sub , array( '<input$1src=@$2://$3@', '<input$1src=@$2@', '<input$1src="' . $path . '$2"', '<input$1src="$2"' ) );
  474. }
  475. return preg_replace( $exp, $sub, $html );
  476. }
  477. else
  478. return $html;
  479. }
  480. // replace const
  481. function const_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
  482. // const
  483. return preg_replace( '/\{\#(\w+)\#{0,1}\}/', $php_left_delimiter . ( $echo ? " echo " : null ) . '\\1' . $php_right_delimiter, $html );
  484. }
  485. // replace functions/modifiers on constants and strings
  486. function func_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
  487. preg_match_all( '/' . '\{\#{0,1}(\"{0,1}.*?\"{0,1})(\|\w.*?)\#{0,1}\}' . '/', $html, $matches );
  488. for( $i=0, $n=count($matches[0]); $i<$n; $i++ ){
  489. //complete tag ex: {$news.title|substr:0,100}
  490. $tag = $matches[ 0 ][ $i ];
  491. //variable name ex: news.title
  492. $var = $matches[ 1 ][ $i ];
  493. //function and parameters associate to the variable ex: substr:0,100
  494. $extra_var = $matches[ 2 ][ $i ];
  495. // check if there's any function disabled by black_list
  496. $this->function_check( $tag );
  497. $extra_var = $this->var_replace( $extra_var, null, null, null, null, $loop_level );
  498. // check if there's an operator = in the variable tags, if there's this is an initialization so it will not output any value
  499. $is_init_variable = preg_match( "/^(\s*?)\=[^=](.*?)$/", $extra_var );
  500. //function associate to variable
  501. $function_var = ( $extra_var and $extra_var[0] == '|') ? substr( $extra_var, 1 ) : null;
  502. //variable path split array (ex. $news.title o $news[title]) or object (ex. $news->title)
  503. $temp = preg_split( "/\.|\[|\-\>/", $var );
  504. //variable name
  505. $var_name = $temp[ 0 ];
  506. //variable path
  507. $variable_path = substr( $var, strlen( $var_name ) );
  508. //parentesis transform [ e ] in [" e in "]
  509. $variable_path = str_replace( '[', '["', $variable_path );
  510. $variable_path = str_replace( ']', '"]', $variable_path );
  511. //transform .$variable in ["$variable"]
  512. $variable_path = preg_replace('/\.\$(\w+)/', '["$\\1"]', $variable_path );
  513. //transform [variable] in ["variable"]
  514. $variable_path = preg_replace('/\.(\w+)/', '["\\1"]', $variable_path );
  515. //if there's a function
  516. if( $function_var ){
  517. // check if there's a function or a static method and separate, function by parameters
  518. $function_var = str_replace("::", "@double_dot@", $function_var );
  519. // get the position of the first :
  520. if( $dot_position = strpos( $function_var, ":" ) ){
  521. // get the function and the parameters
  522. $function = substr( $function_var, 0, $dot_position );
  523. $params = substr( $function_var, $dot_position+1 );
  524. }
  525. else{
  526. //get the function
  527. $function = str_replace( "@double_dot@", "::", $function_var );
  528. $params = null;
  529. }
  530. // replace back the @double_dot@ with ::
  531. $function = str_replace( "@double_dot@", "::", $function );
  532. $params = str_replace( "@double_dot@", "::", $params );
  533. }
  534. else
  535. $function = $params = null;
  536. $php_var = $var_name . $variable_path;
  537. // compile the variable for php
  538. if( isset( $function ) ){
  539. if( $php_var )
  540. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $php_var, $params ) )" : "$function( $php_var )" ) . $php_right_delimiter;
  541. else
  542. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $params ) )" : "$function()" ) . $php_right_delimiter;
  543. }
  544. else
  545. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . $php_var . $extra_var . $php_right_delimiter;
  546. $html = str_replace( $tag, $php_var, $html );
  547. }
  548. return $html;
  549. }
  550. function var_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
  551. //all variables
  552. if( preg_match_all( '/' . $tag_left_delimiter . '\$(\w+(?:\.\${0,1}[A-Za-z0-9_]+)*(?:(?:\[\${0,1}[A-Za-z0-9_]+\])|(?:\-\>\${0,1}[A-Za-z0-9_]+))*)(.*?)' . $tag_right_delimiter . '/', $html, $matches ) ){
  553. for( $parsed=array(), $i=0, $n=count($matches[0]); $i<$n; $i++ )
  554. $parsed[$matches[0][$i]] = array('var'=>$matches[1][$i],'extra_var'=>$matches[2][$i]);
  555. foreach( $parsed as $tag => $array ){
  556. //variable name ex: news.title
  557. $var = $array['var'];
  558. //function and parameters associate to the variable ex: substr:0,100
  559. $extra_var = $array['extra_var'];
  560. // check if there's any function disabled by black_list
  561. $this->function_check( $tag );
  562. $extra_var = $this->var_replace( $extra_var, null, null, null, null, $loop_level );
  563. // check if there's an operator = in the variable tags, if there's this is an initialization so it will not output any value
  564. $is_init_variable = preg_match( "/^[a-z_A-Z\.\[\](\-\>)]*=[^=]*$/", $extra_var );
  565. //function associate to variable
  566. $function_var = ( $extra_var and $extra_var[0] == '|') ? substr( $extra_var, 1 ) : null;
  567. //variable path split array (ex. $news.title o $news[title]) or object (ex. $news->title)
  568. $temp = preg_split( "/\.|\[|\-\>/", $var );
  569. //variable name
  570. $var_name = $temp[ 0 ];
  571. //variable path
  572. $variable_path = substr( $var, strlen( $var_name ) );
  573. //parentesis transform [ e ] in [" e in "]
  574. $variable_path = str_replace( '[', '["', $variable_path );
  575. $variable_path = str_replace( ']', '"]', $variable_path );
  576. //transform .$variable in ["$variable"] and .variable in ["variable"]
  577. $variable_path = preg_replace('/\.(\${0,1}\w+)/', '["\\1"]', $variable_path );
  578. // if is an assignment also assign the variable to $this->var['value']
  579. if( $is_init_variable )
  580. $extra_var = "=\$this->var['{$var_name}']{$variable_path}" . $extra_var;
  581. //if there's a function
  582. if( $function_var ){
  583. // check if there's a function or a static method and separate, function by parameters
  584. $function_var = str_replace("::", "@double_dot@", $function_var );
  585. // get the position of the first :
  586. if( $dot_position = strpos( $function_var, ":" ) ){
  587. // get the function and the parameters
  588. $function = substr( $function_var, 0, $dot_position );
  589. $params = substr( $function_var, $dot_position+1 );
  590. }
  591. else{
  592. //get the function
  593. $function = str_replace( "@double_dot@", "::", $function_var );
  594. $params = null;
  595. }
  596. // replace back the @double_dot@ with ::
  597. $function = str_replace( "@double_dot@", "::", $function );
  598. $params = str_replace( "@double_dot@", "::", $params );
  599. }
  600. else
  601. $function = $params = null;
  602. //if it is inside a loop
  603. if( $loop_level ){
  604. //verify the variable name
  605. if( $var_name == 'key' )
  606. $php_var = '$key' . $loop_level;
  607. elseif( $var_name == 'value' )
  608. $php_var = '$value' . $loop_level . $variable_path;
  609. elseif( $var_name == 'counter' )
  610. $php_var = '$counter' . $loop_level;
  611. else
  612. $php_var = '$' . $var_name . $variable_path;
  613. }else
  614. $php_var = '$' . $var_name . $variable_path;
  615. // compile the variable for php
  616. if( isset( $function ) )
  617. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $php_var, $params ) )" : "$function( $php_var )" ) . $php_right_delimiter;
  618. else
  619. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . $php_var . $extra_var . $php_right_delimiter;
  620. $html = str_replace( $tag, $php_var, $html );
  621. }
  622. }
  623. return $html;
  624. }
  625. /**
  626. * Check if function is in black list (sandbox)
  627. *
  628. * @param string $code
  629. * @param string $tag
  630. */
  631. protected function function_check( $code ){
  632. $preg = '#(\W|\s)' . implode( '(\W|\s)|(\W|\s)', $this->black_list ) . '(\W|\s)#';
  633. // check if the function is in the black list (or not in white list)
  634. if( count($this->black_list) && preg_match( $preg, $code, $match ) ){
  635. // find the line of the error
  636. $line = 0;
  637. $rows=explode("\n",$this->tpl['source']);
  638. while( !strpos($rows[$line],$code) )
  639. $line++;
  640. // stop the execution of the script
  641. $e = new RainTpl_SyntaxException('Unallowed syntax in ' . $this->tpl['tpl_filename'] . ' template');
  642. throw $e->setTemplateFile($this->tpl['tpl_filename'])
  643. ->setTag($code)
  644. ->setTemplateLine($line);
  645. }
  646. }
  647. /**
  648. * Prints debug info about exception or passes it further if debug is disabled.
  649. *
  650. * @param RainTpl_Exception $e
  651. * @return string
  652. */
  653. protected function printDebug(RainTpl_Exception $e){
  654. if (!$this->debug) {
  655. throw $e;
  656. }
  657. $output = sprintf('<h2>Exception: %s</h2><h3>%s</h3><p>template: %s</p>',
  658. get_class($e),
  659. $e->getMessage(),
  660. $e->getTemplateFile()
  661. );
  662. if ($e instanceof RainTpl_SyntaxException) {
  663. if (null != $e->getTemplateLine()) {
  664. $output .= '<p>line: ' . $e->getTemplateLine() . '</p>';
  665. }
  666. if (null != $e->getTag()) {
  667. $output .= '<p>in tag: ' . htmlspecialchars($e->getTag()) . '</p>';
  668. }
  669. if (null != $e->getTemplateLine() && null != $e->getTag()) {
  670. $rows=explode("\n", htmlspecialchars($this->tpl['source']));
  671. $rows[$e->getTemplateLine()] = '<font color=red>' . $rows[$e->getTemplateLine()] . '</font>';
  672. $output .= '<h3>template code</h3>' . implode('<br />', $rows) . '</pre>';
  673. }
  674. }
  675. $output .= sprintf('<h3>trace</h3><p>In %s on line %d</p><pre>%s</pre>',
  676. $e->getFile(), $e->getLine(),
  677. nl2br(htmlspecialchars($e->getTraceAsString()))
  678. );
  679. return $output;
  680. }
  681. }
  682. /**
  683. * Basic Rain tpl exception.
  684. */
  685. class RainTpl_Exception extends \Exception{
  686. /**
  687. * Path of template file with error.
  688. */
  689. protected $templateFile = '';
  690. /**
  691. * Returns path of template file with error.
  692. *
  693. * @return string
  694. */
  695. public function getTemplateFile()
  696. {
  697. return $this->templateFile;
  698. }
  699. /**
  700. * Sets path of template file with error.
  701. *
  702. * @param string $templateFile
  703. * @return RainTpl_Exception
  704. */
  705. public function setTemplateFile($templateFile)
  706. {
  707. $this->templateFile = (string) $templateFile;
  708. return $this;
  709. }
  710. }
  711. /**
  712. * Exception thrown when template file does not exists.
  713. */
  714. class RainTpl_NotFoundException extends RainTpl_Exception{
  715. }
  716. /**
  717. * Exception thrown when syntax error occurs.
  718. */
  719. class RainTpl_SyntaxException extends RainTpl_Exception{
  720. /**
  721. * Line in template file where error has occured.
  722. *
  723. * @var int | null
  724. */
  725. protected $templateLine = null;
  726. /**
  727. * Tag which caused an error.
  728. *
  729. * @var string | null
  730. */
  731. protected $tag = null;
  732. /**
  733. * Returns line in template file where error has occured
  734. * or null if line is not defined.
  735. *
  736. * @return int | null
  737. */
  738. public function getTemplateLine()
  739. {
  740. return $this->templateLine;
  741. }
  742. /**
  743. * Sets line in template file where error has occured.
  744. *
  745. * @param int $templateLine
  746. * @return RainTpl_SyntaxException
  747. */
  748. public function setTemplateLine($templateLine)
  749. {
  750. $this->templateLine = (int) $templateLine;
  751. return $this;
  752. }
  753. /**
  754. * Returns tag which caused an error.
  755. *
  756. * @return string
  757. */
  758. public function getTag()
  759. {
  760. return $this->tag;
  761. }
  762. /**
  763. * Sets tag which caused an error.
  764. *
  765. * @param string $tag
  766. * @return RainTpl_SyntaxException
  767. */
  768. public function setTag($tag)
  769. {
  770. $this->tag = (string) $tag;
  771. return $this;
  772. }
  773. }
  774. // -- end