rain.tpl.class.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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
  9. */
  10. class RainTPL{
  11. // -------------------------
  12. // CONFIGURATION
  13. // -------------------------
  14. /**
  15. * Template directory
  16. *
  17. * @var string
  18. */
  19. static $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. static $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. static $base_url = null;
  32. /**
  33. * Template extension.
  34. *
  35. * @var string
  36. */
  37. static $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. static $path_replace = true;
  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. static $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. static $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. static $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. static $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. static $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 static $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. static function configure( $setting, $value = null ){
  178. if( is_array( $setting ) )
  179. foreach( $setting as $key => $value )
  180. self::configure( $key, $value );
  181. else if( property_exists( __CLASS__, $setting ) ){
  182. self::$$setting = $value;
  183. self::$config_name_sum[$key] = $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 = self::$tpl_dir . $tpl_basedir; // template directory
  193. $this->tpl['tpl_filename'] = $tpl_dir . $tpl_basename . '.' . self::$tpl_ext; // template filename
  194. $temp_compiled_filename = self::$cache_dir . $tpl_basename . "." . md5( $tpl_dir . implode('', self::$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( self::$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'] ) || ( self::$check_template_update && filemtime($this->tpl['compiled_filename']) < filemtime( $this->tpl['tpl_filename'] ) ) ){
  204. $this->compileFile( $tpl_basename, $tpl_basedir, $this->tpl['tpl_filename'], self::$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( !self::$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 )
  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 )
  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 RainTpl;' .
  311. 'if( $cache = $tpl->cache( $template = basename("'.$include_var.'") ) )' .
  312. ' echo $cache;' .
  313. 'else{' .
  314. ' $tpl_dir_temp = self::$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 RainTpl;' .
  323. '$tpl_dir_temp = self::$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. protected function reduce_path( $path ){
  430. $path = str_replace( "//", "/", $path );
  431. return preg_replace('/\w+\/\.\.\//', '', $path );
  432. }
  433. /**
  434. * replace the path of image src, link href and a href.
  435. * url => template_dir/url
  436. * url# => url
  437. * http://url => http://url
  438. *
  439. * @param string $html
  440. * @return string html sostituito
  441. */
  442. protected function path_replace( $html, $tpl_basedir ){
  443. if( self::$path_replace ){
  444. $tpl_dir = self::$base_url . self::$tpl_dir . $tpl_basedir;
  445. // reduce the path
  446. $path = $this->reduce_path($tpl_dir);
  447. $exp = $sub = array();
  448. if( in_array( "img", self::$path_replace_list ) ){
  449. $exp = array( '/<img(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<img(.*?)src=(?:")([^"]+?)#(?:")/i', '/<img(.*?)src="(.*?)"/', '/<img(.*?)src=(?:\@)([^"]+?)(?:\@)/i' );
  450. $sub = array( '<img$1src=@$2://$3@', '<img$1src=@$2@', '<img$1src="' . $path . '$2"', '<img$1src="$2"' );
  451. }
  452. if( in_array( "script", self::$path_replace_list ) ){
  453. $exp = array_merge( $exp , array( '/<script(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<script(.*?)src=(?:")([^"]+?)#(?:")/i', '/<script(.*?)src="(.*?)"/', '/<script(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
  454. $sub = array_merge( $sub , array( '<script$1src=@$2://$3@', '<script$1src=@$2@', '<script$1src="' . $path . '$2"', '<script$1src="$2"' ) );
  455. }
  456. if( in_array( "link", self::$path_replace_list ) ){
  457. $exp = array_merge( $exp , array( '/<link(.*?)href=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<link(.*?)href=(?:")([^"]+?)#(?:")/i', '/<link(.*?)href="(.*?)"/', '/<link(.*?)href=(?:\@)([^"]+?)(?:\@)/i' ) );
  458. $sub = array_merge( $sub , array( '<link$1href=@$2://$3@', '<link$1href=@$2@' , '<link$1href="' . $path . '$2"', '<link$1href="$2"' ) );
  459. }
  460. if( in_array( "a", self::$path_replace_list ) ){
  461. $exp = array_merge( $exp , array( '/<a(.*?)href=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<a(.*?)href="(.*?)"/', '/<a(.*?)href=(?:\@)([^"]+?)(?:\@)/i' ) );
  462. $sub = array_merge( $sub , array( '<a$1href=@$2://$3@', '<a$1href="' . self::$base_url . '$2"', '<a$1href="$2"' ) );
  463. }
  464. if( in_array( "input", self::$path_replace_list ) ){
  465. $exp = array_merge( $exp , array( '/<input(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<input(.*?)src=(?:")([^"]+?)#(?:")/i', '/<input(.*?)src="(.*?)"/', '/<input(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
  466. $sub = array_merge( $sub , array( '<input$1src=@$2://$3@', '<input$1src=@$2@', '<input$1src="' . $path . '$2"', '<input$1src="$2"' ) );
  467. }
  468. return preg_replace( $exp, $sub, $html );
  469. }
  470. else
  471. return $html;
  472. }
  473. // replace const
  474. function const_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
  475. // const
  476. return preg_replace( '/\{\#(\w+)\#{0,1}\}/', $php_left_delimiter . ( $echo ? " echo " : null ) . '\\1' . $php_right_delimiter, $html );
  477. }
  478. // replace functions/modifiers on constants and strings
  479. function func_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
  480. preg_match_all( '/' . '\{\#{0,1}(\"{0,1}.*?\"{0,1})(\|\w.*?)\#{0,1}\}' . '/', $html, $matches );
  481. for( $i=0, $n=count($matches[0]); $i<$n; $i++ ){
  482. //complete tag ex: {$news.title|substr:0,100}
  483. $tag = $matches[ 0 ][ $i ];
  484. //variable name ex: news.title
  485. $var = $matches[ 1 ][ $i ];
  486. //function and parameters associate to the variable ex: substr:0,100
  487. $extra_var = $matches[ 2 ][ $i ];
  488. // check if there's any function disabled by black_list
  489. $this->function_check( $tag );
  490. $extra_var = $this->var_replace( $extra_var, null, null, null, null, $loop_level );
  491. // check if there's an operator = in the variable tags, if there's this is an initialization so it will not output any value
  492. $is_init_variable = preg_match( "/^(\s*?)\=[^=](.*?)$/", $extra_var );
  493. //function associate to variable
  494. $function_var = ( $extra_var and $extra_var[0] == '|') ? substr( $extra_var, 1 ) : null;
  495. //variable path split array (ex. $news.title o $news[title]) or object (ex. $news->title)
  496. $temp = preg_split( "/\.|\[|\-\>/", $var );
  497. //variable name
  498. $var_name = $temp[ 0 ];
  499. //variable path
  500. $variable_path = substr( $var, strlen( $var_name ) );
  501. //parentesis transform [ e ] in [" e in "]
  502. $variable_path = str_replace( '[', '["', $variable_path );
  503. $variable_path = str_replace( ']', '"]', $variable_path );
  504. //transform .$variable in ["$variable"]
  505. $variable_path = preg_replace('/\.\$(\w+)/', '["$\\1"]', $variable_path );
  506. //transform [variable] in ["variable"]
  507. $variable_path = preg_replace('/\.(\w+)/', '["\\1"]', $variable_path );
  508. //if there's a function
  509. if( $function_var ){
  510. // check if there's a function or a static method and separate, function by parameters
  511. $function_var = str_replace("::", "@double_dot@", $function_var );
  512. // get the position of the first :
  513. if( $dot_position = strpos( $function_var, ":" ) ){
  514. // get the function and the parameters
  515. $function = substr( $function_var, 0, $dot_position );
  516. $params = substr( $function_var, $dot_position+1 );
  517. }
  518. else{
  519. //get the function
  520. $function = str_replace( "@double_dot@", "::", $function_var );
  521. $params = null;
  522. }
  523. // replace back the @double_dot@ with ::
  524. $function = str_replace( "@double_dot@", "::", $function );
  525. $params = str_replace( "@double_dot@", "::", $params );
  526. }
  527. else
  528. $function = $params = null;
  529. $php_var = $var_name . $variable_path;
  530. // compile the variable for php
  531. if( isset( $function ) ){
  532. if( $php_var )
  533. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $php_var, $params ) )" : "$function( $php_var )" ) . $php_right_delimiter;
  534. else
  535. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $params ) )" : "$function()" ) . $php_right_delimiter;
  536. }
  537. else
  538. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . $php_var . $extra_var . $php_right_delimiter;
  539. $html = str_replace( $tag, $php_var, $html );
  540. }
  541. return $html;
  542. }
  543. function var_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
  544. //all variables
  545. 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 ) ){
  546. for( $parsed=array(), $i=0, $n=count($matches[0]); $i<$n; $i++ )
  547. $parsed[$matches[0][$i]] = array('var'=>$matches[1][$i],'extra_var'=>$matches[2][$i]);
  548. foreach( $parsed as $tag => $array ){
  549. //variable name ex: news.title
  550. $var = $array['var'];
  551. //function and parameters associate to the variable ex: substr:0,100
  552. $extra_var = $array['extra_var'];
  553. // check if there's any function disabled by black_list
  554. $this->function_check( $tag );
  555. $extra_var = $this->var_replace( $extra_var, null, null, null, null, $loop_level );
  556. // check if there's an operator = in the variable tags, if there's this is an initialization so it will not output any value
  557. $is_init_variable = preg_match( "/^[a-z_A-Z\.\[\](\-\>)]*=[^=]*$/", $extra_var );
  558. //function associate to variable
  559. $function_var = ( $extra_var and $extra_var[0] == '|') ? substr( $extra_var, 1 ) : null;
  560. //variable path split array (ex. $news.title o $news[title]) or object (ex. $news->title)
  561. $temp = preg_split( "/\.|\[|\-\>/", $var );
  562. //variable name
  563. $var_name = $temp[ 0 ];
  564. //variable path
  565. $variable_path = substr( $var, strlen( $var_name ) );
  566. //parentesis transform [ e ] in [" e in "]
  567. $variable_path = str_replace( '[', '["', $variable_path );
  568. $variable_path = str_replace( ']', '"]', $variable_path );
  569. //transform .$variable in ["$variable"] and .variable in ["variable"]
  570. $variable_path = preg_replace('/\.(\${0,1}\w+)/', '["\\1"]', $variable_path );
  571. // if is an assignment also assign the variable to $this->var['value']
  572. if( $is_init_variable )
  573. $extra_var = "=\$this->var['{$var_name}']{$variable_path}" . $extra_var;
  574. //if there's a function
  575. if( $function_var ){
  576. // check if there's a function or a static method and separate, function by parameters
  577. $function_var = str_replace("::", "@double_dot@", $function_var );
  578. // get the position of the first :
  579. if( $dot_position = strpos( $function_var, ":" ) ){
  580. // get the function and the parameters
  581. $function = substr( $function_var, 0, $dot_position );
  582. $params = substr( $function_var, $dot_position+1 );
  583. }
  584. else{
  585. //get the function
  586. $function = str_replace( "@double_dot@", "::", $function_var );
  587. $params = null;
  588. }
  589. // replace back the @double_dot@ with ::
  590. $function = str_replace( "@double_dot@", "::", $function );
  591. $params = str_replace( "@double_dot@", "::", $params );
  592. }
  593. else
  594. $function = $params = null;
  595. //if it is inside a loop
  596. if( $loop_level ){
  597. //verify the variable name
  598. if( $var_name == 'key' )
  599. $php_var = '$key' . $loop_level;
  600. elseif( $var_name == 'value' )
  601. $php_var = '$value' . $loop_level . $variable_path;
  602. elseif( $var_name == 'counter' )
  603. $php_var = '$counter' . $loop_level;
  604. else
  605. $php_var = '$' . $var_name . $variable_path;
  606. }else
  607. $php_var = '$' . $var_name . $variable_path;
  608. // compile the variable for php
  609. if( isset( $function ) )
  610. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $php_var, $params ) )" : "$function( $php_var )" ) . $php_right_delimiter;
  611. else
  612. $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . $php_var . $extra_var . $php_right_delimiter;
  613. $html = str_replace( $tag, $php_var, $html );
  614. }
  615. }
  616. return $html;
  617. }
  618. /**
  619. * Check if function is in black list (sandbox)
  620. *
  621. * @param string $code
  622. * @param string $tag
  623. */
  624. protected function function_check( $code ){
  625. $preg = '#(\W|\s)' . implode( '(\W|\s)|(\W|\s)', self::$black_list ) . '(\W|\s)#';
  626. // check if the function is in the black list (or not in white list)
  627. if( count(self::$black_list) && preg_match( $preg, $code, $match ) ){
  628. // find the line of the error
  629. $line = 0;
  630. $rows=explode("\n",$this->tpl['source']);
  631. while( !strpos($rows[$line],$code) )
  632. $line++;
  633. // stop the execution of the script
  634. $e = new RainTpl_SyntaxException('Unallowed syntax in ' . $this->tpl['tpl_filename'] . ' template');
  635. throw $e->setTemplateFile($this->tpl['tpl_filename'])
  636. ->setTag($code)
  637. ->setTemplateLine($line);
  638. }
  639. }
  640. /**
  641. * Prints debug info about exception or passes it further if debug is disabled.
  642. *
  643. * @param RainTpl_Exception $e
  644. * @return string
  645. */
  646. protected function printDebug(RainTpl_Exception $e){
  647. if (!self::$debug) {
  648. throw $e;
  649. }
  650. $output = sprintf('<h2>Exception: %s</h2><h3>%s</h3><p>template: %s</p>',
  651. get_class($e),
  652. $e->getMessage(),
  653. $e->getTemplateFile()
  654. );
  655. if ($e instanceof RainTpl_SyntaxException) {
  656. if (null != $e->getTemplateLine()) {
  657. $output .= '<p>line: ' . $e->getTemplateLine() . '</p>';
  658. }
  659. if (null != $e->getTag()) {
  660. $output .= '<p>in tag: ' . htmlspecialchars($e->getTag()) . '</p>';
  661. }
  662. if (null != $e->getTemplateLine() && null != $e->getTag()) {
  663. $rows=explode("\n", htmlspecialchars($this->tpl['source']));
  664. $rows[$e->getTemplateLine()] = '<font color=red>' . $rows[$e->getTemplateLine()] . '</font>';
  665. $output .= '<h3>template code</h3>' . implode('<br />', $rows) . '</pre>';
  666. }
  667. }
  668. $output .= sprintf('<h3>trace</h3><p>In %s on line %d</p><pre>%s</pre>',
  669. $e->getFile(), $e->getLine(),
  670. nl2br(htmlspecialchars($e->getTraceAsString()))
  671. );
  672. return $output;
  673. }
  674. }
  675. /**
  676. * Basic Rain tpl exception.
  677. */
  678. class RainTpl_Exception extends Exception{
  679. /**
  680. * Path of template file with error.
  681. */
  682. protected $templateFile = '';
  683. /**
  684. * Returns path of template file with error.
  685. *
  686. * @return string
  687. */
  688. public function getTemplateFile()
  689. {
  690. return $this->templateFile;
  691. }
  692. /**
  693. * Sets path of template file with error.
  694. *
  695. * @param string $templateFile
  696. * @return RainTpl_Exception
  697. */
  698. public function setTemplateFile($templateFile)
  699. {
  700. $this->templateFile = (string) $templateFile;
  701. return $this;
  702. }
  703. }
  704. /**
  705. * Exception thrown when template file does not exists.
  706. */
  707. class RainTpl_NotFoundException extends RainTpl_Exception{
  708. }
  709. /**
  710. * Exception thrown when syntax error occurs.
  711. */
  712. class RainTpl_SyntaxException extends RainTpl_Exception{
  713. /**
  714. * Line in template file where error has occured.
  715. *
  716. * @var int | null
  717. */
  718. protected $templateLine = null;
  719. /**
  720. * Tag which caused an error.
  721. *
  722. * @var string | null
  723. */
  724. protected $tag = null;
  725. /**
  726. * Returns line in template file where error has occured
  727. * or null if line is not defined.
  728. *
  729. * @return int | null
  730. */
  731. public function getTemplateLine()
  732. {
  733. return $this->templateLine;
  734. }
  735. /**
  736. * Sets line in template file where error has occured.
  737. *
  738. * @param int $templateLine
  739. * @return RainTpl_SyntaxException
  740. */
  741. public function setTemplateLine($templateLine)
  742. {
  743. $this->templateLine = (int) $templateLine;
  744. return $this;
  745. }
  746. /**
  747. * Returns tag which caused an error.
  748. *
  749. * @return string
  750. */
  751. public function getTag()
  752. {
  753. return $this->tag;
  754. }
  755. /**
  756. * Sets tag which caused an error.
  757. *
  758. * @param string $tag
  759. * @return RainTpl_SyntaxException
  760. */
  761. public function setTag($tag)
  762. {
  763. $this->tag = (string) $tag;
  764. return $this;
  765. }
  766. }
  767. // -- end