Template.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. * (c) 2009 Armin Ronacher
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. /**
  12. * Default base class for compiled templates.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. abstract class Twig_Template implements Twig_TemplateInterface
  17. {
  18. protected static $cache = array();
  19. protected $parent;
  20. protected $parents = array();
  21. protected $env;
  22. protected $blocks = array();
  23. protected $traits = array();
  24. /**
  25. * Constructor.
  26. *
  27. * @param Twig_Environment $env A Twig_Environment instance
  28. */
  29. public function __construct(Twig_Environment $env)
  30. {
  31. $this->env = $env;
  32. }
  33. /**
  34. * Returns the template name.
  35. *
  36. * @return string The template name
  37. */
  38. abstract public function getTemplateName();
  39. /**
  40. * @deprecated since 1.20 (to be removed in 2.0)
  41. */
  42. public function getEnvironment()
  43. {
  44. @trigger_error('The '.__METHOD__.' method is deprecated since version 1.20 and will be removed in 2.0.', E_USER_DEPRECATED);
  45. return $this->env;
  46. }
  47. /**
  48. * Returns the parent template.
  49. *
  50. * This method is for internal use only and should never be called
  51. * directly.
  52. *
  53. * @param array $context
  54. *
  55. * @return Twig_TemplateInterface|false The parent template or false if there is no parent
  56. *
  57. * @internal
  58. */
  59. public function getParent(array $context)
  60. {
  61. if (null !== $this->parent) {
  62. return $this->parent;
  63. }
  64. try {
  65. $parent = $this->doGetParent($context);
  66. if (false === $parent) {
  67. return false;
  68. }
  69. if ($parent instanceof self) {
  70. return $this->parents[$parent->getTemplateName()] = $parent;
  71. }
  72. if (!isset($this->parents[$parent])) {
  73. $this->parents[$parent] = $this->loadTemplate($parent);
  74. }
  75. } catch (Twig_Error_Loader $e) {
  76. $e->setTemplateFile(null);
  77. $e->guess();
  78. throw $e;
  79. }
  80. return $this->parents[$parent];
  81. }
  82. protected function doGetParent(array $context)
  83. {
  84. return false;
  85. }
  86. public function isTraitable()
  87. {
  88. return true;
  89. }
  90. /**
  91. * Displays a parent block.
  92. *
  93. * This method is for internal use only and should never be called
  94. * directly.
  95. *
  96. * @param string $name The block name to display from the parent
  97. * @param array $context The context
  98. * @param array $blocks The current set of blocks
  99. *
  100. * @internal
  101. */
  102. public function displayParentBlock($name, array $context, array $blocks = array())
  103. {
  104. $name = (string) $name;
  105. if (isset($this->traits[$name])) {
  106. $this->traits[$name][0]->displayBlock($name, $context, $blocks, false);
  107. } elseif (false !== $parent = $this->getParent($context)) {
  108. $parent->displayBlock($name, $context, $blocks, false);
  109. } else {
  110. throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block', $name), -1, $this->getTemplateName());
  111. }
  112. }
  113. /**
  114. * Displays a block.
  115. *
  116. * This method is for internal use only and should never be called
  117. * directly.
  118. *
  119. * @param string $name The block name to display
  120. * @param array $context The context
  121. * @param array $blocks The current set of blocks
  122. * @param bool $useBlocks Whether to use the current set of blocks
  123. *
  124. * @internal
  125. */
  126. public function displayBlock($name, array $context, array $blocks = array(), $useBlocks = true)
  127. {
  128. $name = (string) $name;
  129. if ($useBlocks && isset($blocks[$name])) {
  130. $template = $blocks[$name][0];
  131. $block = $blocks[$name][1];
  132. } elseif (isset($this->blocks[$name])) {
  133. $template = $this->blocks[$name][0];
  134. $block = $this->blocks[$name][1];
  135. } else {
  136. $template = null;
  137. $block = null;
  138. }
  139. if (null !== $template) {
  140. // avoid RCEs when sandbox is enabled
  141. if (!$template instanceof self) {
  142. throw new LogicException('A block must be a method on a Twig_Template instance.');
  143. }
  144. try {
  145. $template->$block($context, $blocks);
  146. } catch (Twig_Error $e) {
  147. if (!$e->getTemplateFile()) {
  148. $e->setTemplateFile($template->getTemplateName());
  149. }
  150. // this is mostly useful for Twig_Error_Loader exceptions
  151. // see Twig_Error_Loader
  152. if (false === $e->getTemplateLine()) {
  153. $e->setTemplateLine(-1);
  154. $e->guess();
  155. }
  156. throw $e;
  157. } catch (Exception $e) {
  158. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getTemplateName(), $e);
  159. }
  160. } elseif (false !== $parent = $this->getParent($context)) {
  161. $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false);
  162. }
  163. }
  164. /**
  165. * Renders a parent block.
  166. *
  167. * This method is for internal use only and should never be called
  168. * directly.
  169. *
  170. * @param string $name The block name to render from the parent
  171. * @param array $context The context
  172. * @param array $blocks The current set of blocks
  173. *
  174. * @return string The rendered block
  175. *
  176. * @internal
  177. */
  178. public function renderParentBlock($name, array $context, array $blocks = array())
  179. {
  180. ob_start();
  181. $this->displayParentBlock($name, $context, $blocks);
  182. return ob_get_clean();
  183. }
  184. /**
  185. * Renders a block.
  186. *
  187. * This method is for internal use only and should never be called
  188. * directly.
  189. *
  190. * @param string $name The block name to render
  191. * @param array $context The context
  192. * @param array $blocks The current set of blocks
  193. * @param bool $useBlocks Whether to use the current set of blocks
  194. *
  195. * @return string The rendered block
  196. *
  197. * @internal
  198. */
  199. public function renderBlock($name, array $context, array $blocks = array(), $useBlocks = true)
  200. {
  201. ob_start();
  202. $this->displayBlock($name, $context, $blocks, $useBlocks);
  203. return ob_get_clean();
  204. }
  205. /**
  206. * Returns whether a block exists or not.
  207. *
  208. * This method is for internal use only and should never be called
  209. * directly.
  210. *
  211. * This method does only return blocks defined in the current template
  212. * or defined in "used" traits.
  213. *
  214. * It does not return blocks from parent templates as the parent
  215. * template name can be dynamic, which is only known based on the
  216. * current context.
  217. *
  218. * @param string $name The block name
  219. *
  220. * @return bool true if the block exists, false otherwise
  221. *
  222. * @internal
  223. */
  224. public function hasBlock($name)
  225. {
  226. return isset($this->blocks[(string) $name]);
  227. }
  228. /**
  229. * Returns all block names.
  230. *
  231. * This method is for internal use only and should never be called
  232. * directly.
  233. *
  234. * @return array An array of block names
  235. *
  236. * @see hasBlock
  237. *
  238. * @internal
  239. */
  240. public function getBlockNames()
  241. {
  242. return array_keys($this->blocks);
  243. }
  244. protected function loadTemplate($template, $templateName = null, $line = null, $index = null)
  245. {
  246. try {
  247. if (is_array($template)) {
  248. return $this->env->resolveTemplate($template);
  249. }
  250. if ($template instanceof self) {
  251. return $template;
  252. }
  253. return $this->env->loadTemplate($template, $index);
  254. } catch (Twig_Error $e) {
  255. if (!$e->getTemplateFile()) {
  256. $e->setTemplateFile($templateName ? $templateName : $this->getTemplateName());
  257. }
  258. if ($e->getTemplateLine()) {
  259. throw $e;
  260. }
  261. if (!$line) {
  262. $e->guess();
  263. } else {
  264. $e->setTemplateLine($line);
  265. }
  266. throw $e;
  267. }
  268. }
  269. /**
  270. * Returns all blocks.
  271. *
  272. * This method is for internal use only and should never be called
  273. * directly.
  274. *
  275. * @return array An array of blocks
  276. *
  277. * @see hasBlock
  278. *
  279. * @internal
  280. */
  281. public function getBlocks()
  282. {
  283. return $this->blocks;
  284. }
  285. /**
  286. * Returns the template source code.
  287. *
  288. * @return string|null The template source code or null if it is not available
  289. */
  290. public function getSource()
  291. {
  292. $reflector = new ReflectionClass($this);
  293. $file = $reflector->getFileName();
  294. if (!file_exists($file)) {
  295. return;
  296. }
  297. $source = file($file, FILE_IGNORE_NEW_LINES);
  298. array_splice($source, 0, $reflector->getEndLine());
  299. $i = 0;
  300. while (isset($source[$i]) && '/* */' === substr_replace($source[$i], '', 3, -2)) {
  301. $source[$i] = str_replace('*//* ', '*/', substr($source[$i], 3, -2));
  302. ++$i;
  303. }
  304. array_splice($source, $i);
  305. return implode("\n", $source);
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. public function display(array $context, array $blocks = array())
  311. {
  312. $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks));
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. public function render(array $context)
  318. {
  319. $level = ob_get_level();
  320. ob_start();
  321. try {
  322. $this->display($context);
  323. } catch (Exception $e) {
  324. while (ob_get_level() > $level) {
  325. ob_end_clean();
  326. }
  327. throw $e;
  328. }
  329. return ob_get_clean();
  330. }
  331. protected function displayWithErrorHandling(array $context, array $blocks = array())
  332. {
  333. try {
  334. $this->doDisplay($context, $blocks);
  335. } catch (Twig_Error $e) {
  336. if (!$e->getTemplateFile()) {
  337. $e->setTemplateFile($this->getTemplateName());
  338. }
  339. // this is mostly useful for Twig_Error_Loader exceptions
  340. // see Twig_Error_Loader
  341. if (false === $e->getTemplateLine()) {
  342. $e->setTemplateLine(-1);
  343. $e->guess();
  344. }
  345. throw $e;
  346. } catch (Exception $e) {
  347. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getTemplateName(), $e);
  348. }
  349. }
  350. /**
  351. * Auto-generated method to display the template with the given context.
  352. *
  353. * @param array $context An array of parameters to pass to the template
  354. * @param array $blocks An array of blocks to pass to the template
  355. */
  356. abstract protected function doDisplay(array $context, array $blocks = array());
  357. /**
  358. * Returns a variable from the context.
  359. *
  360. * This method is for internal use only and should never be called
  361. * directly.
  362. *
  363. * This method should not be overridden in a sub-class as this is an
  364. * implementation detail that has been introduced to optimize variable
  365. * access for versions of PHP before 5.4. This is not a way to override
  366. * the way to get a variable value.
  367. *
  368. * @param array $context The context
  369. * @param string $item The variable to return from the context
  370. * @param bool $ignoreStrictCheck Whether to ignore the strict variable check or not
  371. *
  372. * @return mixed The content of the context variable
  373. *
  374. * @throws Twig_Error_Runtime if the variable does not exist and Twig is running in strict mode
  375. *
  376. * @internal
  377. */
  378. final protected function getContext($context, $item, $ignoreStrictCheck = false)
  379. {
  380. if (!array_key_exists($item, $context)) {
  381. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  382. return;
  383. }
  384. throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist', $item), -1, $this->getTemplateName());
  385. }
  386. return $context[$item];
  387. }
  388. /**
  389. * Returns the attribute value for a given array/object.
  390. *
  391. * @param mixed $object The object or array from where to get the item
  392. * @param mixed $item The item to get from the array or object
  393. * @param array $arguments An array of arguments to pass if the item is an object method
  394. * @param string $type The type of attribute (@see Twig_Template constants)
  395. * @param bool $isDefinedTest Whether this is only a defined check
  396. * @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not
  397. *
  398. * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
  399. *
  400. * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
  401. */
  402. protected function getAttribute($object, $item, array $arguments = array(), $type = self::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
  403. {
  404. // array
  405. if (self::METHOD_CALL !== $type) {
  406. $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item;
  407. if ((is_array($object) && array_key_exists($arrayItem, $object))
  408. || ($object instanceof ArrayAccess && isset($object[$arrayItem]))
  409. ) {
  410. if ($isDefinedTest) {
  411. return true;
  412. }
  413. return $object[$arrayItem];
  414. }
  415. if (self::ARRAY_CALL === $type || !is_object($object)) {
  416. if ($isDefinedTest) {
  417. return false;
  418. }
  419. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  420. return;
  421. }
  422. if ($object instanceof ArrayAccess) {
  423. $message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist', $arrayItem, get_class($object));
  424. } elseif (is_object($object)) {
  425. $message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface', $item, get_class($object));
  426. } elseif (is_array($object)) {
  427. if (empty($object)) {
  428. $message = sprintf('Key "%s" does not exist as the array is empty', $arrayItem);
  429. } else {
  430. $message = sprintf('Key "%s" for array with keys "%s" does not exist', $arrayItem, implode(', ', array_keys($object)));
  431. }
  432. } elseif (self::ARRAY_CALL === $type) {
  433. if (null === $object) {
  434. $message = sprintf('Impossible to access a key ("%s") on a null variable', $item);
  435. } else {
  436. $message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s")', $item, gettype($object), $object);
  437. }
  438. } elseif (null === $object) {
  439. $message = sprintf('Impossible to access an attribute ("%s") on a null variable', $item);
  440. } else {
  441. $message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s")', $item, gettype($object), $object);
  442. }
  443. throw new Twig_Error_Runtime($message, -1, $this->getTemplateName());
  444. }
  445. }
  446. if (!is_object($object)) {
  447. if ($isDefinedTest) {
  448. return false;
  449. }
  450. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  451. return;
  452. }
  453. if (null === $object) {
  454. $message = sprintf('Impossible to invoke a method ("%s") on a null variable', $item);
  455. } else {
  456. $message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s")', $item, gettype($object), $object);
  457. }
  458. throw new Twig_Error_Runtime($message, -1, $this->getTemplateName());
  459. }
  460. // object property
  461. if (self::METHOD_CALL !== $type && !$object instanceof self) { // Twig_Template does not have public properties, and we don't want to allow access to internal ones
  462. if (isset($object->$item) || array_key_exists((string) $item, $object)) {
  463. if ($isDefinedTest) {
  464. return true;
  465. }
  466. if ($this->env->hasExtension('sandbox')) {
  467. $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
  468. }
  469. return $object->$item;
  470. }
  471. }
  472. $class = get_class($object);
  473. // object method
  474. if (!isset(self::$cache[$class]['methods'])) {
  475. // get_class_methods returns all methods accessible in the scope, but we only want public ones to be accessible in templates
  476. if ($object instanceof self) {
  477. $ref = new ReflectionClass($class);
  478. $methods = array();
  479. foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $refMethod) {
  480. $methodName = strtolower($refMethod->name);
  481. // Accessing the environment from templates is forbidden to prevent untrusted changes to the environment
  482. if ('getenvironment' !== $methodName) {
  483. $methods[$methodName] = true;
  484. }
  485. }
  486. self::$cache[$class]['methods'] = $methods;
  487. } else {
  488. self::$cache[$class]['methods'] = array_change_key_case(array_flip(get_class_methods($object)));
  489. }
  490. }
  491. $call = false;
  492. $lcItem = strtolower($item);
  493. if (isset(self::$cache[$class]['methods'][$lcItem])) {
  494. $method = (string) $item;
  495. } elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) {
  496. $method = 'get'.$item;
  497. } elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) {
  498. $method = 'is'.$item;
  499. } elseif (isset(self::$cache[$class]['methods']['__call'])) {
  500. $method = (string) $item;
  501. $call = true;
  502. } else {
  503. if ($isDefinedTest) {
  504. return false;
  505. }
  506. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  507. return;
  508. }
  509. throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist', $item, get_class($object)), -1, $this->getTemplateName());
  510. }
  511. if ($isDefinedTest) {
  512. return true;
  513. }
  514. if ($this->env->hasExtension('sandbox')) {
  515. $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method);
  516. }
  517. // Some objects throw exceptions when they have __call, and the method we try
  518. // to call is not supported. If ignoreStrictCheck is true, we should return null.
  519. try {
  520. $ret = call_user_func_array(array($object, $method), $arguments);
  521. } catch (BadMethodCallException $e) {
  522. if ($call && ($ignoreStrictCheck || !$this->env->isStrictVariables())) {
  523. return;
  524. }
  525. throw $e;
  526. }
  527. // useful when calling a template method from a template
  528. // this is not supported but unfortunately heavily used in the Symfony profiler
  529. if ($object instanceof Twig_TemplateInterface) {
  530. return $ret === '' ? '' : new Twig_Markup($ret, $this->env->getCharset());
  531. }
  532. return $ret;
  533. }
  534. }