Added auto-escaper support for functions
authorArnaud Le Blanc <arnaud.lb@gmail.com>
Fri, 24 Dec 2010 16:21:26 +0000 (17:21 +0100)
committerFabien Potencier <fabien.potencier@gmail.com>
Thu, 30 Dec 2010 08:31:08 +0000 (09:31 +0100)
Functions' output is escaped by default and functions can declare
themselves "safe" using the "is_safe" option.

lib/Twig/NodeVisitor/SafeAnalysis.php
test/Twig/Tests/Fixtures/tags/autoescape/functions.test [new file with mode: 0644]

index b684618..2f2403b 100644 (file)
@@ -58,6 +58,16 @@ class Twig_NodeVisitor_SafeAnalysis implements Twig_NodeVisitorInterface
             } else {
                 $this->setSafe($node, array());
             }
+        } elseif ($node instanceof Twig_Node_Expression_Function) {
+            // function expression is safe when the function is safe
+            $name = $node->getNode('name')->getAttribute('name');
+            $args = $node->getNode('arguments');
+            $function = $env->getFunction($name);
+            if (null !== $function) {
+                $this->setSafe($node, $function->getSafe($args));
+            } else {
+                $this->setSafe($node, array());
+            }
         } else {
             $this->setSafe($node, array());
         }
diff --git a/test/Twig/Tests/Fixtures/tags/autoescape/functions.test b/test/Twig/Tests/Fixtures/tags/autoescape/functions.test
new file mode 100644 (file)
index 0000000..ce62744
--- /dev/null
@@ -0,0 +1,83 @@
+--TEST--
+"autoescape" tag applies escaping after calling functions
+--TEMPLATE--
+
+autoescape off
+{% autoescape off %}
+
+safe_br
+{{ safe_br() }}
+
+unsafe_br
+{{ unsafe_br() }}
+
+{% endautoescape %}
+
+autoescape on
+{% autoescape on %}
+
+safe_br
+{{ safe_br() }}
+
+unsafe_br
+{{ unsafe_br() }}
+
+unsafe_br()|raw
+{{ (unsafe_br())|raw }}
+
+safe_br()|escape
+{{ (safe_br())|escape }}
+
+safe_br()|raw
+{{ (safe_br())|raw }}
+
+unsafe_br()|escape
+{{ (unsafe_br())|escape }}
+
+{% endautoescape %}
+
+autoescape on js
+{% autoescape on js %}
+
+safe_br
+{{ safe_br() }}
+
+{% endautoescape %}
+--DATA--
+return array()
+--EXPECT--
+
+autoescape off
+
+safe_br
+<br />
+
+unsafe_br
+<br />
+
+
+autoescape on
+
+safe_br
+<br />
+
+unsafe_br
+&lt;br /&gt;
+
+unsafe_br()|raw
+<br />
+
+safe_br()|escape
+&lt;br /&gt;
+
+safe_br()|raw
+<br />
+
+unsafe_br()|escape
+&lt;br /&gt;
+
+
+autoescape on js
+
+safe_br
+\x3cbr \x2f\x3e