3 * Smarty Internal Plugin Template
4 * This file contains the Smarty template engine
12 * Main class with template data structures and methods
15 * @subpackage Template
16 * @property Smarty_Template_Source $source
17 * @property Smarty_Template_Compiled $compiled
18 * @property Smarty_Template_Cached $cached
20 class Smarty_Internal_Template extends Smarty_Internal_TemplateBase
27 public $cache_id = null;
32 public $compile_id = null;
38 public $caching = null;
40 * cache lifetime in seconds
44 public $cache_lifetime = null;
50 public $template_resource = null;
52 * flag if compiled template is invalid and must be (re)compiled
56 public $mustCompile = null;
58 * flag if template does contain nocache code sections
62 public $has_nocache_code = false;
64 * special compiled and cached template properties
68 public $properties = array('file_dependency' => array(),
70 'function' => array());
76 public $required_plugins = array('compiled' => array(), 'nocache' => array());
78 * Global smarty instance
82 public $smarty = null;
84 * blocks for template inheritance
88 public $block_data = array();
94 public $variable_filters = array();
96 * optional log of tag/attributes
100 public $used_tags = array();
102 * internal flag to allow relative path in child template blocks
106 public $allow_relative_path = false;
108 * internal capture runtime stack
112 public $_capture_stack = array(0 => array());
115 * Create template data object
116 * Some of the global Smarty settings copied to template scope
117 * It load the required template resources and cacher plugins
119 * @param string $template_resource template resource string
120 * @param Smarty $smarty Smarty instance
121 * @param Smarty_Internal_Template $_parent back pointer to parent object with variables or null
122 * @param mixed $_cache_id cache id or null
123 * @param mixed $_compile_id compile id or null
124 * @param bool $_caching use caching?
125 * @param int $_cache_lifetime cache life-time in seconds
127 public function __construct($template_resource, $smarty, $_parent = null, $_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null)
129 $this->smarty = & $smarty;
131 $this->cache_id = $_cache_id === null ? $this->smarty->cache_id : $_cache_id;
132 $this->compile_id = $_compile_id === null ? $this->smarty->compile_id : $_compile_id;
133 $this->caching = $_caching === null ? $this->smarty->caching : $_caching;
134 if ($this->caching === true) {
135 $this->caching = Smarty::CACHING_LIFETIME_CURRENT;
137 $this->cache_lifetime = $_cache_lifetime === null ? $this->smarty->cache_lifetime : $_cache_lifetime;
138 $this->parent = $_parent;
140 $this->template_resource = $template_resource;
141 // copy block data of template inheritance
142 if ($this->parent instanceof Smarty_Internal_Template) {
143 $this->block_data = $this->parent->block_data;
148 * Returns if the current template must be compiled by the Smarty compiler
149 * It does compare the timestamps of template source and the compiled templates and checks the force compile configuration
151 * @throws SmartyException
152 * @return boolean true if the template must be compiled
154 public function mustCompile()
156 if (!$this->source->exists) {
157 if ($this->parent instanceof Smarty_Internal_Template) {
158 $parent_resource = " in '$this->parent->template_resource}'";
160 $parent_resource = '';
162 throw new SmartyException("Unable to load template {$this->source->type} '{$this->source->name}'{$parent_resource}");
164 if ($this->mustCompile === null) {
165 $this->mustCompile = (!$this->source->uncompiled && ($this->smarty->force_compile || $this->source->recompiled || $this->compiled->timestamp === false ||
166 ($this->smarty->compile_check && $this->compiled->timestamp < $this->source->timestamp)));
169 return $this->mustCompile;
173 * Compiles the template
174 * If the template is not evaluated the compiled template is saved on disk
176 public function compileTemplateSource()
178 if (!$this->source->recompiled) {
179 $this->properties['file_dependency'] = array();
180 if ($this->source->components) {
181 // for the extends resource the compiler will fill it
182 // uses real resource for file dependency
183 // $source = end($this->source->components);
184 // $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $source->type);
186 $this->properties['file_dependency'][$this->source->uid] = array($this->source->filepath, $this->source->timestamp, $this->source->type);
190 if ($this->smarty->compile_locking && !$this->source->recompiled) {
191 if ($saved_timestamp = $this->compiled->timestamp) {
192 touch($this->compiled->filepath);
197 $code = $this->compiler->compileTemplate($this);
199 catch (Exception $e) {
200 // restore old timestamp in case of error
201 if ($this->smarty->compile_locking && !$this->source->recompiled && $saved_timestamp) {
202 touch($this->compiled->filepath, $saved_timestamp);
206 // compiling succeded
207 if (!$this->source->recompiled && $this->compiler->write_compiled_code) {
208 // write compiled template
209 $_filepath = $this->compiled->filepath;
210 if ($_filepath === false) {
211 throw new SmartyException('getCompiledFilepath() did not return a destination to save the compiled template to');
213 Smarty_Internal_Write_File::writeFile($_filepath, $code, $this->smarty);
214 $this->compiled->exists = true;
215 $this->compiled->isCompiled = true;
217 // release compiler object to free memory
218 unset($this->compiler);
222 * Writes the cached template output
224 * @param string $content
228 public function writeCachedContent($content)
230 if ($this->source->recompiled || !($this->caching == Smarty::CACHING_LIFETIME_CURRENT || $this->caching == Smarty::CACHING_LIFETIME_SAVED)) {
231 // don't write cache file
234 $this->properties['cache_lifetime'] = $this->cache_lifetime;
235 $this->properties['unifunc'] = 'content_' . str_replace(array('.', ','), '_', uniqid('', true));
236 $content = $this->createTemplateCodeFrame($content, true);
237 /** @var Smarty_Internal_Template $_smarty_tpl
238 * used in evaluated code
240 $_smarty_tpl = $this;
241 eval("?>" . $content);
242 $this->cached->valid = true;
243 $this->cached->processed = true;
245 return $this->cached->write($this, $content);
249 * Template code runtime function to get subtemplate content
251 * @param string $template the resource handle of the template file
252 * @param mixed $cache_id cache id to be used with this template
253 * @param mixed $compile_id compile id to be used with this template
254 * @param integer $caching cache mode
255 * @param integer $cache_lifetime life time of cache data
257 * @param int $parent_scope scope in which {include} should execute
259 * @returns string template content
261 public function getSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope)
263 // already in template cache?
264 if ($this->smarty->allow_ambiguous_resources) {
265 $_templateId = Smarty_Resource::getUniqueTemplateName($this, $template) . $cache_id . $compile_id;
267 $_templateId = $this->smarty->joined_template_dir . '#' . $template . $cache_id . $compile_id;
270 if (isset($_templateId[150])) {
271 $_templateId = sha1($_templateId);
273 if (isset($this->smarty->template_objects[$_templateId])) {
274 // clone cached template object because of possible recursive call
275 $tpl = clone $this->smarty->template_objects[$_templateId];
276 $tpl->parent = $this;
277 $tpl->caching = $caching;
278 $tpl->cache_lifetime = $cache_lifetime;
280 $tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
282 // get variables from calling scope
283 if ($parent_scope == Smarty::SCOPE_LOCAL) {
284 $tpl->tpl_vars = $this->tpl_vars;
285 $tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
286 } elseif ($parent_scope == Smarty::SCOPE_PARENT) {
287 $tpl->tpl_vars = & $this->tpl_vars;
288 } elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
289 $tpl->tpl_vars = & Smarty::$global_tpl_vars;
290 } elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
291 $tpl->tpl_vars = & $this->tpl_vars;
293 $tpl->tpl_vars = & $scope_ptr->tpl_vars;
295 $tpl->config_vars = $this->config_vars;
297 // set up variable values
298 foreach ($data as $_key => $_val) {
299 $tpl->tpl_vars[$_key] = new Smarty_variable($_val);
303 return $tpl->fetch(null, null, null, null, false, false, true);
307 * Template code runtime function to set up an inline subtemplate
309 * @param string $template the resource handle of the template file
310 * @param mixed $cache_id cache id to be used with this template
311 * @param mixed $compile_id compile id to be used with this template
312 * @param integer $caching cache mode
313 * @param integer $cache_lifetime life time of cache data
315 * @param int $parent_scope scope in which {include} should execute
316 * @param string $hash nocache hash code
318 * @returns string template content
320 public function setupInlineSubTemplate($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $parent_scope, $hash)
322 $tpl = new $this->smarty->template_class($template, $this->smarty, $this, $cache_id, $compile_id, $caching, $cache_lifetime);
323 $tpl->properties['nocache_hash'] = $hash;
324 // get variables from calling scope
325 if ($parent_scope == Smarty::SCOPE_LOCAL) {
326 $tpl->tpl_vars = $this->tpl_vars;
327 $tpl->tpl_vars['smarty'] = clone $this->tpl_vars['smarty'];
328 } elseif ($parent_scope == Smarty::SCOPE_PARENT) {
329 $tpl->tpl_vars = & $this->tpl_vars;
330 } elseif ($parent_scope == Smarty::SCOPE_GLOBAL) {
331 $tpl->tpl_vars = & Smarty::$global_tpl_vars;
332 } elseif (($scope_ptr = $this->getScopePointer($parent_scope)) == null) {
333 $tpl->tpl_vars = & $this->tpl_vars;
335 $tpl->tpl_vars = & $scope_ptr->tpl_vars;
337 $tpl->config_vars = $this->config_vars;
339 // set up variable values
340 foreach ($data as $_key => $_val) {
341 $tpl->tpl_vars[$_key] = new Smarty_variable($_val);
349 * Create code frame for compiled and cached templates
351 * @param string $content optional template content
352 * @param bool $cache flag for cache file
356 public function createTemplateCodeFrame($content = '', $cache = false)
358 $plugins_string = '';
359 // include code for plugins
361 if (!empty($this->required_plugins['compiled'])) {
362 $plugins_string = '<?php ';
363 foreach ($this->required_plugins['compiled'] as $tmp) {
364 foreach ($tmp as $data) {
365 $file = addslashes($data['file']);
366 if (is_Array($data['function'])) {
367 $plugins_string .= "if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) include '{$file}';\n";
369 $plugins_string .= "if (!is_callable('{$data['function']}')) include '{$file}';\n";
373 $plugins_string .= '?>';
375 if (!empty($this->required_plugins['nocache'])) {
376 $this->has_nocache_code = true;
377 $plugins_string .= "<?php echo '/*%%SmartyNocache:{$this->properties['nocache_hash']}%%*/<?php \$_smarty = \$_smarty_tpl->smarty; ";
378 foreach ($this->required_plugins['nocache'] as $tmp) {
379 foreach ($tmp as $data) {
380 $file = addslashes($data['file']);
381 if (is_Array($data['function'])) {
382 $plugins_string .= addslashes("if (!is_callable(array('{$data['function'][0]}','{$data['function'][1]}'))) include '{$file}';\n");
384 $plugins_string .= addslashes("if (!is_callable('{$data['function']}')) include '{$file}';\n");
388 $plugins_string .= "?>/*/%%SmartyNocache:{$this->properties['nocache_hash']}%%*/';?>\n";
391 // build property code
392 $this->properties['has_nocache_code'] = $this->has_nocache_code;
394 if (!$this->source->recompiled) {
395 $output = "<?php /*%%SmartyHeaderCode:{$this->properties['nocache_hash']}%%*/";
396 if ($this->smarty->direct_access_security) {
397 $output .= "if(!defined('SMARTY_DIR')) exit('no direct access allowed');\n";
401 // remove compiled code of{function} definition
402 unset($this->properties['function']);
403 if (!empty($this->smarty->template_functions)) {
404 // copy code of {function} tags called in nocache mode
405 foreach ($this->smarty->template_functions as $name => $function_data) {
406 if (isset($function_data['called_nocache'])) {
407 foreach ($function_data['called_functions'] as $func_name) {
408 $this->smarty->template_functions[$func_name]['called_nocache'] = true;
412 foreach ($this->smarty->template_functions as $name => $function_data) {
413 if (isset($function_data['called_nocache'])) {
414 unset($function_data['called_nocache'], $function_data['called_functions'], $this->smarty->template_functions[$name]['called_nocache']);
415 $this->properties['function'][$name] = $function_data;
420 $this->properties['version'] = Smarty::SMARTY_VERSION;
421 if (!isset($this->properties['unifunc'])) {
422 $this->properties['unifunc'] = 'content_' . str_replace(array('.', ','), '_', uniqid('', true));
424 if (!$this->source->recompiled) {
425 $output .= "\$_valid = \$_smarty_tpl->decodeProperties(" . var_export($this->properties, true) . ',' . ($cache ? 'true' : 'false') . "); /*/%%SmartyHeaderCode%%*/?>\n";
426 $output .= '<?php if ($_valid && !is_callable(\'' . $this->properties['unifunc'] . '\')) {function ' . $this->properties['unifunc'] . '($_smarty_tpl) {?>';
428 $output .= $plugins_string;
430 if (!$this->source->recompiled) {
431 $output .= "<?php }} ?>\n";
438 * This function is executed automatically when a compiled or cached template file is included
439 * - Decode saved properties from compiled template and cache files
440 * - Check if compiled or cache file is valid
442 * @param array $properties special template properties
443 * @param bool $cache flag if called from cache file
445 * @return bool flag if compiled or cache file is valid
447 public function decodeProperties($properties, $cache = false)
449 $this->has_nocache_code = $properties['has_nocache_code'];
450 $this->properties['nocache_hash'] = $properties['nocache_hash'];
451 if (isset($properties['cache_lifetime'])) {
452 $this->properties['cache_lifetime'] = $properties['cache_lifetime'];
454 if (isset($properties['file_dependency'])) {
455 $this->properties['file_dependency'] = array_merge($this->properties['file_dependency'], $properties['file_dependency']);
457 if (!empty($properties['function'])) {
458 $this->properties['function'] = array_merge($this->properties['function'], $properties['function']);
459 $this->smarty->template_functions = array_merge($this->smarty->template_functions, $properties['function']);
461 $this->properties['version'] = (isset($properties['version'])) ? $properties['version'] : '';
462 $this->properties['unifunc'] = $properties['unifunc'];
463 // check file dependencies at compiled code
465 if ($this->properties['version'] != Smarty::SMARTY_VERSION) {
467 } elseif (((!$cache && $this->smarty->compile_check && empty($this->compiled->_properties) && !$this->compiled->isCompiled) || $cache && ($this->smarty->compile_check === true || $this->smarty->compile_check === Smarty::COMPILECHECK_ON)) && !empty($this->properties['file_dependency'])) {
468 foreach ($this->properties['file_dependency'] as $_file_to_check) {
469 if ($_file_to_check[2] == 'file' || $_file_to_check[2] == 'php') {
470 if ($this->source->filepath == $_file_to_check[0] && isset($this->source->timestamp)) {
471 // do not recheck current template
472 $mtime = $this->source->timestamp;
474 // file and php types can be checked without loading the respective resource handlers
475 $mtime = @filemtime($_file_to_check[0]);
477 } elseif ($_file_to_check[2] == 'string') {
480 $source = Smarty_Resource::source(null, $this->smarty, $_file_to_check[0]);
481 $mtime = $source->timestamp;
483 if (!$mtime || $mtime > $_file_to_check[1]) {
490 // CACHING_LIFETIME_SAVED cache expiry has to be validated here since otherwise we'd define the unifunc
491 if ($this->caching === Smarty::CACHING_LIFETIME_SAVED &&
492 $this->properties['cache_lifetime'] >= 0 &&
493 (time() > ($this->cached->timestamp + $this->properties['cache_lifetime']))
497 $this->cached->valid = $is_valid;
499 $this->mustCompile = !$is_valid;
501 // store data in reusable Smarty_Template_Compiled
503 $this->compiled->_properties = $properties;
510 * Template code runtime function to create a local Smarty variable for array assignments
512 * @param string $tpl_var tempate variable name
513 * @param bool $nocache cache mode of variable
514 * @param int $scope scope of variable
516 public function createLocalArrayVariable($tpl_var, $nocache = false, $scope = Smarty::SCOPE_LOCAL)
518 if (!isset($this->tpl_vars[$tpl_var])) {
519 $this->tpl_vars[$tpl_var] = new Smarty_variable(array(), $nocache, $scope);
521 $this->tpl_vars[$tpl_var] = clone $this->tpl_vars[$tpl_var];
522 if ($scope != Smarty::SCOPE_LOCAL) {
523 $this->tpl_vars[$tpl_var]->scope = $scope;
525 if (!(is_array($this->tpl_vars[$tpl_var]->value) || $this->tpl_vars[$tpl_var]->value instanceof ArrayAccess)) {
526 settype($this->tpl_vars[$tpl_var]->value, 'array');
532 * Template code runtime function to get pointer to template variable array of requested scope
534 * @param int $scope requested variable scope
536 * @return array array of template variables
538 public function &getScope($scope)
540 if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) {
541 return $this->parent->tpl_vars;
542 } elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) {
543 $ptr = $this->parent;
544 while (!empty($ptr->parent)) {
548 return $ptr->tpl_vars;
549 } elseif ($scope == Smarty::SCOPE_GLOBAL) {
550 return Smarty::$global_tpl_vars;
558 * Get parent or root of template parent chain
560 * @param int $scope pqrent or root scope
562 * @return mixed object
564 public function getScopePointer($scope)
566 if ($scope == Smarty::SCOPE_PARENT && !empty($this->parent)) {
567 return $this->parent;
568 } elseif ($scope == Smarty::SCOPE_ROOT && !empty($this->parent)) {
569 $ptr = $this->parent;
570 while (!empty($ptr->parent)) {
581 * [util function] counts an array, arrayaccess/traversable or PDOStatement object
583 * @param mixed $value
585 * @return int the count for arrays and objects that implement countable, 1 for other objects that don't, and 0 for empty elements
587 public function _count($value)
589 if (is_array($value) === true || $value instanceof Countable) {
590 return count($value);
591 } elseif ($value instanceof IteratorAggregate) {
592 // Note: getIterator() returns a Traversable, not an Iterator
593 // thus rewind() and valid() methods may not be present
594 return iterator_count($value->getIterator());
595 } elseif ($value instanceof Iterator) {
596 return iterator_count($value);
597 } elseif ($value instanceof PDOStatement) {
598 return $value->rowCount();
599 } elseif ($value instanceof Traversable) {
600 return iterator_count($value);
601 } elseif ($value instanceof ArrayAccess) {
602 if ($value->offsetExists(0)) {
605 } elseif (is_object($value)) {
606 return count($value);
613 * runtime error not matching capture tags
616 public function capture_error()
618 throw new SmartyException("Not matching {capture} open/close in \"{$this->template_resource}\"");
622 * Empty cache for this template
624 * @param integer $exp_time expiration time
626 * @return integer number of cache files deleted
628 public function clearCache($exp_time = null)
630 Smarty_CacheResource::invalidLoadedCache($this->smarty);
632 return $this->cached->handler->clear($this->smarty, $this->template_name, $this->cache_id, $this->compile_id, $exp_time);
636 * set Smarty property in template context
638 * @param string $property_name property name
639 * @param mixed $value value
641 * @throws SmartyException
643 public function __set($property_name, $value)
645 switch ($property_name) {
650 $this->$property_name = $value;
654 // FIXME: routing of template -> smarty attributes
656 if (property_exists($this->smarty, $property_name)) {
657 $this->smarty->$property_name = $value;
663 throw new SmartyException("invalid template property '$property_name'.");
667 * get Smarty property in template context
669 * @param string $property_name property name
671 * @throws SmartyException
673 public function __get($property_name)
675 switch ($property_name) {
677 if (strlen($this->template_resource) == 0) {
678 throw new SmartyException('Missing template name');
680 $this->source = Smarty_Resource::source($this);
681 // cache template object under a unique ID
682 // do not cache eval resources
683 if ($this->source->type != 'eval') {
684 if ($this->smarty->allow_ambiguous_resources) {
685 $_templateId = $this->source->unique_resource . $this->cache_id . $this->compile_id;
687 $_templateId = $this->smarty->joined_template_dir . '#' . $this->template_resource . $this->cache_id . $this->compile_id;
690 if (isset($_templateId[150])) {
691 $_templateId = sha1($_templateId);
693 $this->smarty->template_objects[$_templateId] = $this;
696 return $this->source;
699 $this->compiled = $this->source->getCompiled($this);
701 return $this->compiled;
704 if (!class_exists('Smarty_Template_Cached')) {
705 include SMARTY_SYSPLUGINS_DIR . 'smarty_cacheresource.php';
707 $this->cached = new Smarty_Template_Cached($this);
709 return $this->cached;
712 $this->smarty->loadPlugin($this->source->compiler_class);
713 $this->compiler = new $this->source->compiler_class($this->source->template_lexer_class, $this->source->template_parser_class, $this->smarty);
715 return $this->compiler;
717 // FIXME: routing of template -> smarty attributes
719 if (property_exists($this->smarty, $property_name)) {
720 return $this->smarty->$property_name;
724 throw new SmartyException("template property '$property_name' does not exist.");
728 * Template data object destructor
731 public function __destruct()
733 if ($this->smarty->cache_locking && isset($this->cached) && $this->cached->is_locked) {
734 $this->cached->handler->releaseLock($this->smarty, $this->cached);