1 package CGI
::Ex
::Template
;
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2007 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
11 our $VERSION = '2.13';
13 our $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
14 our $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
15 our $PACKAGE_CONTEXT = 'CGI::Ex::Template::Context';
16 our $QR_PRIVATE = qr/^[_.]/;
19 cet
=> \
&parse_tree_tt3
,
20 ht
=> sub { my $self = shift; local $self->{'V2EQUALS'} = 0; local $self->{'EXPR'} = 0; $self->parse_tree_hte(@_) },
21 hte
=> sub { my $self = shift; local $self->{'V2EQUALS'} = 0; $self->parse_tree_hte(@_) },
22 tt3
=> \
&parse_tree_tt3
,
23 tt2
=> sub { my $self = shift; local $self->{'V2PIPE'} = 1; $self->parse_tree_tt3(@_) },
24 tt1
=> sub { my $self = shift; local $self->{'V2PIPE'} = 1; local $self->{'V1DOLLAR'} = 1; $self->parse_tree_tt3(@_) },
28 asp
=> ['<%', '%>' ], # ASP
29 default => ['\[%', '%\]' ], # default
30 html
=> ['<!--', '-->' ], # HTML comments
31 mason
=> ['<%', '>' ], # HTML::Mason
32 metatext
=> ['%%', '%%' ], # Text::MetaText
33 php
=> ['<\?', '\?>' ], # PHP
34 star
=> ['\[\*', '\*\]' ], # TT alternate
35 template
=> ['\[%', '%\]' ], # Normal Template Toolkit
36 template1
=> ['[\[%]%', '%[%\]]'], # allow TT1 style
37 tt2
=> ['\[%', '%\]' ], # TT2
42 abs => sub { local $^W; abs shift },
43 atan2 => sub { local $^W; atan2($_[0], $_[1]) },
44 chunk
=> \
&vmethod_chunk
,
45 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
46 cos => sub { local $^W; cos $_[0] },
47 defined => sub { defined $_[0] ? 1 : '' },
48 exp => sub { local $^W; exp $_[0] },
49 fmt
=> \
&vmethod_fmt_scalar
,
50 'format' => \
&vmethod_format
,
51 hash
=> sub { {value
=> $_[0]} },
52 hex => sub { local $^W; hex $_[0] },
53 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; s/\'/'/g; $_ },
54 indent
=> \
&vmethod_indent
,
55 int => sub { local $^W; int $_[0] },
56 item
=> sub { $_[0] },
57 js
=> sub { local $_ = $_[0]; return if ! $_; s/\n/\\n/g; s/\r/\\r/g; s/(?<!\\)([\"\'])/\\$1/g; $_ },
58 lc => sub { lc $_[0] },
59 lcfirst => sub { lcfirst $_[0] },
60 length => sub { defined($_[0]) ? length($_[0]) : 0 },
61 list
=> sub { [$_[0]] },
62 log => sub { local $^W; log $_[0] },
63 lower
=> sub { lc $_[0] },
64 match
=> \
&vmethod_match
,
65 new
=> sub { defined $_[0] ? $_[0] : '' },
67 oct => sub { local $^W; oct $_[0] },
68 rand => sub { local $^W; rand shift },
69 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
70 repeat
=> \
&vmethod_repeat
,
71 replace
=> \
&vmethod_replace
,
72 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return $str =~ /$pat/ },
73 sin => sub { local $^W; sin $_[0] },
75 split => \
&vmethod_split
,
76 sprintf => sub { local $^W; my $pat = shift; sprintf($pat, @_) },
77 sqrt => sub { local $^W; sqrt $_[0] },
78 srand => sub { local $^W; srand $_[0]; '' },
79 stderr
=> sub { print STDERR
$_[0]; '' },
80 substr => \
&vmethod_substr
,
81 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
82 uc => sub { uc $_[0] },
83 ucfirst => sub { ucfirst $_[0] },
84 upper
=> sub { uc $_[0] },
89 our $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
90 eval => [\
&filter_eval
, 1],
91 evaltt
=> [\
&filter_eval
, 1],
92 file
=> [\
&filter_redirect
, 1],
93 redirect
=> [\
&filter_redirect
, 1],
97 defined => sub { return 1 if @_ == 1; defined $_[0]->[ defined($_[1]) ? $_[1] : 0 ] },
98 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
99 fmt
=> \
&vmethod_fmt_list
,
100 grep => sub { local $^W; my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
101 hash
=> sub { local $^W; my $list = shift; return {@$list} if ! @_; my $i = shift || 0; return {map {$i++ => $_} @$list} },
102 import
=> sub { my $ref = shift; push @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_; '' },
103 item
=> sub { $_[0]->[ $_[1] || 0 ] },
104 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
105 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
106 list
=> sub { $_[0] },
107 max
=> sub { local $^W; $#{ $_[0] } },
108 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
109 new
=> sub { local $^W; return [@_] },
111 nsort
=> \
&vmethod_nsort
,
112 pick
=> \
&vmethod_pick
,
113 pop => sub { pop @{ $_[0] } },
114 push => sub { my $ref = shift; push @$ref, @_; return '' },
115 reverse => sub { [ reverse @{ $_[0] } ] },
116 shift => sub { shift @{ $_[0] } },
117 size
=> sub { local $^W; scalar @{ $_[0] } },
118 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
119 sort => \
&vmethod_sort
,
120 splice => \
&vmethod_splice
,
121 unique
=> sub { my %u; return [ grep { ! $u{$_}++ } @{ $_[0] } ] },
122 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
126 defined => sub { return 1 if @_ == 1; defined $_[0]->{ defined($_[1]) ? $_[1] : '' } },
127 delete => sub { my $h = shift; delete @{ $h }{map {defined($_) ? $_ : ''} @_}; '' },
128 each => sub { [%{ $_[0] }] },
129 exists => sub { exists $_[0]->{ defined($_[1]) ? $_[1] : '' } },
130 fmt
=> \
&vmethod_fmt_hash
,
131 hash
=> sub { $_[0] },
132 import
=> sub { my ($a, $b) = @_; @{$a}{keys %$b} = values %$b if ref($b) eq 'HASH'; '' },
133 item
=> sub { my ($h, $k) = @_; $k = '' if ! defined $k; $QR_PRIVATE && $k =~ $QR_PRIVATE ? undef : $h->{$k} },
134 items
=> sub { [ %{ $_[0] } ] },
135 keys => sub { [keys %{ $_[0] }] },
136 list
=> \
&vmethod_list_hash
,
137 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
139 nsort
=> sub { my $ref = shift; [sort { $ref->{$a} <=> $ref->{$b}} keys %$ref] },
140 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } sort keys %{ $_[0] } ] },
141 size
=> sub { scalar keys %{ $_[0] } },
142 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
143 values => sub { [values %{ $_[0] }] },
151 foreach (values %$VOBJS) {
152 $_->{'Text'} = $_->{'fmt'};
153 $_->{'Hash'} = $_->{'hash'};
154 $_->{'List'} = $_->{'list'};
158 #name parse_sub play_sub block postdir continue no_interp
159 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1],
160 BREAK
=> [sub {}, \
&play_control
],
161 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
162 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
163 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
164 CLEAR
=> [sub {}, \
&play_CLEAR
],
165 '#' => [sub {}, sub {}],
166 CONFIG
=> [\
&parse_CONFIG
, \
&play_CONFIG
],
167 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
168 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
169 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
170 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
171 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
172 END => [sub {}, sub {}],
173 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
174 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
175 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
176 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
177 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
178 GET
=> [\
&parse_GET
, \
&play_GET
],
179 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
180 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
181 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
182 LAST
=> [sub {}, \
&play_control
],
183 LOOP
=> [\
&parse_LOOP
, \
&play_LOOP
, 1, 1],
184 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
185 META
=> [\
&parse_META
, \
&play_META
],
186 NEXT => [sub {}, \
&play_control
],
187 PERL
=> [sub {}, \
&play_PERL
, 1, 0, 0, 1],
188 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
189 RAWPERL
=> [sub {}, \
&play_RAWPERL
, 1, 0, 0, 1],
190 RETURN
=> [sub {}, \
&play_control
],
191 SET
=> [\
&parse_SET
, \
&play_SET
],
192 STOP
=> [sub {}, \
&play_control
],
193 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
194 TAGS
=> [\
&parse_TAGS
, sub {}],
195 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
196 TRY
=> [sub {}, \
&play_TRY
, 1],
197 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
198 USE
=> [\
&parse_USE
, \
&play_USE
],
199 VIEW
=> [\
&parse_VIEW
, \
&play_VIEW
, 1],
200 WHILE
=> [\
&parse_WHILE
, \
&play_WHILE
, 1, 1],
201 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
202 #name parse_sub play_sub block postdir continue no_interp
205 ### setup the operator parsing
207 # type precedence symbols action (undef means play_operator will handle)
208 ['prefix', 99, ['\\'], undef ],
209 ['postfix', 98, ['++'], undef ],
210 ['postfix', 98, ['--'], undef ],
211 ['prefix', 97, ['++'], undef ],
212 ['prefix', 97, ['--'], undef ],
213 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
214 ['prefix', 93, ['!'], sub { ! $_[0] } ],
215 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
216 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
217 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
218 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
219 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
220 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
221 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
222 ['left', 85, ['~', '_'], undef ],
223 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
224 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
225 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
226 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
227 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
228 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
229 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
230 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
231 ['none', 75, ['=='], sub { $_[0] == $_[1] } ],
232 ['none', 75, ['eq'], sub { $_[0] eq $_[1] } ],
233 ['none', 75, ['!='], sub { $_[0] != $_[1] } ],
234 ['none', 75, ['ne'], sub { $_[0] ne $_[1] } ],
235 ['none', 75, ['<=>'], sub { $_[0] <=> $_[1] } ],
236 ['none', 75, ['cmp'], sub { $_[0] cmp $_[1] } ],
237 ['left', 70, ['&&'], undef ],
238 ['right', 65, ['||'], undef ],
239 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
240 ['ternary', 55, ['?', ':'], undef ],
241 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
242 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
243 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
244 ['assign', 53, ['/='], sub { $_[0] / $_[1] } ],
245 ['assign', 53, ['%='], sub { $_[0] % $_[1] } ],
246 ['assign', 53, ['**='], sub { $_[0] ** $_[1] } ],
247 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
248 ['assign', 52, ['='], undef ],
249 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
250 ['left', 45, ['and', 'AND'], undef ],
251 ['right', 40, ['or', 'OR'], undef ],
253 our ($QR_OP, $QR_OP_PREFIX, $QR_OP_ASSIGN, $OP, $OP_PREFIX, $OP_DISPATCH, $OP_ASSIGN, $OP_POSTFIX, $OP_TERNARY);
254 sub _op_qr
{ # no mixed \w\W operators
256 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {! /\{\}|\[\]/} grep {/^\W{2,}$/} @_;
257 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
258 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
259 $chr = "[$chr]" if $chr;
260 $word = "\\b(?:$word)\\b" if $word;
261 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
264 $QR_OP = _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS);
265 $QR_OP_PREFIX = _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS);
266 $QR_OP_ASSIGN = _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS);
267 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
268 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
269 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
270 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
271 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
272 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
276 our $QR_DIRECTIVE = '( [a-zA-Z]+\b | \| )';
277 our $QR_COMMENTS = '(?-s: \# .* \s*)*';
278 our $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\.][\w\-\.]* (?:/[\w\-\.]+)*';
279 our $QR_BLOCK = '\w+\b (?: :\w+\b)* )';
280 our $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
281 our $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=;) )';
283 our $WHILE_MAX = 1000;
284 our $EXTRA_COMPILE_EXT = '.sto';
285 our $MAX_EVAL_RECURSE = 50;
286 our $MAX_MACRO_RECURSE = 50;
289 our @CONFIG_COMPILETIME = qw(SYNTAX ANYCASE INTERPOLATE PRE_CHOMP POST_CHOMP SEMICOLONS V1DOLLAR V2PIPE V2EQUALS);
290 our @CONFIG_RUNTIME = qw(DUMP VMETHOD_FUNCTIONS);
293 if ($ENV{'MOD_PERL'}) {
294 eval {require Scalar
::Util
};
295 require CGI
::Ex
::Template
::Extra
;
296 require CGI
::Ex
::Template
::HTE
;
300 ###----------------------------------------------------------------###
304 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
306 ### allow for lowercase args
307 if (my @keys = grep {/^[a-z][a-z_]+$/} keys %$args) {
308 @{ $args }{ map { uc $_ } @keys } = delete @{ $args }{ @keys };
311 my $self = bless $args, $class;
313 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
314 if ($self->{'DEBUG'}) {
315 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
316 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
322 ###----------------------------------------------------------------###
327 local $self->{'_vars'} = shift || {};
328 my $out_ref = shift || $self->throw('undef', "Missing output ref");
329 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
330 my $i = length $$out_ref;
332 ### parse and execute
335 ### handed us a precompiled document
336 if (ref($file) eq 'HASH' && $file->{'_tree'}) {
339 ### load the document
341 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
344 ### prevent recursion
345 $self->throw('file', "recursion into '$doc->{name}'")
346 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
347 local $self->{'_in'}->{$doc->{'name'}} = 1;
349 ### execute the document
350 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
351 $$out_ref = ${ $doc->{'_content'} };
353 local $self->{'_component'} = $doc;
354 local $self->{'_template'} = $self->{'_top_level'} ? $doc : $self->{'_template'};
355 local @{ $self }{@CONFIG_RUNTIME} = @{ $self }{@CONFIG_RUNTIME};
356 $self->execute_tree($doc->{'_tree'}, $out_ref);
359 ### trim whitespace from the beginning and the end of a block or template
360 if ($self->{'TRIM'}) {
361 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
362 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
366 ### handle exceptions
368 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
369 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
370 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
376 ###----------------------------------------------------------------###
378 sub load_parsed_tree
{
381 return if ! defined $file;
383 my $doc = {name
=> $file};
384 my $ref = $self->{'_documents'}->{$file};
386 ### looks like a string reference
388 $doc->{'_content'} = $file;
389 $doc->{'name'} = 'input text';
390 $doc->{'_is_str_ref'} = 1;
392 ### looks like a previously cached-in-memory document
394 && ( time - $ref->{'cache_time'} < ($self->{'STAT_TTL'} || $STAT_TTL) # don't stat more than once a second
395 || $ref->{'modtime'} == (stat $ref->{'_filename'})[9] # otherwise see if the file was modified
397 $doc = $self->{'_documents'}->{$file};
400 ### looks like a block name of some sort
401 } elsif ($self->{'BLOCKS'}->{$file}) {
402 my $block = $self->{'BLOCKS'}->{$file};
404 ### allow for predefined blocks that are a code or a string
405 if (UNIVERSAL
::isa
($block, 'CODE')) {
408 if (! UNIVERSAL
::isa
($block, 'HASH')) {
409 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
411 $block = eval { $self->load_parsed_tree(\
$copy) }
412 || $self->throw('block', 'Parse error on predefined block');
414 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
417 ### handle cached not_founds
418 } elsif ($self->{'_not_found'}->{$file}
419 && ((time - $self->{'_not_found'}->{$file}->{'cache_time'}
420 < ($self->{'NEGATIVE_STAT_TTL'} || $self->{'STAT_TTL'} || $STAT_TTL)) # negative cache for a second
421 || do { delete $self->{'_not_found'}->{$file}; 0 } # clear cache on failure
423 die $self->{'_not_found'}->{$file}->{'exception'};
425 ### go and look on the file system
427 $doc->{'_filename'} = eval { $self->include_filename($file) };
429 ### allow for blocks in other files
430 if ($self->{'EXPOSE_BLOCKS'}
431 && ! $self->{'_looking_in_block_file'}) {
432 local $self->{'_looking_in_block_file'} = 1;
434 while ($file =~ s
|/([^/.]+)$||) {
435 $block_name = length($block_name) ? "$1/$block_name" : $1;
436 my $ref = eval { $self->load_parsed_tree($file) } || next;
437 my $_tree = $ref->{'_tree'};
438 foreach my $node (@$_tree) {
440 next if $node->[0] eq 'META';
441 last if $node->[0] ne 'BLOCK';
442 next if $block_name ne $node->[3];
443 $doc->{'_content'} = $ref->{'_content'};
444 $doc->{'_tree'} = $node->[4];
445 $doc->{'modtime'} = $ref->{'modtime'};
446 $file = $ref->{'name'};
450 $err = '' if ! $doc->{'_tree'};
451 } elsif ($self->{'DEFAULT'}) {
452 $err = '' if ($doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) });
455 ### cache the negative error
456 if (! defined($self->{'NEGATIVE_STAT_TTL'}) || $self->{'NEGATIVE_STAT_TTL'}) {
457 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
458 $self->{'_not_found'}->{$file} = {
460 exception
=> $self->exception($err->type, $err->info." (cached)"),
467 ### no tree yet - look for a file cache
468 if (! $doc->{'_tree'}) {
469 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
470 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
471 if ($self->{'COMPILE_DIR'}) {
472 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
474 $doc->{'_compile_filename'} = $doc->{'_filename'};
476 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
477 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
479 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
481 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
482 $doc->{'compile_was_used'} = 1;
484 my $str = $self->slurp($doc->{'_filename'});
485 $doc->{'_content'} = \
$str;
488 my $str = $self->slurp($doc->{'_filename'});
489 $doc->{'_content'} = \
$str;
495 ### haven't found a parsed tree yet - parse the content into a tree
496 if (! $doc->{'_tree'}) {
497 if ($self->{'CONSTANTS'}) {
498 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
499 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
502 local $self->{'_component'} = $doc;
503 $doc->{'_tree'} = eval { $self->parse_tree($doc->{'_content'}) }
504 || do { my $e = $@; $e->doc($doc) if UNIVERSAL
::can
($e, 'doc') && ! $e->doc; die $e }; # errors die
507 ### cache parsed_tree in memory unless asked not to do so
508 if (! $doc->{'_is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
509 $self->{'_documents'}->{$file} ||= $doc;
510 $doc->{'cache_time'} = time;
512 ### allow for config option to keep the cache size down
513 if ($self->{'CACHE_SIZE'}) {
514 my $all = $self->{'_documents'};
515 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
517 foreach my $file (sort {$all->{$b}->{'cache_time'} <=> $all->{$a}->{'cache_time'}} keys %$all) {
518 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
524 ### save a cache on the fileside as asked
525 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
526 my $dir = $doc->{'_compile_filename'};
530 File
::Path
::mkpath
($dir);
533 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
534 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
540 ###----------------------------------------------------------------###
543 my $syntax = $_[0]->{'SYNTAX'} || 'cet';
544 my $meth = $SYNTAX->{$syntax} || $_[0]->throw('parse', "Unknown SYNTAX \"$syntax\"");
551 if (! $str_ref || ! defined $$str_ref) {
552 $self->throw('parse.no_string', "No string or undefined during parse");
555 my $STYLE = $self->{'TAG_STYLE'} || 'default';
556 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
557 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
558 local $self->{'_end_tag'} = $END;
560 local @{ $self }{@CONFIG_COMPILETIME} = @{ $self }{@CONFIG_COMPILETIME};
562 my @tree; # the parsed tree
563 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
564 my @state; # maintain block levels
565 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
566 local $self->{'_no_interp'} = 0; # no interpolation in some blocks (usually PERL)
567 my @in_view; # let us know if we are in a view
568 my @blocks; # store blocks for later moving to front
569 my @meta; # place to store any found meta information (to go into META)
570 my $post_chomp = 0; # previous post_chomp setting
571 my $continue = 0; # flag for multiple directives in the same tag
572 my $post_op = 0; # found a post-operative DIRECTIVE
573 my $capture; # flag to start capture
576 local pos $$str_ref = 0;
579 ### continue looking for information in a semi-colon delimited tag
581 $node = [undef, $continue, undef];
583 ### find the next opening tag
585 $$str_ref =~ m{ \G (.*?) $START }gcxs
588 ### found a text portion - chomp it, interpolate it and store it
591 my $_last = pos $$str_ref;
593 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
594 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
595 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
598 push @$pointer, $text;
599 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
603 $node = [undef, pos($$str_ref), undef];
605 ### take care of whitespace and comments flags
606 my $pre_chomp = $$str_ref =~ m{ \G ([+=~-]) }gcx ? $1 : $self->{'PRE_CHOMP'};
607 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
608 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
609 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
610 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
611 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
612 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
615 ### leading # means to comment the entire section
616 if ($$str_ref =~ m{ \G \# }gcx) {
617 $$str_ref =~ m{ \G (.*?) ([+~=-]?) ($END) }gcxs # brute force - can't comment tags with nested %]
618 || $self->throw('parse', "Missing closing tag", undef, pos($$str_ref));
620 $node->[2] = pos($$str_ref) - length($3);
621 push @$pointer, $node;
624 $post_chomp ||= $self->{'POST_CHOMP'};
625 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
628 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
631 ### look for DIRECTIVES
632 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcxo # find a word
633 && ($func = $self->{'ANYCASE'} ? uc($1) : $1)
634 && ($DIRECTIVES->{$func}
635 || ((pos($$str_ref) -= length $1) && 0))
636 ) { # is it a directive
637 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcx;
641 ### store out this current node level to the appropriate tree location
642 # on a post operator - replace the original node with the new one - store the old in the new
643 if ($DIRECTIVES->{$func}->[3] && $post_op) {
644 my @post_op = @$post_op;
647 $node->[4] = [\
@post_op];
648 # if there was not a semi-colon - see if semis were required
649 } elsif ($post_op && $self->{'SEMICOLONS'}) {
650 $self->throw('parse', "Missing semi-colon with SEMICOLONS => 1", undef, $node->[1]);
652 # handle directive captures for an item like "SET foo = BLOCK"
654 push @{ $capture->[4] }, $node;
659 push @$pointer, $node;
662 ### parse any remaining tag details
663 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, $str_ref, $node) };
665 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
668 $node->[2] = pos $$str_ref;
670 ### anything that behaves as a block ending
671 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
673 $self->throw('parse', "Found an $func tag while not in a block", $node, pos($$str_ref));
675 my $parent_node = pop @state;
677 if ($func ne 'END') {
678 pop @$pointer; # we will store the node in the parent instead
679 $parent_node->[5] = $node;
680 my $parent_type = $parent_node->[0];
681 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
682 $self->throw('parse', "Found unmatched nested block", $node, pos($$str_ref));
686 ### restore the pointer up one level (because we hit the end of a block)
687 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
690 if ($func eq 'END') {
691 if ($parent_node->[0] eq 'BLOCK') { # move BLOCKS to front
692 if (defined($parent_node->[3]) && @in_view) {
693 push @{ $in_view[-1] }, $parent_node;
695 push @blocks, $parent_node;
697 if ($pointer->[-1] && ! $pointer->[-1]->[6]) {
698 splice(@$pointer, -1, 1, ());
700 } elsif ($parent_node->[0] eq 'VIEW') {
701 my $ref = { map {($_->[3] => $_->[4])} @{ pop @in_view }};
702 unshift @{ $parent_node->[3] }, $ref;
703 } elsif ($DIRECTIVES->{$parent_node->[0]}->[5]) { # allow no_interp to turn on and off
704 $self->{'_no_interp'}--;
707 ### continuation block - such as an elsif
710 $pointer = $node->[4] ||= [];
713 ### handle block directives
714 } elsif ($DIRECTIVES->{$func}->[2] && ! $post_op) {
716 $pointer = $node->[4] ||= []; # allow future parsed nodes before END tag to end up in current node
717 push @in_view, [] if $func eq 'VIEW';
718 $self->{'_no_interp'}++ if $DIRECTIVES->{$node->[0]}->[5] # allow no_interp to turn on and off
720 } elsif ($func eq 'TAGS') {
721 ($START, $END) = @{ $node->[3] };
723 ### allow for one more closing tag of the old style
724 if ($$str_ref =~ m{ \G ([+~=-]?) $self->{'_end_tag'} }gcxs
) {
725 $post_chomp = $1 || $self->{'POST_CHOMP'};
726 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
729 $self->{'_end_tag'} = $END; # need to keep track so parse_expr knows when to stop
732 $self->{'_end_tag'} = $END;
734 } elsif ($func eq 'META') {
735 unshift @meta, %{ $node->[3] }; # first defined win
736 $node->[3] = undef; # only let these be defined once - at the front of the tree
739 ### allow for bare variable getting and setting
740 } elsif (defined(my $var = $self->parse_expr($str_ref))) {
741 if ($post_op && $self->{'SEMICOLONS'}) {
742 $self->throw('parse', "Missing semi-colon with SEMICOLONS => 1", undef, $node->[1]);
744 push @$pointer, $node;
745 if ($$str_ref =~ m{ \G ($QR_OP_ASSIGN) >? (?! [+=~-]? $END) \s* $QR_COMMENTS }gcx) {
747 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, $str_ref, $node, $1, $var) };
749 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
756 $node->[2] = pos $$str_ref;
759 ### look for the closing tag
760 if ($$str_ref =~ m{ \G (?: ; \s* $QR_COMMENTS)? ([+=~-]?) $END }gcxs) {
761 $post_chomp = $1 || $self->{'POST_CHOMP'};
762 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
768 ### semi-colon = end of statement - we will need to continue parsing this tag
769 if ($$str_ref =~ m{ \G ; \s* $QR_COMMENTS }gcxo) {
772 ### we are flagged to start capturing the output of the next directive - set it up
773 } elsif ($node->[6]) {
777 ### allow next directive to be post-operative (or not)
782 ### no closing tag yet - no need to get an opening tag on next loop
783 $self->throw('parse', "Not sure how to handle tag", $node, pos($$str_ref)) if $continue == pos $$str_ref;
784 $continue = pos $$str_ref;
788 unshift(@tree, @blocks) if @blocks;
789 unshift(@tree, ['META', 0, 0, {@meta}]) if @meta;
790 $self->throw('parse', "Missing END directive", $state[-1], pos($$str_ref)) if @state > 0;
792 ### pull off the last text portion - if any
793 if (pos($$str_ref) != length($$str_ref)) {
794 my $text = substr $$str_ref, pos($$str_ref);
795 my $_last = pos($$str_ref);
797 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
798 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
799 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
802 push @$pointer, $text;
803 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
811 require CGI
::Ex
::Template
::HTE
;
812 &CGI
::Ex
::Template
::HTE
::parse_tree_hte
;
818 my $ARGS = shift || {};
819 my $is_aq = $ARGS->{'auto_quote'} ? 1 : 0;
820 my $mark = pos $$str_ref;
822 ### allow for custom auto_quoting (such as hash constructors)
824 if ($$str_ref =~ m{ \G $ARGS->{'auto_quote'} }gcx
) {
827 ### allow for auto-quoted $foo
828 } elsif ($$str_ref =~ m{ \G \$ (\w+\b (?:\.\w+\b)*) \s* $QR_COMMENTS }gcxo) {
830 if ($$str_ref !~ m{ \G \( }gcx || $name =~ /^(?:qw|m|\d)/) {
831 return $self->parse_expr(\
$name);
833 ### this is a little cryptic/odd - but TT allows items in
834 ### autoquote position to only be prefixed by a $ - gross
835 ### so we will defer to the regular parsing - but after the $
836 pos($$str_ref) = $mark + 1;
837 $is_aq = undef; # but don't allow operators - false flag handed down
839 ### allow for ${foo.bar} type constructs
840 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
841 my $var = $self->parse_expr($str_ref);
842 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
843 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
849 ### test for leading prefix operators
851 while (! $is_aq && $$str_ref =~ m{ \G ($QR_OP_PREFIX) }gcxo) {
852 push @{ $has_prefix }, $1;
853 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
859 my $already_parsed_args;
862 if ($$str_ref =~ m{ \G 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }gcxo) {
863 my $number = eval { hex $1 } || 0;
864 push @var, \
$number;
867 ### allow for numbers
868 } elsif ($$str_ref =~ m{ \G ( $QR_NUM ) \s* $QR_COMMENTS }gcxo) {
870 push @var, \
$number;
873 ### allow for quoted array constructor
874 } elsif (! $is_aq && $$str_ref =~ m{ \G qw ([^\w\s]) \s* }gcxo) {
876 $quote =~ y
|([{<|)]}>|;
877 $$str_ref =~ m{ \G (.*?) (?<!\\) \Q$quote\E \s* $QR_COMMENTS }gcxs
878 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, pos($$str_ref));
880 $str =~ s{ ^ \s+ }{}x;
881 $str =~ s{ \s+ $ }{}x;
882 $str =~ s{ \\ \Q$quote\E }{$quote}gx;
883 push @var, [undef, '[]', split /\s+/, $str];
885 ### allow for regex constructor
886 } elsif (! $is_aq && $$str_ref =~ m{ \G / }gcx) {
887 $$str_ref =~ m{ \G (.*?) (?<! \\) / ([msixeg]*) \s* $QR_COMMENTS }gcxos
888 || $self->throw('parse', 'Unclosed regex tag "/"', undef, pos($$str_ref));
889 my ($str, $opts) = ($1, $2);
890 $self->throw('parse', 'e option not allowed on regex', undef, pos($$str_ref)) if $opts =~ /e/;
891 $self->throw('parse', 'g option not supported on regex', undef, pos($$str_ref)) if $opts =~ /g/;
897 $self->throw('parse', "Invalid regex: $@", undef, pos($$str_ref)) if ! eval { "" =~ /$str/; 1 };
898 push @var, [undef, 'qr', $str, $opts];
900 ### looks like a normal variable start
901 } elsif ($$str_ref =~ m{ \G (\w+) \s* $QR_COMMENTS }gcxo) {
903 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
905 ### allow for literal strings
906 } elsif ($$str_ref =~ m{ \G ([\"\']) }gcx) {
908 $$str_ref =~ m{ \G (.*?) (?<! \\) $quote \s* $QR_COMMENTS }gcxs
909 || $self->throw('parse', "Unclosed quoted string ($1)", undef, pos($$str_ref));
911 if ($quote eq "'") { # no interpolation on single quoted strings
912 $str =~ s{ \\\' }{\'}xg;
921 ? split(m{ (?: ^ | (?<!\\)) (\$\w+ | \$\{ .*? (?<!\\) \}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
922 : split(m{ (?: ^ | (?<!\\)) (\$\w+ (?:\.\w+)* | \$\{ .*? (?<!\\) \}) }x
, $str);
924 foreach my $piece (@pieces) {
925 $piece =~ s/\\\$/\$/g;
927 next if ! ($n++ % 2);
928 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
929 && $piece !~ m{ ^ \$\{ \s* (.*?) (?<!\\) \} $ }x
;
931 $name =~ s/\\\}/\}/g;
932 $piece = $self->parse_expr(\
$name);
934 @pieces = grep {defined && length} @pieces;
935 if (@pieces == 1 && ! ref $pieces[0]) {
936 push @var, \
$pieces[0];
938 } elsif (! @pieces) {
942 push @var, [undef, '~', @pieces];
946 return ${ $var[0] } if $is_literal;
951 ### allow for leading $foo type constructs
952 } elsif ($$str_ref =~ m{ \G \$ (\w+) \b \s* $QR_COMMENTS }gcxo) {
953 if ($self->{'V1DOLLAR'}) {
955 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
960 ### allow for ${foo.bar} type constructs
961 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
962 push @var, $self->parse_expr($str_ref);
963 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
964 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
966 ### looks like an array constructor
967 } elsif (! $is_aq && $$str_ref =~ m{ \G \[ \s* $QR_COMMENTS }gcxo) {
968 local $self->{'_operator_precedence'} = 0; # reset presedence
969 my $arrayref = [undef, '[]'];
970 while (defined(my $var = $self->parse_expr($str_ref))) {
971 push @$arrayref, $var;
972 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
974 $$str_ref =~ m{ \G \] \s* $QR_COMMENTS }gcxo
975 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, pos($$str_ref));
976 push @var, $arrayref;
978 ### looks like a hash constructor
979 } elsif (! $is_aq && $$str_ref =~ m{ \G \{ \s* $QR_COMMENTS }gcxo) {
980 local $self->{'_operator_precedence'} = 0; # reset precedence
981 my $hashref = [undef, '{}'];
982 while (defined(my $key = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b) (?! \\.) \\s* $QR_COMMENTS"}))) {
983 $$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo;
984 my $val = $self->parse_expr($str_ref);
985 push @$hashref, $key, $val;
986 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
988 $$str_ref =~ m{ \G \} \s
* $QR_COMMENTS }gcxo
989 || $self->throw('parse.missing.curly_bracket', "Missing close \}", undef, pos($$str_ref));
992 ### looks like a paren grouper
993 } elsif (! $is_aq && $$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
994 local $self->{'_operator_precedence'} = 0; # reset precedence
995 my $var = $self->parse_expr($str_ref, {allow_parened_ops
=> 1});
997 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
998 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1000 $self->throw('parse', 'Paren group cannot be followed by an open paren', undef, pos($$str_ref))
1001 if $$str_ref =~ m{ \G \( }gcx;
1003 $already_parsed_args = 1;
1005 push @var, \
$var, 0;
1007 } elsif (! defined $var->[0]) {
1013 ### nothing to find - return failure
1015 pos($$str_ref) = $mark if $is_aq || $has_prefix;
1019 # auto_quoted thing was too complicated
1021 pos($$str_ref) = $mark;
1025 ### looks for args for the initial
1026 if ($already_parsed_args) {
1028 } elsif ($$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1029 local $self->{'_operator_precedence'} = 0; # reset precedence
1030 my $args = $self->parse_args($str_ref, {is_parened
=> 1});
1031 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1032 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1039 ### allow for nested items
1040 while ($$str_ref =~ m{ \G ( \.(?!\.) | \|(?!\|) ) }gcx) {
1041 if ($1 eq '|' && $self->{'V2PIPE'}) {
1042 pos($$str_ref) -= 1;
1046 push(@var, $1) if ! $ARGS->{'no_dots'};
1048 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1050 ### allow for interpolated variables in the middle - one.$foo.two
1051 if ($$str_ref =~ m{ \G \$ (\w+) \b \s* $QR_COMMENTS }gcxo) {
1052 push @var, $self->{'V1DOLLAR'} ? $1 : [$1, 0];
1054 ### or one.${foo.bar}.two
1055 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
1056 push @var, $self->parse_expr($str_ref);
1057 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
1058 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
1061 } elsif ($$str_ref =~ m{ \G (-? \w+) \s* $QR_COMMENTS }gcxo) {
1065 $self->throw('parse', "Not sure how to continue parsing", undef, pos($$str_ref));
1068 ### looks for args for the nested item
1069 if ($$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1070 local $self->{'_operator_precedence'} = 0; # reset precedence
1071 my $args = $self->parse_args($str_ref, {is_parened
=> 1});
1072 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1073 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1081 ### flatten literals and constants as much as possible
1084 $var = ${ $var[0] };
1086 $var[0] = [undef, '~', $var];
1089 } elsif ($is_namespace) {
1090 $var = $self->play_expr(\
@var, {is_namespace_during_compile
=> 1});
1095 ### allow for all "operators"
1096 if (! $self->{'_operator_precedence'} && defined $is_aq) {
1100 my $mark = pos $$str_ref;
1101 if ($self->{'_end_tag'} && $$str_ref =~ m{ \G [+=~-]? $self->{'_end_tag'} }gcx
) {
1102 pos($$str_ref) = $mark;
1104 } elsif ($$str_ref !~ m{ \G ($QR_OP) }gcxo) {
1105 pos($$str_ref) = $mark;
1108 if ($OP_ASSIGN->{$1} && ! $ARGS->{'allow_parened_ops'}) { # only allow assignment in parens
1109 pos($$str_ref) = $mark;
1112 local $self->{'_operator_precedence'} = 1;
1114 $op = 'eq' if $op eq '==' && (! defined($self->{'V2EQUALS'}) || $self->{'V2EQUALS'});
1115 $op = 'ne' if $op eq '!=' && (! defined($self->{'V2EQUALS'}) || $self->{'V2EQUALS'});
1117 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1119 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1120 if ($OP_POSTFIX->{$op}) {
1121 $var = [[undef, $op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1124 ### allow for prefix operator precedence
1125 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1127 if ($#$tree == 1) { # only one operator - keep simple things fast
1128 $var = [[undef, $tree->[0], $var, $tree->[1]], 0];
1130 unshift @$tree, $var;
1131 $var = $self->apply_precedence($tree, $found);
1136 $var = [[undef, $has_prefix->[-1], $var ], 0];
1137 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1140 ### add the operator to the tree
1141 my $var2 = $self->parse_expr($str_ref, {from_here
=> 1});
1142 $self->throw('parse', 'Missing variable after "'.$op.'"', undef, pos($$str_ref)) if ! defined $var2;
1143 push (@{ $tree ||= [] }, $op, $var2);
1144 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1147 ### if we found operators - tree the nodes by operator precedence
1149 if (@$tree == 2) { # only one operator - keep simple things fast
1150 $var = [[undef, $tree->[0], $var, $tree->[1]], 0];
1152 unshift @$tree, $var;
1153 $var = $self->apply_precedence($tree, $found);
1158 ### allow for prefix on non-chained variables
1160 $var = [[undef, $_, $var], 0] for reverse @$has_prefix;
1166 ### this is used to put the parsed variables into the correct operations tree
1167 sub apply_precedence
{
1168 my ($self, $tree, $found) = @_;
1172 ### look at the operators we found in the order we found them
1173 for my $prec (sort keys %$found) {
1174 my $ops = $found->{$prec};
1175 local $found->{$prec};
1176 delete $found->{$prec};
1178 ### split the array on the current operators for this level
1181 for (my $i = 1; $i <= $#$tree; $i += 2) {
1182 next if ! $ops->{ $tree->[$i] };
1183 push @ops, $tree->[$i];
1184 push @exprs, [splice @$tree, 0, $i, ()];
1188 next if ! @exprs; # this iteration didn't have the current operator
1189 push @exprs, $tree if scalar @$tree; # add on any remaining items
1191 ### simplify sub expressions
1192 for my $node (@exprs) {
1194 $node = $node->[0]; # single item - its not a tree
1195 } elsif (@$node == 3) {
1196 $node = [[undef, $node->[1], $node->[0], $node->[2]], 0]; # single operator - put it straight on
1198 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1202 ### assemble this current level
1205 # 1) items at the same precedence level must all be either right or left or ternary associative
1206 # 2) ternary items cannot share precedence with anybody else.
1207 # 3) there really shouldn't be another operator at the same level as a postfix
1208 my $type = $OP->{$ops[0]}->[0];
1210 if ($type eq 'ternary') {
1211 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1213 ### return simple ternary
1215 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1216 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1217 return [[undef, $op, @exprs], 0];
1221 ### reorder complex ternary - rare case
1222 while ($#ops >= 1) {
1223 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1224 for (my $i = $#ops; $i >= 0; $i --) {
1225 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1226 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1227 my $node = [[undef, $op, @exprs[$i .. $i + 2]], 0];
1228 splice @exprs, $i, 3, $node;
1231 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1233 } elsif ($type eq 'right' || $type eq 'assign') {
1234 my $val = $exprs[-1];
1235 $val = [[undef, $ops[$_ - 1], $exprs[$_], $val], 0] for reverse (0 .. $#exprs - 1);
1239 my $val = $exprs[0];
1240 $val = [[undef, $ops[$_ - 1], $val, $exprs[$_]], 0] for (1 .. $#exprs);
1246 $self->throw('parse', "Couldn't apply precedence");
1249 ### look for arguments - both positional and named
1252 my $str_ref = shift;
1253 my $ARGS = shift || {};
1258 my $end = $self->{'_end_tag'} || '(?!)';
1260 my $mark = pos $$str_ref;
1262 ### look to see if the next thing is a directive or a closing tag
1263 if (! $ARGS->{'is_parened'}
1264 && ! $ARGS->{'require_arg'}
1265 && $$str_ref =~ m{ \G $QR_DIRECTIVE (?: \s+ | (?: \s* $QR_COMMENTS (?: ;|[+=~-]?$end))) }gcxo
1266 && ((pos($$str_ref) = $mark) || 1) # always revert
1267 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc($1) : $1} # looks like a directive - we are done
1271 if ($$str_ref =~ m{ \G [+=~-]? $end }gcx) {
1272 pos($$str_ref) = $mark;
1276 ### find the initial arg
1278 if ($ARGS->{'allow_bare_filenames'}) {
1279 $name = $self->parse_expr($str_ref, {auto_quote
=> "
1280 ($QR_FILENAME # file name
1281 | $QR_BLOCK # or block
1282 (?= [+=~-]? $end # an end tag
1283 | \\s*[+,;] # followed by explicit + , or ;
1284 | \\s+ (?! [\\s=]) # or space not before an =
1285 ) \\s* $QR_COMMENTS"});
1286 # filenames can be separated with a "+" - why a "+" ?
1287 if ($$str_ref =~ m{ \G \+ (?! [+=~-]? $end) \s* $QR_COMMENTS }gcxo) {
1289 $ARGS->{'require_arg'} = 1;
1293 if (! defined $name) {
1294 $name = $self->parse_expr($str_ref);
1295 if (! defined $name) {
1296 if ($ARGS->{'require_arg'} && ! @args && ! $ARGS->{'positional_only'} && ! @named) {
1297 $self->throw('parse', 'Argument required', undef, pos($$str_ref));
1304 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1306 ### see if it is named or positional
1307 if ($$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo) {
1308 $self->throw('parse', 'Named arguments not allowed', undef, $mark) if $ARGS->{'positional_only'};
1309 my $val = $self->parse_expr($str_ref);
1310 $name = $name->[0] if ref($name) && @$name == 2 && ! $name->[1]; # strip a level of indirection on named arguments
1311 push @named, $name, $val;
1316 ### look for trailing comma
1317 $ARGS->{'require_arg'} = ($$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo) || 0;
1320 ### allow for named arguments to be added at the front (if asked)
1321 if ($ARGS->{'named_at_front'}) {
1322 unshift @args, [[undef, '{}', @named], 0];
1323 } elsif (scalar @named) { # only add at end - if there are some
1324 push @args, [[undef, '{}', @named], 0]
1330 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1331 sub interpolate_node
{
1332 my ($self, $tree, $offset) = @_;
1333 return if $self->{'_no_interp'};
1335 ### split on variables while keeping the variables
1336 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ .*? (?<!\\) \}) }x
, $tree->[-1];
1337 if ($#pieces <= 0) {
1338 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1344 foreach my $piece (@pieces) {
1345 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1346 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1347 if (! ($n++ % 2)) { # odds will always be text chunks
1348 next if ! length $piece;
1349 push @sub_tree, $piece;
1350 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1351 || $piece =~ m{ ^ \$\{ \s* (.*?) (?<!\\) \} $ }x
) {
1353 $name =~ s/\\\}/\}/g;
1354 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1356 $self->throw('parse', "Parse error during interpolate node");
1360 ### replace the tree
1361 splice @$tree, -1, 1, @sub_tree;
1364 ###----------------------------------------------------------------###
1367 my ($self, $tree, $out_ref) = @_;
1369 # node contains (0: DIRECTIVE,
1372 # 3: parsed tag details,
1373 # 4: sub tree for block types
1374 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
1375 # 6: flag to capture next directive
1376 for my $node (@$tree) {
1377 ### text nodes are just the bare text
1379 $$out_ref .= $node if defined $node;
1383 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
1385 $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
1390 ### allow for the parse tree to store literals
1391 return $_[1] if ! ref $_[1];
1395 my $ARGS = shift || {};
1398 ### determine the top level of this particular variable access
1400 my $name = $var->[$i++];
1401 my $args = $var->[$i++];
1403 if (! defined $name->[0]) { # operator
1404 return $self->play_operator($name) if wantarray && $name->[1] eq '..';
1405 $ref = $self->play_operator($name);
1406 } else { # a named variable access (ie via $name.foo)
1407 $name = $self->play_expr($name);
1408 if (defined $name) {
1409 return if $QR_PRIVATE && $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1410 return \
$self->{'_vars'}->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $self->{'_vars'}->{$name};
1411 $ref = $self->{'_vars'}->{$name};
1414 } elsif (defined $name) {
1415 if ($ARGS->{'is_namespace_during_compile'}) {
1416 $ref = $self->{'NAMESPACE'}->{$name};
1418 return if $QR_PRIVATE && $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1419 return \
$self->{'_vars'}->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $self->{'_vars'}->{$name};
1420 $ref = $self->{'_vars'}->{$name};
1421 if (! defined $ref) {
1422 $ref = ($name eq 'template' || $name eq 'component') ? $self->{"_$name"} : $VOBJS->{$name};
1423 $ref = $SCALAR_OPS->{$name} if ! $ref && (! defined($self->{'VMETHOD_FUNCTIONS'}) || $self->{'VMETHOD_FUNCTIONS'});
1430 while (defined $ref) {
1432 ### check at each point if the rurned thing was a code
1433 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1434 return $ref if $i >= $#$var && $ARGS->{'return_ref'};
1435 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1436 if (defined $results[0]) {
1437 $ref = ($#results > 0) ? \
@results : $results[0];
1438 } elsif (defined $results[1]) {
1439 die $results[1]; # TT behavior - why not just throw ?
1446 ### descend one chained level
1447 last if $i >= $#$var;
1448 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1449 $name = $var->[$i++];
1450 $args = $var->[$i++];
1452 ### allow for named portions of a variable name (foo.$name.bar)
1454 if (ref($name) eq 'ARRAY') {
1455 $name = $self->play_expr($name);
1456 if (! defined($name) || ($QR_PRIVATE && $name =~ $QR_PRIVATE) || $name =~ /^\./) {
1461 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1464 if ($QR_PRIVATE && $name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1469 ### allow for scalar and filter access (this happens for every non virtual method call)
1471 if ($SCALAR_OPS->{$name}) { # normal scalar op
1472 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1474 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1475 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1477 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1478 || $FILTER_OPS->{$name} # predefined filters in CET
1479 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1480 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1482 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1483 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1485 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1488 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1489 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1491 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1493 my $sub = $filter->[0];
1494 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1495 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1496 if (! $sub && $err) {
1497 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1499 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1500 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1501 if ref($sub) !~ /Template::Exception$/;
1505 $ref = $sub->($ref);
1508 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1511 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1512 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1513 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1516 if (scalar keys %seen_filters
1517 && $seen_filters{$var->[$i - 5] || ''}) {
1518 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1526 ### method calls on objects
1527 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1528 return $ref if $i >= $#$var && $ARGS->{'return_ref'};
1529 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1530 my @results = eval { $ref->$name(@args) };
1532 my $class = ref $ref;
1533 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1534 } elsif (defined $results[0]) {
1535 $ref = ($#results > 0) ? \
@results : $results[0];
1537 } elsif (defined $results[1]) {
1538 die $results[1]; # TT behavior - why not just throw ?
1543 # didn't find a method by that name - so fail down to hash and array access
1546 ### hash member access
1547 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1548 if ($was_dot_call && exists($ref->{$name}) ) {
1549 return \
$ref->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $ref->{$name};
1550 $ref = $ref->{$name};
1551 } elsif ($HASH_OPS->{$name}) {
1552 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1553 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1554 return $var; # abort - can't fold namespace variable
1556 return \
$ref->{$name} if $i >= $#$var && $ARGS->{'return_ref'};
1561 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1562 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1563 return \
$ref->[$name] if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $ref->[$name];
1564 $ref = $ref->[$name];
1565 } elsif ($LIST_OPS->{$name}) {
1566 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1575 ### allow for undefinedness
1576 if (! defined $ref) {
1577 if ($self->{'_debug_undef'}) {
1578 my $chunk = $var->[$i - 2];
1579 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1580 die "$chunk is undefined\n";
1582 $ref = $self->undefined_any($var);
1589 sub is_empty_named_args
{
1590 my ($self, $hash_ident) = @_;
1591 # [[undef, '{}', 'key1', 'val1', 'key2, 'val2'], 0]
1592 return @{ $hash_ident->[0] } <= 2;
1596 my ($self, $var, $val, $ARGS) = @_;
1600 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1601 $var = [$var, 0] if ! ref $var;
1603 ### determine the top level of this particular variable access
1604 my $ref = $var->[$i++];
1605 my $args = $var->[$i++];
1607 ### non-named types can't be set
1608 return if ref($ref) ne 'ARRAY' || ! defined $ref->[0];
1610 # named access (ie via $name.foo)
1611 $ref = $self->play_expr($ref);
1612 if (defined $ref && (! $QR_PRIVATE || $ref !~ $QR_PRIVATE)) { # don't allow vars that begin with _
1614 return $self->{'_vars'}->{$ref} = $val;
1616 $ref = $self->{'_vars'}->{$ref} ||= {};
1621 } elsif (defined $ref) {
1622 return if $QR_PRIVATE && $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1624 return $self->{'_vars'}->{$ref} = $val;
1626 $ref = $self->{'_vars'}->{$ref} ||= {};
1630 while (defined $ref) {
1632 ### check at each point if the returned thing was a code
1633 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1634 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1635 if (defined $results[0]) {
1636 $ref = ($#results > 0) ? \
@results : $results[0];
1637 } elsif (defined $results[1]) {
1638 die $results[1]; # TT behavior - why not just throw ?
1644 ### descend one chained level
1645 last if $i >= $#$var;
1646 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1647 my $name = $var->[$i++];
1648 my $args = $var->[$i++];
1650 ### allow for named portions of a variable name (foo.$name.bar)
1652 if (ref($name) eq 'ARRAY') {
1653 $name = $self->play_expr($name);
1654 if (! defined($name) || $name =~ /^[_.]/) {
1658 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1661 if ($QR_PRIVATE && $name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1669 ### method calls on objects
1670 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1672 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1677 my @results = eval { $ref->$name(@args) };
1679 if (defined $results[0]) {
1680 $ref = ($#results > 0) ? \
@results : $results[0];
1681 } elsif (defined $results[1]) {
1682 die $results[1]; # TT behavior - why not just throw ?
1686 return if $lvalueish;
1689 my $class = ref $ref;
1690 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1691 # fall on down to "normal" accessors
1694 ### hash member access
1695 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1697 return $ref->{$name} = $val;
1699 $ref = $ref->{$name} ||= {};
1704 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1705 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1707 return $ref->[$name] = $val;
1709 $ref = $ref->[$name] ||= {};
1723 ###----------------------------------------------------------------###
1726 my ($self, $tree) = @_;
1727 ### $tree looks like [undef, '+', 4, 5]
1729 if ($OP_DISPATCH->{$tree->[1]}) {
1731 if ($OP_ASSIGN->{$tree->[1]}) {
1732 my $val = $OP_DISPATCH->{$tree->[1]}->($self->play_expr($tree->[2]), $self->play_expr($tree->[3]));
1733 $self->set_variable($tree->[2], $val);
1736 return $OP_DISPATCH->{$tree->[1]}->(@$tree == 3 ? $self->play_expr($tree->[2]) : ($self->play_expr($tree->[2]), $self->play_expr($tree->[3])));
1740 my $op = $tree->[1];
1742 ### do custom and short-circuitable operators
1744 my $val = $self->play_expr($tree->[3]);
1745 $self->set_variable($tree->[2], $val);
1748 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1749 my $val = $self->play_expr($tree->[2]) || $self->play_expr($tree->[3]);
1750 return defined($val) ? $val : '';
1752 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1753 my $val = $self->play_expr($tree->[2]) && $self->play_expr($tree->[3]);
1754 return defined($val) ? $val : '';
1756 } elsif ($op eq '?') {
1758 return $self->play_expr($tree->[2]) ? $self->play_expr($tree->[3]) : $self->play_expr($tree->[4]);
1760 } elsif ($op eq '~' || $op eq '_') {
1763 $s .= $self->play_expr($tree->[$_]) for 2 .. $#$tree;
1766 } elsif ($op eq '[]') {
1767 return [map {$self->play_expr($tree->[$_])} 2 .. $#$tree];
1769 } elsif ($op eq '{}') {
1772 push @e, $self->play_expr($tree->[$_]) for 2 .. $#$tree;
1775 } elsif ($op eq '++') {
1777 my $val = 0 + $self->play_expr($tree->[2]);
1778 $self->set_variable($tree->[2], $val + 1);
1779 return $tree->[3] ? $val : $val + 1; # ->[3] is set to 1 during parsing of postfix ops
1781 } elsif ($op eq '--') {
1783 my $val = 0 + $self->play_expr($tree->[2]);
1784 $self->set_variable($tree->[2], $val - 1);
1785 return $tree->[3] ? $val : $val - 1; # ->[3] is set to 1 during parsing of postfix ops
1787 } elsif ($op eq '\\') {
1788 my $var = $tree->[2];
1790 my $ref = $self->play_expr($var, {return_ref
=> 1});
1791 return $ref if ! ref $ref;
1792 return sub { sub { $$ref } } if ref $ref eq 'SCALAR' || ref $ref eq 'REF';
1794 my $self_copy = $self;
1795 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
1797 my $last = ['temp deref key', $var->[-1] ? [@{ $var->[-1] }] : 0];
1798 return sub { sub { # return a double sub so that the current play_expr will return a coderef
1799 local $self_copy->{'_vars'}->{'temp deref key'} = $ref;
1800 $last->[-1] = (ref $last->[-1] ? [@{ $last->[-1] }, @_] : [@_]) if @_;
1801 return $self->play_expr($last);
1803 } elsif ($op eq 'qr') {
1804 return $tree->[3] ? qr{(?$tree->[3]:$tree->[2])} : qr{$tree->[2]};
1807 $self->throw('operator', "Un-implemented operation $op");
1810 ###----------------------------------------------------------------###
1813 my ($self, $str_ref, $node) = @_;
1815 my $end = $self->{'_end_tag'} || '(?!)';
1816 my $block_name = $self->parse_expr($str_ref, {auto_quote
=> "
1817 ($QR_FILENAME # file name
1818 | $QR_BLOCK # or block
1819 (?= [+=~-]? $end # an end tag
1820 | \\s*[+,;] # followed by explicit + , or ;
1821 | \\s+ (?! [\\s=]) # or space not before an =
1822 ) \\s* $QR_COMMENTS"});
1824 return '' if ! defined $block_name;
1826 my $prepend = join "/", map {$_->[3]} grep {ref($_) && $_->[0] eq 'BLOCK'} @{ $self->{'_state'} || {} };
1827 return $prepend ? "$prepend/$block_name" : $block_name;
1831 my ($self, $block_name, $node, $out_ref) = @_;
1833 ### store a named reference - but do nothing until something processes it
1834 $self->{'BLOCKS'}->{$block_name} = {
1835 _tree
=> $node->[4],
1836 name
=> $self->{'_component'}->{'name'} .'/'. $block_name,
1842 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1845 my ($self, $ident, $node) = @_;
1846 my $var = $self->play_expr($ident);
1847 $var = $self->undefined_get($ident, $node) if ! defined $var;
1852 my ($self, $str_ref) = @_;
1853 return if $$str_ref =~ m{ \G DEFAULT \s* }gcx;
1854 return $self->parse_expr($str_ref);
1858 my ($self, $str_ref) = @_;
1859 return $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b (?: \\.\\w+\\b)*) $QR_AQ_SPACE \\s* $QR_COMMENTS"});
1863 my ($self, $undef, $node) = @_;
1864 $self->throw(lc($node->[0]), 'Control exception', $node);
1868 my ($self, $undef, $node, $out_ref) = @_;
1874 require CGI
::Ex
::Template
::Extra
;
1875 &CGI
::Ex
::Template
::Extra
::parse_CONFIG
;
1879 require CGI
::Ex
::Template
::Extra
;
1880 &CGI
::Ex
::Template
::Extra
::play_CONFIG
;
1884 require CGI
::Ex
::Template
::Extra
;
1885 &CGI
::Ex
::Template
::Extra
::parse_DEBUG
;
1889 require CGI
::Ex
::Template
::Extra
;
1890 &CGI
::Ex
::Template
::Extra
::play_DEBUG
;
1893 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1896 my ($self, $set) = @_;
1898 my ($op, $set, $default) = @$_;
1899 next if ! defined $set;
1900 my $val = $self->play_expr($set);
1902 $default = defined($default) ? $self->play_expr($default) : '';
1903 $self->set_variable($set, $default);
1910 my ($self, $str_ref) = @_;
1911 return $self->parse_args($str_ref, {named_at_front
=> 1});
1915 require CGI
::Ex
::Template
::Extra
;
1916 &CGI
::Ex
::Template
::Extra
::play_DUMP
;
1920 require CGI
::Ex
::Template
::Extra
;
1921 &CGI
::Ex
::Template
::Extra
::parse_FILTER
;
1925 require CGI
::Ex
::Template
::Extra
;
1926 &CGI
::Ex
::Template
::Extra
::play_FILTER
;
1930 my ($self, $str_ref) = @_;
1931 my $items = $self->parse_expr($str_ref);
1933 if ($$str_ref =~ m{ \G (= | [Ii][Nn]\b) \s* }gcx) {
1935 $items = $self->parse_expr($str_ref);
1937 return [$var, $items];
1941 my ($self, $ref, $node, $out_ref) = @_;
1943 ### get the items - make sure it is an arrayref
1944 my ($var, $items) = @$ref;
1946 $items = $self->play_expr($items);
1947 return '' if ! defined $items;
1949 if (ref($items) !~ /Iterator$/) {
1950 $items = $self->iterator($items);
1953 my $sub_tree = $node->[4];
1955 local $self->{'_vars'}->{'loop'} = $items;
1957 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1959 my ($item, $error) = $items->get_first;
1962 $self->set_variable($var, $item);
1964 ### execute the sub tree
1965 eval { $self->execute_tree($sub_tree, $out_ref) };
1967 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1968 if ($err->type eq 'next') {
1969 ($item, $error) = $items->get_next;
1972 last if $err->type =~ /last|break/;
1977 ($item, $error) = $items->get_next;
1979 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1980 ### if the FOREACH tag doesn't set a var - then everything gets localized
1983 ### localize variable access for the foreach
1984 my $swap = $self->{'_vars'};
1985 local $self->{'_vars'} = my $copy = {%$swap};
1987 ### iterate use the iterator object
1988 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1989 my ($item, $error) = $items->get_first;
1992 if (ref($item) eq 'HASH') {
1993 @$copy{keys %$item} = values %$item;
1996 ### execute the sub tree
1997 eval { $self->execute_tree($sub_tree, $out_ref) };
1999 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2000 if ($err->type eq 'next') {
2001 ($item, $error) = $items->get_next;
2004 last if $err->type =~ /last|break/;
2009 ($item, $error) = $items->get_next;
2011 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
2018 my ($self, $str_ref) = @_;
2019 my $ref = $self->parse_expr($str_ref);
2020 $self->throw('parse', "Missing variable name", undef, pos($$str_ref)) if ! defined $ref;
2025 my ($self, $ident, $node, $out_ref) = @_;
2026 my $var = $self->play_expr($ident);
2030 $var = $self->undefined_get($ident, $node);
2031 $$out_ref .= $var if defined $var;
2037 my ($self, $str_ref) = @_;
2038 return $self->parse_expr($str_ref);
2042 my ($self, $var, $node, $out_ref) = @_;
2044 my $val = $self->play_expr($var);
2046 my $body_ref = $node->[4] ||= [];
2047 $self->execute_tree($body_ref, $out_ref);
2051 while ($node = $node->[5]) { # ELSE, ELSIF's
2052 if ($node->[0] eq 'ELSE') {
2053 my $body_ref = $node->[4] ||= [];
2054 $self->execute_tree($body_ref, $out_ref);
2057 my $var = $node->[3];
2058 my $val = $self->play_expr($var);
2060 my $body_ref = $node->[4] ||= [];
2061 $self->execute_tree($body_ref, $out_ref);
2068 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2071 my ($self, $str_ref, $node, $out_ref) = @_;
2073 ### localize the swap
2074 my $swap = $self->{'_vars'} || {};
2075 local $self->{'_vars'} = {%$swap};
2077 ### localize the blocks
2078 my $blocks = $self->{'BLOCKS'} || {};
2079 local $self->{'BLOCKS'} = {%$blocks};
2081 return $DIRECTIVES->{'PROCESS'}->[1]->($self, $str_ref, $node, $out_ref);
2084 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2087 my ($self, $args, $node, $out_ref) = @_;
2088 if ($self->{'NO_INCLUDES'}) {
2089 $self->throw('file', "NO_INCLUDES was set during a $node->[0] directive");
2092 my ($named, @files) = @$args;
2094 foreach my $name (@files) {
2095 my $filename = $self->play_expr($name);
2096 $$out_ref .= $self->_insert($filename);
2103 require CGI
::Ex
::Template
::Extra
;
2104 &CGI
::Ex
::Template
::Extra
::parse_LOOP
;
2108 require CGI
::Ex
::Template
::Extra
;
2109 &CGI
::Ex
::Template
::Extra
::play_LOOP
;
2113 require CGI
::Ex
::Template
::Extra
;
2114 &CGI
::Ex
::Template
::Extra
::parse_MACRO
;
2118 require CGI
::Ex
::Template
::Extra
;
2119 &CGI
::Ex
::Template
::Extra
::play_MACRO
;
2123 my ($self, $str_ref) = @_;
2124 my $args = $self->parse_args($str_ref, {named_at_front
=> 1});
2126 return $hash if ($hash = $self->play_expr($args->[0])) && UNIVERSAL
::isa
($hash, 'HASH');
2132 my ($self, $hash) = @_;
2134 my @keys = keys %$hash;
2137 if ($self->{'_top_level'}) {
2138 $ref = $self->{'_template'} ||= {};
2140 $ref = $self->{'_component'} ||= {};
2143 @{ $ref }{ @keys } = @{ $hash }{ @keys };
2148 require CGI
::Ex
::Template
::Extra
;
2149 &CGI
::Ex
::Template
::Extra
::play_PERL
;
2153 my ($self, $str_ref) = @_;
2155 return $self->parse_args($str_ref, {
2156 named_at_front
=> 1,
2157 allow_bare_filenames
=> 1,
2163 my ($self, $info, $node, $out_ref) = @_;
2164 if ($self->{'NO_INCLUDES'}) {
2165 $self->throw('file', "NO_INCLUDES was set during a $node->[0] directive");
2168 my ($args, @files) = @$info;
2171 # [[undef, '{}', 'key1', 'val1', 'key2', 'val2'], 0]
2173 foreach (my $i = 2; $i < @$args; $i+=2) {
2174 my $key = $args->[$i];
2175 my $val = $self->play_expr($args->[$i+1]);
2176 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2177 foreach my $key (keys %$val) {
2178 $self->set_variable([$key,0], $val->{$key});
2182 $self->set_variable($key, $val);
2185 ### iterate on any passed block or filename
2186 foreach my $ref (@files) {
2187 next if ! defined $ref;
2188 my $filename = $self->play_expr($ref);
2189 my $out = ''; # have temp item to allow clear to correctly clear
2191 ### normal blocks or filenames
2192 if (! ref $filename) {
2193 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2195 ### allow for $template which is used in some odd instances
2198 if ($ref->[0] eq 'template') {
2201 $doc = $self->play_expr($ref);
2202 if (ref($doc) ne 'HASH' || ! $doc->{'_tree'}) {
2203 $self->throw('process', "Passed item doesn't appear to be a valid document");
2206 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2207 local $self->{'_process_dollar_template'} = 1;
2208 local $self->{'_component'} = $filename;
2209 return if ! $doc->{'_tree'};
2211 ### execute and trim
2212 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2213 if ($self->{'TRIM'}) {
2214 $out =~ s{ \s+ $ }{}x;
2215 $out =~ s{ ^ \s+ }{}x;
2218 ### handle exceptions
2220 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2221 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2226 ### append any output
2229 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2237 require CGI
::Ex
::Template
::Extra
;
2238 &CGI
::Ex
::Template
::Extra
::play_RAWPERL
;
2242 my ($self, $str_ref, $node, $initial_op, $initial_var) = @_;
2247 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcx # find a word
2248 && ((pos($$str_ref) -= length($1)) || 1) # always revert
2249 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
2250 $node->[6] = 1; # set a flag to keep parsing
2251 my $val = $node->[4] ||= []; # setup storage
2252 return [[$initial_op, $initial_var, $val]];
2253 } else { # get a normal variable
2254 return [[$initial_op, $initial_var, $self->parse_expr($str_ref)]];
2259 my $set = $self->parse_expr($str_ref);
2260 last if ! defined $set;
2262 if ($$str_ref =~ m{ \G ($QR_OP_ASSIGN) >? \s* }gcx) {
2264 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcx # find a word
2265 && ((pos($$str_ref) -= length($1)) || 1) # always revert
2266 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
2267 $node->[6] = 1; # set a flag to keep parsing
2268 my $val = $node->[4] ||= []; # setup storage
2269 push @SET, [$op, $set, $val];
2271 } else { # get a normal variable
2272 push @SET, [$op, $set, $self->parse_expr($str_ref)];
2275 push @SET, ['=', $set, undef];
2283 my ($self, $set, $node) = @_;
2285 my ($op, $set, $val) = @$_;
2286 if (! defined $val) { # not defined
2287 # do nothing - allow for setting to undef
2288 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2289 my $sub_tree = $node->[4];
2290 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2292 $self->execute_tree($sub_tree, \
$val);
2293 } else { # normal var
2294 $val = $self->play_expr($val);
2297 if ($OP_DISPATCH->{$op}) {
2299 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2302 $self->set_variable($set, $val);
2307 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2310 my ($self, $var, $node, $out_ref) = @_;
2312 my $val = $self->play_expr($var);
2313 $val = '' if ! defined $val;
2314 ### $node->[4] is thrown away
2317 while ($node = $node->[5]) { # CASES
2318 my $var = $node->[3];
2319 if (! defined $var) {
2320 $default = $node->[4];
2324 my $val2 = $self->play_expr($var);
2325 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2326 for my $test (@$val2) { # find matching values
2327 next if ! defined $val && defined $test;
2328 next if defined $val && ! defined $test;
2329 if ($val ne $test) { # check string-wise first - then numerical
2330 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2331 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2332 next if $val != $test;
2335 my $body_ref = $node->[4] ||= [];
2336 $self->execute_tree($body_ref, $out_ref);
2342 $self->execute_tree($default, $out_ref);
2349 my ($self, $str_ref, $node) = @_;
2352 if ($$str_ref =~ m{ \G (\w+) \s* $QR_COMMENTS }gcxs) {
2353 my $ref = $TAGS->{lc $1} || $self->throw('parse', "Invalid TAGS name \"$1\"", undef, pos($$str_ref));
2354 ($start, $end) = @$ref;
2357 local $self->{'_operator_precedence'} = 1; # prevent operator matching
2358 $start = $$str_ref =~ m{ \G (?= [\'\"\/]) }gcx
2359 ? $self->parse_expr($str_ref)
2360 : $self->parse_expr($str_ref, {auto_quote
=> "(\\S+) \\s+ $QR_COMMENTS"})
2361 || $self->throw('parse', "Invalid opening tag in TAGS", undef, pos($$str_ref));
2362 $end = $$str_ref =~ m{ \G (?= [\'\"\/]) }gcx
2363 ? $self->parse_expr($str_ref)
2364 : $self->parse_expr($str_ref, {auto_quote
=> "(\\S+) \\s* $QR_COMMENTS"})
2365 || $self->throw('parse', "Invalid closing tag in TAGS", undef, pos($$str_ref));
2366 for my $tag ($start, $end) {
2367 $tag = $self->play_expr($tag);
2368 $tag = quotemeta($tag) if ! ref $tag;
2371 return [$start, $end];
2375 my ($self, $str_ref, $node) = @_;
2376 my $name = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b (?: \\.\\w+\\b)*) $QR_AQ_SPACE \\s* $QR_COMMENTS"});
2377 $self->throw('parse.missing', "Missing name in THROW", $node, pos($$str_ref)) if ! $name;
2378 my $args = $self->parse_args($str_ref, {named_at_front
=> 1});
2379 return [$name, $args];
2383 my ($self, $ref, $node) = @_;
2384 my ($name, $args) = @$ref;
2386 $name = $self->play_expr($name);
2388 my ($named, @args) = @$args;
2389 push @args, $named if ! $self->is_empty_named_args($named); # add named args back on at end - if there are some
2391 @args = map { $self->play_expr($_) } @args;
2392 $self->throw($name, \
@args, $node); # dies
2393 return; # but return just in case
2397 my ($self, $foo, $node, $out_ref) = @_;
2400 my $body_ref = $node->[4];
2401 eval { $self->execute_tree($body_ref, \
$out) };
2404 if (! $node->[5]) { # no catch or final
2405 if (! $err) { # no final block and no error
2409 $self->throw('parse.missing', "Missing CATCH block", $node);
2412 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2413 if ($err->type =~ /stop|return/) {
2419 ### loop through the nested catch and final blocks
2422 my $type = $err ? $err->type : '';
2424 while ($node = $node->[5]) { # CATCH
2425 if ($node->[0] eq 'FINAL') {
2426 $final = $node->[4];
2430 my $name = $self->play_expr($node->[3]);
2431 $name = '' if ! defined $name || lc($name) eq 'default';
2432 if ($type =~ / ^ \Q$name\E \b /x
2433 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2434 $catch_body_ref = $node->[4] || [];
2435 $last_found = $name;
2439 ### play the best catch block
2441 if (! $catch_body_ref) {
2445 local $self->{'_vars'}->{'error'} = $err;
2446 local $self->{'_vars'}->{'e'} = $err;
2447 eval { $self->execute_tree($catch_body_ref, \
$out) };
2455 $self->execute_tree($final, \
$out) if $final;
2463 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2464 return [[undef, '!', $ref], 0];
2467 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2470 require CGI
::Ex
::Template
::Extra
;
2471 &CGI
::Ex
::Template
::Extra
::parse_USE
;
2475 require CGI
::Ex
::Template
::Extra
;
2476 &CGI
::Ex
::Template
::Extra
::play_USE
;
2480 require CGI
::Ex
::Template
::Extra
;
2481 &CGI
::Ex
::Template
::Extra
::parse_VIEW
;
2485 require CGI
::Ex
::Template
::Extra
;
2486 &CGI
::Ex
::Template
::Extra
::play_VIEW
;
2489 sub parse_WHILE
{ $DIRECTIVES->{'IF'}->[0]->(@_) }
2492 my ($self, $var, $node, $out_ref) = @_;
2493 return if ! defined $var;
2495 my $sub_tree = $node->[4];
2497 ### iterate use the iterator object
2498 my $count = $WHILE_MAX;
2499 while (--$count > 0) {
2501 $self->play_expr($var) || last;
2503 ### execute the sub tree
2504 eval { $self->execute_tree($sub_tree, $out_ref) };
2506 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2507 next if $err->type =~ /next/;
2508 last if $err->type =~ /last|break/;
2513 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2518 sub parse_WRAPPER
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2521 my ($self, $args, $node, $out_ref) = @_;
2522 my $sub_tree = $node->[4] || return;
2524 my ($named, @files) = @$args;
2527 $self->execute_tree($sub_tree, \
$out);
2529 foreach my $name (reverse @files) {
2530 local $self->{'_vars'}->{'content'} = $out;
2532 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [$named, $name], $node, \
$out);
2539 ###----------------------------------------------------------------###
2543 $self->{'_vars'} = shift if $#_ == 0;
2544 return $self->{'_vars'} ||= {};
2547 sub include_filename
{
2548 my ($self, $file) = @_;
2549 if ($file =~ m
|^/|) {
2550 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2551 return $file if -e
$file;
2552 } elsif ($file =~ m{(^|/)\.\./}) {
2553 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2554 return $file if -e
$file;
2557 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2558 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2559 my $paths = $self->{'INCLUDE_PATH'} || [];
2560 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2561 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2562 $paths; # return of the do
2564 foreach my $path (@$paths) {
2565 return "$path/$file" if -e
"$path/$file";
2568 $self->throw('file', "$file: not found");
2572 my ($self, $path) = @_;
2573 return $path if ref $path;
2574 my $delim = $self->{'DELIMITER'} || ':';
2575 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2576 return [split $delim, $path];
2580 my ($self, $file) = @_;
2581 return $self->slurp($self->include_filename($file));
2585 my ($self, $file) = @_;
2586 open(my $fh, '<', $file) || $self->throw('file', "$file couldn't be opened: $!");
2587 read $fh, my $txt, -s
$file;
2591 sub process_simple
{
2593 my $in = shift || die "Missing input";
2594 my $swap = shift || die "Missing variable hash";
2595 my $out = shift || die "Missing output string ref";
2598 delete $self->{'_debug_off'};
2599 delete $self->{'_debug_format'};
2600 local $self->{'_start_top_level'} = 1;
2601 $self->_process($in, $swap, $out);
2604 if ($err->type !~ /stop|return|next|last|break/) {
2605 $self->{'error'} = $err;
2613 my ($self, $in, $swap, $out, @ARGS) = @_;
2614 delete $self->{'error'};
2617 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2622 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2624 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2626 $content = \
$content;
2627 } else { # should be a file handle
2630 $content = \
$content;
2633 ### should be a filename
2638 ### prepare block localization
2639 my $blocks = $self->{'BLOCKS'} ||= {};
2646 ### localize the stash
2648 my $var1 = $self->{'_vars'} ||= {};
2649 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2650 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2651 my $copy = {%$var2, %$var1, %$swap};
2653 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2654 local $self->{'_template'};
2656 delete $self->{'_debug_off'};
2657 delete $self->{'_debug_format'};
2659 ### handle pre process items that go before every document
2661 if ($self->{'PRE_PROCESS'}) {
2662 $self->_load_template_meta($content);
2663 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2664 $self->_process($name, $copy, \
$pre);
2668 ### process the central file now - catching errors to allow for the ERROR config
2670 ### handle the PROCESS config - which loads another template in place of the real one
2671 if (exists $self->{'PROCESS'}) {
2672 $self->_load_template_meta($content);
2673 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2674 next if ! length $name;
2675 $self->_process($name, $copy, \
$output);
2678 ### handle "normal" content
2680 local $self->{'_start_top_level'} = 1;
2681 $self->_process($content, $copy, \
$output);
2685 ### catch errors with ERROR config
2687 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2688 die $err if $err->type =~ /stop|return/;
2689 my $catch = $self->{'ERRORS'} || $self->{'ERROR'} || die $err;
2690 $catch = {default => $catch} if ! ref $catch;
2691 my $type = $err->type;
2694 foreach my $name (keys %$catch) {
2695 my $_name = (! defined $name || lc($name) eq 'default') ? '' : $name;
2696 if ($type =~ / ^ \Q$_name\E \b /x
2697 && (! defined($last_found) || length($last_found) < length($_name))) { # more specific wins
2698 $last_found = $_name;
2699 $file = $catch->{$name};
2703 ### found error handler - try it out
2704 if (defined $file) {
2706 local $copy->{'error'} = local $copy->{'e'} = $err;
2707 $self->_process($file, $copy, \
$output);
2711 ### handle wrapper directives
2712 if (exists $self->{'WRAPPER'}) {
2713 $self->_load_template_meta($content);
2714 foreach my $name (reverse @{ $self->split_paths($self->{'WRAPPER'}) }) {
2715 next if ! length $name;
2716 local $copy->{'content'} = $output;
2718 $self->_process($name, $copy, \
$out);
2723 $output = $pre . $output if length $pre;
2725 ### handle post process items that go after every document
2726 if ($self->{'POST_PROCESS'}) {
2727 $self->_load_template_meta($content);
2728 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2729 $self->_process($name, $copy, \
$output);
2735 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2736 if ($err->type !~ /stop|return|next|last|break/) {
2737 $self->{'error'} = $err;
2744 ### clear blocks as asked (AUTO_RESET) defaults to on
2745 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2747 ### send the content back out
2748 $out ||= $self->{'OUTPUT'};
2750 if (UNIVERSAL
::isa
($out, 'CODE')) {
2752 } elsif (UNIVERSAL
::can
($out, 'print')) {
2753 $out->print($output);
2754 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2756 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2757 push @$out, $output;
2758 } else { # should be a file handle
2761 } elsif ($out) { # should be a filename
2763 if ($out =~ m
|^/|) {
2764 if (! $self->{'ABSOLUTE'}) {
2765 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2769 } elsif ($out =~ m
|^\
.\
.?/|) {
2770 if (! $self->{'RELATIVE'}) {
2771 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2776 if (! $self->{'OUTPUT_PATH'}) {
2777 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2779 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2783 if (open my $fh, '>', $file) {
2784 if (my $bm = $args->{'binmode'}) {
2785 if (+$bm == 1) { binmode $fh }
2786 else { binmode $fh, $bm }
2790 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2797 return if $self->{'error'};
2801 sub error
{ shift-
>{'error'} }
2803 sub _load_template_meta
{
2805 return if $self->{'_template'}; # only do once as need
2808 ### load the meta data for the top document
2809 ### this is needed by some of the custom handlers such as PRE_PROCESS and POST_PROCESS
2810 my $content = shift;
2811 my $doc = $self->{'_template'} = $self->load_parsed_tree($content) || {};
2812 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'META')
2813 ? $doc->{'_tree'}->[0]->[3] : {};
2815 $self->{'_template'} = $doc;
2816 @{ $doc }{keys %$meta} = values %$meta;
2823 ###----------------------------------------------------------------###
2829 return $type if ref($type) =~ /Template::Exception$/;
2830 if (ref($info) eq 'ARRAY') {
2831 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2832 if (@$info >= 2 || scalar keys %$hash) {
2834 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2835 $hash->{'args'} = $info;
2837 } elsif (@$info == 1) {
2844 return $PACKAGE_EXCEPTION->new($type, $info, @_);
2847 sub throw
{ die shift-
>exception(@_) }
2851 require CGI
::Ex
::Template
::Extra
;
2852 return CGI
::Ex
::Template
::Context-
>new({_template
=> $self});
2857 $PACKAGE_ITERATOR->new(@_);
2861 my ($self, $ident, $node) = @_;
2862 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2867 my ($self, $ident) = @_;
2868 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2874 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2878 require CGI
::Ex
::Template
::Extra
;
2879 &CGI
::Ex
::Template
::Extra
::list_plugins
;
2883 my ($self, $node) = @_;
2884 my $info = $self->node_info($node);
2885 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2886 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2891 my ($self, $node) = @_;
2892 my $doc = $self->{'_component'};
2894 my $j = $node->[2] || return ''; # META can be 0
2895 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2896 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2900 file
=> $doc->{'name'},
2901 line
=> $self->get_line_number_by_index($doc, $i),
2906 sub get_line_number_by_index
{
2907 my ($self, $doc, $index, $include_char) = @_;
2908 return 1 if $index <= 0;
2910 ### get the line offsets for the doc
2911 my $lines = $doc->{'_line_offsets'} ||= do {
2912 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2916 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2923 ### binary search them (this is fast even on big docs)
2924 my ($i, $j) = (0, $#$lines);
2925 if ($index > $lines->[-1]) {
2929 last if abs($i - $j) <= 1;
2930 my $k = int(($i + $j) / 2);
2931 $j = $k if $lines->[$k] >= $index;
2932 $i = $k if $lines->[$k] <= $index;
2935 return $include_char ? ($i + 1, $index - $lines->[$i]) : $i + 1;
2938 ###----------------------------------------------------------------###
2939 ### long virtual methods or filters
2940 ### many of these vmethods have used code from Template/Stash.pm to
2941 ### assure conformance with the TT spec.
2944 my ($self, $name, $sub) = @_;
2945 $SYNTAX->{$name} = $sub;
2949 sub define_operator
{
2950 my ($self, $args) = @_;
2951 push @$OPERATORS, [@{ $args }{qw(type precedence symbols play_sub)}];
2956 sub define_directive
{
2957 my ($self, $name, $args) = @_;
2958 $DIRECTIVES->{$name} = [@{ $args }{qw(parse_sub play_sub is_block is_postop continues no_interp)}];
2962 sub define_vmethod
{
2963 my ($self, $type, $name, $sub) = @_;
2964 if ( $type =~ /scalar|item|text/i) { $SCALAR_OPS->{$name} = $sub }
2965 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2966 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2967 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2968 else { die "Invalid type vmethod type $type" }
2972 sub vmethod_fmt_scalar
{
2973 my $str = shift; $str = '' if ! defined $str;
2974 my $pat = shift; $pat = '%s' if ! defined $pat;
2976 return @_ ? sprintf($pat, $_[0], $str)
2977 : sprintf($pat, $str);
2980 sub vmethod_fmt_list
{
2981 my $ref = shift || return '';
2982 my $pat = shift; $pat = '%s' if ! defined $pat;
2983 my $sep = shift; $sep = ' ' if ! defined $sep;
2985 return @_ ? join($sep, map {sprintf $pat, $_[0], $_} @$ref)
2986 : join($sep, map {sprintf $pat, $_} @$ref);
2989 sub vmethod_fmt_hash
{
2990 my $ref = shift || return '';
2991 my $pat = shift; $pat = "%s\t%s" if ! defined $pat;
2992 my $sep = shift; $sep = "\n" if ! defined $sep;
2994 return ! @_ ? join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref)
2995 : @_ == 1 ? join($sep, map {sprintf $pat, $_[0], $_, $ref->{$_}} sort keys %$ref) # don't get to pick - it applies to the key
2996 : join($sep, map {sprintf $pat, $_[0], $_, $_[1], $ref->{$_}} sort keys %$ref);
3001 my $size = shift || 1;
3003 if ($size < 0) { # chunk from the opposite end
3004 $str = reverse $str;
3006 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
3008 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
3013 sub vmethod_indent
{
3014 my $str = shift; $str = '' if ! defined $str;
3015 my $pre = shift; $pre = 4 if ! defined $pre;
3016 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
3017 $str =~ s/^/$pre/mg;
3021 sub vmethod_format
{
3022 my $str = shift; $str = '' if ! defined $str;
3023 my $pat = shift; $pat = '%s' if ! defined $pat;
3025 return join "\n", map{ sprintf $pat, $_[0], $_ } split(/\n/, $str);
3027 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
3031 sub vmethod_list_hash
{
3032 my ($hash, $what) = @_;
3033 $what = 'pairs' if ! $what || $what !~ /^(keys|values|each|pairs)$/;
3034 return $HASH_OPS->{$what}->($hash);
3039 my ($str, $pat, $global) = @_;
3040 return [] if ! defined $str || ! defined $pat;
3041 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
3042 return @res ? \
@res : '';
3046 my ($list, $field) = @_;
3047 return defined($field)
3048 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
3049 : UNIVERSAL
::can
($_, $field) ? $_->$field()
3051 : [sort {$a <=> $b} @$list];
3059 my @ind = map { $ref->[ rand @$ref ] } 1 .. $n;
3060 return $n == 1 ? $ind[0] : \
@ind;
3063 sub vmethod_repeat
{
3064 my ($str, $n, $join) = @_;
3065 return '' if ! defined $str || ! length $str;
3066 $n = 1 if ! defined($n) || ! length $n;
3067 $join = '' if ! defined $join;
3068 return join $join, ($str) x
$n;
3071 ### This method is a combination of my submissions along
3072 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
3073 sub vmethod_replace
{
3074 my ($text, $pattern, $replace, $global) = @_;
3075 $text = '' unless defined $text;
3076 $pattern = '' unless defined $pattern;
3077 $replace = '' unless defined $replace;
3078 $global = 1 unless defined $global;
3080 my ($chunk, $start, $end) = @_;
3081 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
3083 : ($2 > $#$start || $2 == 0) ? ''
3084 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
3089 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
3091 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
3097 my ($list, $field) = @_;
3098 return defined($field)
3099 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
3100 : UNIVERSAL
::can
($_, $field) ? $_->$field()
3102 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
3105 sub vmethod_splice
{
3106 my ($ref, $i, $len, @replace) = @_;
3107 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
3109 return [splice @$ref, $i || 0, $len, @replace];
3110 } elsif (defined $i) {
3111 return [splice @$ref, $i];
3113 return [splice @$ref];
3118 my ($str, $pat, $lim) = @_;
3119 $str = '' if ! defined $str;
3120 if (defined $lim) { return defined $pat ? [split $pat, $str, $lim] : [split ' ', $str, $lim] }
3121 else { return defined $pat ? [split $pat, $str ] : [split ' ', $str ] }
3124 sub vmethod_substr
{
3125 my ($str, $i, $len, $replace) = @_;
3127 return substr($str, $i) if ! defined $len;
3128 return substr($str, $i, $len) if ! defined $replace;
3129 substr($str, $i, $len, $replace);
3135 utf8
::encode
($str) if defined &utf8
::encode
;
3136 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
3142 utf8
::encode
($str) if defined &utf8
::encode
;
3143 $str =~ s/([^;\/?:@&=+\$,A-Za-z0-9\-_.!~*\'()])/sprintf
('%%%02X', ord($1))/eg
;
3148 my $context = shift;
3152 ### prevent recursion
3153 my $t = $context->_template;
3154 local $t->{'_eval_recurse'} = $t->{'_eval_recurse'} || 0;
3155 $context->throw('eval_recurse', "MAX_EVAL_RECURSE $MAX_EVAL_RECURSE reached")
3156 if ++$t->{'_eval_recurse'} > ($t->{'MAX_EVAL_RECURSE'} || $MAX_EVAL_RECURSE);
3160 local $t->{'SYNTAX'} = $syntax || $t->{'SYNTAX'};
3161 return $context->process(\
$text);
3165 sub filter_redirect
{
3166 my ($context, $file, $options) = @_;
3167 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3168 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3169 if $file =~ m{(^|/)\.\./};
3175 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3177 open (my $fh, '>', "$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3178 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3179 if (+$bm == 1) { binmode $fh }
3180 else { binmode $fh, $bm}
3187 ###----------------------------------------------------------------###
3190 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3192 require Data
::Dumper
;
3193 return Data
::Dumper
::Dumper
($obj->parse_tree(\
$str));
3196 sub dump_parse_expr
{
3197 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3199 require Data
::Dumper
;
3200 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3203 ###----------------------------------------------------------------###
3204 ### support for few HTML::Template and HTML::Template::Expr calling syntax
3206 sub register_function
{
3207 my ($name, $sub) = @_;
3208 $SCALAR_OPS->{$name} = $sub;
3212 require CGI
::Ex
::Template
::HTE
;
3213 &CGI
::Ex
::Template
::HTE
::param
;
3217 require CGI
::Ex
::Template
::HTE
;
3218 &CGI
::Ex
::Template
::HTE
::output
;
3221 sub clear_param
{ shift-
>{'param'} = {} }
3223 sub query
{ shift-
>throw('query', "Not implemented in CGI::Ex::Template") }
3225 sub new_file
{ my $class = shift; my $in = shift; $class->new(source
=> $in, type
=> 'filename', @_) }
3226 sub new_scalar_ref
{ my $class = shift; my $in = shift; $class->new(source
=> $in, type
=> 'scalarref', @_) }
3227 sub new_array_ref
{ my $class = shift; my $in = shift; $class->new(source
=> $in, type
=> 'arrayref', @_) }
3228 sub new_filehandle
{ my $class = shift; my $in = shift; $class->new(source
=> $in, type
=> 'filehandle', @_) }
3230 ###----------------------------------------------------------------###
3232 package CGI
::Ex
::Template
::Exception
;
3235 '""' => \
&as_string
,
3236 bool
=> sub { defined shift },
3240 my ($class, $type, $info, $node, $pos, $doc) = @_;
3241 return bless [$type, $info, $node, $pos, $doc], $class;
3244 sub type
{ shift-
>[0] }
3246 sub info
{ shift-
>[1] }
3250 $self->[2] = shift if @_;
3256 $self->[3] = shift if @_;
3262 $self->[4] = shift if @_;
3268 if ($self->type =~ /^parse/) {
3269 if (my $doc = $self->doc) {
3270 my ($line, $char) = CGI
::Ex
::Template-
>get_line_number_by_index($doc, $self->offset, 'include_char');
3271 return $self->type ." error - $doc->{'name'} line $line char $char: ". $self->info;
3273 return $self->type .' error - '. $self->info .' (At char '. $self->offset .')';
3276 return $self->type .' error - '. $self->info;
3280 ###----------------------------------------------------------------###
3282 package CGI
::Ex
::Template
::Iterator
;
3285 my ($class, $items) = @_;
3286 $items = [] if ! defined $items;
3287 if (UNIVERSAL
::isa
($items, 'HASH')) {
3288 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3289 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3290 $items = $items->as_list;
3291 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3294 return bless [$items, 0], $class;
3299 return (undef, 3) if ! @{ $self->[0] };
3300 return ($self->[0]->[$self->[1] = 0], undef);
3305 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3306 return ($self->items->[$self->[1]], undef);
3309 sub items
{ shift-
>[0] }
3311 sub index { shift-
>[1] }
3313 sub max
{ $#{ shift-
>[0] } }
3315 sub size
{ shift-
>max + 1 }
3317 sub count
{ shift-
>index + 1 }
3319 sub number
{ shift-
>index + 1 }
3321 sub first
{ (shift-
>index == 0) || 0 }
3323 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3327 return undef if $self->index <= 0;
3328 return $self->items->[$self->index - 1];
3333 return undef if $self->index >= $self->max;
3334 return $self->items->[$self->index + 1];
3337 ###----------------------------------------------------------------###
3341 ### See the perldoc in CGI/Ex/Template.pod