blib/lib/Template/Filters.pm untested

filter: Statementstmt 0.0% 0 / 239 Branchbran 0.0% 0 / 58 Conditioncond 0.0% 0 / 77 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 438 CC 30 SCAR 37.5
CC
30
Cov
0%
fetch
182.0
redirect_filter_factory
30.0
truncate_filter_factory
12.0
CRAP 42.4
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.105';
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 $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;
430 $pad = ' ' x $pad if $pad =~ /^\d+$/;
431  
432 return sub {
433 my $text = shift // '';
434 $text =~ s/^/$pad/mg;
435 return $text;
436 }
437 }
438  
439 #------------------------------------------------------------------------
440 # format_filter_factory() [% FILTER format(format) %]
441 #
442 # Create a filter to format text according to a printf()-like format
443 # string.
444 #------------------------------------------------------------------------
445  
446 sub format_filter_factory {
447 my ($context, $format) = @_;
448 $format //= '%s';
449  
450 return sub {
451 my $text = shift // '';
452 return join("\n", map{ sprintf($format, $_) } split(/\n/, $text));
453 }
454 }
455  
456  
457 #------------------------------------------------------------------------
458 # repeat_filter_factory($n) [% FILTER repeat(n) %]
459 #
460 # Create a filter to repeat text n times.
461 #------------------------------------------------------------------------
462  
463 sub repeat_filter_factory {
464 my ($context, $iter) = @_;
465 $iter = 1 unless defined $iter and length $iter;
466  
467 return sub {
468 my $text = shift // '';
469 return join('\n', $text) x $iter;
470 }
471 }
472  
473  
474 #------------------------------------------------------------------------
475 # replace_filter_factory($s, $r) [% FILTER replace(search, replace) %]
476 #
477 # Create a filter to replace 'search' text with 'replace'
478 #------------------------------------------------------------------------
479  
480 sub replace_filter_factory {
481 my ($context, $search, $replace) = @_;
482 $search //= '';
483 $replace //= '';
484  
485 return sub {
486 my $text = shift // '';
487 my $prev_end = -1;
488 $text =~ s{$search}{
489 my $s = $-[0];
490 my $e = $+[0];
491 if ($s == $e && $s == $prev_end) {
492 '';
493 } else {
494 $prev_end = $e;
495 $replace;
496 }
497 }eg;
498 return $text;
499 }
500 }
501  
502  
503 #------------------------------------------------------------------------
504 # remove_filter_factory($text) [% FILTER remove(text) %]
505 #
506 # Create a filter to remove 'search' string from the input text.
507 #------------------------------------------------------------------------
508  
509 sub remove_filter_factory {
510 my ($context, $search) = @_;
511  
512 return sub {
513 my $text = shift // '';
514 $text =~ s/$search//g;
515 return $text;
516 }
517 }
518  
519  
520 #------------------------------------------------------------------------
521 # truncate_filter_factory($n) [% FILTER truncate(n) %]
522 #
523 # Create a filter to truncate text after n characters.
524 #------------------------------------------------------------------------
525  
526 sub truncate_filter_factory {
527 my ($context, $len, $char) = @_;
528 $len //= $TRUNCATE_LENGTH;
529 $char //= $TRUNCATE_ADDON;
530  
531 # Calculate visual length of the addon, treating HTML character entity
532 # references (e.g. &hellip; &#8230; &#x2026;) as single characters
533 my $lchar = _visual_length($char);
534 if ($len < $lchar) {
535 $char = substr($char, 0, $len);
536 $lchar = $len;
537 }
538  
539 return sub {
540 my $text = shift;
541 return $text if _visual_length($text) <= $len;
542 return _truncate_visual($text, $len - $lchar) . $char;
543 }
544 }
545  
546  
547 #------------------------------------------------------------------------
548 # _visual_length($str)
549 #
550 # Returns the "visual" length of a string, counting each HTML character
551 # entity reference (&name; &#digits; &#xhex;) as a single character.
552 #------------------------------------------------------------------------
553  
554 sub _visual_length {
555 my $str = shift;
556 (my $copy = $str) =~ s/&(?:[a-zA-Z][a-zA-Z0-9]*|#[0-9]+|#x[0-9a-fA-F]+);/_/g;
557 return length $copy;
558 }
559  
560  
561 #------------------------------------------------------------------------
562 # _truncate_visual($str, $maxlen)
563 #
564 # Truncates $str to at most $maxlen visual characters, treating HTML
565 # character entity references as single characters and never splitting
566 # one in the middle.
567 #------------------------------------------------------------------------
568  
569 sub _truncate_visual {
570 my ($str, $maxlen) = @_;
571 my $result = '';
572 my $vlen = 0;
573  
574 while ($str =~ /\G(&(?:[a-zA-Z][a-zA-Z0-9]*|#[0-9]+|#x[0-9a-fA-F]+);|.)/gs) {
575 last if $vlen >= $maxlen;
576 $result .= $1;
577 $vlen++;
578 }
579 return $result;
580 }
581  
582  
583 #------------------------------------------------------------------------
584 # eval_filter_factory [% FILTER eval %]
585 #
586 # Create a filter to evaluate template text.
587 #------------------------------------------------------------------------
588  
589 sub eval_filter_factory {
590 my $context = shift;
591  
592 return sub {
593 my $text = shift;
594 $context->process(\$text);
595 }
596 }
597  
598  
599 #------------------------------------------------------------------------
600 # perl_filter_factory [% FILTER perl %]
601 #
602 # Create a filter to process Perl text iff the context EVAL_PERL flag
603 # is set.
604 #------------------------------------------------------------------------
605  
606 sub perl_filter_factory {
607 my $context = shift;
608 my $stash = $context->stash;
609  
610 return (undef, Template::Exception->new('perl', 'EVAL_PERL is not set'))
611 unless $context->eval_perl();
612  
613 return sub {
614 my $text = shift;
615 local($Template::Perl::context) = $context;
616 local($Template::Perl::stash) = $stash;
617 my $out = eval <<EOF;
618 package Template::Perl;
619 \$stash = \$context->stash();
620 $text
621 EOF
622 $context->throw($@) if $@;
623 return $out;
624 }
625 }
626  
627  
628 #------------------------------------------------------------------------
629 # redirect_filter_factory($context, $file) [% FILTER redirect(file) %]
630 #
631 # Create a filter to redirect the block text to a file.
632 #------------------------------------------------------------------------
633  
634 sub redirect_filter_factory {
635 my ($context, $file, $options) = @_;
636 my $outpath = $context->config->{ OUTPUT_PATH };
637  
638 return (undef, Template::Exception->new('redirect',
639 'OUTPUT_PATH is not set'))
640 unless $outpath;
641  
642 $context->throw('redirect', "relative filenames are not supported: $file")
643 if $file =~ m{(^|/)\.\./};
644  
645 $options = { binmode => $options } unless ref $options;
646  
647 sub {
648 my $text = shift;
649 my $outpath = $context->config->{ OUTPUT_PATH }
650 || return '';
651 $outpath .= "/$file";
652 my $error = Template::_output($outpath, \$text, $options);
653 die Template::Exception->new('redirect', $error)
654 if $error;
655 return '';
656 }
657 }
658  
659  
660 #------------------------------------------------------------------------
661 # stdout_filter_factory($context, $binmode) [% FILTER stdout(binmode) %]
662 #
663 # Create a filter to print a block to stdout, with an optional binmode.
664 #------------------------------------------------------------------------
665  
666 sub stdout_filter_factory {
667 my ($context, $options) = @_;
668  
669 $options = { binmode => $options } unless ref $options;
670  
671 sub {
672 my $text = shift;
673 binmode(STDOUT) if $options->{ binmode };
674 print STDOUT $text;
675 return '';
676 }
677 }
678  
679  
680 1;
681  
682 __END__