blib/lib/Template/Filters.pm untested

filter: Statementstmt 0.0% 0 / 243 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 51 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 440 CC 42 SCAR 38.6
CC
42
Cov
0%
fetch
210.0
truncate_filter_factory
30.0
redirect_filter_factory
30.0
CRAP 47.5
1 #============================================================= -*-Perl-*-
2 #
3 # Template::Filters
4 #
5 # DESCRIPTION
6 # Defines filter plugins as used by the FILTER directive.
7 #
8 # AUTHORS
9 # Andy Wardley <abw@wardley.org>, with a number of filters contributed
10 # by Leslie Michael Orchard <deus_x@nijacode.com>
11 #
12 # COPYRIGHT
13 # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved.
14 #
15 # This module is free software; you can redistribute it and/or
16 # modify it under the same terms as Perl itself.
17 #
18 #============================================================================
19  
20 package Template::Filters;
21  
22 use strict;
23 use warnings;
24 use locale;
25 use base 'Template::Base';
26 use Template::Constants;
27 use Scalar::Util 'blessed';
28  
29 our $VERSION = '3.100';
30 our $AVAILABLE = { };
31 our $TRUNCATE_LENGTH = 32;
32 our $TRUNCATE_ADDON = '...';
33  
34  
35 #------------------------------------------------------------------------
36 # standard filters, defined in one of the following forms:
37 # name => \&static_filter
38 # name => [ \&subref, $is_dynamic ]
39 # If the $is_dynamic flag is set then the sub-routine reference
40 # is called to create a new filter each time it is requested; if
41 # not set, then it is a single, static sub-routine which is returned
42 # for every filter request for that name.
43 #------------------------------------------------------------------------
44  
45 our $FILTERS = {
46 # static filters
47 'html' => \&html_filter,
48 'html_para' => \&html_paragraph,
49 'html_break' => \&html_para_break,
50 'html_para_break' => \&html_para_break,
51 'html_line_break' => \&html_line_break,
52 'xml' => \&xml_filter,
53 'uri' => \&uri_filter,
54 'url' => \&url_filter,
55 'upper' => sub { uc $_[0] },
56 'lower' => sub { lc $_[0] },
57 'ucfirst' => sub { ucfirst $_[0] },
58 'lcfirst' => sub { lcfirst $_[0] },
59 'stderr' => sub { print STDERR @_; return '' },
60 'trim' => sub { for ($_[0]) { s/^\s+//; s/\s+$// }; $_[0] },
61 'null' => sub { return '' },
62 'collapse' => sub { for ($_[0]) { s/^\s+//; s/\s+$//; s/\s+/ /g };
63 $_[0] },
64  
65 # dynamic filters
66 'html_entity' => [ \&html_entity_filter_factory, 1 ],
67 'indent' => [ \&indent_filter_factory, 1 ],
68 'format' => [ \&format_filter_factory, 1 ],
69 'truncate' => [ \&truncate_filter_factory, 1 ],
70 'repeat' => [ \&repeat_filter_factory, 1 ],
71 'replace' => [ \&replace_filter_factory, 1 ],
72 'remove' => [ \&remove_filter_factory, 1 ],
73 'eval' => [ \&eval_filter_factory, 1 ],
74 'evaltt' => [ \&eval_filter_factory, 1 ], # alias
75 'perl' => [ \&perl_filter_factory, 1 ],
76 'evalperl' => [ \&perl_filter_factory, 1 ], # alias
77 'redirect' => [ \&redirect_filter_factory, 1 ],
78 'file' => [ \&redirect_filter_factory, 1 ], # alias
79 'stdout' => [ \&stdout_filter_factory, 1 ],
80 };
81  
82 # name of module implementing plugin filters
83 our $PLUGIN_FILTER = 'Template::Plugin::Filter';
84  
85  
86  
87 #========================================================================
88 # -- PUBLIC METHODS --
89 #========================================================================
90  
91 #------------------------------------------------------------------------
92 # fetch($name, \@args, $context)
93 #
94 # Attempts to instantiate or return a reference to a filter sub-routine
95 # named by the first parameter, $name, with additional constructor
96 # arguments passed by reference to a list as the second parameter,
97 # $args. A reference to the calling Template::Context object is
98 # passed as the third parameter.
99 #
100 # Returns a reference to a filter sub-routine or a pair of values
101 # (undef, STATUS_DECLINED) or ($error, STATUS_ERROR) to decline to
102 # deliver the filter or to indicate an error.
103 #------------------------------------------------------------------------
104  
105 sub fetch {
106 my ($self, $name, $args, $context) = @_;
107 my ($factory, $is_dynamic, $filter, $error);
108  
109 $self->debug("fetch($name, ",
110 defined $args ? ('[ ', join(', ', @$args), ' ]') : '<no args>', ', ',
111 defined $context ? $context : '<no context>',
112 ')') if $self->{ DEBUG };
113  
114 # allow $name to be specified as a reference to
115 # a plugin filter object; any other ref is
116 # assumed to be a coderef and hence already a filter;
117 # non-refs are assumed to be regular name lookups
118  
119 if (ref $name) {
120 if (blessed($name) && $name->isa($PLUGIN_FILTER)) {
121 $factory = $name->factory()
122 || return $self->error($name->error());
123 }
124 else {
125 return $name;
126 }
127 }
128 else {
129 return (undef, Template::Constants::STATUS_DECLINED)
130 unless ($factory = $self->{ FILTERS }->{ $name }
131 || $FILTERS->{ $name });
132 }
133  
134 # factory can be an [ $code, $dynamic ] or just $code
135 if (ref $factory eq 'ARRAY') {
136 ($factory, $is_dynamic) = @$factory;
137 }
138 else {
139 $is_dynamic = 0;
140 }
141  
142 if (ref $factory eq 'CODE') {
143 if ($is_dynamic) {
144 # if the dynamic flag is set then the sub-routine is a
145 # factory which should be called to create the actual
146 # filter...
147 eval {
148 ($filter, $error) = &$factory($context, $args ? @$args : ());
149 };
150 $error ||= $@;
151 $error = "invalid FILTER for '$name' (not a CODE ref)"
152 unless $error || ref($filter) eq 'CODE';
153 }
154 else {
155 # ...otherwise, it's a static filter sub-routine
156 $filter = $factory;
157 }
158 }
159 else {
160 $error = "invalid FILTER entry for '$name' (not a CODE ref)";
161 }
162  
163 if ($error) {
164 return $self->{ TOLERANT }
165 ? (undef, Template::Constants::STATUS_DECLINED)
166 : ($error, Template::Constants::STATUS_ERROR) ;
167 }
168 else {
169 return $filter;
170 }
171 }
172  
173  
174 #------------------------------------------------------------------------
175 # store($name, \&filter)
176 #
177 # Stores a new filter in the internal FILTERS hash. The first parameter
178 # is the filter name, the second a reference to a subroutine or
179 # array, as per the standard $FILTERS entries.
180 #------------------------------------------------------------------------
181  
182 sub store {
183 my ($self, $name, $filter) = @_;
184  
185 $self->debug("store($name, $filter)") if $self->{ DEBUG };
186  
187 $self->{ FILTERS }->{ $name } = $filter;
188 return 1;
189 }
190  
191  
192 #========================================================================
193 # -- PRIVATE METHODS --
194 #========================================================================
195  
196 #------------------------------------------------------------------------
197 # _init(\%config)
198 #
199 # Private initialisation method.
200 #------------------------------------------------------------------------
201  
202 sub _init {
203 my ($self, $params) = @_;
204  
205 $self->{ FILTERS } = $params->{ FILTERS } || { };
206 $self->{ TOLERANT } = $params->{ TOLERANT } || 0;
207 $self->{ DEBUG } = ( $params->{ DEBUG } || 0 )
208 & Template::Constants::DEBUG_FILTERS;
209  
210  
211 return $self;
212 }
213  
214 #========================================================================
215 # -- STATIC FILTER SUBS --
216 #========================================================================
217  
218 #------------------------------------------------------------------------
219 # uri_filter() and url_filter() below can match using either RFC3986 or
220 # RFC2732. See https://github.com/abw/Template2/issues/13
221 #-----------------------------------------------------------------------
222  
223 our $UNSAFE_SPEC = {
224 RFC2732 => q{A-Za-z0-9\-_.~!*'()},
225 RFC3986 => q{A-Za-z0-9\-_.~},
226 };
227 our $UNSAFE_CHARS = $UNSAFE_SPEC->{ RFC3986 };
228 our $URI_REGEX;
229 our $URL_REGEX;
230 our $URI_ESCAPES;
231  
232 sub use_rfc2732 {
233 $UNSAFE_CHARS = $UNSAFE_SPEC->{ RFC2732 };
234 $URI_REGEX = $URL_REGEX = undef;
235 }
236  
237 sub use_rfc3986 {
238 $UNSAFE_CHARS = $UNSAFE_SPEC->{ RFC3986 };
239 $URI_REGEX = $URL_REGEX = undef;
240 }
241  
242 sub uri_escapes {
243 return {
244 map { ( chr($_), sprintf("%%%02X", $_) ) } (0..255),
245 };
246 }
247  
248 #------------------------------------------------------------------------
249 # uri_filter() [% FILTER uri %]
250 #
251 # URI escape a string. This code is borrowed from Gisle Aas' URI::Escape
252 # module, copyright 1995-2004. See RFC2396, RFC2732 and RFC3986 for
253 # details.
254 #-----------------------------------------------------------------------
255  
256 sub uri_filter {
257 my $text = shift;
258  
259 $URI_REGEX ||= qr/([^$UNSAFE_CHARS])/;
260 $URI_ESCAPES ||= uri_escapes();
261  
262 if ($] >= 5.008 && utf8::is_utf8($text)) {
263 utf8::encode($text);
264 }
265  
266 $text =~ s/$URI_REGEX/$URI_ESCAPES->{$1}/eg;
267 $text;
268 }
269  
270  
271  
272 #------------------------------------------------------------------------
273 # url_filter() [% FILTER uri %]
274 #
275 # NOTE: the difference: url vs uri.
276 # This implements the old-style, non-strict behaviour of the uri filter
277 # which allows any valid URL characters to pass through so that
278 # http://example.com/blah.html does not get the ':' and '/' characters
279 # munged.
280 #-----------------------------------------------------------------------
281  
282 sub url_filter {
283 my $text = shift;
284  
285 $URL_REGEX ||= qr/([^;\/?:@&=+\$,$UNSAFE_CHARS])/;
286 $URI_ESCAPES ||= uri_escapes();
287  
288 if ($] >= 5.008 && utf8::is_utf8($text)) {
289 utf8::encode($text);
290 }
291  
292 $text =~ s/$URL_REGEX/$URI_ESCAPES->{$1}/eg;
293 $text;
294 }
295  
296  
297 #------------------------------------------------------------------------
298 # html_filter() [% FILTER html %]
299 #
300 # Convert any '<', '>', '&', '"' or "'" characters to the HTML
301 # equivalents, '&lt;', '&gt;', '&amp;', '&quot;' and '&#39;',
302 # respectively.
303 #------------------------------------------------------------------------
304  
305 sub html_filter {
306 my $text = shift;
307 for ($text) {
308 s/&/&amp;/g;
309 s/</&lt;/g;
310 s/>/&gt;/g;
311 s/"/&quot;/g;
312 s/'/&#39;/g;
313 }
314 return $text;
315 }
316  
317  
318 #------------------------------------------------------------------------
319 # xml_filter() [% FILTER xml %]
320 #
321 # Same as the html filter, but uses &apos; for single quotes (the XML
322 # named entity) instead of &#39; (the numeric reference used for HTML).
323 #------------------------------------------------------------------------
324  
325 sub xml_filter {
326 my $text = shift;
327 for ($text) {
328 s/&/&amp;/g;
329 s/</&lt;/g;
330 s/>/&gt;/g;
331 s/"/&quot;/g;
332 s/'/&apos;/g;
333 }
334 return $text;
335 }
336  
337  
338 #------------------------------------------------------------------------
339 # html_paragraph() [% FILTER html_para %]
340 #
341 # Wrap each paragraph of text (delimited by two or more newlines) in the
342 # <p>...</p> HTML tags.
343 #------------------------------------------------------------------------
344  
345 sub html_paragraph {
346 my $text = shift;
347 return "<p>\n"
348 . join("\n</p>\n\n<p>\n", split(/(?:\r?\n){2,}/, $text))
349 . "</p>\n";
350 }
351  
352  
353 #------------------------------------------------------------------------
354 # html_para_break() [% FILTER html_para_break %]
355 #
356 # Join each paragraph of text (delimited by two or more newlines) with
357 # <br><br> HTML tags.
358 #------------------------------------------------------------------------
359  
360 sub html_para_break {
361 my $text = shift;
362 $text =~ s|(\r?\n){2,}|$1<br />$1<br />$1|g;
363 return $text;
364 }
365  
366 #------------------------------------------------------------------------
367 # html_line_break() [% FILTER html_line_break %]
368 #
369 # replaces any newlines with <br> HTML tags.
370 #------------------------------------------------------------------------
371  
372 sub html_line_break {
373 my $text = shift;
374 $text =~ s|(\r?\n)|<br />$1|g;
375 return $text;
376 }
377  
378 #========================================================================
379 # -- DYNAMIC FILTER FACTORIES --
380 #========================================================================
381  
382 #------------------------------------------------------------------------
383 # html_entity_filter_factory(\%options) [% FILTER html %]
384 #
385 # Dynamic version of the static html filter which attempts to locate the
386 # Apache::Util or HTML::Entities modules to perform full entity encoding
387 # of the text passed. Returns an exception if one or other of the
388 # modules can't be located.
389 #------------------------------------------------------------------------
390  
391 sub use_html_entities {
392 require HTML::Entities;
393 return ($AVAILABLE->{ HTML_ENTITY } = \&HTML::Entities::encode_entities);
394 }
395  
396 sub use_apache_util {
397 require Apache::Util;
398 Apache::Util::escape_html(''); # TODO: explain this
399 return ($AVAILABLE->{ HTML_ENTITY } = \&Apache::Util::escape_html);
400 }
401  
402 sub html_entity_filter_factory {
403 my $context = shift;
404 my $haz;
405  
406 # if Apache::Util is installed then we use escape_html
407 $haz = $AVAILABLE->{ HTML_ENTITY }
408 || eval { use_apache_util() }
409 || eval { use_html_entities() }
410 || -1; # we use -1 for "not available" because it's a true value
411  
412 return ref $haz eq 'CODE'
413 ? $haz
414 : (undef, Template::Exception->new(
415 html_entity => 'cannot locate Apache::Util or HTML::Entities' )
416 );
417 }
418  
419  
420 #------------------------------------------------------------------------
421 # indent_filter_factory($pad) [% FILTER indent(pad) %]
422 #
423 # Create a filter to indent text by a fixed pad string or when $pad is
424 # numerical, a number of space.
425 #------------------------------------------------------------------------
426  
427 sub indent_filter_factory {
428 my ($context, $pad) = @_;
429 $pad = 4 unless defined $pad;
430 $pad = ' ' x $pad if $pad =~ /^\d+$/;
431  
432 return sub {
433 my $text = shift;
434 $text = '' unless defined $text;
435 $text =~ s/^/$pad/mg;
436 return $text;
437 }
438 }
439  
440 #------------------------------------------------------------------------
441 # format_filter_factory() [% FILTER format(format) %]
442 #
443 # Create a filter to format text according to a printf()-like format
444 # string.
445 #------------------------------------------------------------------------
446  
447 sub format_filter_factory {
448 my ($context, $format) = @_;
449 $format = '%s' unless defined $format;
450  
451 return sub {
452 my $text = shift;
453 $text = '' unless defined $text;
454 return join("\n", map{ sprintf($format, $_) } split(/\n/, $text));
455 }
456 }
457  
458  
459 #------------------------------------------------------------------------
460 # repeat_filter_factory($n) [% FILTER repeat(n) %]
461 #
462 # Create a filter to repeat text n times.
463 #------------------------------------------------------------------------
464  
465 sub repeat_filter_factory {
466 my ($context, $iter) = @_;
467 $iter = 1 unless defined $iter and length $iter;
468  
469 return sub {
470 my $text = shift;
471 $text = '' unless defined $text;
472 return join('\n', $text) x $iter;
473 }
474 }
475  
476  
477 #------------------------------------------------------------------------
478 # replace_filter_factory($s, $r) [% FILTER replace(search, replace) %]
479 #
480 # Create a filter to replace 'search' text with 'replace'
481 #------------------------------------------------------------------------
482  
483 sub replace_filter_factory {
484 my ($context, $search, $replace) = @_;
485 $search = '' unless defined $search;
486 $replace = '' unless defined $replace;
487  
488 return sub {
489 my $text = shift;
490 $text = '' unless defined $text;
491 $text =~ s/$search/$replace/g;
492 return $text;
493 }
494 }
495  
496  
497 #------------------------------------------------------------------------
498 # remove_filter_factory($text) [% FILTER remove(text) %]
499 #
500 # Create a filter to remove 'search' string from the input text.
501 #------------------------------------------------------------------------
502  
503 sub remove_filter_factory {
504 my ($context, $search) = @_;
505  
506 return sub {
507 my $text = shift;
508 $text = '' unless defined $text;
509 $text =~ s/$search//g;
510 return $text;
511 }
512 }
513  
514  
515 #------------------------------------------------------------------------
516 # truncate_filter_factory($n) [% FILTER truncate(n) %]
517 #
518 # Create a filter to truncate text after n characters.
519 #------------------------------------------------------------------------
520  
521 sub truncate_filter_factory {
522 my ($context, $len, $char) = @_;
523 $len = $TRUNCATE_LENGTH unless defined $len;
524 $char = $TRUNCATE_ADDON unless defined $char;
525  
526 # Calculate visual length of the addon, treating HTML character entity
527 # references (e.g. &hellip; &#8230; &#x2026;) as single characters
528 my $lchar = _visual_length($char);
529 if ($len < $lchar) {
530 $char = substr($char, 0, $len);
531 $lchar = $len;
532 }
533  
534 return sub {
535 my $text = shift;
536 return $text if _visual_length($text) <= $len;
537 return _truncate_visual($text, $len - $lchar) . $char;
538 }
539 }
540  
541  
542 #------------------------------------------------------------------------
543 # _visual_length($str)
544 #
545 # Returns the "visual" length of a string, counting each HTML character
546 # entity reference (&name; &#digits; &#xhex;) as a single character.
547 #------------------------------------------------------------------------
548  
549 sub _visual_length {
550 my $str = shift;
551 (my $copy = $str) =~ s/&(?:[a-zA-Z][a-zA-Z0-9]*|#[0-9]+|#x[0-9a-fA-F]+);/_/g;
552 return length $copy;
553 }
554  
555  
556 #------------------------------------------------------------------------
557 # _truncate_visual($str, $maxlen)
558 #
559 # Truncates $str to at most $maxlen visual characters, treating HTML
560 # character entity references as single characters and never splitting
561 # one in the middle.
562 #------------------------------------------------------------------------
563  
564 sub _truncate_visual {
565 my ($str, $maxlen) = @_;
566 my $result = '';
567 my $vlen = 0;
568  
569 while ($str =~ /\G(&(?:[a-zA-Z][a-zA-Z0-9]*|#[0-9]+|#x[0-9a-fA-F]+);|.)/gs) {
570 last if $vlen >= $maxlen;
571 $result .= $1;
572 $vlen++;
573 }
574 return $result;
575 }
576  
577  
578 #------------------------------------------------------------------------
579 # eval_filter_factory [% FILTER eval %]
580 #
581 # Create a filter to evaluate template text.
582 #------------------------------------------------------------------------
583  
584 sub eval_filter_factory {
585 my $context = shift;
586  
587 return sub {
588 my $text = shift;
589 $context->process(\$text);
590 }
591 }
592  
593  
594 #------------------------------------------------------------------------
595 # perl_filter_factory [% FILTER perl %]
596 #
597 # Create a filter to process Perl text iff the context EVAL_PERL flag
598 # is set.
599 #------------------------------------------------------------------------
600  
601 sub perl_filter_factory {
602 my $context = shift;
603 my $stash = $context->stash;
604  
605 return (undef, Template::Exception->new('perl', 'EVAL_PERL is not set'))
606 unless $context->eval_perl();
607  
608 return sub {
609 my $text = shift;
610 local($Template::Perl::context) = $context;
611 local($Template::Perl::stash) = $stash;
612 my $out = eval <<EOF;
613 package Template::Perl;
614 \$stash = \$context->stash();
615 $text
616 EOF
617 $context->throw($@) if $@;
618 return $out;
619 }
620 }
621  
622  
623 #------------------------------------------------------------------------
624 # redirect_filter_factory($context, $file) [% FILTER redirect(file) %]
625 #
626 # Create a filter to redirect the block text to a file.
627 #------------------------------------------------------------------------
628  
629 sub redirect_filter_factory {
630 my ($context, $file, $options) = @_;
631 my $outpath = $context->config->{ OUTPUT_PATH };
632  
633 return (undef, Template::Exception->new('redirect',
634 'OUTPUT_PATH is not set'))
635 unless $outpath;
636  
637 $context->throw('redirect', "relative filenames are not supported: $file")
638 if $file =~ m{(^|/)\.\./};
639  
640 $options = { binmode => $options } unless ref $options;
641  
642 sub {
643 my $text = shift;
644 my $outpath = $context->config->{ OUTPUT_PATH }
645 || return '';
646 $outpath .= "/$file";
647 my $error = Template::_output($outpath, \$text, $options);
648 die Template::Exception->new('redirect', $error)
649 if $error;
650 return '';
651 }
652 }
653  
654  
655 #------------------------------------------------------------------------
656 # stdout_filter_factory($context, $binmode) [% FILTER stdout(binmode) %]
657 #
658 # Create a filter to print a block to stdout, with an optional binmode.
659 #------------------------------------------------------------------------
660  
661 sub stdout_filter_factory {
662 my ($context, $options) = @_;
663  
664 $options = { binmode => $options } unless ref $options;
665  
666 sub {
667 my $text = shift;
668 binmode(STDOUT) if $options->{ binmode };
669 print STDOUT $text;
670 return '';
671 }
672 }
673  
674  
675 1;
676  
677 __END__