Sandbox.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2010 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. * Represents a sandbox node.
  12. *
  13. * @package twig
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_Node_Sandbox extends Twig_Node
  17. {
  18. public function __construct(Twig_NodeInterface $body, $lineno, $tag = null)
  19. {
  20. parent::__construct(array('body' => $body), array(), $lineno, $tag);
  21. // in a sandbox tag, only include tags are allowed
  22. if (!$this->getNode('body') instanceof Twig_Node_Include) {
  23. foreach ($this->getNode('body') as $node) {
  24. if ($node instanceof Twig_Node_Text && ctype_space($node->getAttribute('data'))) {
  25. continue;
  26. }
  27. if (!$node instanceof Twig_Node_Include) {
  28. throw new Twig_Error_Syntax('Only "include" tags are allowed within a "sandbox" section', $node->getLine());
  29. }
  30. }
  31. }
  32. }
  33. /**
  34. * Compiles the node to PHP.
  35. *
  36. * @param Twig_Compiler A Twig_Compiler instance
  37. */
  38. public function compile(Twig_Compiler $compiler)
  39. {
  40. $compiler
  41. ->addDebugInfo($this)
  42. ->write("\$sandbox = \$this->env->getExtension('sandbox');\n")
  43. ->write("if (!\$alreadySandboxed = \$sandbox->isSandboxed()) {\n")
  44. ->indent()
  45. ->write("\$sandbox->enableSandbox();\n")
  46. ->outdent()
  47. ->write("}\n")
  48. ->subcompile($this->getNode('body'))
  49. ->write("if (!\$alreadySandboxed) {\n")
  50. ->indent()
  51. ->write("\$sandbox->disableSandbox();\n")
  52. ->outdent()
  53. ->write("}\n")
  54. ;
  55. }
  56. }