Sandbox.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. public function getTokenParsers()
  21. {
  22. return array(new Twig_TokenParser_Sandbox());
  23. }
  24. public function getNodeVisitors()
  25. {
  26. return array(new Twig_NodeVisitor_Sandbox());
  27. }
  28. public function enableSandbox()
  29. {
  30. $this->sandboxed = true;
  31. }
  32. public function disableSandbox()
  33. {
  34. $this->sandboxed = false;
  35. }
  36. public function isSandboxed()
  37. {
  38. return $this->sandboxedGlobally || $this->sandboxed;
  39. }
  40. public function isSandboxedGlobally()
  41. {
  42. return $this->sandboxedGlobally;
  43. }
  44. public function setSecurityPolicy(Twig_Sandbox_SecurityPolicyInterface $policy)
  45. {
  46. $this->policy = $policy;
  47. }
  48. public function getSecurityPolicy()
  49. {
  50. return $this->policy;
  51. }
  52. public function checkSecurity($tags, $filters, $functions)
  53. {
  54. if ($this->isSandboxed()) {
  55. $this->policy->checkSecurity($tags, $filters, $functions);
  56. }
  57. }
  58. public function checkMethodAllowed($obj, $method)
  59. {
  60. if ($this->isSandboxed()) {
  61. $this->policy->checkMethodAllowed($obj, $method);
  62. }
  63. }
  64. public function checkPropertyAllowed($obj, $method)
  65. {
  66. if ($this->isSandboxed()) {
  67. $this->policy->checkPropertyAllowed($obj, $method);
  68. }
  69. }
  70. public function ensureToStringAllowed($obj)
  71. {
  72. if ($this->isSandboxed() && is_object($obj)) {
  73. $this->policy->checkMethodAllowed($obj, '__toString');
  74. }
  75. return $obj;
  76. }
  77. public function getName()
  78. {
  79. return 'sandbox';
  80. }
  81. }