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 ###----------------------------------------------------------------###
10 use constant trace
=> $ENV{'CET_TRACE'} || 0; # enable for low level tracing
13 $SCALAR_OPS $HASH_OPS $LIST_OPS $FILTER_OPS $VOBJS
14 $DIRECTIVES $QR_DIRECTIVE
35 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
44 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
45 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
46 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
47 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
48 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
51 default => ['[%', '%]'], # default
52 template
=> ['[%', '%]'], # default
53 metatext
=> ['%%', '%%'], # Text::MetaText
54 star
=> ['[*', '*]'], # TT alternate
55 php
=> ['<?', '?>'], # PHP
56 asp
=> ['<%', '%>'], # ASP
57 mason
=> ['<%', '>' ], # HTML::Mason
58 html
=> ['<!--', '-->'], # HTML comments
63 as
=> \
&vmethod_as_scalar
,
64 chunk
=> \
&vmethod_chunk
,
65 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
66 defined => sub { defined $_[0] ? 1 : '' },
67 indent
=> \
&vmethod_indent
,
68 int => sub { local $^W; int $_[0] },
69 fmt
=> \
&vmethod_as_scalar
,
70 'format' => \
&vmethod_format
,
71 hash
=> sub { {value
=> $_[0]} },
72 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; $_ },
73 item
=> sub { $_[0] },
74 lcfirst => sub { lcfirst $_[0] },
75 length => sub { defined($_[0]) ? length($_[0]) : 0 },
76 list
=> sub { [$_[0]] },
77 lower
=> sub { lc $_[0] },
78 match
=> \
&vmethod_match
,
79 new
=> sub { defined $_[0] ? $_[0] : '' },
81 rand => sub { local $^W; rand shift },
82 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
83 repeat
=> \
&vmethod_repeat
,
84 replace
=> \
&vmethod_replace
,
85 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return $str =~ /$pat/ },
87 split => \
&vmethod_split
,
88 stderr
=> sub { print STDERR
$_[0]; '' },
89 substr => \
&vmethod_substr
,
90 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
91 ucfirst => sub { ucfirst $_[0] },
92 upper
=> sub { uc $_[0] },
96 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
97 eval => [\
&filter_eval
, 1],
98 evaltt
=> [\
&filter_eval
, 1],
99 file
=> [\
&filter_redirect
, 1],
100 redirect
=> [\
&filter_redirect
, 1],
104 as
=> \
&vmethod_as_list
,
105 defined => sub { return 1 if @_ == 1; defined $_[0]->[ defined($_[1]) ? $_[1] : 0 ] },
106 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
107 fmt
=> \
&vmethod_as_list
,
108 grep => sub { local $^W; my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
109 hash
=> sub { local $^W; my $list = shift; return {@$list} if ! @_; my $i = shift || 0; return {map {$i++ => $_} @$list} },
110 import
=> sub { my $ref = shift; push @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_; '' },
111 item
=> sub { $_[0]->[ $_[1] || 0 ] },
112 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
113 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
114 list
=> sub { $_[0] },
115 max
=> sub { local $^W; $#{ $_[0] } },
116 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
117 new
=> sub { local $^W; return [@_] },
119 nsort
=> \
&vmethod_nsort
,
120 pop => sub { pop @{ $_[0] } },
121 push => sub { my $ref = shift; push @$ref, @_; return '' },
122 random
=> sub { my $ref = shift; $ref->[ rand @$ref ] },
123 reverse => sub { [ reverse @{ $_[0] } ] },
124 shift => sub { shift @{ $_[0] } },
125 size
=> sub { local $^W; scalar @{ $_[0] } },
126 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
127 sort => \
&vmethod_sort
,
128 splice => \
&vmethod_splice
,
129 unique
=> sub { my %u; return [ grep { ! $u{$_}++ } @{ $_[0] } ] },
130 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
134 as
=> \
&vmethod_as_hash
,
135 defined => sub { return 1 if @_ == 1; defined $_[0]->{ defined($_[1]) ? $_[1] : '' } },
136 delete => sub { my $h = shift; my @v = delete @{ $h }{map {defined($_) ? $_ : ''} @_}; @_ == 1 ? $v[0] : \
@v },
137 each => sub { [%{ $_[0] }] },
138 exists => sub { exists $_[0]->{ defined($_[1]) ? $_[1] : '' } },
139 fmt
=> \
&vmethod_as_hash
,
140 hash
=> sub { $_[0] },
141 import
=> sub { my ($a, $b) = @_; @{$a}{keys %$b} = values %$b if ref($b) eq 'HASH'; '' },
142 item
=> sub { my ($h, $k) = @_; $k = '' if ! defined $k; $k =~ $QR_PRIVATE ? undef : $h->{$k} },
143 items
=> sub { [ %{ $_[0] } ] },
144 keys => sub { [keys %{ $_[0] }] },
145 list
=> \
&vmethod_list_hash
,
146 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
148 nsort
=> sub { my $ref = shift; [sort { $ref->{$a} <=> $ref->{$b}} keys %$ref] },
149 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } sort keys %{ $_[0] } ] },
150 size
=> sub { scalar keys %{ $_[0] } },
151 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
152 values => sub { [values %{ $_[0] }] },
160 foreach (values %$VOBJS) {
161 $_->{'Text'} = $_->{'as'};
162 $_->{'Hash'} = $_->{'hash'};
163 $_->{'List'} = $_->{'list'};
167 #name parse_sub play_sub block postdir continue move_to_front
168 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
169 BREAK
=> [sub {}, \
&play_control
],
170 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
171 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
172 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
173 CLEAR
=> [sub {}, \
&play_CLEAR
],
174 '#' => [sub {}, sub {}],
175 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
176 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
177 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
178 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
179 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
180 END => [undef, sub {}],
181 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
182 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
183 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
184 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
185 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
186 GET
=> [\
&parse_GET
, \
&play_GET
],
187 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
188 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
189 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
190 LAST
=> [sub {}, \
&play_control
],
191 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
192 META
=> [undef, sub {}],
193 METADEF
=> [undef, \
&play_METADEF
],
194 NEXT => [sub {}, \
&play_control
],
195 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
196 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
197 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
198 RETURN
=> [sub {}, \
&play_control
],
199 SET
=> [\
&parse_SET
, \
&play_SET
],
200 STOP
=> [sub {}, \
&play_control
],
201 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
202 TAGS
=> [undef, sub {}],
203 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
204 TRY
=> [sub {}, \
&play_TRY
, 1],
205 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
206 USE
=> [\
&parse_USE
, \
&play_USE
],
207 WHILE
=> [\
&parse_IF
, \
&play_WHILE
, 1, 1],
208 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
209 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
211 $QR_DIRECTIVE = qr{ ^ (\w+|\|) (?= $|[\s;\#]) }x;
213 ### setup the operator parsing
215 # type precedence symbols action (undef means play_operator will handle)
216 ['postfix', 99, ['++'], undef ],
217 ['postfix', 99, ['--'], undef ],
218 ['prefix', 98, ['++'], undef ],
219 ['prefix', 98, ['--'], undef ],
220 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
221 ['prefix', 93, ['!'], sub { ! $_[0] } ],
222 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
223 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
224 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
225 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
226 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
227 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
228 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
229 ['left', 85, ['~', '_'], sub { join "", @_ } ],
230 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
231 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
232 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
233 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
234 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
235 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
236 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
237 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
238 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
239 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
240 ['left', 70, ['&&'], undef ],
241 ['right', 65, ['||'], undef ],
242 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
243 ['ternary', 55, ['?', ':'], undef ],
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', 53, ['%='], sub { $_[0] % $_[1] } ],
249 ['assign', 53, ['**='], sub { $_[0]** $_[1] } ],
250 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
251 ['assign', 52, ['='], undef ],
252 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
253 ['left', 45, ['and', 'AND'], undef ],
254 ['right', 40, ['or', 'OR'], undef ],
255 ['', 0, ['hash'], sub { return {@_}; } ],
256 ['', 0, ['array'], sub { return [@_] } ],
258 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
259 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
260 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
261 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
262 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
263 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
264 sub _op_qr
{ # no mixed \w\W operators
266 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W{2,}$/} @_;
267 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
268 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
269 $chr = "[$chr]" if $chr;
270 $word = "\\b(?:$word)\\b" if $word;
271 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
273 sub _build_op_qr
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
274 sub _build_op_qr_prefix
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
275 sub _build_op_qr_assign
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
276 $QR_OP = _build_op_qr
();
277 $QR_OP_PREFIX = _build_op_qr_prefix
();
278 $QR_OP_ASSIGN = _build_op_qr_assign
();
280 $QR_COMMENTS = '(?-s: \# .* \s*)*';
281 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
282 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
283 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
284 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
285 $QR_PRIVATE = qr/^[_.]/;
288 $EXTRA_COMPILE_EXT = '.sto';
290 eval {require Scalar
::Util
};
293 ###----------------------------------------------------------------###
297 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
298 my $self = bless $args, $class;
300 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
301 if ($self->{'DEBUG'}) {
302 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
303 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
309 ###----------------------------------------------------------------###
314 local $self->{'_vars'} = shift || {};
315 my $out_ref = shift || $self->throw('undef', "Missing output ref");
316 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
317 my $i = length $$out_ref;
319 ### parse and execute
322 ### load the document
323 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
325 ### prevent recursion
326 $self->throw('file', "recursion into '$doc->{name}'")
327 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
328 local $self->{'_in'}->{$doc->{'name'}} = 1;
330 ### execute the document
331 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
332 $$out_ref = ${ $doc->{'_content'} };
334 local $self->{'_vars'}->{'component'} = $doc;
335 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
336 $self->execute_tree($doc->{'_tree'}, $out_ref);
337 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
341 ### trim whitespace from the beginning and the end of a block or template
342 if ($self->{'TRIM'}) {
343 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
344 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
347 ### handle exceptions
349 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
350 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
351 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
357 ###----------------------------------------------------------------###
359 sub load_parsed_tree
{
362 return if ! defined $file;
364 my $doc = {name
=> $file};
366 ### looks like a string reference
368 $doc->{'_content'} = $file;
369 $doc->{'name'} = 'input text';
370 $doc->{'is_str_ref'} = 1;
372 ### looks like a previously cached-in-memory document
373 } elsif ($self->{'_documents'}->{$file}
374 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
375 || ($self->{'_documents'}->{$file}->{'modtime'}
376 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
377 $doc = $self->{'_documents'}->{$file};
378 $doc->{'_cache_time'} = time;
381 ### looks like a block name of some sort
382 } elsif ($self->{'BLOCKS'}->{$file}) {
383 my $block = $self->{'BLOCKS'}->{$file};
385 ### allow for predefined blocks that are a code or a string
386 if (UNIVERSAL
::isa
($block, 'CODE')) {
389 if (! UNIVERSAL
::isa
($block, 'HASH')) {
390 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
392 $block = eval { $self->load_parsed_tree(\
$copy) }
393 || $self->throw('block', 'Parse error on predefined block');
395 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
399 ### go and look on the file system
401 $doc->{'_filename'} = eval { $self->include_filename($file) };
403 ### allow for blocks in other files
404 if ($self->{'EXPOSE_BLOCKS'}
405 && ! $self->{'_looking_in_block_file'}) {
406 local $self->{'_looking_in_block_file'} = 1;
408 while ($file =~ s
|/([^/.]+)$||) {
409 $block_name = length($block_name) ? "$1/$block_name" : $1;
410 my $ref = eval { $self->load_parsed_tree($file) } || next;
411 my $_tree = $ref->{'_tree'};
412 foreach my $node (@$_tree) {
414 next if $node->[0] eq 'METADEF';
415 last if $node->[0] ne 'BLOCK';
416 next if $block_name ne $node->[3];
417 $doc->{'_content'} = $ref->{'_content'};
418 $doc->{'_tree'} = $node->[4];
419 $doc->{'modtime'} = $ref->{'modtime'};
420 $file = $ref->{'name'};
424 die $err if ! $doc->{'_tree'};
425 } elsif ($self->{'DEFAULT'}) {
426 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
432 ### no tree yet - look for a file cache
433 if (! $doc->{'_tree'}) {
434 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
435 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
436 if ($self->{'COMPILE_DIR'}) {
437 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
439 $doc->{'_compile_filename'} = $doc->{'_filename'};
441 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
442 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
444 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
446 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
447 $doc->{'compile_was_used'} = 1;
449 my $str = $self->slurp($doc->{'_filename'});
450 $doc->{'_content'} = \
$str;
453 my $str = $self->slurp($doc->{'_filename'});
454 $doc->{'_content'} = \
$str;
460 ### haven't found a parsed tree yet - parse the content into a tree
461 if (! $doc->{'_tree'}) {
462 if ($self->{'CONSTANTS'}) {
463 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
464 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
467 local $self->{'_vars'}->{'component'} = $doc;
468 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
471 ### cache parsed_tree in memory unless asked not to do so
472 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
473 $self->{'_documents'}->{$file} ||= $doc;
474 $doc->{'_cache_time'} = time;
476 ### allow for config option to keep the cache size down
477 if ($self->{'CACHE_SIZE'}) {
478 my $all = $self->{'_documents'};
479 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
481 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
482 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
488 ### save a cache on the fileside as asked
489 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
490 my $dir = $doc->{'_compile_filename'};
494 File
::Path
::mkpath
($dir);
497 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
498 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
507 if (! $str_ref || ! defined $$str_ref) {
508 $self->throw('parse.no_string', "No string or undefined during parse");
511 my $STYLE = $self->{'TAG_STYLE'} || 'default';
512 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
513 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
514 my $len_s = length $START;
515 my $len_e = length $END;
517 my @tree; # the parsed tree
518 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
519 my @state; # maintain block levels
520 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
521 local $self->{'_in_perl'}; # no interpolation in perl
522 my @move_to_front; # items that need to be declared first (usually BLOCKS)
523 my @meta; # place to store any found meta information (to go into METADEF)
524 my $i = 0; # start index
525 my $j = 0; # end index
526 my $last = 0; # previous end index
527 my $post_chomp = 0; # previous post_chomp setting
528 my $continue; # multiple directives in the same tag
529 my $post_op; # found a post-operative DIRECTIVE
530 my $capture; # flag to start capture
535 ### continue looking for information in a semi-colon delimited tag
538 $node = [undef, $i, $j];
540 ### look through the string using index
542 $i = index($$str_ref, $START, $last);
543 last if $i == -1; # no start tag found - we are done
544 if ($last != $i) { # found a text portion - chomp it, interpolate it and store it
545 my $text = substr($$str_ref, $last, $i - $last);
548 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
549 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
550 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
553 push @$pointer, $text;
554 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
557 $j = index($$str_ref, $END, $i + $len_s);
559 if ($j == -1) { # missing closing tag
560 $last = length($$str_ref);
563 $tag = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
564 $node = [undef, $i + $len_s, $j];
566 ### take care of whitespace and comments flags
567 my $pre_chomp = $tag =~ s{ ^ ([+=~-]) }{}x ? $1 : $self->{'PRE_CHOMP'};
568 $post_chomp = $tag =~ s{ ([+=~-]) $ }{}x ? $1 : $self->{'POST_CHOMP'};
569 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
570 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
571 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
572 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
573 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
574 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
575 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
577 if ($tag =~ /^\#/) { # leading # means to comment the entire section
579 push @$pointer, $node;
582 $tag =~ s{ ^ \s+ $QR_COMMENTS }{}ox;
591 ### look for DIRECTIVES
592 if ($tag =~ $QR_DIRECTIVE # find a word
593 && $DIRECTIVES->{$1} ) { # is it a directive
594 $node->[0] = $func = $1;
595 $tag =~ s{ ^ (\w+ | \|) \s* $QR_COMMENTS }{}ox;
597 ### store out this current node level
598 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
599 my @post_op = @$post_op;
602 $node->[4] = [\
@post_op];
604 # do nothing - it will be handled further down
606 push @$pointer, $node;
609 ### anything that behaves as a block ending
610 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
612 $self->throw('parse', "Found an $func tag while not in a block", $node);
614 my $parent_node = pop @state;
616 if ($func ne 'END') {
617 pop @$pointer; # we will store the node in the parent instead
618 $parent_node->[5] = $node;
619 my $parent_type = $parent_node->[0];
620 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
621 $self->throw('parse', "Found unmatched nested block", $node, 0);
625 ### restore the pointer up one level (because we hit the end of a block)
626 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
629 if ($func eq 'END') {
630 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
631 push @move_to_front, $parent_node;
632 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
633 splice(@$pointer, -1, 1, ());
635 } elsif ($parent_node->[0] =~ /PERL$/) {
636 delete $self->{'_in_perl'};
639 ### continuation block - such as an elsif
641 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
643 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
647 $pointer = $node->[4] ||= [];
650 } elsif ($func eq 'TAGS') {
651 if ($tag =~ / ^ (\w+) /x && $TAGS->{$1}) {
652 $tag =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox;
653 ($START, $END) = @{ $TAGS->{$1} };
654 } elsif ($tag =~ s{ ^ (\S+) \s+ (\S+) \s* $QR_COMMENTS }{}ox) {
655 ($START, $END) = ($1, $2);
657 $len_s = length $START;
658 $len_e = length $END;
660 } elsif ($func eq 'META') {
661 my $args = $self->parse_args(\
$tag);
663 if (($hash = $self->play_expr($args->[-1]))
664 && UNIVERSAL
::isa
($hash, 'HASH')) {
665 unshift @meta, %$hash; # first defined win
668 ### all other "normal" tags
670 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
672 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
675 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
677 $pointer = $node->[4] ||= [];
681 ### allow for bare variable getting and setting
682 } elsif (defined(my $var = $self->parse_expr(\
$tag))) {
683 push @$pointer, $node;
684 if ($tag =~ s{ ^ ($QR_OP_ASSIGN) >? \s* $QR_COMMENTS }{}ox) {
686 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, \
$tag, $node, $1, $var) };
688 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
697 my $all = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
700 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
703 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
705 my $parent_node = $capture;
706 push @{ $parent_node->[4] }, $node;
710 ### we are flagged to start capturing the output of the next directive - set it up
712 $continue = $j - length $tag;
713 $node->[2] = $continue;
717 ### semi-colon = end of statement - we will need to continue parsing this tag
718 } elsif ($tag =~ s{ ^ ; \s* $QR_COMMENTS }{}ox) {
719 $continue = $j - length $tag;
720 $node->[2] = $continue;
723 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
724 } elsif ($tag =~ $QR_DIRECTIVE # find a word
725 && $DIRECTIVES->{$1} # is it a directive
726 && $DIRECTIVES->{$1}->[3]) { # it is a post operative directive
727 $continue = $j - length $tag;
728 $node->[2] = $continue;
731 ### unlink TT2 - look for another directive
732 } elsif (length $tag) {
733 #$self->throw('parse', "Found trailing info \"$tag\"", $node);
734 $continue = $j - length $tag;
735 $node->[2] = $continue;
744 if (@move_to_front) {
745 unshift @tree, @move_to_front;
748 unshift @tree, ['METADEF', 0, 0, {@meta}];
752 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
755 ### pull off the last text portion - if any
756 if ($last != length($$str_ref)) {
757 my $text = substr($$str_ref, $last, length($$str_ref) - $last);
760 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
761 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
762 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
765 push @$pointer, $text;
766 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
774 my ($self, $tree, $out_ref) = @_;
776 # node contains (0: DIRECTIVE,
779 # 3: parsed tag details,
780 # 4: sub tree for block types
781 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
782 # 6: flag to capture next directive
783 for my $node (@$tree) {
784 ### text nodes are just the bare text
786 warn "NODE: TEXT\n" if trace
;
787 $$out_ref .= $node if defined $node;
791 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
792 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
794 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
795 $$out_ref .= $val if defined $val;
799 ###----------------------------------------------------------------###
804 my $ARGS = shift || {};
806 ### allow for custom auto_quoting (such as hash constructors)
807 if ($ARGS->{'auto_quote'}) {
808 if ($$str_ref =~ $ARGS->{'auto_quote'}) {
810 substr($$str_ref, 0, length($str), '');
811 $$str_ref =~ s{ ^ \s* $QR_COMMENTS }{}ox;
813 ### allow for auto-quoted $foo or ${foo.bar} type constructs
814 } elsif ($$str_ref =~ s{ ^ \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }{}ox
815 || $$str_ref =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
817 return $self->parse_expr(\
$name);
821 my $copy = $$str_ref; # copy while parsing to allow for errors
823 ### test for leading prefix operators
825 while ($copy =~ s{ ^ ($QR_OP_PREFIX) \s* $QR_COMMENTS }{}ox) {
826 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
827 push @{ $has_prefix }, $1;
835 if ($copy =~ s{ ^ 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }{}ox) {
836 my $number = eval { hex $1 } || 0;
837 push @var, \
$number;
840 ### allow for numbers
841 } elsif ($copy =~ s{ ^ ( $QR_NUM ) \s* $QR_COMMENTS }{}ox) {
843 push @var, \
$number;
846 ### allow for quoted array constructor
847 } elsif ($copy =~ s{ ^ qw (\W) \s* }{}x) {
849 $quote =~ y
|([{<|)]}>|;
850 $copy =~ s{ ^ (.*) \Q$quote\E \s* $QR_COMMENTS }{}sx
851 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, length($$str_ref) - length($copy));
853 $str =~ s{ ^ \s+ | \s+ $ }{}x;
854 my $arrayref = ['array', split /\s+/, $str];
855 push @var, \
$arrayref;
857 ### looks like a normal variable start
858 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
860 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
862 ### allow for literal strings
863 } elsif ($copy =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }{}sox) {
864 if ($1 eq "'") { # no interpolation on single quoted strings
866 $str =~ s{ \\\' }{\'}xg;
874 $str =~ s/\\([\"\$])/$1/g;
875 my @pieces = $ARGS->{'auto_quote'}
876 ? split(m{ (\$\w+ | \$\{ [^\}]+ \
}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
877 : split(m{ (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $str);
879 foreach my $piece (@pieces) {
880 next if ! ($n++ % 2);
881 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
882 && $piece !~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
;
884 $piece = $self->parse_expr(\
$name);
886 @pieces = grep {defined && length} @pieces;
887 if (@pieces == 1 && ! ref $pieces[0]) {
888 push @var, \
$pieces[0];
890 } elsif (! @pieces) {
894 push @var, \
['~', @pieces];
897 if ($ARGS->{'auto_quote'}){
899 return ${ $var[0] } if $is_literal;
904 ### allow for leading $foo or ${foo.bar} type constructs
905 } elsif ($copy =~ s{ ^ \$ (\w+) \b \s* $QR_COMMENTS }{}ox
906 || $copy =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
908 push @var, $self->parse_expr(\
$name);
910 ### looks like an array constructor
911 } elsif ($copy =~ s{ ^ \[ \s* $QR_COMMENTS }{}ox) {
912 local $self->{'_operator_precedence'} = 0; # reset presedence
913 my $arrayref = ['array'];
914 while (defined(my $var = $self->parse_expr(\
$copy))) {
915 push @$arrayref, $var;
916 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
918 $copy =~ s{ ^ \] \s* $QR_COMMENTS }{}ox
919 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, length($$str_ref) - length($copy));
920 push @var, \
$arrayref;
922 ### looks like a hash constructor
923 } elsif ($copy =~ s{ ^ \{ \s* $QR_COMMENTS }{}ox) {
924 local $self->{'_operator_precedence'} = 0; # reset precedence
925 my $hashref = ['hash'];
926 while (defined(my $key = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))) {
927 $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox;
928 my $val = $self->parse_expr(\
$copy);
929 push @$hashref, $key, $val;
930 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
932 $copy =~ s{ ^ \} \s* $QR_COMMENTS }{}ox
933 || $self->throw('parse.missing.curly_bracket', "Missing close \} ($copy)", undef, length($$str_ref) - length($copy));
934 push @var, \
$hashref;
936 ### looks like a paren grouper
937 } elsif ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
938 local $self->{'_operator_precedence'} = 0; # reset precedence
939 my $var = $self->parse_expr(\
$copy, {allow_parened_ops
=> 1});
940 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
941 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
943 pop(@var); # pull off the trailing args of the paren group
945 ### nothing to find - return failure
950 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
952 ### looks for args for the initial
953 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
954 local $self->{'_operator_precedence'} = 0; # reset precedence
955 my $args = $self->parse_args(\
$copy);
956 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
957 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
963 ### allow for nested items
964 while ($copy =~ s{ ^ ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }{}ox) {
965 push(@var, $1) if ! $ARGS->{'no_dots'};
967 ### allow for interpolated variables in the middle - one.$foo.two or one.${foo.bar}.two
968 if ($copy =~ s{ ^ \$(\w+) \s* $QR_COMMENTS }{}ox
969 || $copy =~ s{ ^ \$\{ \s* ([^\}]+)\} \s* $QR_COMMENTS }{}ox) {
971 my $var = $self->parse_expr(\
$name);
975 } elsif ($copy =~ s{ ^ (-? \w+) \s* $QR_COMMENTS }{}ox) {
979 $self->throw('parse', "Not sure how to continue parsing on \"$copy\" ($$str_ref)");
982 ### looks for args for the nested item
983 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
984 local $self->{'_operator_precedence'} = 0; # reset precedence
985 my $args = $self->parse_args(\
$copy);
986 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
987 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
995 ### flatten literals and constants as much as possible
996 my $var = ($is_literal && $#var == 1) ? ${ $var[0] }
997 : $is_namespace ? $self->play_expr(\
@var, {is_namespace_during_compile
=> 1})
1000 ### allow for all "operators"
1001 if (! $self->{'_operator_precedence'}) {
1004 while ($copy =~ s{ ^ ($QR_OP) (\s* $QR_COMMENTS) }{}ox) { ## look for operators - then move along
1005 if (! $ARGS->{'allow_parened_ops'} && $OP_ASSIGN->{$1}) {
1006 $copy = $1 . $2 . $copy;
1010 local $self->{'_operator_precedence'} = 1;
1013 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1014 if ($OP_POSTFIX->{$op}) {
1015 $var = [\
[$op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1018 ### allow for prefix operator precedence
1019 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1021 if ($#$tree == 1) { # only one operator - keep simple things fast
1022 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1024 unshift @$tree, $var;
1025 $var = $self->apply_precedence($tree, $found);
1030 $var = [ \
[ $has_prefix->[-1], $var ], 0 ];
1031 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1034 ### add the operator to the tree
1035 my $var2 = $self->parse_expr(\
$copy);
1036 push (@{ $tree ||= [] }, $op, $var2);
1037 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1040 ### if we found operators - tree the nodes by operator precedence
1042 if (@$tree == 2) { # only one operator - keep simple things fast
1043 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1045 unshift @$tree, $var;
1046 $var = $self->apply_precedence($tree, $found);
1051 ### allow for prefix on non-chained variables
1053 $var = [ \
[ $_, $var ], 0 ] for reverse @$has_prefix;
1056 $$str_ref = $copy; # commit the changes
1060 ### this is used to put the parsed variables into the correct operations tree
1061 sub apply_precedence
{
1062 my ($self, $tree, $found) = @_;
1066 ### look at the operators we found in the order we found them
1067 for my $prec (sort keys %$found) {
1068 my $ops = $found->{$prec};
1069 local $found->{$prec};
1070 delete $found->{$prec};
1072 ### split the array on the current operators for this level
1075 for (my $i = 1; $i <= $#$tree; $i += 2) {
1076 next if ! $ops->{ $tree->[$i] };
1077 push @ops, $tree->[$i];
1078 push @exprs, [splice @$tree, 0, $i, ()];
1082 next if ! @exprs; # this iteration didn't have the current operator
1083 push @exprs, $tree if scalar @$tree; # add on any remaining items
1085 ### simplify sub expressions
1086 for my $node (@exprs) {
1088 $node = $node->[0]; # single item - its not a tree
1089 } elsif (@$node == 3) {
1090 $node = [ \
[ $node->[1], $node->[0], $node->[2] ], 0 ]; # single operator - put it straight on
1092 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1096 ### assemble this current level
1099 # 1) items at the same precedence level must all be either right or left or ternary associative
1100 # 2) ternary items cannot share precedence with anybody else.
1101 # 3) there really shouldn't be another operator at the same level as a postfix
1102 my $type = $OP->{$ops[0]}->[0];
1104 if ($type eq 'ternary') {
1105 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1107 ### return simple ternary
1109 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1110 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1111 return [ \
[ $op, @exprs ], 0 ];
1115 ### reorder complex ternary - rare case
1116 while ($#ops >= 1) {
1117 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1118 for (my $i = $#ops; $i >= 0; $i --) {
1119 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1120 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1121 my $node = [ \
[$op, @exprs[$i .. $i + 2] ], 0 ];
1122 splice @exprs, $i, 3, $node;
1125 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1127 } elsif ($type eq 'right' || $type eq 'assign') {
1128 my $val = $exprs[-1];
1129 $val = [ \
[ $ops[$_ - 1], $exprs[$_], $val ], 0 ] for reverse (0 .. $#exprs - 1);
1133 my $val = $exprs[0];
1134 $val = [ \
[ $ops[$_ - 1], $val, $exprs[$_] ], 0 ] for (1 .. $#exprs);
1140 $self->throw('parse', "Couldn't apply precedence");
1143 ### look for arguments - both positional and named
1146 my $str_ref = shift;
1147 my $ARGS = shift || {};
1148 my $copy = $$str_ref;
1152 while (length $$str_ref) {
1153 my $copy = $$str_ref;
1154 if (defined(my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
1155 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
1156 $self->throw('parse', 'Named arguments not allowed') if $ARGS->{'positional_only'};
1157 my $val = $self->parse_expr(\
$copy);
1158 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1159 push @named, $name, $val;
1161 } elsif (defined(my $arg = $self->parse_expr($str_ref))) {
1163 $$str_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1169 ### allow for named arguments to be added also
1170 push @args, [\
['hash', @named], 0] if scalar @named;
1175 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1176 sub interpolate_node
{
1177 my ($self, $tree, $offset) = @_;
1178 return if $self->{'_in_perl'};
1180 ### split on variables while keeping the variables
1181 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $tree->[-1];
1182 if ($#pieces <= 0) {
1183 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1189 foreach my $piece (@pieces) {
1190 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1191 if (! ($n++ % 2)) { # odds will always be text chunks
1192 next if ! length $piece;
1193 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1194 push @sub_tree, $piece;
1195 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1196 || $piece =~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
) {
1198 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1200 $self->throw('parse', "Parse error during interpolate node");
1204 ### replace the tree
1205 splice @$tree, -1, 1, @sub_tree;
1208 ###----------------------------------------------------------------###
1211 ### allow for the parse tree to store literals
1212 return $_[1] if ! ref $_[1];
1216 my $ARGS = shift || {};
1219 ### determine the top level of this particular variable access
1221 my $name = $var->[$i++];
1222 my $args = $var->[$i++];
1223 warn "play_expr: begin \"$name\"\n" if trace
;
1225 if (ref $name eq 'SCALAR') { # a scalar literal
1227 } elsif (ref $name eq 'REF') { # operator
1228 return $self->play_operator($$name) if ${ $name }->[0] eq '..';
1229 $ref = $self->play_operator($$name);
1230 } else { # a named variable access (ie via $name.foo)
1231 $name = $self->play_expr($name);
1232 if (defined $name) {
1233 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1234 $ref = $self->{'_vars'}->{$name};
1237 } elsif (defined $name) {
1238 if ($ARGS->{'is_namespace_during_compile'}) {
1239 $ref = $self->{'NAMESPACE'}->{$name};
1241 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1242 $ref = $self->{'_vars'}->{$name};
1243 $ref = $VOBJS->{$name} if ! defined $ref;
1249 while (defined $ref) {
1251 ### check at each point if the rurned thing was a code
1252 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1253 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1254 if (defined $results[0]) {
1255 $ref = ($#results > 0) ? \
@results : $results[0];
1256 } elsif (defined $results[1]) {
1257 die $results[1]; # TT behavior - why not just throw ?
1264 ### descend one chained level
1265 last if $i >= $#$var;
1266 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1267 $name = $var->[$i++];
1268 $args = $var->[$i++];
1269 warn "play_expr: nested \"$name\"\n" if trace
;
1271 ### allow for named portions of a variable name (foo.$name.bar)
1273 if (ref($name) eq 'ARRAY') {
1274 $name = $self->play_expr($name);
1275 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1280 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1283 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1288 ### allow for scalar and filter access (this happens for every non virtual method call)
1290 if ($SCALAR_OPS->{$name}) { # normal scalar op
1291 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1293 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1294 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1296 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1297 || $FILTER_OPS->{$name} # predefined filters in CET
1298 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1299 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1301 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1302 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1304 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1307 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1308 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1310 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1312 my $sub = $filter->[0];
1313 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1314 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1315 if (! $sub && $err) {
1316 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1318 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1319 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1320 if ref($sub) !~ /Template::Exception$/;
1324 $ref = $sub->($ref);
1327 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1330 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1331 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1332 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1335 if (scalar keys %seen_filters
1336 && $seen_filters{$var->[$i - 5] || ''}) {
1337 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1345 ### method calls on objects
1346 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1347 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1348 my @results = eval { $ref->$name(@args) };
1350 my $class = ref $ref;
1351 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1352 } elsif (defined $results[0]) {
1353 $ref = ($#results > 0) ? \
@results : $results[0];
1355 } elsif (defined $results[1]) {
1356 die $results[1]; # TT behavior - why not just throw ?
1361 # didn't find a method by that name - so fail down to hash and array access
1364 ### hash member access
1365 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1366 if ($was_dot_call && exists($ref->{$name}) ) {
1367 $ref = $ref->{$name};
1368 } elsif ($HASH_OPS->{$name}) {
1369 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1370 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1371 return $var; # abort - can't fold namespace variable
1377 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1378 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1379 $ref = $ref->[$name];
1380 } elsif ($LIST_OPS->{$name}) {
1381 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1390 ### allow for undefinedness
1391 if (! defined $ref) {
1392 if ($self->{'_debug_undef'}) {
1393 my $chunk = $var->[$i - 2];
1394 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1395 die "$chunk is undefined\n";
1397 $ref = $self->undefined_any($var);
1405 my ($self, $var, $val, $ARGS) = @_;
1409 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1410 $var = [$var, 0] if ! ref $var;
1412 ### determine the top level of this particular variable access
1413 my $ref = $var->[$i++];
1414 my $args = $var->[$i++];
1416 if (ref($ref) eq 'ARRAY') { # named access (ie via $name.foo)
1417 $ref = $self->play_expr($ref);
1418 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1420 return $self->{'_vars'}->{$ref} = $val;
1422 $ref = $self->{'_vars'}->{$ref} ||= {};
1427 } else { # all other types can't be set
1430 } elsif (defined $ref) {
1431 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1433 return $self->{'_vars'}->{$ref} = $val;
1435 $ref = $self->{'_vars'}->{$ref} ||= {};
1439 while (defined $ref) {
1441 ### check at each point if the returned thing was a code
1442 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1443 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1444 if (defined $results[0]) {
1445 $ref = ($#results > 0) ? \
@results : $results[0];
1446 } elsif (defined $results[1]) {
1447 die $results[1]; # TT behavior - why not just throw ?
1453 ### descend one chained level
1454 last if $i >= $#$var;
1455 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1456 my $name = $var->[$i++];
1457 my $args = $var->[$i++];
1459 ### allow for named portions of a variable name (foo.$name.bar)
1461 if (ref($name) eq 'ARRAY') {
1462 $name = $self->play_expr($name);
1463 if (! defined($name) || $name =~ /^[_.]/) {
1467 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1470 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1478 ### method calls on objects
1479 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1481 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1486 my @results = eval { $ref->$name(@args) };
1488 if (defined $results[0]) {
1489 $ref = ($#results > 0) ? \
@results : $results[0];
1490 } elsif (defined $results[1]) {
1491 die $results[1]; # TT behavior - why not just throw ?
1495 return if $lvalueish;
1498 my $class = ref $ref;
1499 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1500 # fall on down to "normal" accessors
1503 ### hash member access
1504 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1506 return $ref->{$name} = $val;
1508 $ref = $ref->{$name} ||= {};
1513 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1514 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1516 return $ref->[$name] = $val;
1518 $ref = $ref->[$name] ||= {};
1532 ###----------------------------------------------------------------###
1538 if ($OP_DISPATCH->{$tree->[0]}) {
1540 if ($OP_ASSIGN->{$tree->[0]}) {
1541 my $val = $OP_DISPATCH->{$tree->[0]}->( $self->play_expr($tree->[1]), $self->play_expr($tree->[2]) );
1542 $self->set_variable($tree->[1], $val);
1545 return $OP_DISPATCH->{$tree->[0]}->( map { $self->play_expr($tree->[$_]) } 1 .. $#$tree );
1549 my $op = $tree->[0];
1551 ### do custom and short-circuitable operators
1553 my $val = $self->play_expr($tree->[2]);
1554 $self->set_variable($tree->[1], $val);
1557 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1558 return $self->play_expr($tree->[1]) || $self->play_expr($tree->[2]) || '';
1560 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1561 my $var = $self->play_expr($tree->[1]) && $self->play_expr($tree->[2]);
1562 return $var ? $var : 0;
1564 } elsif ($op eq '?') {
1566 return $self->play_expr($tree->[1]) ? $self->play_expr($tree->[2]) : $self->play_expr($tree->[3]);
1568 } elsif ($op eq '++') {
1570 my $val = 0 + $self->play_expr($tree->[1]);
1571 $self->set_variable($tree->[1], $val + 1);
1572 return $tree->[2] ? $val : $val + 1; # ->[2] is set to 1 during parsing of postfix ops
1574 } elsif ($op eq '--') {
1576 my $val = 0 + $self->play_expr($tree->[1]);
1577 $self->set_variable($tree->[1], $val - 1);
1578 return $tree->[2] ? $val : $val - 1; # ->[2] is set to 1 during parsing of postfix ops
1581 $self->throw('operator', "Un-implemented operation $op");
1584 ###----------------------------------------------------------------###
1587 my ($self, $tag_ref, $node) = @_;
1589 my $block_name = '';
1590 if ($$tag_ref =~ s{ ^ (\w+ (?: :\w+)*) \s* (?! [\.\|]) }{}x
1591 || $$tag_ref =~ s{ ^ '(|.*?[^\\])' \s* (?! [\.\|]) }{}x
1592 || $$tag_ref =~ s{ ^ "(|.*?[^\\])" \s* (?! [\.\|]) }{}x
1595 ### allow for nested blocks to have nested names
1596 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1597 $block_name = join("/", @names, $block_name) if scalar @names;
1604 my ($self, $block_name, $node, $out_ref) = @_;
1606 ### store a named reference - but do nothing until something processes it
1607 $self->{'BLOCKS'}->{$block_name} = {
1608 _tree
=> $node->[4],
1609 name
=> $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1615 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1617 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1620 my ($self, $tag_ref) = @_;
1621 return if $$tag_ref =~ s{ ^ DEFAULT \s* }{}x;
1622 return $self->parse_expr($tag_ref);
1626 my ($self, $tag_ref) = @_;
1627 return $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
1631 my ($self, $undef, $node) = @_;
1632 $self->throw(lc($node->[0]), 'Control exception', $node);
1636 my ($self, $undef, $node, $out_ref) = @_;
1641 my ($self, $tag_ref) = @_;
1642 $$tag_ref =~ s{ ^ (on | off | format) \s* }{}xi || $self->throw('parse', "Unknown DEBUG option");
1644 if ($ret->[0] eq 'format') {
1645 $$tag_ref =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* }{}xs || $self->throw('parse', "Missing format string");
1652 my ($self, $ref) = @_;
1653 if ($ref->[0] eq 'on') {
1654 delete $self->{'_debug_off'};
1655 } elsif ($ref->[0] eq 'off') {
1656 $self->{'_debug_off'} = 1;
1657 } elsif ($ref->[0] eq 'format') {
1658 $self->{'_debug_format'} = $ref->[1];
1662 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1665 my ($self, $set) = @_;
1667 my ($op, $set, $default) = @$_;
1668 next if ! defined $set;
1669 my $val = $self->play_expr($set);
1671 $default = defined($default) ? $self->play_expr($default) : '';
1672 $self->set_variable($set, $default);
1679 my ($self, $tag_ref) = @_;
1680 my $ref = $self->parse_expr($tag_ref);
1685 my ($self, $ident, $node) = @_;
1686 require Data
::Dumper
;
1687 local $Data::Dumper
::Sortkeys
= 1;
1688 my $info = $self->node_info($node);
1692 $out = Data
::Dumper
::Dumper
($self->play_expr($ident));
1693 $var = $info->{'text'};
1694 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1695 $var =~ s/\s*[+\-~=]?$//;
1697 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1698 local @{ $self->{'_vars'} }{ @were_never_here };
1699 delete @{ $self->{'_vars'} }{ @were_never_here };
1700 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1701 $var = 'EntireStash';
1703 if ($ENV{'REQUEST_METHOD'}) {
1705 $out = "<pre>$out</pre>";
1706 $out =~ s/\$VAR1/$var/;
1707 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1709 $out =~ s/\$VAR1/$var/;
1716 my ($self, $tag_ref) = @_;
1718 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1722 my $filter = $self->parse_expr($tag_ref);
1723 $filter = '' if ! defined $filter;
1725 return [$name, $filter];
1729 my ($self, $ref, $node, $out_ref) = @_;
1730 my ($name, $filter) = @$ref;
1732 return '' if ! @$filter;
1734 $self->{'FILTERS'}->{$name} = $filter if length $name;
1736 my $sub_tree = $node->[4];
1740 eval { $self->execute_tree($sub_tree, \
$out) };
1741 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1743 my $var = [\
$out, 0, '|', @$filter]; # make a temporary var out of it
1746 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1750 my ($self, $tag_ref) = @_;
1751 my $items = $self->parse_expr($tag_ref);
1753 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1755 $items = $self->parse_expr($tag_ref);
1757 return [$var, $items];
1761 my ($self, $ref, $node, $out_ref) = @_;
1763 ### get the items - make sure it is an arrayref
1764 my ($var, $items) = @$ref;
1766 $items = $self->play_expr($items);
1767 return '' if ! defined $items;
1769 if (ref($items) !~ /Iterator$/) {
1770 $items = $PACKAGE_ITERATOR->new($items);
1773 my $sub_tree = $node->[4];
1775 local $self->{'_vars'}->{'loop'} = $items;
1777 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1779 my ($item, $error) = $items->get_first;
1782 $self->set_variable($var, $item);
1784 ### execute the sub tree
1785 eval { $self->execute_tree($sub_tree, $out_ref) };
1787 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1788 if ($err->type eq 'next') {
1789 ($item, $error) = $items->get_next;
1792 last if $err->type =~ /last|break/;
1797 ($item, $error) = $items->get_next;
1799 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1800 ### if the FOREACH tag doesn't set a var - then everything gets localized
1803 ### localize variable access for the foreach
1804 my $swap = $self->{'_vars'};
1805 local $self->{'_vars'} = my $copy = {%$swap};
1807 ### iterate use the iterator object
1808 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1809 my ($item, $error) = $items->get_first;
1812 if (ref($item) eq 'HASH') {
1813 @$copy{keys %$item} = values %$item;
1816 ### execute the sub tree
1817 eval { $self->execute_tree($sub_tree, $out_ref) };
1819 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1820 if ($err->type eq 'next') {
1821 ($item, $error) = $items->get_next;
1824 last if $err->type =~ /last|break/;
1829 ($item, $error) = $items->get_next;
1831 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1838 my ($self, $tag_ref) = @_;
1839 my $ref = $self->parse_expr($tag_ref);
1840 $self->throw('parse', "Missing variable name") if ! defined $ref;
1845 my ($self, $ident, $node) = @_;
1846 my $var = $self->play_expr($ident);
1847 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1851 my ($self, $tag_ref) = @_;
1852 return $self->parse_expr($tag_ref);
1856 my ($self, $var, $node, $out_ref) = @_;
1858 my $val = $self->play_expr($var);
1860 my $body_ref = $node->[4] ||= [];
1861 $self->execute_tree($body_ref, $out_ref);
1865 while ($node = $node->[5]) { # ELSE, ELSIF's
1866 if ($node->[0] eq 'ELSE') {
1867 my $body_ref = $node->[4] ||= [];
1868 $self->execute_tree($body_ref, $out_ref);
1871 my $var = $node->[3];
1872 my $val = $self->play_expr($var);
1874 my $body_ref = $node->[4] ||= [];
1875 $self->execute_tree($body_ref, $out_ref);
1882 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1885 my ($self, $tag_ref, $node, $out_ref) = @_;
1887 ### localize the swap
1888 my $swap = $self->{'_vars'};
1889 local $self->{'_vars'} = {%$swap};
1891 ### localize the blocks
1892 my $blocks = $self->{'BLOCKS'};
1893 local $self->{'BLOCKS'} = {%$blocks};
1895 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1900 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1903 my ($self, $var, $node, $out_ref) = @_;
1904 my ($names, $args) = @$var;
1906 foreach my $name (@$names) {
1907 my $filename = $self->play_expr($name);
1908 $$out_ref .= $self->_insert($filename);
1915 my ($self, $tag_ref, $node) = @_;
1916 my $copy = $$tag_ref;
1918 my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1919 $self->throw('parse', "Missing macro name") if ! defined $name;
1921 $name = [ $name, 0 ];
1925 if ($copy =~ s{ ^ \( \s* }{}x) {
1926 $args = $self->parse_args(\
$copy, {positional_only
=> 1});
1927 $copy =~ s
{ ^ \
) \s
* }{}x
|| $self->throw('parse.missing', "Missing close ')'");
1930 $node->[6] = 1; # set a flag to keep parsing
1932 return [$name, $args];
1936 my ($self, $ref, $node, $out_ref) = @_;
1937 my ($name, $args) = @$ref;
1939 ### get the sub tree
1940 my $sub_tree = $node->[4];
1941 if (! $sub_tree || ! $sub_tree->[0]) {
1942 $self->set_variable($name, undef);
1944 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1945 $sub_tree = $sub_tree->[0]->[4];
1948 my $self_copy = $self;
1949 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
1951 ### install a closure in the stash that will handle the macro
1952 $self->set_variable($name, sub {
1954 my $copy = $self_copy->{'_vars'};
1955 local $self_copy->{'_vars'}= {%$copy};
1958 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
1959 my @positional = @_;
1960 foreach my $var (@$args) {
1961 $self_copy->set_variable($var, shift(@positional));
1963 foreach my $name (sort keys %$named) {
1964 $self_copy->set_variable([$name, 0], $named->{$name});
1967 ### finally - run the sub tree
1969 $self_copy->execute_tree($sub_tree, \
$out);
1977 my ($self, $hash) = @_;
1979 if ($self->{'_top_level'}) {
1980 $ref = $self->{'_vars'}->{'template'} ||= {};
1982 $ref = $self->{'_vars'}->{'component'} ||= {};
1984 foreach my $key (keys %$hash) {
1985 next if $key eq 'name' || $key eq 'modtime';
1986 $ref->{$key} = $hash->{$key};
1991 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
1994 my ($self, $info, $node, $out_ref) = @_;
1995 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1997 ### fill in any variables
1998 my $perl = $node->[4] || return;
2000 $self->execute_tree($perl, \
$out);
2001 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2006 package CGI
::Ex
::Template
::Perl
;
2008 my $context = $self->context;
2009 my $stash = $context->stash;
2011 ### setup a fake handle
2013 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2014 my $old_fh = select PERLOUT
;
2019 ### put the handle back
2027 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2035 my ($self, $tag_ref) = @_;
2036 my $info = [[], []];
2037 while (defined(my $filename = $self->parse_expr($tag_ref, {
2038 auto_quote
=> qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2040 push @{$info->[0]}, $filename;
2041 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2044 ### allow for post process variables
2045 while (length $$tag_ref) {
2046 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2048 my $var = $self->parse_expr($tag_ref);
2049 last if ! defined $var;
2050 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2051 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2054 my $val = $self->parse_expr($tag_ref);
2055 push @{$info->[1]}, [$var, $val];
2056 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2063 my ($self, $info, $node, $out_ref) = @_;
2065 my ($files, $args) = @$info;
2069 my ($key, $val) = @$_;
2070 $val = $self->play_expr($val);
2071 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2072 foreach my $key (keys %$val) {
2073 $self->set_variable([$key,0], $val->{$key});
2077 $self->set_variable($key, $val);
2080 ### iterate on any passed block or filename
2081 foreach my $ref (@$files) {
2082 next if ! defined $ref;
2083 my $filename = $self->play_expr($ref);
2084 my $out = ''; # have temp item to allow clear to correctly clear
2086 ### normal blocks or filenames
2087 if (! ref $filename) {
2088 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2090 ### allow for $template which is used in some odd instances
2092 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2093 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2094 local $self->{'_process_dollar_template'} = 1;
2095 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2096 return if ! $doc->{'_tree'};
2098 ### execute and trim
2099 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2100 if ($self->{'TRIM'}) {
2101 $out =~ s{ \s+ $ }{}x;
2102 $out =~ s{ ^ \s+ }{}x;
2105 ### handle exceptions
2107 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2108 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2113 ### append any output
2116 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2124 my ($self, $info, $node, $out_ref) = @_;
2125 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2127 ### fill in any variables
2128 my $tree = $node->[4] || return;
2130 $self->execute_tree($tree, \
$perl);
2131 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2137 package CGI
::Ex
::Template
::Perl
;
2139 my $context = $self->context;
2140 my $stash = $context->stash;
2147 $$out_ref .= $output;
2150 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2158 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2160 my $copy = $$tag_ref;
2164 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2165 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2166 $node->[6] = 1; # set a flag to keep parsing
2167 my $val = $node->[4] ||= []; # setup storage
2168 return [[$initial_op, $initial_var, $val]];
2169 } else { # get a normal variable
2170 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2174 while (length $$tag_ref) {
2175 my $set = $self->parse_expr($tag_ref);
2176 last if ! defined $set;
2178 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2180 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2181 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2182 $node->[6] = 1; # set a flag to keep parsing
2183 my $val = $node->[4] ||= []; # setup storage
2184 push @SET, [$op, $set, $val];
2186 } else { # get a normal variable
2187 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2190 push @SET, ['=', $set, undef];
2197 my ($self, $set, $node) = @_;
2199 my ($op, $set, $val) = @$_;
2200 if (! defined $val) { # not defined
2202 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2203 my $sub_tree = $node->[4];
2204 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2206 $self->execute_tree($sub_tree, \
$val);
2207 } else { # normal var
2208 $val = $self->play_expr($val);
2211 if ($OP_DISPATCH->{$op}) {
2213 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2216 $self->set_variable($set, $val);
2221 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2224 my ($self, $var, $node, $out_ref) = @_;
2226 my $val = $self->play_expr($var);
2227 $val = '' if ! defined $val;
2228 ### $node->[4] is thrown away
2231 while ($node = $node->[5]) { # CASES
2232 my $var = $node->[3];
2233 if (! defined $var) {
2234 $default = $node->[4];
2238 my $val2 = $self->play_expr($var);
2239 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2240 for my $test (@$val2) { # find matching values
2241 next if ! defined $val && defined $test;
2242 next if defined $val && ! defined $test;
2243 if ($val ne $test) { # check string-wise first - then numerical
2244 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2245 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2246 next if $val != $test;
2249 my $body_ref = $node->[4] ||= [];
2250 $self->execute_tree($body_ref, $out_ref);
2256 $self->execute_tree($default, $out_ref);
2263 my ($self, $tag_ref, $node) = @_;
2264 my $name = $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2265 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2266 my $args = $self->parse_args($tag_ref);
2267 return [$name, $args];
2271 my ($self, $ref, $node) = @_;
2272 my ($name, $args) = @$ref;
2273 $name = $self->play_expr($name);
2274 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2275 $self->throw($name, \
@args, $node);
2279 my ($self, $foo, $node, $out_ref) = @_;
2282 my $body_ref = $node->[4];
2283 eval { $self->execute_tree($body_ref, \
$out) };
2286 if (! $node->[5]) { # no catch or final
2287 if (! $err) { # no final block and no error
2291 $self->throw('parse.missing', "Missing CATCH block", $node);
2294 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2295 if ($err->type =~ /stop|return/) {
2301 ### loop through the nested catch and final blocks
2304 my $type = $err ? $err->type : '';
2306 while ($node = $node->[5]) { # CATCH
2307 if ($node->[0] eq 'FINAL') {
2308 $final = $node->[4];
2312 my $name = $self->play_expr($node->[3]);
2313 $name = '' if ! defined $name || lc($name) eq 'default';
2314 if ($type =~ / ^ \Q$name\E \b /x
2315 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2316 $catch_body_ref = $node->[4] || [];
2317 $last_found = $name;
2321 ### play the best catch block
2323 if (! $catch_body_ref) {
2327 local $self->{'_vars'}->{'error'} = $err;
2328 local $self->{'_vars'}->{'e'} = $err;
2329 eval { $self->execute_tree($catch_body_ref, \
$out) };
2337 $self->execute_tree($final, \
$out) if $final;
2345 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2346 return [ \
[ '!', $ref ], 0 ];
2349 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2352 my ($self, $tag_ref) = @_;
2355 my $copy = $$tag_ref;
2356 if (defined(my $_var = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2357 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2363 my $module = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2364 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2365 $module =~ s/\./::/g;
2368 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2369 $args = $self->parse_args(\
$copy);
2372 $copy =~ s
{ ^ \
) \s
* $QR_COMMENTS }{}ox
|| $self->throw('parse.missing', "Missing close ')'");
2376 return [$var, $module, $args];
2380 my ($self, $ref, $node, $out_ref) = @_;
2381 my ($var, $module, $args) = @$ref;
2383 ### get the stash storage location - default to the module
2384 $var = $module if ! defined $var;
2385 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2386 pop @var; # remove the trailing '.'
2388 ### look for a plugin_base
2389 my $BASE = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2392 foreach my $base (ref($BASE) eq 'ARRAY' ? @$BASE : $BASE) {
2393 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2394 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2395 : "${base}::${module}";
2396 my $require = "$package.pm";
2397 $require =~ s
|::|/|g
;
2399 ### try and load the module - fall back to bare module if allowed
2400 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2401 my $shape = $package->load;
2402 my $context = $self->context;
2403 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2404 $obj = $shape->new($context, @args);
2405 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2406 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2407 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2408 foreach my $package (@packages) {
2409 my $require = "$package.pm";
2410 $require =~ s
|::|/|g
;
2411 eval {require $require} || next;
2412 my $shape = $package->load;
2413 my $context = $self->context;
2414 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2415 $obj = $shape->new($context, @args);
2417 } elsif ($self->{'LOAD_PERL'}) {
2418 my $require = "$module.pm";
2419 $require =~ s
|::|/|g
;
2420 if (eval {require $require}) {
2421 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2422 $obj = $module->new(@args);
2426 if (! defined $obj) {
2427 my $err = "$module: plugin not found";
2428 $self->throw('plugin', $err);
2432 $self->set_variable(\
@var, $obj);
2438 my ($self, $var, $node, $out_ref) = @_;
2439 return '' if ! defined $var;
2441 my $sub_tree = $node->[4];
2443 ### iterate use the iterator object
2444 my $count = $WHILE_MAX;
2445 while (--$count > 0) {
2447 $self->play_expr($var) || last;
2449 ### execute the sub tree
2450 eval { $self->execute_tree($sub_tree, $out_ref) };
2452 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2453 next if $err->type =~ /next/;
2454 last if $err->type =~ /last|break/;
2459 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2464 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2467 my ($self, $var, $node, $out_ref) = @_;
2468 my $sub_tree = $node->[4] || return;
2470 my ($names, $args) = @$var;
2473 $self->execute_tree($sub_tree, \
$out);
2475 foreach my $name (reverse @$names) {
2476 local $self->{'_vars'}->{'content'} = $out;
2478 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2485 ###----------------------------------------------------------------###
2489 $self->{'_vars'} = shift if $#_ == 0;
2490 return $self->{'_vars'} ||= {};
2493 sub include_filename
{
2494 my ($self, $file) = @_;
2495 if ($file =~ m
|^/|) {
2496 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2497 return $file if -e
$file;
2498 } elsif ($file =~ m{(^|/)\.\./}) {
2499 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2500 return $file if -e
$file;
2503 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2504 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2505 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2506 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2507 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2508 $paths; # return of the do
2510 foreach my $path (@$paths) {
2511 return "$path/$file" if -e
"$path/$file";
2514 $self->throw('file', "$file: not found");
2518 my ($self, $path) = @_;
2519 return $path if ref $path;
2520 my $delim = $self->{'DELIMITER'} || ':';
2521 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2522 return [split $delim, $path];
2526 my ($self, $file) = @_;
2527 return $self->slurp($self->include_filename($file));
2531 my ($self, $file) = @_;
2533 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2534 read FH
, my $txt, -s
$file;
2539 sub process_simple
{
2541 my $in = shift || die "Missing input";
2542 my $swap = shift || die "Missing variable hash";
2543 my $out = shift || die "Missing output string ref";
2546 delete $self->{'_debug_off'};
2547 delete $self->{'_debug_format'};
2548 local $self->{'_start_top_level'} = 1;
2549 $self->_process($in, $swap, $out);
2552 if ($err->type !~ /stop|return|next|last|break/) {
2553 $self->{'error'} = $err;
2561 my ($self, $in, $swap, $out, @ARGS) = @_;
2562 delete $self->{'error'};
2565 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2566 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2571 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2573 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2575 $content = \
$content;
2576 } else { # should be a file handle
2579 $content = \
$content;
2582 ### should be a filename
2587 ### prepare block localization
2588 my $blocks = $self->{'BLOCKS'} ||= {};
2595 ### localize the stash
2597 my $var1 = $self->{'_vars'} ||= {};
2598 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2599 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2600 my $copy = {%$var2, %$var1, %$swap};
2601 local $copy->{'template'};
2603 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2605 delete $self->{'_debug_off'};
2606 delete $self->{'_debug_format'};
2608 ### handle pre process items that go before every document
2609 if ($self->{'PRE_PROCESS'}) {
2610 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2612 $self->_process($name, $copy, \
$out);
2613 $output = $out . $output;
2617 ### handle the process config - which loads a template in place of the real one
2618 if (exists $self->{'PROCESS'}) {
2619 ### load the meta data for the top document
2620 my $doc = $self->load_parsed_tree($content) || {};
2621 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2622 ? $doc->{'_tree'}->[0]->[3] : {};
2624 $copy->{'template'} = $doc;
2625 @{ $doc }{keys %$meta} = values %$meta;
2627 ### process any other templates
2628 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2629 next if ! length $name;
2630 $self->_process($name, $copy, \
$output);
2633 ### handle "normal" content
2635 local $self->{'_start_top_level'} = 1;
2636 $self->_process($content, $copy, \
$output);
2640 ### handle post process items that go after every document
2641 if ($self->{'POST_PROCESS'}) {
2642 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2643 $self->_process($name, $copy, \
$output);
2649 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2650 if ($err->type !~ /stop|return|next|last|break/) {
2651 $self->{'error'} = $err;
2658 ### clear blocks as asked (AUTO_RESET) defaults to on
2659 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2661 ### send the content back out
2662 $out ||= $self->{'OUTPUT'};
2664 if (UNIVERSAL
::isa
($out, 'CODE')) {
2666 } elsif (UNIVERSAL
::can
($out, 'print')) {
2667 $out->print($output);
2668 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2670 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2671 push @$out, $output;
2672 } else { # should be a file handle
2675 } elsif ($out) { # should be a filename
2677 if ($out =~ m
|^/|) {
2678 if (! $self->{'ABSOLUTE'}) {
2679 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2683 } elsif ($out =~ m
|^\
.\
.?/|) {
2684 if (! $self->{'RELATIVE'}) {
2685 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2690 if (! $self->{'OUTPUT_PATH'}) {
2691 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2693 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2698 if (open FH
, ">$file") {
2699 if (my $bm = $args->{'binmode'}) {
2700 if (+$bm == 1) { binmode FH
}
2701 else { binmode FH
, $bm }
2706 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2713 return if $self->{'error'};
2717 sub error
{ shift-
>{'error'} }
2721 print STDERR
"DEBUG: ", @_;
2724 ###----------------------------------------------------------------###
2727 my ($self, $type, $info, $node) = @_;
2728 return $type if ref($type) =~ /Template::Exception$/;
2729 if (ref($info) eq 'ARRAY') {
2730 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2731 if (@$info >= 2 || scalar keys %$hash) {
2733 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2734 $hash->{'args'} = $info;
2736 } elsif (@$info == 1) {
2743 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2746 sub throw
{ die shift-
>exception(@_) }
2750 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2754 my ($self, $ident, $node) = @_;
2755 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2760 my ($self, $ident) = @_;
2761 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2767 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2772 my $args = shift || {};
2773 my $base = $args->{'base'} || '';
2775 return $self->{'_plugins'}->{$base} ||= do {
2779 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2781 foreach my $dir (@dirs) {
2783 File
::Find
::find
(sub {
2784 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2786 push @plugins, $mod;
2790 \
@plugins; # return of the do
2795 my ($self, $node) = @_;
2796 my $info = $self->node_info($node);
2797 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2798 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2803 my ($self, $node) = @_;
2804 my $doc = $self->{'_vars'}->{'component'};
2806 my $j = $node->[2] || return ''; # METADEF can be 0
2807 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2808 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2812 file
=> $doc->{'name'},
2813 line
=> $self->get_line_number_by_index($doc, $i),
2818 sub get_line_number_by_index
{
2819 my ($self, $doc, $index) = @_;
2820 ### get the line offsets for the doc
2821 my $lines = $doc->{'line_offsets'} ||= do {
2822 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2826 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2832 ### binary search them (this is fast even on big docs)
2833 return $#$lines + 1 if $index > $lines->[-1];
2834 my ($i, $j) = (0, $#$lines);
2836 return $i + 1 if abs($i - $j) <= 1;
2837 my $k = int(($i + $j) / 2);
2838 $j = $k if $lines->[$k] >= $index;
2839 $i = $k if $lines->[$k] <= $index;
2843 ###----------------------------------------------------------------###
2844 ### long virtual methods or filters
2845 ### many of these vmethods have used code from Template/Stash.pm to
2846 ### assure conformance with the TT spec.
2848 sub define_vmethod
{
2849 my ($self, $type, $name, $sub) = @_;
2850 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2851 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2852 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2853 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2855 die "Invalid type vmethod type $type";
2860 sub vmethod_as_scalar
{
2861 my $str = shift; $str = '' if ! defined $str;
2862 my $pat = shift; $pat = '%s' if ! defined $pat;
2864 return @_ ? sprintf($pat, $_[0], $str)
2865 : sprintf($pat, $str);
2868 sub vmethod_as_list
{
2869 my $ref = shift || return '';
2870 my $pat = shift; $pat = '%s' if ! defined $pat;
2871 my $sep = shift; $sep = ' ' if ! defined $sep;
2873 return @_ ? join($sep, map {sprintf $pat, $_[0], $_} @$ref)
2874 : join($sep, map {sprintf $pat, $_} @$ref);
2877 sub vmethod_as_hash
{
2878 my $ref = shift || return '';
2879 my $pat = shift; $pat = "%s\t%s" if ! defined $pat;
2880 my $sep = shift; $sep = "\n" if ! defined $sep;
2882 return ! @_ ? join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref)
2883 : @_ == 1 ? join($sep, map {sprintf $pat, $_[0], $_, $ref->{$_}} sort keys %$ref) # don't get to pick - it applies to the key
2884 : join($sep, map {sprintf $pat, $_[0], $_, $_[1], $ref->{$_}} sort keys %$ref);
2889 my $size = shift || 1;
2891 if ($size < 0) { # chunk from the opposite end
2892 $str = reverse $str;
2894 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2896 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2901 sub vmethod_indent
{
2902 my $str = shift; $str = '' if ! defined $str;
2903 my $pre = shift; $pre = 4 if ! defined $pre;
2904 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
2905 $str =~ s/^/$pre/mg;
2909 sub vmethod_format
{
2910 my $str = shift; $str = '' if ! defined $str;
2911 my $pat = shift; $pat = '%s' if ! defined $pat;
2913 return join "\n", map{ sprintf $pat, $_[0], $_ } split(/\n/, $str);
2915 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2919 sub vmethod_list_hash
{
2920 my ($hash, $what) = @_;
2921 $what = 'pairs' if ! $what || $what !~ /^(keys|values|each|pairs)$/;
2922 return $HASH_OPS->{$what}->($hash);
2927 my ($str, $pat, $global) = @_;
2928 return [] if ! defined $str || ! defined $pat;
2929 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2930 return @res ? \
@res : '';
2934 my ($list, $field) = @_;
2935 return defined($field)
2936 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2937 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2939 : [sort {$a <=> $b} @$list];
2942 sub vmethod_repeat
{
2943 my ($str, $n, $join) = @_;
2944 return '' if ! defined $str || ! length $str;
2945 $n = 1 if ! defined($n) || ! length $n;
2946 $join = '' if ! defined $join;
2947 return join $join, ($str) x
$n;
2950 ### This method is a combination of my submissions along
2951 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2952 sub vmethod_replace
{
2953 my ($text, $pattern, $replace, $global) = @_;
2954 $text = '' unless defined $text;
2955 $pattern = '' unless defined $pattern;
2956 $replace = '' unless defined $replace;
2957 $global = 1 unless defined $global;
2959 my ($chunk, $start, $end) = @_;
2960 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
2962 : ($2 > $#$start || $2 == 0) ? ''
2963 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2968 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2970 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2976 my ($list, $field) = @_;
2977 return defined($field)
2978 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2979 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2981 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2984 sub vmethod_splice
{
2985 my ($ref, $i, $len, @replace) = @_;
2986 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2988 return [splice @$ref, $i || 0, $len, @replace];
2989 } elsif (defined $i) {
2990 return [splice @$ref, $i];
2992 return [splice @$ref];
2997 my ($str, $pat, $lim) = @_;
2998 $str = '' if ! defined $str;
2999 if (defined $lim) { return defined $pat ? [split $pat, $str, $lim] : [split ' ', $str, $lim] }
3000 else { return defined $pat ? [split $pat, $str ] : [split ' ', $str ] }
3003 sub vmethod_substr
{
3004 my ($str, $i, $len, $replace) = @_;
3006 return substr($str, $i) if ! defined $len;
3007 return substr($str, $i, $len) if ! defined $replace;
3008 substr($str, $i, $len, $replace);
3014 utf8
::encode
($str) if defined &utf8
::encode
;
3015 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
3020 my $context = shift;
3023 return $context->process(\
$text);
3027 sub filter_redirect
{
3028 my ($context, $file, $options) = @_;
3029 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3030 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3031 if $file =~ m{(^|/)\.\./};
3037 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3040 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3041 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3042 if (+$bm == 1) { binmode FH
}
3043 else { binmode FH
, $bm}
3051 ###----------------------------------------------------------------###
3054 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3056 require Data
::Dumper
;
3057 return Data
::Dumper
::Dumper
($obj->parse_tree(\
$str));
3060 sub dump_parse_expr
{
3061 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3063 require Data
::Dumper
;
3064 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3067 ###----------------------------------------------------------------###
3069 package CGI
::Ex
::Template
::Exception
;
3072 '""' => \
&as_string
,
3073 bool
=> sub { defined shift },
3077 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3078 return bless [$type, $info, $node, $pos, $str_ref], $class;
3081 sub type
{ shift-
>[0] }
3083 sub info
{ shift-
>[1] }
3087 $self->[2] = shift if $#_ == 0;
3091 sub offset
{ shift-
>[3] || 0 }
3095 $self->[4] = shift if $#_ == 0;
3101 my $msg = $self->type .' error - '. $self->info;
3102 if (my $node = $self->node) {
3103 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3108 ###----------------------------------------------------------------###
3110 package CGI
::Ex
::Template
::Iterator
;
3113 my ($class, $items) = @_;
3114 $items = [] if ! defined $items;
3115 if (UNIVERSAL
::isa
($items, 'HASH')) {
3116 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3117 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3118 $items = $items->as_list;
3119 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3122 return bless [$items, 0], $class;
3127 return (undef, 3) if ! @{ $self->[0] };
3128 return ($self->[0]->[$self->[1] = 0], undef);
3133 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3134 return ($self->items->[$self->[1]], undef);
3137 sub items
{ shift-
>[0] }
3139 sub index { shift-
>[1] }
3141 sub max
{ $#{ shift-
>[0] } }
3143 sub size
{ shift-
>max + 1 }
3145 sub count
{ shift-
>index + 1 }
3147 sub number
{ shift-
>index + 1 }
3149 sub first
{ (shift-
>index == 0) || 0 }
3151 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3155 return undef if $self->index <= 0;
3156 return $self->items->[$self->index - 1];
3161 return undef if $self->index >= $self->max;
3162 return $self->items->[$self->index + 1];
3165 ###----------------------------------------------------------------###
3167 package CGI
::Ex
::Template
::_Context
;
3169 use vars
qw($AUTOLOAD);
3171 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3173 sub config
{ shift-
>_template }
3177 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3180 sub insert
{ shift-
>_template->_insert(@_) }
3182 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3187 my $vars = $self->_template->_vars;
3189 $self->_template->_process($ref, $vars, \
$out);
3196 my $args = shift || {};
3198 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3200 my $out = ''; # have temp item to allow clear to correctly clear
3201 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3203 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3210 my ($self, $name, $filter, $is_dynamic) = @_;
3211 $filter = [ $filter, 1 ] if $is_dynamic;
3212 $self->define_vmethod('filter', $name, $filter);
3216 my ($self, $name, $args, $alias) = @_;
3217 my $t = $self->_template;
3221 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3222 $t->throw('filter', $name) if ! $filter;
3223 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3225 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3226 $filter = $name->factory || $t->throw($name->error);
3228 $t->throw('undef', "$name: filter not found");
3231 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3232 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3233 } elsif ($args && @$args) {
3235 $filter = sub { $sub->(shift, @$args) };
3238 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3243 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3246 my ($self, $type, $info) = @_;
3248 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3250 } elsif (defined $info) {
3251 $self->_template->throw($type, $info);
3253 $self->_template->throw('undef', $type);
3257 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3261 ###----------------------------------------------------------------###
3263 package CGI
::Ex
::Template
::_Stash
;
3265 use vars
qw($AUTOLOAD);
3267 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3270 my ($self, $var) = @_;
3272 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3273 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3275 return $self->_template->play_expr($var, {no_dots
=> 1});
3279 my ($self, $var, $val) = @_;
3281 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3282 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3284 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3288 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3292 ###----------------------------------------------------------------###
3294 package CGI
::Ex
::Template
::EvalPerlHandle
;
3297 my ($class, $out_ref) = @_;
3298 return bless [$out_ref], $class;
3303 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3307 ###----------------------------------------------------------------###
3311 ### See the perldoc in CGI/Ex/Template.pod