1 package CGI
::Ex
::Template
;
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2006 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
10 use constant trace
=> $ENV{'CET_TRACE'} || 0; # enable for low level tracing
13 $SCALAR_OPS $HASH_OPS $LIST_OPS $FILTER_OPS
14 $DIRECTIVES $QR_DIRECTIVE
32 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
41 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
42 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
43 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
44 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
45 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
48 default => ['[%', '%]'], # default
49 template
=> ['[%', '%]'], # default
50 metatext
=> ['%%', '%%'], # Text::MetaText
51 star
=> ['[*', '*]'], # TT alternate
52 php
=> ['<?', '?>'], # PHP
53 asp
=> ['<%', '%>'], # ASP
54 mason
=> ['<%', '>' ], # HTML::Mason
55 html
=> ['<!--', '-->'], # HTML comments
59 chunk
=> \
&vmethod_chunk
,
60 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
62 indent
=> \
&vmethod_indent
,
63 'format' => \
&vmethod_format
,
64 hash
=> sub { {value
=> $_[0]} },
65 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; $_ },
66 lcfirst => sub { lcfirst $_[0] },
67 length => sub { defined($_[0]) ? length($_[0]) : 0 },
68 lower
=> sub { lc $_[0] },
69 match
=> \
&vmethod_match
,
71 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
72 repeat
=> \
&vmethod_repeat
,
73 replace
=> \
&vmethod_replace
,
74 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return scalar $str =~ /$pat/ },
76 split => \
&vmethod_split
,
77 stderr
=> sub { print STDERR
$_[0]; '' },
78 substr => sub { my ($str, $i, $len) = @_; defined($len) ? substr($str, $i, $len) : substr($str, $i) },
79 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
80 ucfirst => sub { ucfirst $_[0] },
81 upper
=> sub { uc $_[0] },
85 $FILTER_OPS ||= { # generally - non-dynamic filters belong in scalar ops
86 eval => [\
&filter_eval
, 1],
87 evaltt
=> [\
&filter_eval
, 1],
88 file
=> [\
&filter_redirect
, 1],
89 redirect
=> [\
&filter_redirect
, 1],
93 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
94 grep => sub { my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
95 hash
=> sub { my ($list, $i) = @_; defined($i) ? {map {$i++ => $_} @$list} : {@$list} },
96 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
97 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
98 list
=> sub { $_[0] },
99 max
=> sub { $#{ $_[0] } },
100 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
101 nsort
=> \
&vmethod_nsort
,
102 pop => sub { pop @{ $_[0] } },
103 push => sub { my $ref = shift; push @$ref, @_; return '' },
104 reverse => sub { [ reverse @{ $_[0] } ] },
105 shift => sub { shift @{ $_[0] } },
106 size
=> sub { scalar @{ $_[0] } },
107 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
108 sort => \
&vmethod_sort
,
109 splice => \
&vmethod_splice
,
110 unique
=> sub { my %u; return [ grep { ! $u{$_} ++ } @{ $_[0] } ] },
111 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
115 defined => sub { return '' if ! defined $_[1]; defined $_[0]->{ $_[1] } },
116 delete => sub { return '' if ! defined $_[1]; delete $_[0]->{ $_[1] } },
117 each => sub { [%{ $_[0] }] },
118 exists => sub { return '' if ! defined $_[1]; exists $_[0]->{ $_[1] } },
119 hash
=> sub { $_[0] },
120 import
=> sub { my ($a, $b) = @_; return '' if ref($b) ne 'HASH'; @{$a}{keys %$b} = values %$b; '' },
121 keys => sub { [keys %{ $_[0] }] },
122 list
=> sub { [$_[0]] },
123 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } keys %{ $_[0] } ] },
124 nsort
=> sub { my $ref = shift; [sort {$ref->{$a} <=> $ref->{$b} } keys %$ref] },
125 size
=> sub { scalar keys %{ $_[0] } },
126 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
127 values => sub { [values %{ $_[0] }] },
131 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
132 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
133 BREAK
=> [sub {}, \
&play_control
],
134 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
135 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
136 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
137 CLEAR
=> [sub {}, \
&play_CLEAR
],
138 '#' => [sub {}, sub {}],
139 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
140 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
141 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
142 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
143 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
144 END => [undef, sub {}],
145 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
146 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
147 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
148 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
149 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
150 GET
=> [\
&parse_GET
, \
&play_GET
],
151 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
152 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
153 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
154 LAST
=> [sub {}, \
&play_control
],
155 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
156 META
=> [undef, sub {}],
157 METADEF
=> [undef, \
&play_METADEF
],
158 NEXT => [sub {}, \
&play_control
],
159 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
160 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
161 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
162 RETURN
=> [sub {}, \
&play_control
],
163 SET
=> [\
&parse_SET
, \
&play_SET
],
164 STOP
=> [sub {}, \
&play_control
],
165 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
166 TAGS
=> [undef, sub {}],
167 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
168 TRY
=> [sub {}, \
&play_TRY
, 1],
169 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
170 USE
=> [\
&parse_USE
, \
&play_USE
],
171 WHILE
=> [\
&parse_IF
, \
&play_WHILE
, 1, 1],
172 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
173 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
175 $QR_DIRECTIVE = qr{ ^ (\w+|\|) (?= $|[\s;\#]) }x;
177 ### setup the operator parsing
179 # name => # order, precedence, symbols, only_in_parens, sub to create
180 [2, 96, ['**', '^', 'pow'], 0, sub { $_[0] ** $_[1] } ],
181 [1, 93, ['!'], 0, sub { ! $_[0] } ],
182 [1, 93, ['-'], 0, sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
183 [2, 90, ['*'], 0, sub { $_[0] * $_[1] } ],
184 [2, 90, ['/'], 0, sub { $_[0] / $_[1] } ],
185 [2, 90, ['div', 'DIV'], 0, sub { int($_[0] / $_[1]) } ],
186 [2, 90, ['%', 'mod', 'MOD'], 0, sub { $_[0] % $_[1] } ],
187 [2, 85, ['+'], 0, sub { $_[0] + $_[1] } ],
188 [2, 85, ['-'], 0, sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
189 [2, 85, ['_', '~'], 0, sub { join "", @_ } ],
190 [2, 80, ['<'], 0, sub { $_[0] < $_[1] } ],
191 [2, 80, ['>'], 0, sub { $_[0] > $_[1] } ],
192 [2, 80, ['<='], 0, sub { $_[0] <= $_[1] } ],
193 [2, 80, ['>='], 0, sub { $_[0] >= $_[1] } ],
194 [2, 80, ['lt'], 0, sub { $_[0] lt $_[1] } ],
195 [2, 80, ['gt'], 0, sub { $_[0] gt $_[1] } ],
196 [2, 80, ['le'], 0, sub { $_[0] le $_[1] } ],
197 [2, 80, ['ge'], 0, sub { $_[0] ge $_[1] } ],
198 [2, 75, ['==', 'eq'], 0, sub { $_[0] eq $_[1] } ],
199 [2, 75, ['!=', 'ne'], 0, sub { $_[0] ne $_[1] } ],
200 [2, 70, ['&&'], 0, undef ],
201 [2, 65, ['||'], 0, undef ],
202 [2, 60, ['..'], 0, sub { $_[0] .. $_[1] } ],
203 [3, 55, ['?', ':'], 0, undef ],
204 [2, 52, ['='], 1, undef ],
205 [1, 50, ['not', 'NOT'], 0, sub { ! $_[0] } ],
206 [2, 45, ['and', 'AND'], 0, undef ],
207 [2, 40, ['or', 'OR'], 0, undef ],
208 [0, 0, ['hash'], 0, sub { return {@_}; } ],
209 [0, 0, ['array'], 0, sub { return [@_] } ],
211 $OP_DISPATCH ||= {map {my $ref = $_; map {$_ => $ref->[4]} @{$ref->[2]}} @$OPERATORS};
212 $OP_UNARY ||= {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] == 1} @$OPERATORS};
213 $OP_BINARY ||= {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] == 2} @$OPERATORS};
214 $OP_TRINARY ||= {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] == 3} @$OPERATORS};
215 sub _op_qr
{ # no mixed \w\W operators
217 my $chrs = join '|', map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W{2,}$/} @_;
218 my $chr = join '', map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
219 my $word = join '|', grep {++$used{$_} < 2} grep {/^\w+$/} @_;
220 $chr = "[$chr]" if $chr;
221 $word = "\\b(?:$word)\\b" if $word;
222 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
224 sub _build_op_qr
{ _op_qr
(sort map {@{ $_->[2] }} grep {$_->[0] > 1 && ! $_->[3]} @$OPERATORS) } # all binary, trinary, non-parened ops
225 sub _build_op_qr_unary
{ _op_qr
(sort map {@{ $_->[2] }} grep {$_->[0] == 1 } @$OPERATORS) } # unary operators
226 sub _build_op_qr_paren
{ _op_qr
(sort map {@{ $_->[2] }} grep { $_->[3]} @$OPERATORS) } # paren
227 $QR_OP ||= _build_op_qr
();
228 $QR_OP_UNARY ||= _build_op_qr_unary
();
229 $QR_OP_PARENED ||= _build_op_qr_paren
();
232 $QR_COMMENTS = '(?-s: \# .* \s*)*';
233 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
234 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
235 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
236 $QR_PRIVATE ||= qr/^_/;
239 $EXTRA_COMPILE_EXT = '.sto';
242 ###----------------------------------------------------------------###
246 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
247 my $self = bless $args, $class;
249 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
250 if ($self->{'DEBUG'}) {
251 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
252 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
258 ###----------------------------------------------------------------###
263 local $self->{'_vars'} = shift || {};
264 my $out_ref = shift || $self->throw('undef', "Missing output ref");
265 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
266 my $i = length $$out_ref;
268 ### parse and execute
271 ### load the document
272 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
274 ### prevent recursion
275 $self->throw('file', "recursion into '$doc->{name}'")
276 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
277 local $self->{'_in'}->{$doc->{'name'}} = 1;
279 ### execute the document
280 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
281 $$out_ref = ${ $doc->{'_content'} };
283 local $self->{'_vars'}->{'component'} = $doc;
284 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
285 $self->execute_tree($doc->{'_tree'}, $out_ref);
286 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
290 ### trim whitespace from the beginning and the end of a block or template
291 if ($self->{'TRIM'}) {
292 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
293 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
296 ### handle exceptions
298 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
299 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
300 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
306 ###----------------------------------------------------------------###
308 sub load_parsed_tree
{
311 return if ! defined $file;
313 my $doc = {name
=> $file};
315 ### looks like a string reference
317 $doc->{'_content'} = $file;
318 $doc->{'name'} = 'input text';
319 $doc->{'is_str_ref'} = 1;
321 ### looks like a previously cached-in-memory document
322 } elsif ($self->{'_documents'}->{$file}
323 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
324 || ($self->{'_documents'}->{$file}->{'modtime'}
325 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
326 $doc = $self->{'_documents'}->{$file};
327 $doc->{'_cache_time'} = time;
330 ### looks like a block name of some sort
331 } elsif ($self->{'BLOCKS'}->{$file}) {
332 my $block = $self->{'BLOCKS'}->{$file};
334 ### allow for predefined blocks that are a code or a string
335 if (UNIVERSAL
::isa
($block, 'CODE')) {
338 if (! UNIVERSAL
::isa
($block, 'HASH')) {
339 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
341 $block = eval { $self->load_parsed_tree(\
$copy) }
342 || $self->throw('block', 'Parse error on predefined block');
344 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
348 ### go and look on the file system
350 $doc->{'_filename'} = eval { $self->include_filename($file) };
352 ### allow for blocks in other files
353 if ($self->{'EXPOSE_BLOCKS'}
354 && ! $self->{'_looking_in_block_file'}) {
355 local $self->{'_looking_in_block_file'} = 1;
357 while ($file =~ s
|/([^/.]+)$||) {
358 $block_name = length($block_name) ? "$1/$block_name" : $1;
359 my $ref = eval { $self->load_parsed_tree($file) } || next;
360 my $_tree = $ref->{'_tree'};
361 foreach my $node (@$_tree) {
363 next if $node->[0] eq 'METADEF';
364 last if $node->[0] ne 'BLOCK';
365 next if $block_name ne $node->[3];
366 $doc->{'_content'} = $ref->{'_content'};
367 $doc->{'_tree'} = $node->[4];
368 $doc->{'modtime'} = $ref->{'modtime'};
369 $file = $ref->{'name'};
373 die $err if ! $doc->{'_tree'};
374 } elsif ($self->{'DEFAULT'}) {
375 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
381 ### no tree yet - look for a file cache
382 if (! $doc->{'_tree'}) {
383 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
384 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
385 if ($self->{'COMPILE_DIR'}) {
386 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
388 $doc->{'_compile_filename'} = $doc->{'_filename'};
390 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
391 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
393 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
395 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
396 $doc->{'compile_was_used'} = 1;
398 my $str = $self->slurp($doc->{'_filename'});
399 $doc->{'_content'} = \
$str;
402 my $str = $self->slurp($doc->{'_filename'});
403 $doc->{'_content'} = \
$str;
409 ### haven't found a parsed tree yet - parse the content into a tree
410 if (! $doc->{'_tree'}) {
411 if ($self->{'CONSTANTS'}) {
412 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
413 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
416 local $self->{'_vars'}->{'component'} = $doc;
417 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
420 ### cache parsed_tree in memory unless asked not to do so
421 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
422 $self->{'_documents'}->{$file} ||= $doc;
423 $doc->{'_cache_time'} = time;
425 ### allow for config option to keep the cache size down
426 if ($self->{'CACHE_SIZE'}) {
427 my $all = $self->{'_documents'};
428 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
430 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
431 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
437 ### save a cache on the fileside as asked
438 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
439 my $dir = $doc->{'_compile_filename'};
443 File
::Path
::mkpath
($dir);
446 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
447 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
456 if (! $str_ref || ! defined $$str_ref) {
457 $self->throw('parse.no_string', "No string or undefined during parse");
460 my $STYLE = $self->{'TAG_STYLE'} || 'default';
461 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
462 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
463 my $len_s = length $START;
464 my $len_e = length $END;
466 my @tree; # the parsed tree
467 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
468 my @state; # maintain block levels
469 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
470 local $self->{'_in_perl'}; # no interpolation in perl
471 my @move_to_front; # items that need to be declared first (usually BLOCKS)
472 my @meta; # place to store any found meta information (to go into METADEF)
473 my $i = 0; # start index
474 my $j = 0; # end index
475 my $last = 0; # previous end index
476 my $post_chomp = 0; # previous post_chomp setting
477 my $continue; # multiple directives in the same tag
478 my $post_op; # found a post-operative DIRECTIVE
479 my $capture; # flag to start capture
484 ### continue looking for information in a semi-colon delimited tag
487 $node = [undef, $i, $j];
489 ### look through the string using index
491 $i = index($$str_ref, $START, $last);
492 last if $i == -1; # no start tag found - we are done
493 if ($last != $i) { # found a text portion - chomp it, interpolate it and store it
494 my $text = substr($$str_ref, $last, $i - $last);
497 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
498 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
499 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
502 push @$pointer, $text;
503 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
506 $j = index($$str_ref, $END, $i + $len_s);
508 if ($j == -1) { # missing closing tag
509 $last = length($$str_ref);
512 $tag = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
513 $node = [undef, $i + $len_s, $j];
515 ### take care of whitespace and comments flags
516 my $pre_chomp = $tag =~ s{ ^ ([+=~-]) }{}x ? $1 : $self->{'PRE_CHOMP'};
517 $post_chomp = $tag =~ s{ ([+=~-]) $ }{}x ? $1 : $self->{'POST_CHOMP'};
518 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
519 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
520 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
521 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
522 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
523 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
524 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
526 if ($tag =~ /^\#/) { # leading # means to comment the entire section
528 push @$pointer, $node;
531 $tag =~ s{ ^ \s+ $QR_COMMENTS }{}ox;
540 ### look for DIRECTIVES
541 if ($tag =~ $QR_DIRECTIVE # find a word
542 && $DIRECTIVES->{$1} ) { # is it a directive
543 $node->[0] = $func = $1;
544 $tag =~ s{ ^ (\w+ | \|) \s* $QR_COMMENTS }{}ox;
546 ### store out this current node level
547 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
548 my @post_op = @$post_op;
551 $node->[4] = [\
@post_op];
553 # do nothing - it will be handled further down
555 push @$pointer, $node;
558 ### anything that behaves as a block ending
559 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
561 $self->throw('parse', "Found an $func tag while not in a block", $node);
563 my $parent_node = pop @state;
565 if ($func ne 'END') {
566 pop @$pointer; # we will store the node in the parent instead
567 $parent_node->[5] = $node;
568 my $parent_type = $parent_node->[0];
569 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
570 $self->throw('parse', "Found unmatched nested block", $node, 0);
574 ### restore the pointer up one level (because we hit the end of a block)
575 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
578 if ($func eq 'END') {
579 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
580 push @move_to_front, $parent_node;
581 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
582 splice(@$pointer, -1, 1, ());
584 } elsif ($parent_node->[0] =~ /PERL$/) {
585 delete $self->{'_in_perl'};
588 ### continuation block - such as an elsif
590 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
592 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
596 $pointer = $node->[4] ||= [];
599 } elsif ($func eq 'TAGS') {
600 if ($tag =~ / ^ (\w+) /x && $TAGS->{$1}) {
601 $tag =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox;
602 ($START, $END) = @{ $TAGS->{$1} };
603 } elsif ($tag =~ s{ ^ (\S+) \s+ (\S+) \s* $QR_COMMENTS }{}ox) {
604 ($START, $END) = ($1, $2);
606 $len_s = length $START;
607 $len_e = length $END;
609 } elsif ($func eq 'META') {
610 my $args = $self->parse_args(\
$tag);
612 if (($hash = $self->vivify_args($args)->[-1])
613 && UNIVERSAL
::isa
($hash, 'HASH')) {
614 unshift @meta, %$hash; # first defined win
617 ### all other "normal" tags
619 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
621 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
624 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
626 $pointer = $node->[4] ||= [];
630 ### allow for bare variable getting and setting
631 } elsif (defined(my $var = $self->parse_variable(\
$tag))) {
632 push @$pointer, $node;
633 if ($tag =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
635 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, \
$tag, $node, $var) };
637 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
646 my $all = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
649 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
652 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
654 my $parent_node = $capture;
655 push @{ $parent_node->[4] }, $node;
659 ### we are flagged to start capturing the output of the next directive - set it up
661 $continue = $j - length $tag;
662 $node->[2] = $continue;
666 ### semi-colon = end of statement - we will need to continue parsing this tag
667 } elsif ($tag =~ s{ ^ ; \s* $QR_COMMENTS }{}ox) {
668 $continue = $j - length $tag;
669 $node->[2] = $continue;
672 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
673 } elsif ($tag =~ $QR_DIRECTIVE # find a word
674 && $DIRECTIVES->{$1} # is it a directive
675 && $DIRECTIVES->{$1}->[3]) { # it is a post operative directive
676 $continue = $j - length $tag;
677 $node->[2] = $continue;
681 $self->throw('parse', "Found trailing info \"$tag\"", $node) if length $tag;
687 if (@move_to_front) {
688 unshift @tree, @move_to_front;
691 unshift @tree, ['METADEF', 0, 0, {@meta}];
695 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
698 ### pull off the last text portion - if any
699 if ($last != length($$str_ref)) {
700 my $text = substr($$str_ref, $last, length($$str_ref) - $last);
703 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
704 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
705 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
708 push @$pointer, $text;
709 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
717 my ($self, $tree, $out_ref) = @_;
719 # node contains (0: DIRECTIVE,
722 # 3: parsed tag details,
723 # 4: sub tree for block types
724 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
725 # 6: flag to capture next directive
726 for my $node (@$tree) {
727 ### text nodes are just the bare text
729 warn "NODE: TEXT\n" if trace
;
730 $$out_ref .= $node if defined $node;
734 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
735 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
737 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
738 $$out_ref .= $val if defined $val;
742 ###----------------------------------------------------------------###
747 my $ARGS = shift || {};
749 ### allow for custom auto_quoting (such as hash constructors)
750 if ($ARGS->{'auto_quote'}) {
751 if ($$str_ref =~ $ARGS->{'auto_quote'}) {
753 substr($$str_ref, 0, length($str), '');
754 $$str_ref =~ s{ ^ \s* $QR_COMMENTS }{}ox;
756 ### allow for auto-quoted $foo or ${foo.bar} type constructs
757 } elsif ($$str_ref =~ s{ ^ \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }{}ox
758 || $$str_ref =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
760 return $self->parse_variable(\
$name);
764 my $copy = $$str_ref; # copy while parsing to allow for errors
766 ### test for leading unary operators
768 if ($copy =~ s{ ^ ($QR_OP_UNARY) \s* $QR_COMMENTS }{}ox) {
769 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
777 ### allow for numbers
778 if ($copy =~ s{ ^ ( (?:\d*\.\d+ | \d+) ) \s* $QR_COMMENTS }{}ox) {
780 push @var, \
$number;
783 ### looks like a normal variable start
784 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
786 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
788 ### allow for literal strings
789 } elsif ($copy =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }{}sox) {
790 if ($1 eq "'") { # no interpolation on single quoted strings
792 $str =~ s{ \\\' }{\'}xg;
800 $str =~ s/\\([\"\$])/$1/g;
801 my @pieces = $ARGS->{'auto_quote'}
802 ? split(m{ (\$\w+ | \$\{ [^\}]+ \
}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
803 : split(m{ (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $str);
805 foreach my $piece (@pieces) {
806 next if ! ($n++ % 2);
807 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
808 && $piece !~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
;
810 $piece = $self->parse_variable(\
$name);
812 @pieces = grep {defined && length} @pieces;
813 if (@pieces == 1 && ! ref $pieces[0]) {
814 push @var, \
$pieces[0];
816 } elsif (! @pieces) {
820 push @var, \
['~', @pieces];
823 if ($ARGS->{'auto_quote'}){
825 return ${ $var[0] } if $is_literal;
830 ### allow for leading $foo or ${foo.bar} type constructs
831 } elsif ($copy =~ s{ ^ \$ (\w+) \b \s* $QR_COMMENTS }{}ox
832 || $copy =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
834 push @var, $self->parse_variable(\
$name);
836 ### looks like an array constructor
837 } elsif ($copy =~ s{ ^ \[ \s* $QR_COMMENTS }{}ox) {
838 local $self->{'_operator_precedence'} = 0; # reset presedence
839 my $arrayref = ['array'];
840 while (defined(my $var = $self->parse_variable(\
$copy))) {
841 push @$arrayref, $var;
842 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
844 $copy =~ s{ ^ \] \s* $QR_COMMENTS }{}ox
845 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, length($$str_ref) - length($copy));
846 push @var, \
$arrayref;
848 ### looks like a hash constructor
849 } elsif ($copy =~ s{ ^ \{ \s* $QR_COMMENTS }{}ox) {
850 local $self->{'_operator_precedence'} = 0; # reset precedence
851 my $hashref = ['hash'];
852 while (defined(my $key = $self->parse_variable(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))) {
853 $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox;
854 my $val = $self->parse_variable(\
$copy);
855 push @$hashref, $key, $val;
856 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
858 $copy =~ s{ ^ \} \s* $QR_COMMENTS }{}ox
859 || $self->throw('parse.missing.curly_bracket', "Missing close \} ($copy)", undef, length($$str_ref) - length($copy));
860 push @var, \
$hashref;
862 ### looks like a paren grouper
863 } elsif ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
864 local $self->{'_operator_precedence'} = 0; # reset precedence
865 my $var = $self->parse_variable(\
$copy, {allow_parened_ops
=> 1});
866 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
867 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
869 pop(@var); # pull off the trailing args of the paren group
871 ### nothing to find - return failure
876 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
878 ### looks for args for the initial
879 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
880 local $self->{'_operator_precedence'} = 0; # reset precedence
881 my $args = $self->parse_args(\
$copy);
882 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
883 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
889 ### allow for nested items
890 while ($copy =~ s{ ^ ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }{}ox) {
891 push(@var, $1) if ! $ARGS->{'no_dots'};
893 ### allow for interpolated variables in the middle - one.$foo.two or one.${foo.bar}.two
894 if ($copy =~ s{ ^ \$(\w+) \s* $QR_COMMENTS }{}ox
895 || $copy =~ s{ ^ \$\{ \s* ([^\}]+)\} \s* $QR_COMMENTS }{}ox) {
897 my $var = $self->parse_variable(\
$name);
899 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
902 $self->throw('parse', "Not sure how to continue parsing on \"$copy\" ($$str_ref)");
905 ### looks for args for the nested item
906 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
907 local $self->{'_operator_precedence'} = 0; # reset precedence
908 my $args = $self->parse_args(\
$copy);
909 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
910 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
918 ### flatten literals and constants as much as possible
919 my $var = ($is_literal && $#var == 1) ? ${ $var[0] }
920 : $is_namespace ? $self->get_variable(\
@var, {is_namespace_during_compile
=> 1})
923 ### allow for all "operators"
924 if (! $self->{'_operator_precedence'}) {
927 while ($copy =~ s{ ^ ($QR_OP) \s* $QR_COMMENTS }{}ox ## look for operators - then move along
928 || ($ARGS->{'allow_parened_ops'}
929 && $copy =~ s{ ^ ($QR_OP_PARENED) \s* $QR_COMMENTS }{}ox) ) {
930 local $self->{'_operator_precedence'} = 1;
932 my $var2 = $self->parse_variable(\
$copy);
934 ### allow for unary operator precedence
935 if ($has_unary && (($OP_BINARY->{$op} || $OP_TRINARY->{$op})->[1] < $OP_UNARY->{$has_unary}->[1])) {
937 if ($#$tree == 1) { # only one operator - keep simple things fast
938 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
940 unshift @$tree, $var;
941 $var = $self->apply_precedence($tree, $found);
946 $var = [ \
[ $has_unary, $var ], 0 ];
950 ### add the operator to the tree
951 push (@{ $tree ||= [] }, $op, $var2);
952 my $ref = $OP_BINARY->{$op} || $OP_TRINARY->{$op};
953 $found->{$op} = $ref->[1];
956 ### if we found operators - tree the nodes by operator precedence
958 if (@$tree == 2) { # only one operator - keep simple things fast
959 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
961 unshift @$tree, $var;
962 $var = $self->apply_precedence($tree, $found);
967 ### allow for unary on non-chained variables
969 $var = [ \
[ $has_unary, $var ], 0 ];
972 $$str_ref = $copy; # commit the changes
976 ### this is used to put the parsed variables into the correct operations tree
977 sub apply_precedence
{
978 my ($self, $tree, $found) = @_;
982 ### look at the operators we found in the order we found them
983 for my $op (sort {$found->{$a} <=> $found->{$b}} keys %$found) {
985 delete $found->{$op};
989 ### split the array on the current operator
990 for (my $i = 0; $i <= $#$tree; $i ++) {
991 my $is_trinary = $OP_TRINARY->{$op} && grep {$_ eq $tree->[$i]} @{ $OP_TRINARY->{$op}->[2] };
992 next if $tree->[$i] ne $op && ! $is_trinary;
993 push @trees, [splice @$tree, 0, $i, ()]; # everything up to the operator
994 push @trinary, $tree->[0] if $is_trinary;
995 shift @$tree; # pull off the operator
998 next if ! @trees; # this iteration didn't have the current operator
999 push @trees, $tree if scalar @$tree; # elements after last operator
1001 ### now - for this level split on remaining operators, or add the variable to the tree
1002 for my $node (@trees) {
1004 $node = $node->[0]; # single item - its not a tree
1005 } elsif (@$node == 3) {
1006 $node = [ \
[ $node->[1], $node->[0], $node->[2] ], 0 ]; # single operator - put it straight on
1008 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1013 if ($OP_BINARY->{$op}) {
1014 my $val = $trees[-1];
1015 $val = [ \
[ $op, $trees[$_], $val ], 0 ] for reverse (0 .. $#trees - 1); # reverse order - helps out ||
1019 ### return simple trinary
1020 if (@trinary == 2) {
1021 return [ \
[ $op, @trees ], 0 ];
1024 ### reorder complex trinary - rare case
1025 while ($#trinary >= 1) {
1026 ### if we look starting from the back - the first lead trinary op will always be next to its matching op
1027 for (my $i = $#trinary; $i >= 0; $i --) {
1028 next if $OP_TRINARY->{$trinary[$i]}->[2]->[1] eq $trinary[$i];
1029 my ($op, $op2) = splice @trinary, $i, 2, (); # remove the pair of operators
1030 my $node = [ \
[$op, @trees[$i .. $i + 2] ], 0 ];
1031 splice @trees, $i, 3, $node;
1034 return $trees[0]; # at this point the trinary has been reduced to a single operator
1038 $self->throw('parse', "Couldn't apply precedence");
1041 ### look for arguments - both positional and named
1044 my $str_ref = shift;
1045 my $ARGS = shift || {};
1046 my $copy = $$str_ref;
1050 while (length $$str_ref) {
1051 my $copy = $$str_ref;
1052 if (defined(my $name = $self->parse_variable(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
1053 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
1054 $self->throw('parse', 'Named arguments not allowed') if $ARGS->{'positional_only'};
1055 my $val = $self->parse_variable(\
$copy);
1056 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1057 push @named, $name, $val;
1059 } elsif (defined(my $arg = $self->parse_variable($str_ref))) {
1061 $$str_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1067 ### allow for named arguments to be added also
1068 push @args, [\
['hash', @named], 0] if scalar @named;
1073 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1074 sub interpolate_node
{
1075 my ($self, $tree, $offset) = @_;
1076 return if $self->{'_in_perl'};
1078 ### split on variables while keeping the variables
1079 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $tree->[-1];
1080 if ($#pieces <= 0) {
1081 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1087 foreach my $piece (@pieces) {
1088 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1089 if (! ($n++ % 2)) { # odds will always be text chunks
1090 next if ! length $piece;
1091 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1092 push @sub_tree, $piece;
1093 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1094 || $piece =~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
) {
1096 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_variable(\
$name)];
1098 $self->throw('parse', "Parse error during interpolate node");
1102 ### replace the tree
1103 splice @$tree, -1, 1, @sub_tree;
1106 ###----------------------------------------------------------------###
1109 ### allow for the parse tree to store literals
1110 return $_[1] if ! ref $_[1];
1114 my $ARGS = shift || {};
1117 ### determine the top level of this particular variable access
1118 my $ref = $var->[$i++];
1119 my $args = $var->[$i++];
1120 warn "get_variable: begin \"$ref\"\n" if trace
;
1122 if (ref($ref) eq 'SCALAR') { # a scalar literal
1124 } elsif (ref($ref) eq 'REF') { # operator
1125 return $self->play_operator($$ref) if ${ $ref }->[0] eq '..';
1126 $ref = $self->play_operator($$ref);
1127 } else { # a named variable access (ie via $name.foo)
1128 $ref = $self->get_variable($ref);
1130 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1131 $ref = $self->{'_vars'}->{$ref};
1134 } elsif (defined $ref) {
1135 if ($ARGS->{'is_namespace_during_compile'}) {
1136 $ref = $self->{'NAMESPACE'}->{$ref};
1138 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1139 $ref = $self->{'_vars'}->{$ref};
1145 while (defined $ref) {
1147 ### check at each point if the rurned thing was a code
1148 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1149 my @results = $ref->($args ? @{ $self->vivify_args($args) } : ());
1150 if (defined $results[0]) {
1151 $ref = ($#results > 0) ? \
@results : $results[0];
1152 } elsif (defined $results[1]) {
1153 die $results[1]; # TT behavior - why not just throw ?
1160 ### descend one chained level
1161 last if $i >= $#$var;
1162 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1163 my $name = $var->[$i++];
1164 my $args = $var->[$i++];
1165 warn "get_variable: nested \"$name\"\n" if trace
;
1167 ### allow for named portions of a variable name (foo.$name.bar)
1169 if (ref($name) eq 'ARRAY') {
1170 $name = $self->get_variable($name);
1171 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1176 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1179 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1184 ### allow for scalar and filter access (this happens for every non virtual method call)
1186 if ($SCALAR_OPS->{$name}) { # normal scalar op
1187 $ref = $SCALAR_OPS->{$name}->($ref, $args ? @{ $self->vivify_args($args) } : ());
1189 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1190 $ref = $LIST_OPS->{$name}->([$ref], $args ? @{ $self->vivify_args($args) } : ());
1192 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1193 || $FILTER_OPS->{$name} # predefined filters in CET
1194 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1195 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1197 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1198 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1200 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1203 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1204 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1206 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1208 my $sub = $filter->[0];
1209 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1210 ($sub, my $err) = $sub->($self->context, $args ? @{ $self->vivify_args($args) } : ());
1211 if (! $sub && $err) {
1212 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1214 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1215 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1216 if ref($sub) !~ /Template::Exception$/;
1220 $ref = $sub->($ref);
1223 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1226 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1227 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1228 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1231 if (scalar keys %seen_filters
1232 && $seen_filters{$var->[$i - 5] || ''}) {
1233 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1241 ### method calls on objects
1242 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1243 my @args = $args ? @{ $self->vivify_args($args) } : ();
1244 my @results = eval { $ref->$name(@args) };
1246 my $class = ref $ref;
1247 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1248 } elsif (defined $results[0]) {
1249 $ref = ($#results > 0) ? \
@results : $results[0];
1251 } elsif (defined $results[1]) {
1252 die $results[1]; # TT behavior - why not just throw ?
1257 # didn't find a method by that name - so fail down to hash and array access
1260 ### hash member access
1261 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1262 if ($was_dot_call && exists($ref->{$name}) ) {
1263 $ref = $ref->{$name};
1264 } elsif ($HASH_OPS->{$name}) {
1265 $ref = $HASH_OPS->{$name}->($ref, $args ? @{ $self->vivify_args($args) } : ());
1266 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1267 return $var; # abort - can't fold namespace variable
1273 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1274 if ($name =~ /^\d+$/) {
1275 $ref = ($name > $#$ref) ? undef : $ref->[$name];
1277 $ref = (! $LIST_OPS->{$name}) ? undef : $LIST_OPS->{$name}->($ref, $args ? @{ $self->vivify_args($args) } : ());
1284 ### allow for undefinedness
1285 if (! defined $ref) {
1286 if ($self->{'_debug_undef'}) {
1287 my $chunk = $var->[$i - 2];
1288 $chunk = $self->get_variable($chunk) if ref($chunk) eq 'ARRAY';
1289 die "$chunk is undefined\n";
1291 $ref = $self->undefined_any($var);
1299 my ($self, $var, $val, $ARGS) = @_;
1303 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1304 $var = [$var, 0] if ! ref $var;
1306 ### determine the top level of this particular variable access
1307 my $ref = $var->[$i++];
1308 my $args = $var->[$i++];
1310 if (ref($ref) eq 'ARRAY') { # named access (ie via $name.foo)
1311 $ref = $self->get_variable($ref);
1312 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1314 $self->{'_vars'}->{$ref} = $val;
1317 $ref = $self->{'_vars'}->{$ref} ||= {};
1322 } else { # all other types can't be set
1325 } elsif (defined $ref) {
1326 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1328 $self->{'_vars'}->{$ref} = $val;
1331 $ref = $self->{'_vars'}->{$ref} ||= {};
1335 ### let the top level thing be a code block
1336 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1340 ### vivify the chained levels
1341 while (defined $ref && $#$var > $i) {
1342 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1343 my $name = $var->[$i++];
1344 my $args = $var->[$i++];
1346 ### allow for named portions of a variable name (foo.$name.bar)
1348 if (ref($name) eq 'ARRAY') {
1349 $name = $self->get_variable($name);
1350 if (! defined($name) || $name =~ /^[_.]/) {
1355 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1358 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1362 ### method calls on objects
1363 if (UNIVERSAL
::can
($ref, 'can')) {
1365 my @args = $args ? @{ $self->vivify_args($args) } : ();
1370 my @results = eval { $ref->$name(@args) };
1372 if (defined $results[0]) {
1373 $ref = ($#results > 0) ? \
@results : $results[0];
1374 } elsif (defined $results[1]) {
1375 die $results[1]; # TT behavior - why not just throw ?
1379 return if $lvalueish;
1382 die $@ if ref $@ || $@ !~ /Can\'t locate object method/;
1383 # fall on down to "normal" accessors
1386 ### hash member access
1387 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1389 $ref->{$name} = $val;
1392 $ref = $ref->{$name} ||= {};
1397 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1398 if ($name =~ /^\d+$/) {
1400 $ref->[$name] = $val;
1403 $ref = $ref->[$name] ||= {};
1411 } elsif (! ref($ref) && defined($ref)) {
1415 ### check at each point if the returned thing was a code
1416 if (defined($ref) && UNIVERSAL
::isa
($ref, 'CODE')) {
1417 my @results = $ref->($args ? @{ $self->vivify_args($args) } : ());
1418 if (defined $results[0]) {
1419 $ref = ($#results > 0) ? \
@results : $results[0];
1420 } elsif (defined $results[1]) {
1421 die $results[1]; # TT behavior - why not just throw ?
1435 return [map {$self->get_variable($_)} @$vars];
1438 ###----------------------------------------------------------------###
1444 if ($OP_DISPATCH->{$tree->[0]}) {
1445 my @args = map { $self->get_variable($tree->[$_]) } 1 .. $#$tree;
1447 return $OP_DISPATCH->{$tree->[0]}->(@args);
1450 my $op = $tree->[0];
1452 ### do custom and short-circuitable operators
1454 my $val = $self->get_variable($tree->[2]);
1455 $self->set_variable($tree->[1], $val);
1458 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1459 return $self->get_variable($tree->[1]) || $self->get_variable($tree->[2]) || '';
1461 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1462 my $var = $self->get_variable($tree->[1]) && $self->get_variable($tree->[2]);
1463 return $var ? $var : 0;
1465 } elsif ($op eq '?') {
1467 return $self->get_variable($tree->[1]) ? $self->get_variable($tree->[2]) : $self->get_variable($tree->[3]);
1470 $self->throw('operator', "Un-implemented operation $op");
1473 ###----------------------------------------------------------------###
1476 my ($self, $tag_ref, $node) = @_;
1478 my $block_name = '';
1479 if ($$tag_ref =~ s{ ^ (\w+ (?: :\w+)*) \s* (?! [\.\|]) }{}x
1480 || $$tag_ref =~ s{ ^ '(|.*?[^\\])' \s* (?! [\.\|]) }{}x
1481 || $$tag_ref =~ s{ ^ "(|.*?[^\\])" \s* (?! [\.\|]) }{}x
1484 ### allow for nested blocks to have nested names
1485 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1486 $block_name = join("/", @names, $block_name) if scalar @names;
1493 my ($self, $block_name, $node, $out_ref) = @_;
1495 ### store a named reference - but do nothing until something processes it
1496 $self->{'BLOCKS'}->{$block_name} = {
1497 _tree
=> $node->[4],
1498 name
=> $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1504 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1506 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1509 my ($self, $tag_ref) = @_;
1510 return if $$tag_ref =~ s{ ^ DEFAULT \s* }{}x;
1511 return $self->parse_variable($tag_ref);
1515 my ($self, $tag_ref) = @_;
1516 return $self->parse_variable($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
1520 my ($self, $undef, $node) = @_;
1521 $self->throw(lc($node->[0]), 'Control exception', $node);
1525 my ($self, $undef, $node, $out_ref) = @_;
1530 my ($self, $tag_ref) = @_;
1531 $$tag_ref =~ s{ ^ (on | off | format) \s* }{}xi || $self->throw('parse', "Unknown DEBUG option");
1533 if ($ret->[0] eq 'format') {
1534 $$tag_ref =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* }{}xs || $self->throw('parse', "Missing format string");
1541 my ($self, $ref) = @_;
1542 if ($ref->[0] eq 'on') {
1543 delete $self->{'_debug_off'};
1544 } elsif ($ref->[0] eq 'off') {
1545 $self->{'_debug_off'} = 1;
1546 } elsif ($ref->[0] eq 'format') {
1547 $self->{'_debug_format'} = $ref->[1];
1551 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1554 my ($self, $set) = @_;
1556 my ($set, $default) = @$_;
1557 next if ! defined $set;
1558 my $val = $self->get_variable($set);
1560 $default = defined($default) ? $self->get_variable($default) : '';
1561 $self->set_variable($set, $default);
1568 my ($self, $tag_ref) = @_;
1569 my $ref = $self->parse_variable($tag_ref);
1574 my ($self, $ident, $node) = @_;
1575 require Data
::Dumper
;
1576 my $info = $self->node_info($node);
1580 $out = Data
::Dumper
::Dumper
($self->get_variable($ident));
1581 $var = $info->{'text'};
1582 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1583 $var =~ s/\s*[+\-~=]?$//;
1585 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1586 local @{ $self->{'_vars'} }{ @were_never_here };
1587 delete @{ $self->{'_vars'} }{ @were_never_here };
1588 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1589 $var = 'EntireStash';
1591 if ($ENV{'REQUEST_METHOD'}) {
1593 $out = "<pre>$out</pre>";
1594 $out =~ s/\$VAR1/$var/;
1595 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1597 $out =~ s/\$VAR1/$var/;
1604 my ($self, $tag_ref) = @_;
1606 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1610 my $filter = $self->parse_variable($tag_ref);
1611 $filter = '' if ! defined $filter;
1613 return [$name, $filter];
1617 my ($self, $ref, $node, $out_ref) = @_;
1618 my ($name, $filter) = @$ref;
1620 return '' if ! @$filter;
1622 $self->{'FILTERS'}->{$name} = $filter if length $name;
1624 my $sub_tree = $node->[4];
1628 eval { $self->execute_tree($sub_tree, \
$out) };
1629 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1631 my $var = [\
$out, 0, '|', @$filter]; # make a temporary var out of it
1634 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1638 my ($self, $tag_ref) = @_;
1639 my $items = $self->parse_variable($tag_ref);
1641 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1643 $items = $self->parse_variable($tag_ref);
1645 return [$var, $items];
1649 my ($self, $ref, $node, $out_ref) = @_;
1651 ### get the items - make sure it is an arrayref
1652 my ($var, $items) = @$ref;
1654 $items = $self->get_variable($items);
1655 return '' if ! defined $items;
1657 if (ref($items) !~ /Iterator$/) {
1658 $items = $PACKAGE_ITERATOR->new($items);
1661 my $sub_tree = $node->[4];
1663 local $self->{'_vars'}->{'loop'} = $items;
1665 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1667 my ($item, $error) = $items->get_first;
1670 $self->set_variable($var, $item);
1672 ### execute the sub tree
1673 eval { $self->execute_tree($sub_tree, $out_ref) };
1675 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1676 if ($err->type eq 'next') {
1677 ($item, $error) = $items->get_next;
1680 last if $err->type =~ /last|break/;
1685 ($item, $error) = $items->get_next;
1687 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1688 ### if the FOREACH tag doesn't set a var - then everything gets localized
1691 ### localize variable access for the foreach
1692 my $swap = $self->{'_vars'};
1693 local $self->{'_vars'} = my $copy = {%$swap};
1695 ### iterate use the iterator object
1696 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1697 my ($item, $error) = $items->get_first;
1700 if (ref($item) eq 'HASH') {
1701 @$copy{keys %$item} = values %$item;
1704 ### execute the sub tree
1705 eval { $self->execute_tree($sub_tree, $out_ref) };
1707 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1708 if ($err->type eq 'next') {
1709 ($item, $error) = $items->get_next;
1712 last if $err->type =~ /last|break/;
1717 ($item, $error) = $items->get_next;
1719 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1726 my ($self, $tag_ref) = @_;
1727 my $ref = $self->parse_variable($tag_ref);
1728 $self->throw('parse', "Missing variable name") if ! defined $ref;
1733 my ($self, $ident, $node) = @_;
1734 my $var = $self->get_variable($ident);
1735 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1739 my ($self, $tag_ref) = @_;
1740 return $self->parse_variable($tag_ref);
1744 my ($self, $var, $node, $out_ref) = @_;
1746 my $val = $self->get_variable($var);
1748 my $body_ref = $node->[4] ||= [];
1749 $self->execute_tree($body_ref, $out_ref);
1753 while ($node = $node->[5]) { # ELSE, ELSIF's
1754 if ($node->[0] eq 'ELSE') {
1755 my $body_ref = $node->[4] ||= [];
1756 $self->execute_tree($body_ref, $out_ref);
1759 my $var = $node->[3];
1760 my $val = $self->get_variable($var);
1762 my $body_ref = $node->[4] ||= [];
1763 $self->execute_tree($body_ref, $out_ref);
1770 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1773 my ($self, $tag_ref, $node, $out_ref) = @_;
1775 ### localize the swap
1776 my $swap = $self->{'_vars'};
1777 local $self->{'_vars'} = {%$swap};
1779 ### localize the blocks
1780 my $blocks = $self->{'BLOCKS'};
1781 local $self->{'BLOCKS'} = {%$blocks};
1783 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1788 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1791 my ($self, $var, $node, $out_ref) = @_;
1792 my ($names, $args) = @$var;
1794 foreach my $name (@$names) {
1795 my $filename = $self->get_variable($name);
1796 $$out_ref .= $self->_insert($filename);
1803 my ($self, $tag_ref, $node) = @_;
1804 my $copy = $$tag_ref;
1806 my $name = $self->parse_variable(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1807 $self->throw('parse', "Missing macro name") if ! defined $name;
1809 $name = [ $name, 0 ];
1813 if ($copy =~ s{ ^ \( \s* }{}x) {
1814 $args = $self->parse_args(\
$copy, {positional_only
=> 1});
1815 $copy =~ s
{ ^ \
) \s
* }{}x
|| $self->throw('parse.missing', "Missing close ')'");
1818 $node->[6] = 1; # set a flag to keep parsing
1820 return [$name, $args];
1824 my ($self, $ref, $node, $out_ref) = @_;
1825 my ($name, $args) = @$ref;
1827 ### get the sub tree
1828 my $sub_tree = $node->[4];
1829 if (! $sub_tree || ! $sub_tree->[0]) {
1830 $self->set_variable($name, undef);
1832 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1833 $sub_tree = $sub_tree->[0]->[4];
1836 my $self_copy = $self->weak_copy;
1838 ### install a closure in the stash that will handle the macro
1839 $self->set_variable($name, sub {
1841 my $copy = $self_copy->{'_vars'};
1842 local $self_copy->{'_vars'}= {%$copy};
1845 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
1846 my @positional = @_;
1847 foreach my $var (@$args) {
1848 $self_copy->set_variable($var, shift(@positional));
1850 foreach my $name (sort keys %$named) {
1851 $self_copy->set_variable([$name, 0], $named->{$name});
1854 ### finally - run the sub tree
1856 $self_copy->execute_tree($sub_tree, \
$out);
1864 my ($self, $hash) = @_;
1866 if ($self->{'_top_level'}) {
1867 $ref = $self->{'_vars'}->{'template'} ||= {};
1869 $ref = $self->{'_vars'}->{'component'} ||= {};
1871 foreach my $key (keys %$hash) {
1872 next if $key eq 'name' || $key eq 'modtime';
1873 $ref->{$key} = $hash->{$key};
1878 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
1881 my ($self, $info, $node, $out_ref) = @_;
1882 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1884 ### fill in any variables
1885 my $perl = $node->[4] || return;
1887 $self->execute_tree($perl, \
$out);
1888 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
1893 package CGI
::Ex
::Template
::Perl
;
1895 my $context = $self->context;
1896 my $stash = $context->stash;
1898 ### setup a fake handle
1900 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
1901 my $old_fh = select PERLOUT
;
1906 ### put the handle back
1914 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
1922 my ($self, $tag_ref) = @_;
1923 my $info = [[], []];
1924 while (defined(my $filename = $self->parse_variable($tag_ref, {
1925 auto_quote
=> qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
1927 push @{$info->[0]}, $filename;
1928 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
1931 ### allow for post process variables
1932 while (length $$tag_ref) {
1933 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
1935 my $var = $self->parse_variable($tag_ref);
1936 last if ! defined $var;
1937 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
1938 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
1941 my $val = $self->parse_variable($tag_ref);
1942 push @{$info->[1]}, [$var, $val];
1943 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
1950 my ($self, $info, $node, $out_ref) = @_;
1952 my ($files, $args) = @$info;
1956 my ($key, $val) = @$_;
1957 $val = $self->get_variable($val);
1958 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
1959 foreach my $key (keys %$val) {
1960 $self->set_variable([$key,0], $val->{$key});
1964 $self->set_variable($key, $val);
1967 ### iterate on any passed block or filename
1968 foreach my $ref (@$files) {
1969 next if ! defined $ref;
1970 my $filename = $self->get_variable($ref);
1971 my $out = ''; # have temp item to allow clear to correctly clear
1973 ### normal blocks or filenames
1974 if (! ref $filename) {
1975 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
1977 ### allow for $template which is used in some odd instances
1979 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
1980 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
1981 local $self->{'_process_dollar_template'} = 1;
1982 local $self->{'_vars'}->{'component'} = my $doc = $filename;
1983 return if ! $doc->{'_tree'};
1985 ### execute and trim
1986 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
1987 if ($self->{'TRIM'}) {
1988 $out =~ s{ \s+ $ }{}x;
1989 $out =~ s{ ^ \s+ }{}x;
1992 ### handle exceptions
1994 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
1995 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2000 ### append any output
2003 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2011 my ($self, $info, $node, $out_ref) = @_;
2012 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2014 ### fill in any variables
2015 my $tree = $node->[4] || return;
2017 $self->execute_tree($tree, \
$perl);
2018 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2024 package CGI
::Ex
::Template
::Perl
;
2026 my $context = $self->context;
2027 my $stash = $context->stash;
2034 $$out_ref .= $output;
2037 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2045 my ($self, $tag_ref, $node, $initial_var) = @_;
2047 my $copy = $$tag_ref;
2049 while (length $$tag_ref) {
2054 $set = $initial_var;
2058 $set = $self->parse_variable($tag_ref);
2059 last if ! defined $set;
2060 $get_val = $$tag_ref =~ s{ ^ = >? \s* }{}x;
2062 if (! $get_val) { # no next val
2064 } elsif ($$tag_ref =~ $QR_DIRECTIVE # find a word
2065 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2066 $node->[6] = 1; # set a flag to keep parsing
2067 $val = $node->[4] ||= []; # setup storage
2068 push @SET, [$set, $val];
2070 } else { # get a normal variable
2071 $val = $self->parse_variable($tag_ref);
2073 push @SET, [$set, $val];
2079 my ($self, $set, $node) = @_;
2081 my ($set, $val) = @$_;
2082 if (! defined $val) { # not defined
2084 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2085 my $sub_tree = $node->[4];
2086 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2088 $self->execute_tree($sub_tree, \
$val);
2089 } else { # normal var
2090 $val = $self->get_variable($val);
2093 $self->set_variable($set, $val);
2098 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2101 my ($self, $var, $node, $out_ref) = @_;
2103 my $val = $self->get_variable($var);
2104 $val = '' if ! defined $val;
2105 ### $node->[4] is thrown away
2108 while ($node = $node->[5]) { # CASES
2109 my $var = $node->[3];
2110 if (! defined $var) {
2111 $default = $node->[4];
2115 my $val2 = $self->get_variable($var);
2116 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2117 for my $test (@$val2) { # find matching values
2118 next if ! defined $val && defined $test;
2119 next if defined $val && ! defined $test;
2120 if ($val ne $test) { # check string-wise first - then numerical
2121 next if $val !~ /^ -? (?: \d*\.\d+ | \d+) $/x;
2122 next if $test !~ /^ -? (?: \d*\.\d+ | \d+) $/x;
2123 next if $val != $test;
2126 my $body_ref = $node->[4] ||= [];
2127 $self->execute_tree($body_ref, $out_ref);
2133 $self->execute_tree($default, $out_ref);
2140 my ($self, $tag_ref, $node) = @_;
2141 my $name = $self->parse_variable($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2142 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2143 my $args = $self->parse_args($tag_ref);
2144 return [$name, $args];
2148 my ($self, $ref, $node) = @_;
2149 my ($name, $args) = @$ref;
2150 $name = $self->get_variable($name);
2151 my @args = $args ? @{ $self->vivify_args($args) } : ();
2152 $self->throw($name, \
@args, $node);
2156 my ($self, $foo, $node, $out_ref) = @_;
2159 my $body_ref = $node->[4];
2160 eval { $self->execute_tree($body_ref, \
$out) };
2163 if (! $node->[5]) { # no catch or final
2164 if (! $err) { # no final block and no error
2168 $self->throw('parse.missing', "Missing CATCH block", $node);
2171 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2172 if ($err->type =~ /stop|return/) {
2178 ### loop through the nested catch and final blocks
2181 my $type = $err ? $err->type : '';
2183 while ($node = $node->[5]) { # CATCH
2184 if ($node->[0] eq 'FINAL') {
2185 $final = $node->[4];
2189 my $name = $self->get_variable($node->[3]);
2190 $name = '' if ! defined $name || lc($name) eq 'default';
2191 if ($type =~ / ^ \Q$name\E \b /x
2192 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2193 $catch_body_ref = $node->[4] || [];
2194 $last_found = $name;
2198 ### play the best catch block
2200 if (! $catch_body_ref) {
2204 local $self->{'_vars'}->{'error'} = $err;
2205 local $self->{'_vars'}->{'e'} = $err;
2206 eval { $self->execute_tree($catch_body_ref, \
$out) };
2214 $self->execute_tree($final, \
$out) if $final;
2222 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2223 return [ \
[ '!', $ref ], 0 ];
2226 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2229 my ($self, $tag_ref) = @_;
2232 my $copy = $$tag_ref;
2233 if (defined(my $_var = $self->parse_variable(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2234 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2240 my $module = $self->parse_variable(\
$copy, {auto_quote
=> qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2241 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2242 $module =~ s/\./::/g;
2245 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2246 $args = $self->parse_args(\
$copy);
2249 $copy =~ s
{ ^ \
) \s
* $QR_COMMENTS }{}ox
|| $self->throw('parse.missing', "Missing close ')'");
2253 return [$var, $module, $args];
2257 my ($self, $ref, $node, $out_ref) = @_;
2258 my ($var, $module, $args) = @$ref;
2260 ### get the stash storage location - default to the module
2261 $var = $module if ! defined $var;
2262 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2263 pop @var; # remove the trailing '.'
2265 ### look for a plugin_base
2266 my $base = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2267 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2268 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2269 : "${base}::${module}";
2270 my $require = "$package.pm";
2271 $require =~ s
|::|/|g
;
2273 ### try and load the module - fall back to bare module if allowed
2275 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2276 my $shape = $package->load;
2277 my $context = $self->context;
2278 my @args = $args ? @{ $self->vivify_args($args) } : ();
2279 $obj = $shape->new($context, @args);
2280 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2281 $obj = $PACKAGE_ITERATOR->new($args ? $self->get_variable($args->[0]) : []);
2282 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2283 foreach my $package (@packages) {
2284 my $require = "$package.pm";
2285 $require =~ s
|::|/|g
;
2286 eval {require $require} || next;
2287 my $shape = $package->load;
2288 my $context = $self->context;
2289 my @args = $args ? @{ $self->vivify_args($args) } : ();
2290 $obj = $shape->new($context, @args);
2292 } elsif ($self->{'LOAD_PERL'}) {
2293 my $require = "$module.pm";
2294 $require =~ s
|::|/|g
;
2295 if (eval {require $require}) {
2296 my @args = $args ? @{ $self->vivify_args($args) } : ();
2297 $obj = $module->new(@args);
2300 if (! defined $obj) {
2301 my $err = "$module: plugin not found";
2302 $self->throw('plugin', $err);
2306 $self->set_variable(\
@var, $obj);
2312 my ($self, $var, $node, $out_ref) = @_;
2313 return '' if ! defined $var;
2315 my $sub_tree = $node->[4];
2317 ### iterate use the iterator object
2318 my $count = $WHILE_MAX;
2319 while (--$count > 0) {
2321 $self->get_variable($var) || last;
2323 ### execute the sub tree
2324 eval { $self->execute_tree($sub_tree, $out_ref) };
2326 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2327 next if $err->type =~ /next/;
2328 last if $err->type =~ /last|break/;
2333 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2338 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2341 my ($self, $var, $node, $out_ref) = @_;
2342 my $sub_tree = $node->[4] || return;
2344 my ($names, $args) = @$var;
2347 $self->execute_tree($sub_tree, \
$out);
2349 foreach my $name (reverse @$names) {
2350 local $self->{'_vars'}->{'content'} = $out;
2352 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2359 ###----------------------------------------------------------------###
2363 $self->{'_vars'} = shift if $#_ == 0;
2364 return $self->{'_vars'} ||= {};
2367 sub include_filename
{
2368 my ($self, $file) = @_;
2369 if ($file =~ m
|^/|) {
2370 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2371 return $file if -e
$file;
2372 } elsif ($file =~ m{(^|/)\.\./}) {
2373 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2374 return $file if -e
$file;
2377 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2378 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2379 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2380 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2381 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2382 $paths; # return of the do
2384 foreach my $path (@$paths) {
2385 return "$path/$file" if -e
"$path/$file";
2388 $self->throw('file', "$file: not found");
2392 my ($self, $path) = @_;
2393 return $path if ref $path;
2394 my $delim = $self->{'DELIMITER'} || ':';
2395 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2396 return [split $delim, $path];
2400 my ($self, $file) = @_;
2401 return $self->slurp($self->include_filename($file));
2405 my ($self, $file) = @_;
2407 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2408 read FH
, my $txt, -s
$file;
2413 sub process_simple
{
2415 my $in = shift || die "Missing input";
2416 my $swap = shift || die "Missing variable hash";
2417 my $out = shift || die "Missing output string ref";
2420 delete $self->{'_debug_off'};
2421 delete $self->{'_debug_format'};
2422 local $self->{'_start_top_level'} = 1;
2423 $self->_process($in, $swap, $out);
2426 if ($err->type !~ /stop|return|next|last|break/) {
2427 $self->{'error'} = $err;
2435 my ($self, $in, $swap, $out, @ARGS) = @_;
2436 delete $self->{'error'};
2439 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2440 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2445 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2447 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2449 $content = \
$content;
2450 } else { # should be a file handle
2453 $content = \
$content;
2456 ### should be a filename
2461 ### prepare block localization
2462 my $blocks = $self->{'BLOCKS'} ||= {};
2469 ### localize the stash
2471 my $var1 = $self->{'_vars'} ||= {};
2472 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2473 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2474 my $copy = {%$var2, %$var1, %$swap};
2475 local $copy->{'template'};
2477 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2479 delete $self->{'_debug_off'};
2480 delete $self->{'_debug_format'};
2482 ### handle pre process items that go before every document
2483 if ($self->{'PRE_PROCESS'}) {
2484 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2486 $self->_process($name, $copy, \
$out);
2487 $output = $out . $output;
2491 ### handle the process config - which loads a template in place of the real one
2492 if (exists $self->{'PROCESS'}) {
2493 ### load the meta data for the top document
2494 my $doc = $self->load_parsed_tree($content) || {};
2495 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2496 ? $doc->{'_tree'}->[0]->[3] : {};
2498 $copy->{'template'} = $doc;
2499 @{ $doc }{keys %$meta} = values %$meta;
2501 ### process any other templates
2502 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2503 next if ! length $name;
2504 $self->_process($name, $copy, \
$output);
2507 ### handle "normal" content
2509 local $self->{'_start_top_level'} = 1;
2510 $self->_process($content, $copy, \
$output);
2514 ### handle post process items that go after every document
2515 if ($self->{'POST_PROCESS'}) {
2516 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2517 $self->_process($name, $copy, \
$output);
2523 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2524 if ($err->type !~ /stop|return|next|last|break/) {
2525 $self->{'error'} = $err;
2532 ### clear blocks as asked (AUTO_RESET) defaults to on
2533 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2535 ### send the content back out
2536 $out ||= $self->{'OUTPUT'};
2538 if (UNIVERSAL
::isa
($out, 'CODE')) {
2540 } elsif (UNIVERSAL
::can
($out, 'print')) {
2541 $out->print($output);
2542 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2544 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2545 push @$out, $output;
2546 } else { # should be a file handle
2549 } elsif ($out) { # should be a filename
2551 if ($out =~ m
|^/|) {
2552 if (! $self->{'ABSOLUTE'}) {
2553 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2557 } elsif ($out =~ m
|^\
.\
.?/|) {
2558 if (! $self->{'RELATIVE'}) {
2559 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2564 if (! $self->{'OUTPUT_PATH'}) {
2565 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2567 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2572 if (open FH
, ">$file") {
2573 if (my $bm = $args->{'binmode'}) {
2574 if (+$bm == 1) { binmode FH
}
2575 else { binmode FH
, $bm }
2580 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2587 return if $self->{'error'};
2591 sub error
{ shift-
>{'error'} }
2595 print STDERR
"DEBUG: ", @_;
2598 ###----------------------------------------------------------------###
2601 my ($self, $type, $info, $node) = @_;
2602 return $type if ref($type) =~ /Template::Exception$/;
2603 if (ref($info) eq 'ARRAY') {
2604 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2605 if (@$info >= 2 || scalar keys %$hash) {
2607 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2608 $hash->{'args'} = $info;
2610 } elsif (@$info == 1) {
2617 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2620 sub throw
{ die shift-
>exception(@_) }
2624 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2628 my ($self, $ident, $node) = @_;
2629 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2634 my ($self, $ident) = @_;
2635 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2641 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2646 my $args = shift || {};
2647 my $base = $args->{'base'} || '';
2649 return $self->{'_plugins'}->{$base} ||= do {
2653 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2655 foreach my $dir (@dirs) {
2657 File
::Find
::find
(sub {
2658 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2660 push @plugins, $mod;
2664 \
@plugins; # return of the do
2668 ### get a copy of self without circular refs for use in closures
2672 if (eval { require Scalar
::Util
}
2673 && defined &Scalar
::Util
::weaken
) {
2675 Scalar
::Util
::weaken
($self_copy);
2677 $self_copy = bless {%$self}, ref($self); # hackish way to avoid circular refs on old perls (pre 5.8)
2683 my ($self, $node) = @_;
2684 my $info = $self->node_info($node);
2685 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2686 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2691 my ($self, $node) = @_;
2692 my $doc = $self->{'_vars'}->{'component'};
2694 my $j = $node->[2] || return ''; # METADEF can be 0
2695 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2696 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2700 file
=> $doc->{'name'},
2701 line
=> $self->get_line_number_by_index($doc, $i),
2706 sub get_line_number_by_index
{
2707 my ($self, $doc, $index) = @_;
2708 ### get the line offsets for the doc
2709 my $lines = $doc->{'line_offsets'} ||= do {
2710 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2714 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2720 ### binary search them (this is fast even on big docs)
2721 return $#$lines + 1 if $index > $lines->[-1];
2722 my ($i, $j) = (0, $#$lines);
2724 return $i + 1 if abs($i - $j) <= 1;
2725 my $k = int(($i + $j) / 2);
2726 $j = $k if $lines->[$k] >= $index;
2727 $i = $k if $lines->[$k] <= $index;
2731 ###----------------------------------------------------------------###
2732 ### long virtual methods or filters
2733 ### many of these vmethods have used code from Template/Stash.pm to
2734 ### assure conformance with the TT spec.
2736 sub define_vmethod
{
2737 my ($self, $type, $name, $sub) = @_;
2738 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2739 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2740 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2741 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2743 die "Invalid type vmethod type $type";
2750 my $size = shift || 1;
2752 if ($size < 0) { # chunk from the opposite end
2753 $str = reverse $str;
2755 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2757 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2762 sub vmethod_indent
{
2763 my $str = shift; $str = '' if ! defined $str;
2764 my $pre = shift; $pre = 4 if ! defined $pre;
2765 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
2766 $str =~ s/^/$pre/mg;
2770 sub vmethod_format
{
2771 my $str = shift; $str = '' if ! defined $str;
2772 my $pat = shift; $pat = '%s' if ! defined $pat;
2773 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2777 my ($str, $pat, $global) = @_;
2778 return [] if ! defined $str || ! defined $pat;
2779 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2780 return (@res >= 2) ? \
@res : (@res == 1) ? $res[0] : '';
2784 my ($list, $field) = @_;
2785 return defined($field)
2786 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2787 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2789 : [sort {$a <=> $b} @$list];
2792 sub vmethod_repeat
{
2793 my ($str, $n, $join) = @_;
2794 return if ! length $str;
2795 $n = 1 if ! defined($n) || ! length $n;
2796 $join = '' if ! defined $join;
2797 return join $join, ($str) x
$n;
2800 ### This method is a combination of my submissions along
2801 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2802 sub vmethod_replace
{
2803 my ($text, $pattern, $replace, $global) = @_;
2804 $text = '' unless defined $text;
2805 $pattern = '' unless defined $pattern;
2806 $replace = '' unless defined $replace;
2807 $global = 1 unless defined $global;
2809 my ($chunk, $start, $end) = @_;
2810 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
2812 : ($2 > $#$start || $2 == 0) ? ''
2813 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2818 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2820 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2826 my ($list, $field) = @_;
2827 return defined($field)
2828 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2829 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2831 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2834 sub vmethod_splice
{
2835 my ($ref, $i, $len, @replace) = @_;
2836 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2838 return [splice @$ref, $i || 0, $len, @replace];
2840 return [splice @$ref, $i || 0];
2845 my ($str, $pat, @args) = @_;
2846 $str = '' if ! defined $str;
2847 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2852 utf8
::encode
($str) if defined &utf8
::encode
;
2853 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2858 my $context = shift;
2861 return $context->process(\
$text);
2865 sub filter_redirect
{
2866 my ($context, $file, $options) = @_;
2867 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
2868 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
2869 if $file =~ m{(^|/)\.\./};
2875 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
2878 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
2879 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
2880 if (+$bm == 1) { binmode FH
}
2881 else { binmode FH
, $bm}
2889 ###----------------------------------------------------------------###
2892 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
2894 require Data
::Dumper
;
2895 return Data
::Dumper
::Dumper
($obj->parse_variable(\
$str));
2898 ###----------------------------------------------------------------###
2900 package CGI
::Ex
::Template
::Exception
;
2903 '""' => \
&as_string
,
2904 bool
=> sub { defined shift },
2908 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
2909 return bless [$type, $info, $node, $pos, $str_ref], $class;
2912 sub type
{ shift-
>[0] }
2914 sub info
{ shift-
>[1] }
2918 $self->[2] = shift if $#_ == 0;
2922 sub offset
{ shift-
>[3] || 0 }
2926 $self->[4] = shift if $#_ == 0;
2932 my $msg = $self->type .' error - '. $self->info;
2933 if (my $node = $self->node) {
2934 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
2939 ###----------------------------------------------------------------###
2941 package CGI
::Ex
::Template
::Iterator
;
2944 my ($class, $items) = @_;
2945 $items = [] if ! defined $items;
2946 if (UNIVERSAL
::isa
($items, 'HASH')) {
2947 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
2948 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
2949 $items = $items->as_list;
2950 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
2953 return bless [$items, 0], $class;
2958 return (undef, 3) if ! @{ $self->[0] };
2959 return ($self->[0]->[$self->[1] = 0], undef);
2964 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
2965 return ($self->items->[$self->[1]], undef);
2968 sub items
{ shift-
>[0] }
2970 sub index { shift-
>[1] }
2972 sub max
{ $#{ shift-
>[0] } }
2974 sub size
{ shift-
>max + 1 }
2976 sub count
{ shift-
>index + 1 }
2978 sub number
{ shift-
>index + 1 }
2980 sub first
{ (shift-
>index == 0) || 0 }
2982 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
2986 return undef if $self->index <= 0;
2987 return $self->items->[$self->index - 1];
2992 return undef if $self->index >= $self->max;
2993 return $self->items->[$self->index + 1];
2996 ###----------------------------------------------------------------###
2998 package CGI
::Ex
::Template
::_Context
;
3000 use vars
qw($AUTOLOAD);
3002 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3004 sub config
{ shift-
>_template }
3008 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3011 sub insert
{ shift-
>_template->_insert(@_) }
3013 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3018 my $vars = $self->_template->_vars;
3020 $self->_template->_process($ref, $vars, \
$out);
3027 my $args = shift || {};
3029 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3031 my $out = ''; # have temp item to allow clear to correctly clear
3032 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3034 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3041 my ($self, $name, $filter, $is_dynamic) = @_;
3042 $filter = [ $filter, 1 ] if $is_dynamic;
3043 $self->define_vmethod('filter', $name, $filter);
3047 my ($self, $name, $args, $alias) = @_;
3048 my $t = $self->_template;
3052 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3053 $t->throw('filter', $name) if ! $filter;
3054 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3056 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3057 $filter = $name->factory || $t->throw($name->error);
3059 $t->throw('undef', "$name: filter not found");
3062 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3063 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3064 } elsif ($args && @$args) {
3066 $filter = sub { $sub->(shift, @$args) };
3069 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3074 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3077 my ($self, $type, $info) = @_;
3079 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3081 } elsif (defined $info) {
3082 $self->_template->throw($type, $info);
3084 $self->_template->throw('undef', $type);
3088 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3092 ###----------------------------------------------------------------###
3094 package CGI
::Ex
::Template
::_Stash
;
3096 use vars
qw($AUTOLOAD);
3098 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3101 my ($self, $var) = @_;
3103 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3104 else { $var = $self->_template->parse_variable(\
$var, {no_dots
=> 1}) }
3106 return $self->_template->get_variable($var, {no_dots
=> 1});
3110 my ($self, $var, $val) = @_;
3112 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3113 else { $var = $self->_template->parse_variable(\
$var, {no_dots
=> 1}) }
3115 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3119 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3123 ###----------------------------------------------------------------###
3125 package CGI
::Ex
::Template
::EvalPerlHandle
;
3128 my ($class, $out_ref) = @_;
3129 return bless [$out_ref], $class;
3134 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3138 ###----------------------------------------------------------------###
3142 ### See the perldoc in CGI/Ex/Template.pod