CheckSecurity.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2015 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. * @author Fabien Potencier <fabien@symfony.com>
  12. */
  13. class Twig_Node_CheckSecurity extends Twig_Node
  14. {
  15. protected $usedFilters;
  16. protected $usedTags;
  17. protected $usedFunctions;
  18. public function __construct(array $usedFilters, array $usedTags, array $usedFunctions)
  19. {
  20. $this->usedFilters = $usedFilters;
  21. $this->usedTags = $usedTags;
  22. $this->usedFunctions = $usedFunctions;
  23. parent::__construct();
  24. }
  25. public function compile(Twig_Compiler $compiler)
  26. {
  27. $tags = $filters = $functions = array();
  28. foreach (array('tags', 'filters', 'functions') as $type) {
  29. foreach ($this->{'used'.ucfirst($type)} as $name => $node) {
  30. if ($node instanceof Twig_Node) {
  31. ${$type}[$name] = $node->getLine();
  32. } else {
  33. ${$type}[$node] = null;
  34. }
  35. }
  36. }
  37. $compiler
  38. ->write('$tags = ')->repr(array_filter($tags))->raw(";\n")
  39. ->write('$filters = ')->repr(array_filter($filters))->raw(";\n")
  40. ->write('$functions = ')->repr(array_filter($functions))->raw(";\n\n")
  41. ->write("try {\n")
  42. ->indent()
  43. ->write("\$this->env->getExtension('sandbox')->checkSecurity(\n")
  44. ->indent()
  45. ->write(!$tags ? "array(),\n" : "array('".implode("', '", array_keys($tags))."'),\n")
  46. ->write(!$filters ? "array(),\n" : "array('".implode("', '", array_keys($filters))."'),\n")
  47. ->write(!$functions ? "array()\n" : "array('".implode("', '", array_keys($functions))."')\n")
  48. ->outdent()
  49. ->write(");\n")
  50. ->outdent()
  51. ->write("} catch (Twig_Sandbox_SecurityError \$e) {\n")
  52. ->indent()
  53. ->write("\$e->setTemplateFile(\$this->getTemplateName());\n\n")
  54. ->write("if (\$e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset(\$tags[\$e->getTagName()])) {\n")
  55. ->indent()
  56. ->write("\$e->setTemplateLine(\$tags[\$e->getTagName()]);\n")
  57. ->outdent()
  58. ->write("} elseif (\$e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset(\$filters[\$e->getFilterName()])) {\n")
  59. ->indent()
  60. ->write("\$e->setTemplateLine(\$filters[\$e->getFilterName()]);\n")
  61. ->outdent()
  62. ->write("} elseif (\$e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset(\$functions[\$e->getFunctionName()])) {\n")
  63. ->indent()
  64. ->write("\$e->setTemplateLine(\$functions[\$e->getFunctionName()]);\n")
  65. ->outdent()
  66. ->write("}\n\n")
  67. ->write("throw \$e;\n")
  68. ->outdent()
  69. ->write("}\n\n")
  70. ;
  71. }
  72. }