Sandbox.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. * @author Fabien Potencier <fabien@symfony.com>
  14. */
  15. class Twig_NodeVisitor_Sandbox extends Twig_BaseNodeVisitor
  16. {
  17. protected $inAModule = false;
  18. protected $tags;
  19. protected $filters;
  20. protected $functions;
  21. /**
  22. * {@inheritdoc}
  23. */
  24. protected function doEnterNode(Twig_Node $node, Twig_Environment $env)
  25. {
  26. if ($node instanceof Twig_Node_Module) {
  27. $this->inAModule = true;
  28. $this->tags = array();
  29. $this->filters = array();
  30. $this->functions = array();
  31. return $node;
  32. } elseif ($this->inAModule) {
  33. // look for tags
  34. if ($node->getNodeTag() && !isset($this->tags[$node->getNodeTag()])) {
  35. $this->tags[$node->getNodeTag()] = $node;
  36. }
  37. // look for filters
  38. if ($node instanceof Twig_Node_Expression_Filter && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) {
  39. $this->filters[$node->getNode('filter')->getAttribute('value')] = $node;
  40. }
  41. // look for functions
  42. if ($node instanceof Twig_Node_Expression_Function && !isset($this->functions[$node->getAttribute('name')])) {
  43. $this->functions[$node->getAttribute('name')] = $node;
  44. }
  45. // wrap print to check __toString() calls
  46. if ($node instanceof Twig_Node_Print) {
  47. return new Twig_Node_SandboxedPrint($node->getNode('expr'), $node->getLine(), $node->getNodeTag());
  48. }
  49. }
  50. return $node;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. protected function doLeaveNode(Twig_Node $node, Twig_Environment $env)
  56. {
  57. if ($node instanceof Twig_Node_Module) {
  58. $this->inAModule = false;
  59. $node->setNode('display_start', new Twig_Node(array(new Twig_Node_CheckSecurity($this->filters, $this->tags, $this->functions), $node->getNode('display_start'))));
  60. }
  61. return $node;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function getPriority()
  67. {
  68. return 0;
  69. }
  70. }