Sandbox.php 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. class Twig_Extension_Sandbox extends Twig_Extension
  11. {
  12. protected $sandboxedGlobally;
  13. protected $sandboxed;
  14. protected $policy;
  15. public function __construct(Twig_Sandbox_SecurityPolicyInterface $policy, $sandboxed = false)
  16. {
  17. $this->policy = $policy;
  18. $this->sandboxedGlobally = $sandboxed;
  19. }
  20. /**
  21. * Returns the token parser instances to add to the existing list.
  22. *
  23. * @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
  24. */
  25. public function getTokenParsers()
  26. {
  27. return array(new Twig_TokenParser_Sandbox());
  28. }
  29. /**
  30. * Returns the node visitor instances to add to the existing list.
  31. *
  32. * @return array An array of Twig_NodeVisitorInterface instances
  33. */
  34. public function getNodeVisitors()
  35. {
  36. return array(new Twig_NodeVisitor_Sandbox());
  37. }
  38. public function enableSandbox()
  39. {
  40. $this->sandboxed = true;
  41. }
  42. public function disableSandbox()
  43. {
  44. $this->sandboxed = false;
  45. }
  46. public function isSandboxed()
  47. {
  48. return $this->sandboxedGlobally || $this->sandboxed;
  49. }
  50. public function isSandboxedGlobally()
  51. {
  52. return $this->sandboxedGlobally;
  53. }
  54. public function setSecurityPolicy(Twig_Sandbox_SecurityPolicyInterface $policy)
  55. {
  56. $this->policy = $policy;
  57. }
  58. public function getSecurityPolicy()
  59. {
  60. return $this->policy;
  61. }
  62. public function checkSecurity($tags, $filters, $functions)
  63. {
  64. if ($this->isSandboxed()) {
  65. $this->policy->checkSecurity($tags, $filters, $functions);
  66. }
  67. }
  68. public function checkMethodAllowed($obj, $method)
  69. {
  70. if ($this->isSandboxed()) {
  71. $this->policy->checkMethodAllowed($obj, $method);
  72. }
  73. }
  74. public function checkPropertyAllowed($obj, $method)
  75. {
  76. if ($this->isSandboxed()) {
  77. $this->policy->checkPropertyAllowed($obj, $method);
  78. }
  79. }
  80. public function ensureToStringAllowed($obj)
  81. {
  82. if (is_object($obj)) {
  83. $this->policy->checkMethodAllowed($obj, '__toString');
  84. }
  85. return $obj;
  86. }
  87. /**
  88. * Returns the name of the extension.
  89. *
  90. * @return string The extension name
  91. */
  92. public function getName()
  93. {
  94. return 'sandbox';
  95. }
  96. }