Sandbox.php 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Twig_NodeVisitor_Sandbox implements sandboxing.
  12. *
  13. * @package twig
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_NodeVisitor_Sandbox implements Twig_NodeVisitorInterface
  17. {
  18. protected $inAModule = false;
  19. protected $tags;
  20. protected $filters;
  21. protected $functions;
  22. /**
  23. * Called before child nodes are visited.
  24. *
  25. * @param Twig_NodeInterface $node The node to visit
  26. * @param Twig_Environment $env The Twig environment instance
  27. *
  28. * @return Twig_NodeInterface The modified node
  29. */
  30. public function enterNode(Twig_NodeInterface $node, Twig_Environment $env)
  31. {
  32. if ($node instanceof Twig_Node_Module) {
  33. $this->inAModule = true;
  34. $this->tags = array();
  35. $this->filters = array();
  36. $this->functions = array();
  37. return $node;
  38. } elseif ($this->inAModule) {
  39. // look for tags
  40. if ($node->getNodeTag()) {
  41. $this->tags[] = $node->getNodeTag();
  42. }
  43. // look for filters
  44. if ($node instanceof Twig_Node_Expression_Filter) {
  45. $this->filters[] = $node->getNode('filter')->getAttribute('value');
  46. }
  47. // look for functions
  48. if ($node instanceof Twig_Node_Expression_Function) {
  49. $this->functions[] = $node->getAttribute('name');
  50. }
  51. // wrap print to check __toString() calls
  52. if ($node instanceof Twig_Node_Print) {
  53. return new Twig_Node_SandboxedPrint($node->getNode('expr'), $node->getLine(), $node->getNodeTag());
  54. }
  55. }
  56. return $node;
  57. }
  58. /**
  59. * Called after child nodes are visited.
  60. *
  61. * @param Twig_NodeInterface $node The node to visit
  62. * @param Twig_Environment $env The Twig environment instance
  63. *
  64. * @return Twig_NodeInterface The modified node
  65. */
  66. public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env)
  67. {
  68. if ($node instanceof Twig_Node_Module) {
  69. $this->inAModule = false;
  70. return new Twig_Node_SandboxedModule($node, array_unique($this->filters), array_unique($this->tags), array_unique($this->functions));
  71. }
  72. return $node;
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function getPriority()
  78. {
  79. return 0;
  80. }
  81. }