aboutsummaryrefslogtreecommitdiffstats
path: root/perllib/FixMyStreet/Template/Context.pm
diff options
context:
space:
mode:
authorMatthew Somerville <matthew@mysociety.org>2019-11-26 17:09:56 +0000
committerMatthew Somerville <matthew@mysociety.org>2019-12-09 09:38:03 +0000
commit6c2d3d5a7d84521d34daa2cf7e4be76a54b3b0e0 (patch)
tree75ef8cd6e1df444572ae5ec3a4048e6c3366a088 /perllib/FixMyStreet/Template/Context.pm
parenta4290acdff6781979cc3cd7c0142d553236e5666 (diff)
Switch to default-escaped in templates.
This means any variable used in a template is automatically HTML-escaped, unless it is marked as safe either in code by using a SafeString, or in the template with the `mark_safe` function or the `safe` filter.
Diffstat (limited to 'perllib/FixMyStreet/Template/Context.pm')
-rw-r--r--perllib/FixMyStreet/Template/Context.pm67
1 files changed, 67 insertions, 0 deletions
diff --git a/perllib/FixMyStreet/Template/Context.pm b/perllib/FixMyStreet/Template/Context.pm
new file mode 100644
index 000000000..de3212095
--- /dev/null
+++ b/perllib/FixMyStreet/Template/Context.pm
@@ -0,0 +1,67 @@
+package FixMyStreet::Template::Context;
+
+use strict;
+use warnings;
+use base qw(Template::Context);
+
+sub filter {
+ my $self = shift;
+ my ($name, $args, $alias) = @_;
+
+ # If we're passing through the safe filter, then unwrap
+ # from a Template::HTML::Variable if we are one.
+ if ( $name eq 'safe' ) {
+ return sub {
+ my $value = shift;
+ return $value->plain if UNIVERSAL::isa($value, 'FixMyStreet::Template::Variable');
+ return $value;
+ };
+ }
+
+ my $filter = $self->SUPER::filter(@_);
+
+ # If we are already going to auto-encode, we don't want to do it again.
+ # This makes the html filter a no-op on auto-encoded variables.
+ if ( $name eq 'html' ) {
+ return sub {
+ my $value = shift;
+ return $value if UNIVERSAL::isa($value, 'FixMyStreet::Template::Variable');
+ return $filter->($value);
+ };
+ }
+
+ return sub {
+ my $value = shift;
+
+ if ( UNIVERSAL::isa($value, 'FixMyStreet::Template::Variable') ) {
+ my $result = $filter->($value->plain);
+ return $result if UNIVERSAL::isa($result, 'FixMyStreet::Template::SafeString');
+ return ref($value)->new($result);
+ }
+
+ return $filter->($value);
+ };
+}
+
+1;
+__END__
+
+=head1 NAME
+
+FixMyStreet::Template::Context - Similar to Template::HTML::Context but use
+'safe' rather than 'none' to be clear, also prevents html filter double-encoding,
+and doesn't rewrap a FixMyStreet::Template::SafeString.
+
+=head1 AUTHORS
+
+Martyn Smith, E<lt>msmith@cpan.orgE<gt>
+
+Matthew Somerville, E<lt>matthew@mysociety.orgE<gt>
+
+=head1 LICENSE
+
+This library is free software; you can redistribute it and/or modify
+it under the same terms as Perl itself, either Perl version 5.8.8 or,
+at your option, any later version of Perl 5 you may have available.
+
+=cut