4 * This file is part of Twig.
6 * (c) 2009 Fabien Potencier
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
13 * Represents a security policy which need to be enforced when sandbox mode is enabled.
15 * @author Fabien Potencier <fabien@symfony.com>
17 class Twig_Sandbox_SecurityPolicy
implements Twig_Sandbox_SecurityPolicyInterface
19 protected $allowedTags;
20 protected $allowedFilters;
21 protected $allowedMethods;
22 protected $allowedProperties;
23 protected $allowedFunctions;
25 public function __construct(array $allowedTags = array(), array $allowedFilters = array(), array $allowedMethods = array(), array $allowedProperties = array(), array $allowedFunctions = array())
27 $this->allowedTags
= $allowedTags;
28 $this->allowedFilters
= $allowedFilters;
29 $this->setAllowedMethods($allowedMethods);
30 $this->allowedProperties
= $allowedProperties;
31 $this->allowedFunctions
= $allowedFunctions;
34 public function setAllowedTags(array $tags)
36 $this->allowedTags
= $tags;
39 public function setAllowedFilters(array $filters)
41 $this->allowedFilters
= $filters;
44 public function setAllowedMethods(array $methods)
46 $this->allowedMethods
= array();
47 foreach ($methods as $class => $m) {
48 $this->allowedMethods
[$class] = array_map('strtolower', is_array($m) ? $m : array($m));
52 public function setAllowedProperties(array $properties)
54 $this->allowedProperties
= $properties;
57 public function setAllowedFunctions(array $functions)
59 $this->allowedFunctions
= $functions;
62 public function checkSecurity($tags, $filters, $functions)
64 foreach ($tags as $tag) {
65 if (!in_array($tag, $this->allowedTags
)) {
66 throw new Twig_Sandbox_SecurityError(sprintf('Tag "%s" is not allowed.', $tag));
70 foreach ($filters as $filter) {
71 if (!in_array($filter, $this->allowedFilters
)) {
72 throw new Twig_Sandbox_SecurityError(sprintf('Filter "%s" is not allowed.', $filter));
76 foreach ($functions as $function) {
77 if (!in_array($function, $this->allowedFunctions
)) {
78 throw new Twig_Sandbox_SecurityError(sprintf('Function "%s" is not allowed.', $function));
83 public function checkMethodAllowed($obj, $method)
85 if ($obj instanceof Twig_TemplateInterface
|| $obj instanceof Twig_Markup
) {
90 $method = strtolower($method);
91 foreach ($this->allowedMethods
as $class => $methods) {
92 if ($obj instanceof $class) {
93 $allowed = in_array($method, $methods);
100 throw new Twig_Sandbox_SecurityError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, get_class($obj)));
104 public function checkPropertyAllowed($obj, $property)
107 foreach ($this->allowedProperties
as $class => $properties) {
108 if ($obj instanceof $class) {
109 $allowed = in_array($property, is_array($properties) ? $properties : array($properties));
116 throw new Twig_Sandbox_SecurityError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, get_class($obj)));