6 * Realized by Federico Ulfo & maintained by the Rain Team
7 * Distributed under GNU/LGPL 3 License
15 // -------------------------
17 // -------------------------
24 static $tpl_dir = "tpl/";
28 * Cache directory. Is the directory where RainTPL will compile the template and save the cache
32 static $cache_dir = "tmp/";
36 * Template base URL. RainTPL will add this URL to the relative paths of element selected in $path_replace_list.
40 static $base_url = null;
48 static $tpl_ext = "html";
52 * 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="...">)
53 * Set true to enable the path replace.
57 static $path_replace = true;
61 * You can set what the path_replace method will replace.
62 * Avaible options: a, img, link, script, input
66 static $path_replace_list = array( 'a', 'img', 'link', 'script', 'input' );
70 * You can define in the black list what string are disabled into the template tags
74 static $black_list = array( '\$this', 'raintpl::', 'self::', '_SESSION', '_SERVER', '_ENV', 'eval', 'exec', 'unlink', 'rmdir' );
79 * true: checks template update time, if changed it compile them
80 * false: loads the compiled template. Set false if server doesn't have write permission for cache_directory.
83 static $check_template_update = true;
88 * True: php tags are enabled into the template
89 * False: php tags are disabled into the template and rendered as html
93 static $php_enabled = false;
98 * True: debug mode is used, syntax errors are displayed directly in template. Execution of script is not terminated.
99 * False: exception is thrown on found error.
103 static $debug = false;
105 // -------------------------
108 // -------------------------
110 // -------------------------
113 * Is the array where RainTPL keep the variables assigned
117 public $var = array();
119 protected $tpl = array(), // variables to keep the template directories and info
120 $cache = false, // static cache enabled / disabled
121 $cache_id = null; // identify only one cache
123 protected static $config_name_sum = array(); // takes all the config to create the md5 of the file
125 // -------------------------
129 const CACHE_EXPIRE_TIME
= 3600; // default cache expire time = hour
135 * eg. $t->assign('name','mickey');
137 * @param mixed $variable_name Name of template variable or associative array name/value
138 * @param mixed $value value assigned to this variable. Not set if variable_name is an associative array
141 function assign( $variable, $value = null ){
142 if( is_array( $variable ) )
143 $this->var +
= $variable;
145 $this->var[ $variable ] = $value;
152 * eg. $html = $tpl->draw( 'demo', TRUE ); // return template in string
153 * or $tpl->draw( $tpl_name ); // echo the template
155 * @param string $tpl_name template to load
156 * @param boolean $return_string true=return a string, false=echo the template
160 function draw( $tpl_name, $return_string = false ){
163 // compile the template if necessary and set the template filepath
164 $this->check_template( $tpl_name );
165 } catch (RainTpl_Exception
$e) {
166 $output = $this->printDebug($e);
170 // Cache is off and, return_string is false
171 // Rain just echo the template
173 if( !$this->cache
&& !$return_string ){
174 extract( $this->var );
175 include $this->tpl
['compiled_filename'];
180 // cache or return_string are enabled
181 // rain get the output buffer to save the output in the cache or to return it as string
185 //----------------------
186 // get the output buffer
187 //----------------------
189 extract( $this->var );
190 include $this->tpl
['compiled_filename'];
191 $raintpl_contents = ob_get_clean();
192 //----------------------
195 // save the output in the cache
197 file_put_contents( $this->tpl
['cache_filename'], "<?php if(!class_exists('raintpl')){exit;}?>" . $raintpl_contents );
202 // return or print the template
203 if( $return_string ) return $raintpl_contents; else echo $raintpl_contents;
212 * If exists a valid cache for this template it returns the cache
214 * @param string $tpl_name Name of template (set the same of draw)
215 * @param int $expiration_time Set after how many seconds the cache expire and must be regenerated
216 * @return string it return the HTML or null if the cache must be recreated
219 function cache( $tpl_name, $expire_time = self
::CACHE_EXPIRE_TIME
, $cache_id = null ){
222 $this->cache_id
= $cache_id;
224 if( !$this->check_template( $tpl_name ) && file_exists( $this->tpl
['cache_filename'] ) && ( time() - filemtime( $this->tpl
['cache_filename'] ) < $expire_time ) )
225 return substr( file_get_contents( $this->tpl
['cache_filename'] ), 43 );
227 //delete the cache of the selected template
228 if (file_exists($this->tpl
['cache_filename']))
229 unlink($this->tpl
['cache_filename'] );
237 * Configure the settings of RainTPL
240 static function configure( $setting, $value = null ){
241 if( is_array( $setting ) )
242 foreach( $setting as $key => $value )
243 self
::configure( $key, $value );
244 else if( property_exists( __CLASS__
, $setting ) ){
245 self
::$
$setting = $value;
246 self
::$config_name_sum[$key] = $value; // take trace of all config
252 // check if has to compile the template
253 // return true if the template has changed
254 protected function check_template( $tpl_name ){
256 if( !isset($this->tpl
['checked']) ){
258 $tpl_basename = basename( $tpl_name ); // template basename
259 $tpl_basedir = strpos($tpl_name,"/") ? dirname($tpl_name) . '/' : null; // template basedirectory
260 $tpl_dir = self
::$tpl_dir . $tpl_basedir; // template directory
261 $this->tpl
['tpl_filename'] = $tpl_dir . $tpl_basename . '.' . self
::$tpl_ext; // template filename
262 $temp_compiled_filename = self
::$cache_dir . $tpl_basename . "." . md5( $tpl_dir . implode('', self
::$config_name_sum));
263 $this->tpl
['compiled_filename'] = $temp_compiled_filename . '.rtpl.php'; // cache filename
264 $this->tpl
['cache_filename'] = $temp_compiled_filename . '.s_' . $this->cache_id
. '.rtpl.php'; // static cache filename
266 // if the template doesn't exsist throw an error
267 if( self
::$check_template_update && !file_exists( $this->tpl
['tpl_filename'] ) ){
268 $e = new RainTpl_NotFoundException( 'Template '. $tpl_basename .' not found!' );
269 throw $e->setTemplateFile($this->tpl
['tpl_filename']);
272 // file doesn't exsist, or the template was updated, Rain will compile the template
273 if( !file_exists( $this->tpl
['compiled_filename'] ) || ( self
::$check_template_update && filemtime($this->tpl
['compiled_filename']) < filemtime( $this->tpl
['tpl_filename'] ) ) ){
274 $this->compileFile( $tpl_basename, $tpl_basedir, $this->tpl
['tpl_filename'], self
::$cache_dir, $this->tpl
['compiled_filename'] );
277 $this->tpl
['checked'] = true;
283 * execute stripslaches() on the xml block. Invoqued by preg_replace_callback function below
286 protected function xml_reSubstitution($capture) {
287 return "<?php echo '<?xml ".stripslashes($capture[1])." ?>'; ?>";
291 * Compile and write the compiled template file
294 protected function compileFile( $tpl_basename, $tpl_basedir, $tpl_filename, $cache_dir, $compiled_filename ){
297 $this->tpl
['source'] = $template_code = file_get_contents( $tpl_filename );
300 $template_code = preg_replace( "/<\?xml(.*?)\?>/s", "##XML\\1XML##", $template_code );
303 if( !self
::$php_enabled )
304 $template_code = str_replace( array("<?","?>"), array("<?","?>"), $template_code );
306 //xml re-substitution
307 $template_code = preg_replace_callback ( "/##XML(.*?)XML##/s", array($this, 'xml_reSubstitution'), $template_code );
310 $template_compiled = "<?php if(!class_exists('raintpl')){exit;}?>" . $this->compileTemplate( $template_code, $tpl_basedir );
313 // fix the php-eating-newline-after-closing-tag-problem
314 $template_compiled = str_replace( "?>\n", "?>\n\n", $template_compiled );
316 // create directories
317 if( !is_dir( $cache_dir ) )
318 mkdir( $cache_dir, 0755, true );
320 if( !is_writable( $cache_dir ) )
321 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/');
323 //write compiled file
324 file_put_contents( $compiled_filename, $template_compiled );
333 protected function compileTemplate( $template_code, $tpl_basedir ){
336 $tag_regexp = array( 'loop' => '(\{loop(?: name){0,1}="\${0,1}[^"]*"\})',
337 'loop_close' => '(\{\/loop\})',
338 'if' => '(\{if(?: condition){0,1}="[^"]*"\})',
339 'elseif' => '(\{elseif(?: condition){0,1}="[^"]*"\})',
340 'else' => '(\{else\})',
341 'if_close' => '(\{\/if\})',
342 'function' => '(\{function="[^"]*"\})',
343 'noparse' => '(\{noparse\})',
344 'noparse_close'=> '(\{\/noparse\})',
345 'ignore' => '(\{ignore\})',
346 'ignore_close' => '(\{\/ignore\})',
347 'include' => '(\{include="[^"]*"(?: cache="[^"]*")?\})',
348 'template_info'=> '(\{\$template_info\})',
349 'function' => '(\{function="(\w*?)(?:.*?)"\})'
352 $tag_regexp = "/" . join( "|", $tag_regexp ) . "/";
354 //split the code with the tags regexp
355 $template_code = preg_split ( $tag_regexp, $template_code, -1, PREG_SPLIT_DELIM_CAPTURE
| PREG_SPLIT_NO_EMPTY
);
357 //path replace (src of img, background and href of link)
358 $template_code = $this->path_replace( $template_code, $tpl_basedir );
361 $compiled_code = $this->compileCode( $template_code );
363 //return the compiled code
364 return $compiled_code;
374 protected function compileCode( $parsed_code ){
376 //variables initialization
377 $compiled_code = $open_if = $comment_is_open = $ignore_is_open = null;
380 //read all parsed code
381 while( $html = array_shift( $parsed_code ) ){
384 if( !$comment_is_open && strpos( $html, '{/ignore}' ) !== FALSE )
385 $ignore_is_open = false;
387 //code between tag ignore id deleted
388 elseif( $ignore_is_open ){
393 elseif( strpos( $html, '{/noparse}' ) !== FALSE )
394 $comment_is_open = false;
396 //code between tag noparse is not compiled
397 elseif( $comment_is_open )
398 $compiled_code .= $html;
401 elseif( strpos( $html, '{ignore}' ) !== FALSE )
402 $ignore_is_open = true;
405 elseif( strpos( $html, '{noparse}' ) !== FALSE )
406 $comment_is_open = true;
409 elseif( preg_match( '/\{include="([^"]*)"(?: cache="([^"]*)"){0,1}\}/', $html, $code ) ){
411 //variables substitution
412 $include_var = $this->var_replace( $code[ 1 ], $left_delimiter = null, $right_delimiter = null, $php_left_delimiter = '".' , $php_right_delimiter = '."', $loop_level );
414 // if the cache is active
415 if( isset($code[ 2 ]) ){
418 $compiled_code .= '<?php $tpl = new RainTpl;' .
419 'if( $cache = $tpl->cache( $template = basename("'.$include_var.'") ) )' .
422 ' $tpl_dir_temp = self::$tpl_dir;' .
423 ' $tpl->assign( $this->var );' .
424 ( !$loop_level ? null : '$tpl->assign( "key", $key'.$loop_level.' ); $tpl->assign( "value", $value'.$loop_level.' );' ).
425 ' $tpl->draw( dirname("'.$include_var.'") . ( substr("'.$include_var.'",-1,1) != "/" ? "/" : "" ) . basename("'.$include_var.'") );'.
431 $compiled_code .= '<?php $tpl = new RainTpl;' .
432 '$tpl_dir_temp = self::$tpl_dir;' .
433 '$tpl->assign( $this->var );' .
434 ( !$loop_level ? null : '$tpl->assign( "key", $key'.$loop_level.' ); $tpl->assign( "value", $value'.$loop_level.' );' ).
435 '$tpl->draw( dirname("'.$include_var.'") . ( substr("'.$include_var.'",-1,1) != "/" ? "/" : "" ) . basename("'.$include_var.'") );'.
444 elseif( preg_match( '/\{loop(?: name){0,1}="\${0,1}([^"]*)"\}/', $html, $code ) ){
446 //increase the loop counter
449 //replace the variable in the loop
450 $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 );
453 $counter = "\$counter$loop_level"; // count iteration
454 $key = "\$key$loop_level"; // key
455 $value = "\$value$loop_level"; // value
458 $compiled_code .= "<?php $counter=-1; if( isset($var) && is_array($var) && sizeof($var) ) foreach( $var as $key => $value ){ $counter++; ?>";
463 elseif( strpos( $html, '{
/loop
}' ) !== FALSE ) {
466 $counter = "\$counter$loop_level";
468 //decrease the loop counter
472 $compiled_code .= "<?php } ?>";
477 elseif( preg_match( '/\{
if(?: condition
){0,1}="([^"]*)"\}/', $html, $code ) ){
479 //increase open if counter (for intendation)
485 //condition attribute
486 $condition = $code[ 1 ];
488 // check if there's any function disabled by black_list
489 $this->function_check( $tag );
491 //variable substitution into condition (no delimiter into the condition)
492 $parsed_condition = $this->var_replace( $condition, $tag_left_delimiter = null, $tag_right_delimiter = null, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level );
495 $compiled_code .= "<?php
if( $parsed_condition ){ ?>";
500 elseif( preg_match( '/\{elseif(?: condition){0,1}="([^
"]*)"\
}/', $html, $code ) ){
505 //condition attribute
506 $condition = $code[ 1 ];
508 //variable substitution into condition (no delimiter into the condition)
509 $parsed_condition = $this->var_replace( $condition, $tag_left_delimiter = null, $tag_right_delimiter = null, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level );
512 $compiled_code .= "<?php }elseif( $parsed_condition ){ ?>";
516 elseif( strpos( $html, '{
else}' ) !== FALSE ) {
519 $compiled_code .= '<?php
}else{ ?>';
524 elseif( strpos( $html, '{
/if}' ) !== FALSE ) {
526 //decrease if counter
530 $compiled_code .= '<?php
} ?>';
535 elseif( preg_match( '/\{
function="(\w*)(.*?)"\
}/', $html, $code ) ){
541 $function = $code[ 1 ];
543 // check if there's any
function disabled by black_list
544 $this->function_check( $tag );
546 if( empty( $code[ 2 ] ) )
547 $parsed_function = $function . "()";
549 // parse the function
550 $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 );
553 $compiled_code .= "<?php echo $parsed_function; ?>";
557 elseif ( strpos( $html, '{$template_info}' ) !== FALSE ) {
560 $tag = '{$template_info}';
563 $compiled_code .= '<?php echo "<pre>"; print_r( $this->var ); echo "</pre>"; ?>';
570 //variables substitution (es. {$title})
571 $html = $this->var_replace( $html, $left_delimiter = '\{', $right_delimiter = '\}', $php_left_delimiter = '<?php ', $php_right_delimiter = ';?>', $loop_level, $echo = true );
572 //const substitution (es. {#CONST#})
573 $html = $this->const_replace( $html, $left_delimiter = '\{', $right_delimiter = '\}', $php_left_delimiter = '<?php ', $php_right_delimiter = ';?>', $loop_level, $echo = true );
574 //functions substitution (es. {"string"|functions})
575 $compiled_code .= $this->func_replace( $html, $left_delimiter = '\{', $right_delimiter = '\}', $php_left_delimiter = '<?php ', $php_right_delimiter = ';?>', $loop_level, $echo = true );
580 $e = new RainTpl_SyntaxException('Error! You need to close an {if} tag in ' . $this->tpl
['tpl_filename'] . ' template');
581 throw $e->setTemplateFile($this->tpl
['tpl_filename']);
583 return $compiled_code;
588 protected function reduce_path( $path ){
589 $path = str_replace( "//", "/", $path );
590 return preg_replace('/\w+\/\.\.\//', '', $path );
596 * replace the path of image src, link href and a href.
597 * url => template_dir/url
599 * http://url => http://url
601 * @param string $html
602 * @return string html sostituito
604 protected function path_replace( $html, $tpl_basedir ){
606 if( self
::$path_replace ){
608 $tpl_dir = self
::$base_url . self
::$tpl_dir . $tpl_basedir;
611 $path = $this->reduce_path($tpl_dir);
613 $exp = $sub = array();
615 if( in_array( "img", self
::$path_replace_list ) ){
616 $exp = array( '/<img(.*?)src=(?:")(http|https)\:\/\/([^"]+?)(?:")/i', '/<img(.*?)src=(?:")([^"]+?)#(?:")/i', '/<img(.*?)src="(.*?)"/', '/<img(.*?)src=(?:\@)([^"]+?)(?:\@)/i' );
617 $sub = array( '<img$1src=@$2://$3@', '<img$1src=@$2@', '<img$1src="' . $path . '$2"', '<img
$1src="$2"' );
620 if( in_array( "script
", self::$path_replace_list ) ){
621 $exp = array_merge( $exp , array( '/<script(.*?)src=(?:")(http
|https
)\
:\
/\
/([^
"]+?)(?:")/i
', '/<script(.*?)src
=(?:")([^"]+
?)#(?:")/i', '/<script(.*?)src="(.*?)"/', '/<script(.*?)src=(?:\@)([^"]+?)(?:\@)/i' ) );
622 $sub = array_merge( $sub , array( '<script$1src=@$2://$3@', '<script$1src=@$2@', '<script$1src="' . $path . '$2"', '<script
$1src="$2"' ) );
625 if( in_array( "link
", self::$path_replace_list ) ){
626 $exp = array_merge( $exp , array( '/<link(.*?)href=(?:")(http
|https
)\
:\
/\
/([^
"]+?)(?:")/i
', '/<link(.*?)href
=(?:")([^"]+
?)#(?:")/i', '/<link(.*?)href="(.*?)"/', '/<link(.*?)href=(?:\@)([^"]+?)(?:\@)/i' ) );
627 $sub = array_merge( $sub , array( '<link$1href=@$2://$3@', '<link$1href=@$2@' , '<link$1href="' . $path . '$2"', '<link
$1href="$2"' ) );
630 if( in_array( "a
", self::$path_replace_list ) ){
631 $exp = array_merge( $exp , array( '/<a(.*?)href=(?:")(http
|https
)\
:\
/\
/([^
"]+?)(?:")/i
', '/<a(.*?)href
="(.*?)"/', '/<a(.*?)href
=(?:\
@)([^
"]+?)(?:\@)/i' ) );
632 $sub = array_merge( $sub , array( '<a$1href=@$2://$3@', '<a$1href="' . self::$base_url . '$2"', '<a$1href="$2"' ) );
635 if( in_array( "input", self::$path_replace_list ) ){
636 $exp = array_merge( $exp , array( '/<input(.*?)src
=(?:")(http|https)\:\/\/([^"]+
?)(?:")/i', '/<input(.*?)src=(?:")([^
"]+?)#(?:")/i
', '/<input(.*?)src
="(.*?)"/', '/<input(.*?)src
=(?:\
@)([^
"]+?)(?:\@)/i' ) );
637 $sub = array_merge( $sub , array( '<input$1src=@$2://$3@', '<input$1src=@$2@', '<input$1src="' . $path . '$2"', '<input$1src="$2"' ) );
640 return preg_replace( $exp, $sub, $html );
653 function const_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
655 return preg_replace( '/\{\
#(\w+)\#{0,1}\}/', $php_left_delimiter . ( $echo ? " echo " : null ) . '\\1' . $php_right_delimiter, $html );
660 // replace functions/modifiers on constants and strings
661 function func_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
663 preg_match_all( '/' . '\{\#{0,1}(\"{0,1}.*?\"{0,1})(\|\w.*?)\#{0,1}\}' . '/', $html, $matches );
665 for( $i=0, $n=count($matches[0]); $i<$n; $i++
){
667 //complete tag ex: {$news.title|substr:0,100}
668 $tag = $matches[ 0 ][ $i ];
670 //variable name ex: news.title
671 $var = $matches[ 1 ][ $i ];
673 //function and parameters associate to the variable ex: substr:0,100
674 $extra_var = $matches[ 2 ][ $i ];
676 // check if there's any function disabled by black_list
677 $this->function_check( $tag );
679 $extra_var = $this->var_replace( $extra_var, null, null, null, null, $loop_level );
682 // check if there's an operator = in the variable tags, if there's this is an initialization so it will not output any value
683 $is_init_variable = preg_match( "/^(\s*?)\=[^=](.*?)$/", $extra_var );
685 //function associate to variable
686 $function_var = ( $extra_var and $extra_var[0] == '|') ? substr( $extra_var, 1 ) : null;
688 //variable path split array (ex. $news.title o $news[title]) or object (ex. $news->title)
689 $temp = preg_split( "/\.|\[|\-\>/", $var );
692 $var_name = $temp[ 0 ];
695 $variable_path = substr( $var, strlen( $var_name ) );
697 //parentesis transform [ e ] in [" e in "]
698 $variable_path = str_replace( '[', '["', $variable_path );
699 $variable_path = str_replace( ']', '"]', $variable_path );
701 //transform .$variable in ["$variable"]
702 $variable_path = preg_replace('/\.\$(\w+)/', '["$\\1"]', $variable_path );
704 //transform [variable] in ["variable"]
705 $variable_path = preg_replace('/\.(\w+)/', '["\\1"]', $variable_path );
707 //if there's a function
710 // check if there's a function or a static method and separate, function by parameters
711 $function_var = str_replace("::", "@double_dot@", $function_var );
713 // get the position of the first :
714 if( $dot_position = strpos( $function_var, ":" ) ){
716 // get the function and the parameters
717 $function = substr( $function_var, 0, $dot_position );
718 $params = substr( $function_var, $dot_position+
1 );
724 $function = str_replace( "@double_dot@", "::", $function_var );
729 // replace back the @double_dot@ with ::
730 $function = str_replace( "@double_dot@", "::", $function );
731 $params = str_replace( "@double_dot@", "::", $params );
736 $function = $params = null;
738 $php_var = $var_name . $variable_path;
740 // compile the variable for php
741 if( isset( $function ) ){
743 $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $php_var, $params ) )" : "$function( $php_var )" ) . $php_right_delimiter;
745 $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $params ) )" : "$function()" ) . $php_right_delimiter;
748 $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . $php_var . $extra_var . $php_right_delimiter;
750 $html = str_replace( $tag, $php_var, $html );
760 function var_replace( $html, $tag_left_delimiter, $tag_right_delimiter, $php_left_delimiter = null, $php_right_delimiter = null, $loop_level = null, $echo = null ){
763 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 ) ){
765 for( $parsed=array(), $i=0, $n=count($matches[0]); $i<$n; $i++
)
766 $parsed[$matches[0][$i]] = array('var'=>$matches[1][$i],'extra_var'=>$matches[2][$i]);
768 foreach( $parsed as $tag => $array ){
770 //variable name ex: news.title
771 $var = $array['var'];
773 //function and parameters associate to the variable ex: substr:0,100
774 $extra_var = $array['extra_var'];
776 // check if there's any function disabled by black_list
777 $this->function_check( $tag );
779 $extra_var = $this->var_replace( $extra_var, null, null, null, null, $loop_level );
781 // check if there's an operator = in the variable tags, if there's this is an initialization so it will not output any value
782 $is_init_variable = preg_match( "/^[a-z_A-Z\.\[\](\-\>)]*=[^=]*$/", $extra_var );
784 //function associate to variable
785 $function_var = ( $extra_var and $extra_var[0] == '|') ? substr( $extra_var, 1 ) : null;
787 //variable path split array (ex. $news.title o $news[title]) or object (ex. $news->title)
788 $temp = preg_split( "/\.|\[|\-\>/", $var );
791 $var_name = $temp[ 0 ];
794 $variable_path = substr( $var, strlen( $var_name ) );
796 //parentesis transform [ e ] in [" e in "]
797 $variable_path = str_replace( '[', '["', $variable_path );
798 $variable_path = str_replace( ']', '"]', $variable_path );
800 //transform .$variable in ["$variable"] and .variable in ["variable"]
801 $variable_path = preg_replace('/\.(\${0,1}\w+)/', '["\\1"]', $variable_path );
803 // if is an assignment also assign the variable to $this->var['value']
804 if( $is_init_variable )
805 $extra_var = "=\$this->var['{$var_name}']{$variable_path}" . $extra_var;
809 //if there's a function
812 // check if there's a function or a static method and separate, function by parameters
813 $function_var = str_replace("::", "@double_dot@", $function_var );
816 // get the position of the first :
817 if( $dot_position = strpos( $function_var, ":" ) ){
819 // get the function and the parameters
820 $function = substr( $function_var, 0, $dot_position );
821 $params = substr( $function_var, $dot_position+
1 );
827 $function = str_replace( "@double_dot@", "::", $function_var );
832 // replace back the @double_dot@ with ::
833 $function = str_replace( "@double_dot@", "::", $function );
834 $params = str_replace( "@double_dot@", "::", $params );
837 $function = $params = null;
839 //if it is inside a loop
841 //verify the variable name
842 if( $var_name == 'key' )
843 $php_var = '$key' . $loop_level;
844 elseif( $var_name == 'value
' )
845 $php_var = '$value' . $loop_level . $variable_path;
846 elseif( $var_name == 'counter' )
847 $php_var = '$counter' . $loop_level;
849 $php_var = '$' . $var_name . $variable_path;
851 $php_var = '$' . $var_name . $variable_path;
853 // compile the variable for php
854 if( isset( $function ) )
855 $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . ( $params ? "( $function( $php_var, $params ) )" : "$function( $php_var )" ) . $php_right_delimiter;
857 $php_var = $php_left_delimiter . ( !$is_init_variable && $echo ? 'echo ' : null ) . $php_var . $extra_var . $php_right_delimiter;
859 $html = str_replace( $tag, $php_var, $html );
871 * Check if function is in black list (sandbox)
873 * @param string $code
876 protected function function_check( $code ){
878 $preg = '#(\W|\s)' . implode( '(\W|\s)|(\W|\s)', self::$black_list ) . '(\W|\s)#';
880 // check if the function is in the black list (or not in white list)
881 if( count(self
::$black_list) && preg_match( $preg, $code, $match ) ){
883 // find the line of the error
885 $rows=explode("\n",$this->tpl
['source']);
886 while( !strpos($rows[$line],$code) )
889 // stop the execution of the script
890 $e = new RainTpl_SyntaxException('Unallowed syntax in ' . $this->tpl
['tpl_filename'] . ' template');
891 throw $e->setTemplateFile($this->tpl
['tpl_filename'])
893 ->setTemplateLine($line);
899 * Prints debug info about exception or passes it further if debug is disabled.
901 * @param RainTpl_Exception $e
904 protected function printDebug(RainTpl_Exception
$e){
908 $output = sprintf('<h2>Exception: %s</h2><h3>%s</h3><p>template: %s</p>',
911 $e->getTemplateFile()
913 if ($e instanceof RainTpl_SyntaxException
) {
914 if (null != $e->getTemplateLine()) {
915 $output .= '<p>line: ' . $e->getTemplateLine() . '</p>';
917 if (null != $e->getTag()) {
918 $output .= '<p>in tag: ' . htmlspecialchars($e->getTag()) . '</p>';
920 if (null != $e->getTemplateLine() && null != $e->getTag()) {
921 $rows=explode("\n", htmlspecialchars($this->tpl
['source']));
922 $rows[$e->getTemplateLine()] = '<font color=red>' . $rows[$e->getTemplateLine()] . '</font>';
923 $output .= '<h3>template code</h3>' . implode('<br />', $rows) . '</pre>';
926 $output .= sprintf('<h3>trace</h3><p>In %s on line %d</p><pre>%s</pre>',
927 $e->getFile(), $e->getLine(),
928 nl2br(htmlspecialchars($e->getTraceAsString()))
936 * Basic Rain tpl exception.
938 class RainTpl_Exception
extends Exception
{
940 * Path of template file with error.
942 protected $templateFile = '';
945 * Returns path of template file with error.
949 public function getTemplateFile()
951 return $this->templateFile
;
955 * Sets path of template file with error.
957 * @param string $templateFile
958 * @return RainTpl_Exception
960 public function setTemplateFile($templateFile)
962 $this->templateFile
= (string) $templateFile;
968 * Exception thrown when template file does not exists.
970 class RainTpl_NotFoundException
extends RainTpl_Exception
{
974 * Exception thrown when syntax error occurs.
976 class RainTpl_SyntaxException
extends RainTpl_Exception
{
978 * Line in template file where error has occured.
982 protected $templateLine = null;
985 * Tag which caused an error.
989 protected $tag = null;
992 * Returns line in template file where error has occured
993 * or null if line is not defined.
997 public function getTemplateLine()
999 return $this->templateLine
;
1003 * Sets line in template file where error has occured.
1005 * @param int $templateLine
1006 * @return RainTpl_SyntaxException
1008 public function setTemplateLine($templateLine)
1010 $this->templateLine
= (int) $templateLine;
1015 * Returns tag which caused an error.
1019 public function getTag()
1025 * Sets tag which caused an error.
1027 * @param string $tag
1028 * @return RainTpl_SyntaxException
1030 public function setTag($tag)
1032 $this->tag
= (string) $tag;