4 * Smarty Internal Plugin Smarty Template Compiler Base
5 * This file contains the basic classes and methods for compiling Smarty templates with lexer/parser
13 * Main abstract compiler class
16 * @subpackage Compiler
18 abstract class Smarty_Internal_TemplateCompilerBase
21 * hash for nocache sections
25 private $nocache_hash = null;
28 * suppress generation of nocache code
32 public $suppressNocacheProcessing = false;
35 * suppress generation of merged template code
39 public $suppressMergedTemplates = false;
46 public static $_tag_objects = array();
53 public $_tag_stack = array();
58 * @var Smarty_Internal_Template
60 public $template = null;
67 public $merged_templates = array();
70 * sources which must be compiled
74 public $sources = array();
77 * flag that we are inside {block}
81 public $inheritance = false;
84 * flag when compiling inheritance child template
88 public $inheritance_child = false;
91 * uid of templates called by {extends} for recursion check
95 public $extends_uid = array();
98 * source line offset for error messages
102 public $trace_line_offset = 0;
109 public $trace_uid = '';
116 public $trace_filepath = '';
118 * stack for tracing file and line of nested {block} tags
122 public $trace_stack = array();
125 * plugins loaded by default plugin handler
129 public $default_handler_plugins = array();
132 * saved preprocessed modifier list
136 public $default_modifier_list = null;
139 * force compilation of complete template as nocache
143 public $forceNocache = false;
146 * suppress Smarty header code in compiled template
150 public $suppressHeader = false;
153 * suppress template property header code in compiled template
157 public $suppressTemplatePropertyHeader = false;
160 * suppress pre and post filter
164 public $suppressFilter = false;
167 * flag if compiled template file shall we written
171 public $write_compiled_code = true;
174 * flag if currently a template function is compiled
178 public $compiles_template_function = false;
181 * called subfuntions from template function
185 public $called_functions = array();
188 * flags for used modifier plugins
192 public $modifier_plugins = array();
195 * type of already compiled modifier
199 public $known_modifier_type = array();
202 * method to compile a Smarty template
204 * @param mixed $_content template source
206 * @return bool true if compiling succeeded, false if it failed
208 abstract protected function doCompile($_content);
211 * Initialize compiler
213 public function __construct()
215 $this->nocache_hash = str_replace(array('.', ','), '-', uniqid(rand(), true));
219 * Method to compile a Smarty template
221 * @param Smarty_Internal_Template $template template object to compile
222 * @param bool $nocache true is shall be compiled in nocache mode
224 * @return bool true if compiling succeeded, false if it failed
226 public function compileTemplate(Smarty_Internal_Template $template, $nocache = false)
228 if (empty($template->properties['nocache_hash'])) {
229 $template->properties['nocache_hash'] = $this->nocache_hash;
231 $this->nocache_hash = $template->properties['nocache_hash'];
233 // flag for nochache sections
234 $this->nocache = $nocache;
235 $this->tag_nocache = false;
236 // save template object in compiler class
237 $this->template = $template;
238 // reset has nocache code flag
239 $this->template->has_nocache_code = false;
240 $save_source = $this->template->source;
241 // template header code
242 $template_header = '';
243 if (!$this->suppressHeader) {
244 $template_header .= "<?php /* Smarty version " . Smarty::SMARTY_VERSION . ", created on " . strftime("%Y-%m-%d %H:%M:%S") . "\n";
245 $template_header .= " compiled from \"" . $this->template->source->filepath . "\" */ ?>\n";
248 if (empty($this->template->source->components)) {
249 $this->sources = array($template->source);
251 // we have array of inheritance templates by extends: resource
252 $this->sources = array_reverse($template->source->components);
255 // the $this->sources array can get additional elements while compiling by the {extends} tag
256 while ($this->template->source = array_shift($this->sources)) {
257 $this->smarty->_current_file = $this->template->source->filepath;
258 if ($this->smarty->debugging) {
259 Smarty_Internal_Debug::start_compile($this->template);
261 $no_sources = count($this->sources);
262 if ($loop || $no_sources) {
263 $this->template->properties['file_dependency'][$this->template->source->uid] = array($this->template->source->filepath, $this->template->source->timestamp, $this->template->source->type);
267 $this->inheritance_child = true;
269 $this->inheritance_child = false;
272 $_compiled_code = '';
273 // flag for aborting current and start recompile
274 $this->abort_and_recompile = false;
275 // get template source
276 $_content = $this->template->source->content;
277 if ($_content != '') {
278 // run prefilter if required
279 if ((isset($this->smarty->autoload_filters['pre']) || isset($this->smarty->registered_filters['pre'])) && !$this->suppressFilter) {
280 $_content = Smarty_Internal_Filter_Handler::runFilter('pre', $_content, $template);
283 $_compiled_code = $this->doCompile($_content);
285 } while ($this->abort_and_recompile);
286 if ($this->smarty->debugging) {
287 Smarty_Internal_Debug::end_compile($this->template);
291 $this->template->source = $save_source;
293 $this->smarty->_current_file = $this->template->source->filepath;
295 unset($this->parser->root_buffer, $this->parser->current_buffer, $this->parser, $this->lex, $this->template);
296 self::$_tag_objects = array();
297 // return compiled code to template object
299 if (!$this->suppressMergedTemplates && !empty($this->merged_templates)) {
300 foreach ($this->merged_templates as $code) {
301 $merged_code .= $code;
304 // run postfilter if required on compiled template code
305 if ((isset($this->smarty->autoload_filters['post']) || isset($this->smarty->registered_filters['post'])) && !$this->suppressFilter && $_compiled_code != '') {
306 $_compiled_code = Smarty_Internal_Filter_Handler::runFilter('post', $_compiled_code, $template);
308 if ($this->suppressTemplatePropertyHeader) {
309 $code = $_compiled_code . $merged_code;
311 $code = $template_header . $template->createTemplateCodeFrame($_compiled_code) . $merged_code;
313 // unset content because template inheritance could have replace source with parent code
314 unset ($template->source->content);
321 * This is a call back from the lexer/parser
322 * It executes the required compile plugin for the Smarty tag
324 * @param string $tag tag name
325 * @param array $args array with tag attributes
326 * @param array $parameter array with compilation parameter
328 * @throws SmartyCompilerException
329 * @throws SmartyException
330 * @return string compiled code
332 public function compileTag($tag, $args, $parameter = array())
334 // $args contains the attributes parsed and compiled by the lexer/parser
335 // assume that tag does compile into code, but creates no HTML output
336 $this->has_code = true;
337 $this->has_output = false;
338 // log tag/attributes
339 if (isset($this->smarty->get_used_tags) && $this->smarty->get_used_tags) {
340 $this->template->used_tags[] = array($tag, $args);
342 // check nocache option flag
343 if (in_array("'nocache'", $args) || in_array(array('nocache' => 'true'), $args)
344 || in_array(array('nocache' => '"true"'), $args) || in_array(array('nocache' => "'true'"), $args)
346 $this->tag_nocache = true;
348 // compile the smarty tag (required compile classes to compile the tag are autoloaded)
349 if (($_output = $this->callTagCompiler($tag, $args, $parameter)) === false) {
350 if (isset($this->smarty->template_functions[$tag])) {
351 // template defined by {template} tag
352 $args['_attr']['name'] = "'" . $tag . "'";
353 $_output = $this->callTagCompiler('call', $args, $parameter);
356 if ($_output !== false) {
357 if ($_output !== true) {
358 // did we get compiled code
359 if ($this->has_code) {
360 // Does it create output?
361 if ($this->has_output) {
364 // return compiled code
368 // tag did not produce compiled code
371 // map_named attributes
372 if (isset($args['_attr'])) {
373 foreach ($args['_attr'] as $key => $attribute) {
374 if (is_array($attribute)) {
375 $args = array_merge($args, $attribute);
379 // not an internal compiler tag
380 if (strlen($tag) < 6 || substr($tag, - 5) != 'close') {
381 // check if tag is a registered object
382 if (isset($this->smarty->registered_objects[$tag]) && isset($parameter['object_method'])) {
383 $method = $parameter['object_method'];
384 if (!in_array($method, $this->smarty->registered_objects[$tag][3]) &&
385 (empty($this->smarty->registered_objects[$tag][1]) || in_array($method, $this->smarty->registered_objects[$tag][1]))
387 return $this->callTagCompiler('private_object_function', $args, $parameter, $tag, $method);
388 } elseif (in_array($method, $this->smarty->registered_objects[$tag][3])) {
389 return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $method);
392 $this->trigger_template_error('not allowed method "' . $method . '" in registered object "' . $tag . '"', $this->lex->taglineno);
395 // check if tag is registered
396 foreach (array(Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK) as $plugin_type) {
397 if (isset($this->smarty->registered_plugins[$plugin_type][$tag])) {
398 // if compiler function plugin call it now
399 if ($plugin_type == Smarty::PLUGIN_COMPILER) {
401 foreach ($args as $key => $mixed) {
402 if (is_array($mixed)) {
403 $new_args = array_merge($new_args, $mixed);
405 $new_args[$key] = $mixed;
408 if (!$this->smarty->registered_plugins[$plugin_type][$tag][1]) {
409 $this->tag_nocache = true;
411 $function = $this->smarty->registered_plugins[$plugin_type][$tag][0];
412 if (!is_array($function)) {
413 return $function($new_args, $this);
414 } elseif (is_object($function[0])) {
415 return $this->smarty->registered_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this);
417 return call_user_func_array($function, array($new_args, $this));
420 // compile registered function or block function
421 if ($plugin_type == Smarty::PLUGIN_FUNCTION || $plugin_type == Smarty::PLUGIN_BLOCK) {
422 return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag);
426 // check plugins from plugins folder
427 foreach ($this->smarty->plugin_search_order as $plugin_type) {
428 if ($plugin_type == Smarty::PLUGIN_COMPILER && $this->smarty->loadPlugin('smarty_compiler_' . $tag) && (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this))) {
429 $plugin = 'smarty_compiler_' . $tag;
430 if (is_callable($plugin)) {
431 // convert arguments format for old compiler plugins
433 foreach ($args as $key => $mixed) {
434 if (is_array($mixed)) {
435 $new_args = array_merge($new_args, $mixed);
437 $new_args[$key] = $mixed;
441 return $plugin($new_args, $this->smarty);
443 if (class_exists($plugin, false)) {
444 $plugin_object = new $plugin;
445 if (method_exists($plugin_object, 'compile')) {
446 return $plugin_object->compile($args, $this);
449 throw new SmartyException("Plugin \"{$tag}\" not callable");
451 if ($function = $this->getPlugin($tag, $plugin_type)) {
452 if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) {
453 return $this->callTagCompiler('private_' . $plugin_type . '_plugin', $args, $parameter, $tag, $function);
458 if (is_callable($this->smarty->default_plugin_handler_func)) {
460 // look for already resolved tags
461 foreach ($this->smarty->plugin_search_order as $plugin_type) {
462 if (isset($this->default_handler_plugins[$plugin_type][$tag])) {
468 // call default handler
469 foreach ($this->smarty->plugin_search_order as $plugin_type) {
470 if ($this->getPluginFromDefaultHandler($tag, $plugin_type)) {
477 // if compiler function plugin call it now
478 if ($plugin_type == Smarty::PLUGIN_COMPILER) {
480 foreach ($args as $mixed) {
481 $new_args = array_merge($new_args, $mixed);
483 $function = $this->default_handler_plugins[$plugin_type][$tag][0];
484 if (!is_array($function)) {
485 return $function($new_args, $this);
486 } elseif (is_object($function[0])) {
487 return $this->default_handler_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this);
489 return call_user_func_array($function, array($new_args, $this));
492 return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag);
497 // compile closing tag of block function
498 $base_tag = substr($tag, 0, - 5);
499 // check if closing tag is a registered object
500 if (isset($this->smarty->registered_objects[$base_tag]) && isset($parameter['object_method'])) {
501 $method = $parameter['object_method'];
502 if (in_array($method, $this->smarty->registered_objects[$base_tag][3])) {
503 return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $method);
506 $this->trigger_template_error('not allowed closing tag method "' . $method . '" in registered object "' . $base_tag . '"', $this->lex->taglineno);
509 // registered block tag ?
510 if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag]) || isset($this->default_handler_plugins[Smarty::PLUGIN_BLOCK][$base_tag])) {
511 return $this->callTagCompiler('private_registered_block', $args, $parameter, $tag);
514 if ($function = $this->getPlugin($base_tag, Smarty::PLUGIN_BLOCK)) {
515 return $this->callTagCompiler('private_block_plugin', $args, $parameter, $tag, $function);
517 // registered compiler plugin ?
518 if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag])) {
519 // if compiler function plugin call it now
521 if (!$this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][1]) {
522 $this->tag_nocache = true;
524 $function = $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0];
525 if (!is_array($function)) {
526 return $function($args, $this);
527 } elseif (is_object($function[0])) {
528 return $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0][0]->$function[1]($args, $this);
530 return call_user_func_array($function, array($args, $this));
533 if ($this->smarty->loadPlugin('smarty_compiler_' . $tag)) {
534 $plugin = 'smarty_compiler_' . $tag;
535 if (is_callable($plugin)) {
536 return $plugin($args, $this->smarty);
538 if (class_exists($plugin, false)) {
539 $plugin_object = new $plugin;
540 if (method_exists($plugin_object, 'compile')) {
541 return $plugin_object->compile($args, $this);
544 throw new SmartyException("Plugin \"{$tag}\" not callable");
547 $this->trigger_template_error("unknown tag \"" . $tag . "\"", $this->lex->taglineno);
552 * lazy loads internal compile plugin for tag and calls the compile method
553 * compile objects cached for reuse.
554 * class name format: Smarty_Internal_Compile_TagName
555 * plugin filename format: Smarty_Internal_Tagname.php
557 * @param string $tag tag name
558 * @param array $args list of tag attributes
559 * @param mixed $param1 optional parameter
560 * @param mixed $param2 optional parameter
561 * @param mixed $param3 optional parameter
563 * @return string compiled code
565 public function callTagCompiler($tag, $args, $param1 = null, $param2 = null, $param3 = null)
567 // re-use object if already exists
568 if (isset(self::$_tag_objects[$tag])) {
570 return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3);
572 // lazy load internal compiler plugin
573 $class_name = 'Smarty_Internal_Compile_' . $tag;
574 if ($this->smarty->loadPlugin($class_name)) {
575 // check if tag allowed by security
576 if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) {
577 // use plugin if found
578 self::$_tag_objects[$tag] = new $class_name;
580 return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3);
583 // no internal compile plugin for this tag
588 * Check for plugins and return function name
590 * @param $plugin_name
591 * @param string $plugin_type type of plugin
593 * @return string call name of function
595 public function getPlugin($plugin_name, $plugin_type)
598 if ($this->template->caching && ($this->nocache || $this->tag_nocache)) {
599 if (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) {
600 $function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'];
601 } elseif (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) {
602 $this->template->required_plugins['nocache'][$plugin_name][$plugin_type] = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type];
603 $function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'];
606 if (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) {
607 $function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'];
608 } elseif (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) {
609 $this->template->required_plugins['compiled'][$plugin_name][$plugin_type] = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type];
610 $function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'];
613 if (isset($function)) {
614 if ($plugin_type == 'modifier') {
615 $this->modifier_plugins[$plugin_name] = true;
620 // loop through plugin dirs and find the plugin
621 $function = 'smarty_' . $plugin_type . '_' . $plugin_name;
622 $file = $this->smarty->loadPlugin($function, false);
624 if (is_string($file)) {
625 if ($this->template->caching && ($this->nocache || $this->tag_nocache)) {
626 $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['file'] = $file;
627 $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'] = $function;
629 $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['file'] = $file;
630 $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'] = $function;
632 if ($plugin_type == 'modifier') {
633 $this->modifier_plugins[$plugin_name] = true;
638 if (is_callable($function)) {
639 // plugin function is defined in the script
647 * Check for plugins by default plugin handler
649 * @param string $tag name of tag
650 * @param string $plugin_type type of plugin
652 * @return boolean true if found
654 public function getPluginFromDefaultHandler($tag, $plugin_type)
659 $result = call_user_func_array(
660 $this->smarty->default_plugin_handler_func, array($tag, $plugin_type, $this->template, &$callback, &$script, &$cacheable)
663 $this->tag_nocache = $this->tag_nocache || !$cacheable;
664 if ($script !== null) {
665 if (is_file($script)) {
666 if ($this->template->caching && ($this->nocache || $this->tag_nocache)) {
667 $this->template->required_plugins['nocache'][$tag][$plugin_type]['file'] = $script;
668 $this->template->required_plugins['nocache'][$tag][$plugin_type]['function'] = $callback;
670 $this->template->required_plugins['compiled'][$tag][$plugin_type]['file'] = $script;
671 $this->template->required_plugins['compiled'][$tag][$plugin_type]['function'] = $callback;
673 include_once $script;
675 $this->trigger_template_error("Default plugin handler: Returned script file \"{$script}\" for \"{$tag}\" not found");
678 if (!is_string($callback) && !(is_array($callback) && is_string($callback[0]) && is_string($callback[1]))) {
679 $this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" must be a static function name or array of class and function name");
681 if (is_callable($callback)) {
682 $this->default_handler_plugins[$plugin_type][$tag] = array($callback, true, array());
686 $this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" not callable");
694 * Inject inline code for nocache template sections
695 * This method gets the content of each template element from the parser.
696 * If the content is compiled code and it should be not cached the code is injected
697 * into the rendered output.
699 * @param string $content content of template element
700 * @param boolean $is_code true if content is compiled code
702 * @return string content
704 public function processNocacheCode($content, $is_code)
706 // If the template is not evaluated and we have a nocache section and or a nocache tag
707 if ($is_code && !empty($content)) {
708 // generate replacement code
709 if ((!($this->template->source->recompiled) || $this->forceNocache) && $this->template->caching && !$this->suppressNocacheProcessing &&
710 ($this->nocache || $this->tag_nocache)
712 $this->template->has_nocache_code = true;
713 $_output = addcslashes($content, '\'\\');
714 $_output = str_replace("^#^", "'", $_output);
715 $_output = "<?php echo '/*%%SmartyNocache:{$this->nocache_hash}%%*/" . $_output . "/*/%%SmartyNocache:{$this->nocache_hash}%%*/';?>\n";
716 // make sure we include modifier plugins for nocache code
717 foreach ($this->modifier_plugins as $plugin_name => $dummy) {
718 if (isset($this->template->required_plugins['compiled'][$plugin_name]['modifier'])) {
719 $this->template->required_plugins['nocache'][$plugin_name]['modifier'] = $this->template->required_plugins['compiled'][$plugin_name]['modifier'];
728 $this->modifier_plugins = array();
729 $this->suppressNocacheProcessing = false;
730 $this->tag_nocache = false;
736 * push current file and line offset on stack for tracing {block} source lines
738 * @param string $file new filename
739 * @param string $uid uid of file
740 * @param int $line line offset to source
741 * @param bool $debug false debug end_compile shall not be called
743 public function pushTrace($file, $uid, $line, $debug = true)
745 if ($this->smarty->debugging && $debug) {
746 Smarty_Internal_Debug::end_compile($this->template);
748 array_push($this->trace_stack, array($this->smarty->_current_file, $this->trace_filepath, $this->trace_uid, $this->trace_line_offset));
749 $this->trace_filepath = $this->smarty->_current_file = $file;
750 $this->trace_uid = $uid;
751 $this->trace_line_offset = $line;
752 if ($this->smarty->debugging) {
753 Smarty_Internal_Debug::start_compile($this->template);
758 * restore file and line offset
761 public function popTrace()
763 if ($this->smarty->debugging) {
764 Smarty_Internal_Debug::end_compile($this->template);
766 $r = array_pop($this->trace_stack);
767 $this->smarty->_current_file = $r[0];
768 $this->trace_filepath = $r[1];
769 $this->trace_uid = $r[2];
770 $this->trace_line_offset = $r[3];
771 if ($this->smarty->debugging) {
772 Smarty_Internal_Debug::start_compile($this->template);
777 * display compiler error messages without dying
778 * If parameter $args is empty it is a parser detected syntax error.
779 * In this case the parser is called to obtain information about expected tokens.
780 * If parameter $args contains a string this is used as error message
782 * @param string $args individual error message or null
783 * @param string $line line-number
785 * @throws SmartyCompilerException when an unexpected token is found
787 public function trigger_template_error($args = null, $line = null)
789 // get template source line which has error
791 $line = $this->lex->line;
793 // $line += $this->trace_line_offset;
794 $match = preg_split("/\n/", $this->lex->data);
795 $error_text = 'Syntax error in template "' . (empty($this->trace_filepath) ? $this->template->source->filepath : $this->trace_filepath) . '" on line ' . ($line + $this->trace_line_offset) . ' "' . trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1])) . '" ';
797 // individual error message
798 $error_text .= $args;
800 // expected token from parser
801 $error_text .= ' - Unexpected "' . $this->lex->value . '"';
802 if (count($this->parser->yy_get_expected_tokens($this->parser->yymajor)) <= 4) {
803 foreach ($this->parser->yy_get_expected_tokens($this->parser->yymajor) as $token) {
804 $exp_token = $this->parser->yyTokenName[$token];
805 if (isset($this->lex->smarty_token_names[$exp_token])) {
806 // token type from lexer
807 $expect[] = '"' . $this->lex->smarty_token_names[$exp_token] . '"';
809 // otherwise internal token name
810 $expect[] = $this->parser->yyTokenName[$token];
813 $error_text .= ', expected one of: ' . implode(' , ', $expect);
816 $e = new SmartyCompilerException($error_text);
818 $e->source = trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1]));
820 $e->template = $this->template->source->filepath;