]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/Template.pm
CGI::Ex 2.06
[chaz/p5-CGI-Ex] / lib / CGI / Ex / Template.pm
1 package CGI::Ex::Template;
2
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2006 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
8
9 use strict;
10 use constant trace => $ENV{'CET_TRACE'} || 0; # enable for low level tracing
11 use vars qw($VERSION
12 $TAGS
13 $SCALAR_OPS $HASH_OPS $LIST_OPS $FILTER_OPS $VOBJS
14 $DIRECTIVES $QR_DIRECTIVE
15
16 $OPERATORS
17 $OP_DISPATCH
18 $OP_ASSIGN
19 $OP
20 $OP_PREFIX
21 $OP_POSTFIX
22 $OP_TERNARY
23
24 $QR_OP
25 $QR_OP_PREFIX
26 $QR_OP_ASSIGN
27
28 $QR_COMMENTS
29 $QR_FILENAME
30 $QR_NUM
31 $QR_AQ_NOTDOT
32 $QR_AQ_SPACE
33 $QR_PRIVATE
34
35 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
36 $WHILE_MAX
37 $EXTRA_COMPILE_EXT
38 $DEBUG
39 );
40
41 BEGIN {
42 $VERSION = '2.06';
43
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';
49
50 $TAGS = {
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
59 };
60
61 $SCALAR_OPS = {
62 '0' => sub { shift },
63 as => \&vmethod_as_scalar,
64 chunk => \&vmethod_chunk,
65 collapse => sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
66 defined => sub { 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/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g; s/\"/&quot;/g; $_ },
73 lcfirst => sub { lcfirst $_[0] },
74 length => sub { defined($_[0]) ? length($_[0]) : 0 },
75 list => sub { [$_[0]] },
76 lower => sub { lc $_[0] },
77 match => \&vmethod_match,
78 new => sub { defined $_[0] ? $_[0] : '' },
79 null => sub { '' },
80 rand => sub { local $^W; rand shift },
81 remove => sub { vmethod_replace(shift, shift, '', 1) },
82 repeat => \&vmethod_repeat,
83 replace => \&vmethod_replace,
84 search => sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return scalar $str =~ /$pat/ },
85 size => sub { 1 },
86 split => \&vmethod_split,
87 stderr => sub { print STDERR $_[0]; '' },
88 substr => sub { my ($str, $i, $len) = @_; defined($len) ? substr($str, $i, $len) : substr($str, $i) },
89 trim => sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
90 ucfirst => sub { ucfirst $_[0] },
91 upper => sub { uc $_[0] },
92 uri => \&vmethod_uri,
93 };
94
95 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
96 eval => [\&filter_eval, 1],
97 evaltt => [\&filter_eval, 1],
98 file => [\&filter_redirect, 1],
99 redirect => [\&filter_redirect, 1],
100 };
101
102 $LIST_OPS = {
103 as => \&vmethod_as_list,
104 first => sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
105 fmt => \&vmethod_as_list,
106 grep => sub { my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
107 hash => sub { local $^W; my ($list, $i) = @_; defined($i) ? {map {$i++ => $_} @$list} : {@$list} },
108 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
109 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
110 list => sub { $_[0] },
111 max => sub { $#{ $_[0] } },
112 merge => sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
113 new => sub { local $^W; return [@_] },
114 nsort => \&vmethod_nsort,
115 pop => sub { pop @{ $_[0] } },
116 push => sub { my $ref = shift; push @$ref, @_; return '' },
117 random => sub { my $ref = shift; $ref->[ rand @$ref ] },
118 reverse => sub { [ reverse @{ $_[0] } ] },
119 shift => sub { shift @{ $_[0] } },
120 size => sub { scalar @{ $_[0] } },
121 slice => sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
122 sort => \&vmethod_sort,
123 splice => \&vmethod_splice,
124 unique => sub { my %u; return [ grep { ! $u{$_} ++ } @{ $_[0] } ] },
125 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
126 };
127
128 $HASH_OPS = {
129 as => \&vmethod_as_hash,
130 defined => sub { return '' if ! defined $_[1]; defined $_[0]->{ $_[1] } },
131 delete => sub { return '' if ! defined $_[1]; delete $_[0]->{ $_[1] } },
132 each => sub { [%{ $_[0] }] },
133 exists => sub { return '' if ! defined $_[1]; exists $_[0]->{ $_[1] } },
134 fmt => \&vmethod_as_hash,
135 hash => sub { $_[0] },
136 import => sub { my ($a, $b) = @_; return '' if ref($b) ne 'HASH'; @{$a}{keys %$b} = values %$b; '' },
137 item => sub { my ($h, $k) = @_; return '' if ! defined $k || $k =~ $QR_PRIVATE; $h->{$k} },
138 items => sub { [ %{ $_[0] } ] },
139 keys => sub { [keys %{ $_[0] }] },
140 list => sub { [$_[0]] },
141 new => sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
142 nsort => sub { my $ref = shift; [sort {$ref->{$a} <=> $ref->{$b} } keys %$ref] },
143 pairs => sub { [map { {key => $_, value => $_[0]->{$_}} } keys %{ $_[0] } ] },
144 size => sub { scalar keys %{ $_[0] } },
145 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
146 values => sub { [values %{ $_[0] }] },
147 };
148
149 $VOBJS = {
150 Text => $SCALAR_OPS,
151 List => $LIST_OPS,
152 Hash => $HASH_OPS,
153 };
154 foreach (values %$VOBJS) {
155 $_->{'Text'} = $_->{'as'};
156 $_->{'Hash'} = $_->{'hash'};
157 $_->{'List'} = $_->{'list'};
158 }
159
160 $DIRECTIVES = {
161 #name parse_sub play_sub block postdir continue move_to_front
162 BLOCK => [\&parse_BLOCK, \&play_BLOCK, 1, 0, 0, 1],
163 BREAK => [sub {}, \&play_control],
164 CALL => [\&parse_CALL, \&play_CALL],
165 CASE => [\&parse_CASE, undef, 0, 0, {SWITCH => 1, CASE => 1}],
166 CATCH => [\&parse_CATCH, undef, 0, 0, {TRY => 1, CATCH => 1}],
167 CLEAR => [sub {}, \&play_CLEAR],
168 '#' => [sub {}, sub {}],
169 DEBUG => [\&parse_DEBUG, \&play_DEBUG],
170 DEFAULT => [\&parse_DEFAULT, \&play_DEFAULT],
171 DUMP => [\&parse_DUMP, \&play_DUMP],
172 ELSE => [sub {}, undef, 0, 0, {IF => 1, ELSIF => 1, UNLESS => 1}],
173 ELSIF => [\&parse_IF, undef, 0, 0, {IF => 1, ELSIF => 1, UNLESS => 1}],
174 END => [undef, sub {}],
175 FILTER => [\&parse_FILTER, \&play_FILTER, 1, 1],
176 '|' => [\&parse_FILTER, \&play_FILTER, 1, 1],
177 FINAL => [sub {}, undef, 0, 0, {TRY => 1, CATCH => 1}],
178 FOR => [\&parse_FOREACH, \&play_FOREACH, 1, 1],
179 FOREACH => [\&parse_FOREACH, \&play_FOREACH, 1, 1],
180 GET => [\&parse_GET, \&play_GET],
181 IF => [\&parse_IF, \&play_IF, 1, 1],
182 INCLUDE => [\&parse_INCLUDE, \&play_INCLUDE],
183 INSERT => [\&parse_INSERT, \&play_INSERT],
184 LAST => [sub {}, \&play_control],
185 MACRO => [\&parse_MACRO, \&play_MACRO],
186 META => [undef, sub {}],
187 METADEF => [undef, \&play_METADEF],
188 NEXT => [sub {}, \&play_control],
189 PERL => [\&parse_PERL, \&play_PERL, 1],
190 PROCESS => [\&parse_PROCESS, \&play_PROCESS],
191 RAWPERL => [\&parse_PERL, \&play_RAWPERL, 1],
192 RETURN => [sub {}, \&play_control],
193 SET => [\&parse_SET, \&play_SET],
194 STOP => [sub {}, \&play_control],
195 SWITCH => [\&parse_SWITCH, \&play_SWITCH, 1],
196 TAGS => [undef, sub {}],
197 THROW => [\&parse_THROW, \&play_THROW],
198 TRY => [sub {}, \&play_TRY, 1],
199 UNLESS => [\&parse_UNLESS, \&play_UNLESS, 1, 1],
200 USE => [\&parse_USE, \&play_USE],
201 WHILE => [\&parse_IF, \&play_WHILE, 1, 1],
202 WRAPPER => [\&parse_WRAPPER, \&play_WRAPPER, 1, 1],
203 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
204 };
205 $QR_DIRECTIVE = qr{ ^ (\w+|\|) (?= $|[\s;\#]) }x;
206
207 ### setup the operator parsing
208 $OPERATORS = [
209 # type precedence symbols action (undef means play_operator will handle)
210 ['postfix', 99, ['++'], undef ],
211 ['postfix', 99, ['--'], undef ],
212 ['prefix', 98, ['++'], undef ],
213 ['prefix', 98, ['--'], undef ],
214 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
215 ['prefix', 93, ['!'], sub { ! $_[0] } ],
216 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
217 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
218 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
219 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
220 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
221 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
222 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
223 ['left', 85, ['~', '_'], sub { join "", @_ } ],
224 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
225 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
226 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
227 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
228 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
229 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
230 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
231 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
232 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
233 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
234 ['left', 70, ['&&'], undef ],
235 ['right', 65, ['||'], undef ],
236 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
237 ['ternary', 55, ['?', ':'], undef ],
238 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
239 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
240 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
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', 52, ['='], undef ],
246 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
247 ['left', 45, ['and', 'AND'], undef ],
248 ['right', 40, ['or', 'OR'], undef ],
249 ['', 0, ['hash'], sub { return {@_}; } ],
250 ['', 0, ['array'], sub { return [@_] } ],
251 ];
252 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
253 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
254 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
255 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
256 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
257 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
258 sub _op_qr { # no mixed \w\W operators
259 my %used;
260 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W{2,}$/} @_;
261 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
262 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
263 $chr = "[$chr]" if $chr;
264 $word = "\\b(?:$word)\\b" if $word;
265 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
266 }
267 sub _build_op_qr { _op_qr(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
268 sub _build_op_qr_prefix { _op_qr(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
269 sub _build_op_qr_assign { _op_qr(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
270 $QR_OP = _build_op_qr();
271 $QR_OP_PREFIX = _build_op_qr_prefix();
272 $QR_OP_ASSIGN = _build_op_qr_assign();
273
274 $QR_COMMENTS = '(?-s: \# .* \s*)*';
275 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
276 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
277 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
278 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
279 $QR_PRIVATE = qr/^_/;
280
281 $WHILE_MAX = 1000;
282 $EXTRA_COMPILE_EXT = '.sto';
283
284 eval {require Scalar::Util};
285 };
286
287 ###----------------------------------------------------------------###
288
289 sub new {
290 my $class = shift;
291 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
292 my $self = bless $args, $class;
293
294 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
295 if ($self->{'DEBUG'}) {
296 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
297 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
298 }
299
300 return $self;
301 }
302
303 ###----------------------------------------------------------------###
304
305 sub _process {
306 my $self = shift;
307 my $file = shift;
308 local $self->{'_vars'} = shift || {};
309 my $out_ref = shift || $self->throw('undef', "Missing output ref");
310 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
311 my $i = length $$out_ref;
312
313 ### parse and execute
314 my $doc;
315 eval {
316 ### load the document
317 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
318
319 ### prevent recursion
320 $self->throw('file', "recursion into '$doc->{name}'")
321 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
322 local $self->{'_in'}->{$doc->{'name'}} = 1;
323
324 ### execute the document
325 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
326 $$out_ref = ${ $doc->{'_content'} };
327 } else {
328 local $self->{'_vars'}->{'component'} = $doc;
329 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
330 $self->execute_tree($doc->{'_tree'}, $out_ref);
331 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
332 }
333 };
334
335 ### trim whitespace from the beginning and the end of a block or template
336 if ($self->{'TRIM'}) {
337 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
338 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
339 }
340
341 ### handle exceptions
342 if (my $err = $@) {
343 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
344 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
345 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
346 }
347
348 return 1;
349 }
350
351 ###----------------------------------------------------------------###
352
353 sub load_parsed_tree {
354 my $self = shift;
355 my $file = shift;
356 return if ! defined $file;
357
358 my $doc = {name => $file};
359
360 ### looks like a string reference
361 if (ref $file) {
362 $doc->{'_content'} = $file;
363 $doc->{'name'} = 'input text';
364 $doc->{'is_str_ref'} = 1;
365
366 ### looks like a previously cached-in-memory document
367 } elsif ($self->{'_documents'}->{$file}
368 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
369 || ($self->{'_documents'}->{$file}->{'modtime'}
370 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
371 $doc = $self->{'_documents'}->{$file};
372 $doc->{'_cache_time'} = time;
373 return $doc;
374
375 ### looks like a block name of some sort
376 } elsif ($self->{'BLOCKS'}->{$file}) {
377 my $block = $self->{'BLOCKS'}->{$file};
378
379 ### allow for predefined blocks that are a code or a string
380 if (UNIVERSAL::isa($block, 'CODE')) {
381 $block = $block->();
382 }
383 if (! UNIVERSAL::isa($block, 'HASH')) {
384 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
385 my $copy = $block;
386 $block = eval { $self->load_parsed_tree(\$copy) }
387 || $self->throw('block', 'Parse error on predefined block');
388 }
389 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
390 return $doc;
391
392
393 ### go and look on the file system
394 } else {
395 $doc->{'_filename'} = eval { $self->include_filename($file) };
396 if (my $err = $@) {
397 ### allow for blocks in other files
398 if ($self->{'EXPOSE_BLOCKS'}
399 && ! $self->{'_looking_in_block_file'}) {
400 local $self->{'_looking_in_block_file'} = 1;
401 my $block_name = '';
402 while ($file =~ s|/([^/.]+)$||) {
403 $block_name = length($block_name) ? "$1/$block_name" : $1;
404 my $ref = eval { $self->load_parsed_tree($file) } || next;
405 my $_tree = $ref->{'_tree'};
406 foreach my $node (@$_tree) {
407 next if ! ref $node;
408 next if $node->[0] eq 'METADEF';
409 last if $node->[0] ne 'BLOCK';
410 next if $block_name ne $node->[3];
411 $doc->{'_content'} = $ref->{'_content'};
412 $doc->{'_tree'} = $node->[4];
413 $doc->{'modtime'} = $ref->{'modtime'};
414 $file = $ref->{'name'};
415 last;
416 }
417 }
418 die $err if ! $doc->{'_tree'};
419 } elsif ($self->{'DEFAULT'}) {
420 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
421 } else {
422 die $err;
423 }
424 }
425
426 ### no tree yet - look for a file cache
427 if (! $doc->{'_tree'}) {
428 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
429 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
430 if ($self->{'COMPILE_DIR'}) {
431 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
432 } else {
433 $doc->{'_compile_filename'} = $doc->{'_filename'};
434 }
435 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
436 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
437
438 if (-e $doc->{'_compile_filename'} && (stat _)[9] == $doc->{'modtime'}) {
439 require Storable;
440 $doc->{'_tree'} = Storable::retrieve($doc->{'_compile_filename'});
441 $doc->{'compile_was_used'} = 1;
442 } else {
443 my $str = $self->slurp($doc->{'_filename'});
444 $doc->{'_content'} = \$str;
445 }
446 } else {
447 my $str = $self->slurp($doc->{'_filename'});
448 $doc->{'_content'} = \$str;
449 }
450 }
451
452 }
453
454 ### haven't found a parsed tree yet - parse the content into a tree
455 if (! $doc->{'_tree'}) {
456 if ($self->{'CONSTANTS'}) {
457 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
458 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
459 }
460
461 local $self->{'_vars'}->{'component'} = $doc;
462 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
463 }
464
465 ### cache parsed_tree in memory unless asked not to do so
466 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
467 $self->{'_documents'}->{$file} ||= $doc;
468 $doc->{'_cache_time'} = time;
469
470 ### allow for config option to keep the cache size down
471 if ($self->{'CACHE_SIZE'}) {
472 my $all = $self->{'_documents'};
473 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
474 my $n = 0;
475 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
476 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
477 }
478 }
479 }
480 }
481
482 ### save a cache on the fileside as asked
483 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
484 my $dir = $doc->{'_compile_filename'};
485 $dir =~ s|/[^/]+$||;
486 if (! -d $dir) {
487 require File::Path;
488 File::Path::mkpath($dir);
489 }
490 require Storable;
491 Storable::store($doc->{'_tree'}, $doc->{'_compile_filename'});
492 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
493 }
494
495 return $doc;
496 }
497
498 sub parse_tree {
499 my $self = shift;
500 my $str_ref = shift;
501 if (! $str_ref || ! defined $$str_ref) {
502 $self->throw('parse.no_string', "No string or undefined during parse");
503 }
504
505 my $STYLE = $self->{'TAG_STYLE'} || 'default';
506 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
507 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
508 my $len_s = length $START;
509 my $len_e = length $END;
510
511 my @tree; # the parsed tree
512 my $pointer = \@tree; # pointer to current tree to handle nested blocks
513 my @state; # maintain block levels
514 local $self->{'_state'} = \@state; # allow for items to introspect (usually BLOCKS)
515 local $self->{'_in_perl'}; # no interpolation in perl
516 my @move_to_front; # items that need to be declared first (usually BLOCKS)
517 my @meta; # place to store any found meta information (to go into METADEF)
518 my $i = 0; # start index
519 my $j = 0; # end index
520 my $last = 0; # previous end index
521 my $post_chomp = 0; # previous post_chomp setting
522 my $continue; # multiple directives in the same tag
523 my $post_op; # found a post-operative DIRECTIVE
524 my $capture; # flag to start capture
525 my $func;
526 my $node;
527 my $tag;
528 while (1) {
529 ### continue looking for information in a semi-colon delimited tag
530 if ($continue) {
531 $i = $continue;
532 $node = [undef, $i, $j];
533
534 ### look through the string using index
535 } else {
536 $i = index($$str_ref, $START, $last);
537 last if $i == -1; # no start tag found - we are done
538 if ($last != $i) { # found a text portion - chomp it, interpolate it and store it
539 my $text = substr($$str_ref, $last, $i - $last);
540 my $_last = $last;
541 if ($post_chomp) {
542 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
543 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
544 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
545 }
546 if (length $text) {
547 push @$pointer, $text;
548 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
549 }
550 }
551 $j = index($$str_ref, $END, $i + $len_s);
552 $last = $j + $len_e;
553 if ($j == -1) { # missing closing tag
554 $last = length($$str_ref);
555 last;
556 }
557 $tag = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
558 $node = [undef, $i + $len_s, $j];
559
560 ### take care of whitespace and comments flags
561 my $pre_chomp = $tag =~ s{ ^ ([+=~-]) }{}x ? $1 : $self->{'PRE_CHOMP'};
562 $post_chomp = $tag =~ s{ ([+=~-]) $ }{}x ? $1 : $self->{'POST_CHOMP'};
563 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
564 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
565 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
566 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
567 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
568 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
569 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
570 }
571 if ($tag =~ /^\#/) { # leading # means to comment the entire section
572 $node->[0] = '#';
573 push @$pointer, $node;
574 next;
575 }
576 $tag =~ s{ ^ \s+ $QR_COMMENTS }{}ox;
577 }
578
579 if (! length $tag) {
580 undef $continue;
581 undef $post_op;
582 next;
583 }
584
585 ### look for DIRECTIVES
586 if ($tag =~ $QR_DIRECTIVE # find a word
587 && $DIRECTIVES->{$1} ) { # is it a directive
588 $node->[0] = $func = $1;
589 $tag =~ s{ ^ (\w+ | \|) \s* $QR_COMMENTS }{}ox;
590
591 ### store out this current node level
592 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
593 my @post_op = @$post_op;
594 @$post_op = @$node;
595 $node = $post_op;
596 $node->[4] = [\@post_op];
597 } elsif ($capture) {
598 # do nothing - it will be handled further down
599 } else{
600 push @$pointer, $node;
601 }
602
603 ### anything that behaves as a block ending
604 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
605 if (! @state) {
606 $self->throw('parse', "Found an $func tag while not in a block", $node);
607 }
608 my $parent_node = pop @state;
609
610 if ($func ne 'END') {
611 pop @$pointer; # we will store the node in the parent instead
612 $parent_node->[5] = $node;
613 my $parent_type = $parent_node->[0];
614 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
615 $self->throw('parse', "Found unmatched nested block", $node, 0);
616 }
617 }
618
619 ### restore the pointer up one level (because we hit the end of a block)
620 $pointer = (! @state) ? \@tree : $state[-1]->[4];
621
622 ### normal end block
623 if ($func eq 'END') {
624 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
625 push @move_to_front, $parent_node;
626 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
627 splice(@$pointer, -1, 1, ());
628 }
629 } elsif ($parent_node->[0] =~ /PERL$/) {
630 delete $self->{'_in_perl'};
631 }
632
633 ### continuation block - such as an elsif
634 } else {
635 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \$tag, $node) };
636 if (my $err = $@) {
637 $err->node($node) if UNIVERSAL::can($err, 'node') && ! $err->node;
638 die $err;
639 }
640 push @state, $node;
641 $pointer = $node->[4] ||= [];
642 }
643
644 } elsif ($func eq 'TAGS') {
645 if ($tag =~ / ^ (\w+) /x && $TAGS->{$1}) {
646 $tag =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox;
647 ($START, $END) = @{ $TAGS->{$1} };
648 } elsif ($tag =~ s{ ^ (\S+) \s+ (\S+) \s* $QR_COMMENTS }{}ox) {
649 ($START, $END) = ($1, $2);
650 }
651 $len_s = length $START;
652 $len_e = length $END;
653
654 } elsif ($func eq 'META') {
655 my $args = $self->parse_args(\$tag);
656 my $hash;
657 if (($hash = $self->play_expr($args->[-1]))
658 && UNIVERSAL::isa($hash, 'HASH')) {
659 unshift @meta, %$hash; # first defined win
660 }
661
662 ### all other "normal" tags
663 } else {
664 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \$tag, $node) };
665 if (my $err = $@) {
666 $err->node($node) if UNIVERSAL::can($err, 'node') && ! $err->node;
667 die $err;
668 }
669 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
670 push @state, $node;
671 $pointer = $node->[4] ||= [];
672 }
673 }
674
675 ### allow for bare variable getting and setting
676 } elsif (defined(my $var = $self->parse_expr(\$tag))) {
677 push @$pointer, $node;
678 if ($tag =~ s{ ^ ($QR_OP_ASSIGN) >? \s* $QR_COMMENTS }{}ox) {
679 $node->[0] = 'SET';
680 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, \$tag, $node, $1, $var) };
681 if (my $err = $@) {
682 $err->node($node) if UNIVERSAL::can($err, 'node') && ! $err->node;
683 die $err;
684 }
685 } else {
686 $node->[0] = 'GET';
687 $node->[3] = $var;
688 }
689
690 } else { # error
691 my $all = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
692 $all =~ s/^\s+//;
693 $all =~ s/\s+$//;
694 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
695 }
696
697 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
698 if ($capture) {
699 my $parent_node = $capture;
700 push @{ $parent_node->[4] }, $node;
701 undef $capture;
702 }
703
704 ### we are flagged to start capturing the output of the next directive - set it up
705 if ($node->[6]) {
706 $continue = $j - length $tag;
707 $node->[2] = $continue;
708 $post_op = undef;
709 $capture = $node;
710
711 ### semi-colon = end of statement - we will need to continue parsing this tag
712 } elsif ($tag =~ s{ ^ ; \s* $QR_COMMENTS }{}ox) {
713 $continue = $j - length $tag;
714 $node->[2] = $continue;
715 $post_op = undef;
716
717 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
718 } elsif ($tag =~ $QR_DIRECTIVE # find a word
719 && $DIRECTIVES->{$1} # is it a directive
720 && $DIRECTIVES->{$1}->[3]) { # it is a post operative directive
721 $continue = $j - length $tag;
722 $node->[2] = $continue;
723 $post_op = $node;
724
725 ### unlink TT2 - look for another directive
726 } elsif (length $tag) {
727 #$self->throw('parse', "Found trailing info \"$tag\"", $node);
728 $continue = $j - length $tag;
729 $node->[2] = $continue;
730 $post_op = undef;
731
732 } else {
733 $continue = undef;
734 $post_op = undef;
735 }
736 }
737
738 if (@move_to_front) {
739 unshift @tree, @move_to_front;
740 }
741 if (@meta) {
742 unshift @tree, ['METADEF', 0, 0, {@meta}];
743 }
744
745 if ($#state > -1) {
746 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
747 }
748
749 ### pull off the last text portion - if any
750 if ($last != length($$str_ref)) {
751 my $text = substr($$str_ref, $last, length($$str_ref) - $last);
752 my $_last = $last;
753 if ($post_chomp) {
754 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
755 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
756 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
757 }
758 if (length $text) {
759 push @$pointer, $text;
760 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
761 }
762 }
763
764 return \@tree;
765 }
766
767 sub execute_tree {
768 my ($self, $tree, $out_ref) = @_;
769
770 # node contains (0: DIRECTIVE,
771 # 1: start_index,
772 # 2: end_index,
773 # 3: parsed tag details,
774 # 4: sub tree for block types
775 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
776 # 6: flag to capture next directive
777 for my $node (@$tree) {
778 ### text nodes are just the bare text
779 if (! ref $node) {
780 warn "NODE: TEXT\n" if trace;
781 $$out_ref .= $node if defined $node;
782 next;
783 }
784
785 warn "NODE: $node->[0] (char $node->[1])\n" if trace;
786 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
787
788 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
789 $$out_ref .= $val if defined $val;
790 }
791 }
792
793 ###----------------------------------------------------------------###
794
795 sub parse_expr {
796 my $self = shift;
797 my $str_ref = shift;
798 my $ARGS = shift || {};
799
800 ### allow for custom auto_quoting (such as hash constructors)
801 if ($ARGS->{'auto_quote'}) {
802 if ($$str_ref =~ $ARGS->{'auto_quote'}) {
803 my $str = $1;
804 substr($$str_ref, 0, length($str), '');
805 $$str_ref =~ s{ ^ \s* $QR_COMMENTS }{}ox;
806 return $str;
807 ### allow for auto-quoted $foo or ${foo.bar} type constructs
808 } elsif ($$str_ref =~ s{ ^ \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }{}ox
809 || $$str_ref =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
810 my $name = $1;
811 return $self->parse_expr(\$name);
812 }
813 }
814
815 my $copy = $$str_ref; # copy while parsing to allow for errors
816
817 ### test for leading prefix operators
818 my $has_prefix;
819 while ($copy =~ s{ ^ ($QR_OP_PREFIX) \s* $QR_COMMENTS }{}ox) {
820 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
821 push @{ $has_prefix }, $1;
822 }
823
824 my @var;
825 my $is_literal;
826 my $is_namespace;
827
828 ### allow hex
829 if ($copy =~ s{ ^ 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }{}ox) {
830 my $number = eval { hex $1 } || 0;
831 push @var, \ $number;
832 $is_literal = 1;
833
834 ### allow for numbers
835 } elsif ($copy =~ s{ ^ ( $QR_NUM ) \s* $QR_COMMENTS }{}ox) {
836 my $number = $1;
837 push @var, \ $number;
838 $is_literal = 1;
839
840 ### allow for quoted array constructor
841 } elsif ($copy =~ s{ ^ qw (\W) \s* }{}x) {
842 my $quote = $1;
843 $quote =~ y|([{<|)]}>|;
844 $copy =~ s{ ^ (.*) \Q$quote\E \s* $QR_COMMENTS }{}sx
845 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, length($$str_ref) - length($copy));
846 my $str = $1;
847 $str =~ s{ ^ \s+ | \s+ $ }{}x;
848 my $arrayref = ['array', split /\s+/, $str];
849 push @var, \ $arrayref;
850
851 ### looks like a normal variable start
852 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
853 push @var, $1;
854 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
855
856 ### allow for literal strings
857 } elsif ($copy =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }{}sox) {
858 if ($1 eq "'") { # no interpolation on single quoted strings
859 my $str = $2;
860 $str =~ s{ \\\' }{\'}xg;
861 push @var, \ $str;
862 $is_literal = 1;
863 } else {
864 my $str = $2;
865 $str =~ s/\\n/\n/g;
866 $str =~ s/\\t/\t/g;
867 $str =~ s/\\r/\r/g;
868 $str =~ s/\\([\"\$])/$1/g;
869 my @pieces = $ARGS->{'auto_quote'}
870 ? split(m{ (\$\w+ | \$\{ [^\}]+ \}) }x, $str) # autoquoted items get a single $\w+ - no nesting
871 : split(m{ (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \}) }x, $str);
872 my $n = 0;
873 foreach my $piece (@pieces) {
874 next if ! ($n++ % 2);
875 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
876 && $piece !~ m{ ^ \$\{ \s* ([^\}]+) \} $ }x;
877 my $name = $1;
878 $piece = $self->parse_expr(\$name);
879 }
880 @pieces = grep {defined && length} @pieces;
881 if (@pieces == 1 && ! ref $pieces[0]) {
882 push @var, \ $pieces[0];
883 $is_literal = 1;
884 } elsif (! @pieces) {
885 push @var, \ '';
886 $is_literal = 1;
887 } else {
888 push @var, \ ['~', @pieces];
889 }
890 }
891 if ($ARGS->{'auto_quote'}){
892 $$str_ref = $copy;
893 return ${ $var[0] } if $is_literal;
894 push @var, 0;
895 return \@var;
896 }
897
898 ### allow for leading $foo or ${foo.bar} type constructs
899 } elsif ($copy =~ s{ ^ \$ (\w+) \b \s* $QR_COMMENTS }{}ox
900 || $copy =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
901 my $name = $1;
902 push @var, $self->parse_expr(\$name);
903
904 ### looks like an array constructor
905 } elsif ($copy =~ s{ ^ \[ \s* $QR_COMMENTS }{}ox) {
906 local $self->{'_operator_precedence'} = 0; # reset presedence
907 my $arrayref = ['array'];
908 while (defined(my $var = $self->parse_expr(\$copy))) {
909 push @$arrayref, $var;
910 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
911 }
912 $copy =~ s{ ^ \] \s* $QR_COMMENTS }{}ox
913 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, length($$str_ref) - length($copy));
914 push @var, \ $arrayref;
915
916 ### looks like a hash constructor
917 } elsif ($copy =~ s{ ^ \{ \s* $QR_COMMENTS }{}ox) {
918 local $self->{'_operator_precedence'} = 0; # reset precedence
919 my $hashref = ['hash'];
920 while (defined(my $key = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))) {
921 $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox;
922 my $val = $self->parse_expr(\$copy);
923 push @$hashref, $key, $val;
924 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
925 }
926 $copy =~ s{ ^ \} \s* $QR_COMMENTS }{}ox
927 || $self->throw('parse.missing.curly_bracket', "Missing close \} ($copy)", undef, length($$str_ref) - length($copy));
928 push @var, \ $hashref;
929
930 ### looks like a paren grouper
931 } elsif ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
932 local $self->{'_operator_precedence'} = 0; # reset precedence
933 my $var = $self->parse_expr(\$copy, {allow_parened_ops => 1});
934 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
935 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
936 @var = @$var;
937 pop(@var); # pull off the trailing args of the paren group
938
939 ### nothing to find - return failure
940 } else {
941 return;
942 }
943
944 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
945
946 ### looks for args for the initial
947 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
948 local $self->{'_operator_precedence'} = 0; # reset precedence
949 my $args = $self->parse_args(\$copy);
950 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
951 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
952 push @var, $args;
953 } else {
954 push @var, 0;
955 }
956
957 ### allow for nested items
958 while ($copy =~ s{ ^ ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }{}ox) {
959 push(@var, $1) if ! $ARGS->{'no_dots'};
960
961 ### allow for interpolated variables in the middle - one.$foo.two or one.${foo.bar}.two
962 if ($copy =~ s{ ^ \$(\w+) \s* $QR_COMMENTS }{}ox
963 || $copy =~ s{ ^ \$\{ \s* ([^\}]+)\} \s* $QR_COMMENTS }{}ox) {
964 my $name = $1;
965 my $var = $self->parse_expr(\$name);
966 push @var, $var;
967
968 ### allow for names
969 } elsif ($copy =~ s{ ^ (-? \w+) \s* $QR_COMMENTS }{}ox) {
970 push @var, $1;
971
972 } else {
973 $self->throw('parse', "Not sure how to continue parsing on \"$copy\" ($$str_ref)");
974 }
975
976 ### looks for args for the nested item
977 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
978 local $self->{'_operator_precedence'} = 0; # reset precedence
979 my $args = $self->parse_args(\$copy);
980 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
981 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
982 push @var, $args;
983 } else {
984 push @var, 0;
985 }
986
987 }
988
989 ### flatten literals and constants as much as possible
990 my $var = ($is_literal && $#var == 1) ? ${ $var[0] }
991 : $is_namespace ? $self->play_expr(\@var, {is_namespace_during_compile => 1})
992 : \@var;
993
994 ### allow for all "operators"
995 if (! $self->{'_operator_precedence'}) {
996 my $tree;
997 my $found;
998 while ($copy =~ s{ ^ ($QR_OP) (\s* $QR_COMMENTS) }{}ox) { ## look for operators - then move along
999 if (! $ARGS->{'allow_parened_ops'} && $OP_ASSIGN->{$1}) {
1000 $copy = $1 . $2 . $copy;
1001 last;
1002 }
1003
1004 local $self->{'_operator_precedence'} = 1;
1005 my $op = $1;
1006
1007 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1008 if ($OP_POSTFIX->{$op}) {
1009 $var = [\ [$op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1010 next;
1011
1012 ### allow for prefix operator precedence
1013 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1014 if ($tree) {
1015 if ($#$tree == 1) { # only one operator - keep simple things fast
1016 $var = [\ [$tree->[0], $var, $tree->[1]], 0];
1017 } else {
1018 unshift @$tree, $var;
1019 $var = $self->apply_precedence($tree, $found);
1020 }
1021 undef $tree;
1022 undef $found;
1023 }
1024 $var = [ \ [ $has_prefix->[-1], $var ], 0 ];
1025 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1026 }
1027
1028 ### add the operator to the tree
1029 my $var2 = $self->parse_expr(\$copy);
1030 push (@{ $tree ||= [] }, $op, $var2);
1031 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1032 }
1033
1034 ### if we found operators - tree the nodes by operator precedence
1035 if ($tree) {
1036 if (@$tree == 2) { # only one operator - keep simple things fast
1037 $var = [\ [$tree->[0], $var, $tree->[1]], 0];
1038 } else {
1039 unshift @$tree, $var;
1040 $var = $self->apply_precedence($tree, $found);
1041 }
1042 }
1043 }
1044
1045 ### allow for prefix on non-chained variables
1046 if ($has_prefix) {
1047 $var = [ \ [ $_, $var ], 0 ] for reverse @$has_prefix;
1048 }
1049
1050 $$str_ref = $copy; # commit the changes
1051 return $var;
1052 }
1053
1054 ### this is used to put the parsed variables into the correct operations tree
1055 sub apply_precedence {
1056 my ($self, $tree, $found) = @_;
1057
1058 my @var;
1059 my $trees;
1060 ### look at the operators we found in the order we found them
1061 for my $prec (sort keys %$found) {
1062 my $ops = $found->{$prec};
1063 local $found->{$prec};
1064 delete $found->{$prec};
1065
1066 ### split the array on the current operators for this level
1067 my @ops;
1068 my @exprs;
1069 for (my $i = 1; $i <= $#$tree; $i += 2) {
1070 next if ! $ops->{ $tree->[$i] };
1071 push @ops, $tree->[$i];
1072 push @exprs, [splice @$tree, 0, $i, ()];
1073 shift @$tree;
1074 $i = -1;
1075 }
1076 next if ! @exprs; # this iteration didn't have the current operator
1077 push @exprs, $tree if scalar @$tree; # add on any remaining items
1078
1079 ### simplify sub expressions
1080 for my $node (@exprs) {
1081 if (@$node == 1) {
1082 $node = $node->[0]; # single item - its not a tree
1083 } elsif (@$node == 3) {
1084 $node = [ \ [ $node->[1], $node->[0], $node->[2] ], 0 ]; # single operator - put it straight on
1085 } else {
1086 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1087 }
1088 }
1089
1090 ### assemble this current level
1091
1092 ### some rules:
1093 # 1) items at the same precedence level must all be either right or left or ternary associative
1094 # 2) ternary items cannot share precedence with anybody else.
1095 # 3) there really shouldn't be another operator at the same level as a postfix
1096 my $type = $OP->{$ops[0]}->[0];
1097
1098 if ($type eq 'ternary') {
1099 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1100
1101 ### return simple ternary
1102 if (@exprs == 3) {
1103 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1104 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1105 return [ \ [ $op, @exprs ], 0 ];
1106 }
1107
1108
1109 ### reorder complex ternary - rare case
1110 while ($#ops >= 1) {
1111 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1112 for (my $i = $#ops; $i >= 0; $i --) {
1113 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1114 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1115 my $node = [ \ [$op, @exprs[$i .. $i + 2] ], 0 ];
1116 splice @exprs, $i, 3, $node;
1117 }
1118 }
1119 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1120
1121 } elsif ($type eq 'right' || $type eq 'assign') {
1122 my $val = $exprs[-1];
1123 $val = [ \ [ $ops[$_ - 1], $exprs[$_], $val ], 0 ] for reverse (0 .. $#exprs - 1);
1124 return $val;
1125
1126 } else {
1127 my $val = $exprs[0];
1128 $val = [ \ [ $ops[$_ - 1], $val, $exprs[$_] ], 0 ] for (1 .. $#exprs);
1129 return $val;
1130
1131 }
1132 }
1133
1134 $self->throw('parse', "Couldn't apply precedence");
1135 }
1136
1137 ### look for arguments - both positional and named
1138 sub parse_args {
1139 my $self = shift;
1140 my $str_ref = shift;
1141 my $ARGS = shift || {};
1142 my $copy = $$str_ref;
1143
1144 my @args;
1145 my @named;
1146 while (length $$str_ref) {
1147 my $copy = $$str_ref;
1148 if (defined(my $name = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
1149 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
1150 $self->throw('parse', 'Named arguments not allowed') if $ARGS->{'positional_only'};
1151 my $val = $self->parse_expr(\$copy);
1152 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1153 push @named, $name, $val;
1154 $$str_ref = $copy;
1155 } elsif (defined(my $arg = $self->parse_expr($str_ref))) {
1156 push @args, $arg;
1157 $$str_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1158 } else {
1159 last;
1160 }
1161 }
1162
1163 ### allow for named arguments to be added also
1164 push @args, [\ ['hash', @named], 0] if scalar @named;
1165
1166 return \@args;
1167 }
1168
1169 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1170 sub interpolate_node {
1171 my ($self, $tree, $offset) = @_;
1172 return if $self->{'_in_perl'};
1173
1174 ### split on variables while keeping the variables
1175 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \}) }x, $tree->[-1];
1176 if ($#pieces <= 0) {
1177 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1178 return;
1179 }
1180
1181 my @sub_tree;
1182 my $n = 0;
1183 foreach my $piece (@pieces) {
1184 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1185 if (! ($n++ % 2)) { # odds will always be text chunks
1186 next if ! length $piece;
1187 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1188 push @sub_tree, $piece;
1189 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1190 || $piece =~ m{ ^ \$\{ \s* ([^\}]+) \} $ }x) {
1191 my $name = $1;
1192 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\$name)];
1193 } else {
1194 $self->throw('parse', "Parse error during interpolate node");
1195 }
1196 }
1197
1198 ### replace the tree
1199 splice @$tree, -1, 1, @sub_tree;
1200 }
1201
1202 ###----------------------------------------------------------------###
1203
1204 sub play_expr {
1205 ### allow for the parse tree to store literals
1206 return $_[1] if ! ref $_[1];
1207
1208 my $self = shift;
1209 my $var = shift;
1210 my $ARGS = shift || {};
1211 my $i = 0;
1212
1213 ### determine the top level of this particular variable access
1214 my $ref;
1215 my $name = $var->[$i++];
1216 my $args = $var->[$i++];
1217 warn "play_expr: begin \"$name\"\n" if trace;
1218 if (ref $name) {
1219 if (ref $name eq 'SCALAR') { # a scalar literal
1220 $ref = $$name;
1221 } elsif (ref $name eq 'REF') { # operator
1222 return $self->play_operator($$name) if ${ $name }->[0] eq '..';
1223 $ref = $self->play_operator($$name);
1224 } else { # a named variable access (ie via $name.foo)
1225 $name = $self->play_expr($name);
1226 if (defined $name) {
1227 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1228 $ref = $self->{'_vars'}->{$name};
1229 }
1230 }
1231 } elsif (defined $name) {
1232 if ($ARGS->{'is_namespace_during_compile'}) {
1233 $ref = $self->{'NAMESPACE'}->{$name};
1234 } else {
1235 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1236 $ref = $self->{'_vars'}->{$name};
1237 $ref = $VOBJS->{$name} if ! defined $ref;
1238 }
1239 }
1240
1241
1242 my %seen_filters;
1243 while (defined $ref) {
1244
1245 ### check at each point if the rurned thing was a code
1246 if (UNIVERSAL::isa($ref, 'CODE')) {
1247 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1248 if (defined $results[0]) {
1249 $ref = ($#results > 0) ? \@results : $results[0];
1250 } elsif (defined $results[1]) {
1251 die $results[1]; # TT behavior - why not just throw ?
1252 } else {
1253 $ref = undef;
1254 last;
1255 }
1256 }
1257
1258 ### descend one chained level
1259 last if $i >= $#$var;
1260 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1261 $name = $var->[$i++];
1262 $args = $var->[$i++];
1263 warn "play_expr: nested \"$name\"\n" if trace;
1264
1265 ### allow for named portions of a variable name (foo.$name.bar)
1266 if (ref $name) {
1267 if (ref($name) eq 'ARRAY') {
1268 $name = $self->play_expr($name);
1269 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1270 $ref = undef;
1271 last;
1272 }
1273 } else {
1274 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1275 }
1276 }
1277 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1278 $ref = undef;
1279 last;
1280 }
1281
1282 ### allow for scalar and filter access (this happens for every non virtual method call)
1283 if (! ref $ref) {
1284 if ($SCALAR_OPS->{$name}) { # normal scalar op
1285 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1286
1287 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1288 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1289
1290 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1291 || $FILTER_OPS->{$name} # predefined filters in CET
1292 || (UNIVERSAL::isa($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1293 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1294
1295 if (UNIVERSAL::isa($filter, 'CODE')) {
1296 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1297 if (my $err = $@) {
1298 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1299 die $err;
1300 }
1301 } elsif (! UNIVERSAL::isa($filter, 'ARRAY')) {
1302 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1303
1304 } elsif (@$filter == 2 && UNIVERSAL::isa($filter->[0], 'CODE')) { # these are the TT style filters
1305 eval {
1306 my $sub = $filter->[0];
1307 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1308 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1309 if (! $sub && $err) {
1310 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1311 die $err;
1312 } elsif (! UNIVERSAL::isa($sub, 'CODE')) {
1313 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1314 if ref($sub) !~ /Template::Exception$/;
1315 die $sub;
1316 }
1317 }
1318 $ref = $sub->($ref);
1319 };
1320 if (my $err = $@) {
1321 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1322 die $err;
1323 }
1324 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1325 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1326 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1327 $i = 2;
1328 }
1329 if (scalar keys %seen_filters
1330 && $seen_filters{$var->[$i - 5] || ''}) {
1331 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1332 }
1333 } else {
1334 $ref = undef;
1335 }
1336
1337 } else {
1338
1339 ### method calls on objects
1340 if ($was_dot_call && UNIVERSAL::can($ref, 'can')) {
1341 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1342 my @results = eval { $ref->$name(@args) };
1343 if ($@) {
1344 my $class = ref $ref;
1345 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1346 } elsif (defined $results[0]) {
1347 $ref = ($#results > 0) ? \@results : $results[0];
1348 next;
1349 } elsif (defined $results[1]) {
1350 die $results[1]; # TT behavior - why not just throw ?
1351 } else {
1352 $ref = undef;
1353 last;
1354 }
1355 # didn't find a method by that name - so fail down to hash and array access
1356 }
1357
1358 ### hash member access
1359 if (UNIVERSAL::isa($ref, 'HASH')) {
1360 if ($was_dot_call && exists($ref->{$name}) ) {
1361 $ref = $ref->{$name};
1362 } elsif ($HASH_OPS->{$name}) {
1363 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1364 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1365 return $var; # abort - can't fold namespace variable
1366 } else {
1367 $ref = undef;
1368 }
1369
1370 ### array access
1371 } elsif (UNIVERSAL::isa($ref, 'ARRAY')) {
1372 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1373 $ref = $ref->[$name];
1374 } elsif ($LIST_OPS->{$name}) {
1375 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1376 } else {
1377 $ref = undef;
1378 }
1379 }
1380 }
1381
1382 } # end of while
1383
1384 ### allow for undefinedness
1385 if (! defined $ref) {
1386 if ($self->{'_debug_undef'}) {
1387 my $chunk = $var->[$i - 2];
1388 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1389 die "$chunk is undefined\n";
1390 } else {
1391 $ref = $self->undefined_any($var);
1392 }
1393 }
1394
1395 return $ref;
1396 }
1397
1398 sub set_variable {
1399 my ($self, $var, $val, $ARGS) = @_;
1400 $ARGS ||= {};
1401 my $i = 0;
1402
1403 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1404 $var = [$var, 0] if ! ref $var;
1405
1406 ### determine the top level of this particular variable access
1407 my $ref = $var->[$i++];
1408 my $args = $var->[$i++];
1409 if (ref $ref) {
1410 if (ref($ref) eq 'ARRAY') { # named access (ie via $name.foo)
1411 $ref = $self->play_expr($ref);
1412 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1413 if ($#$var <= $i) {
1414 return $self->{'_vars'}->{$ref} = $val;
1415 } else {
1416 $ref = $self->{'_vars'}->{$ref} ||= {};
1417 }
1418 } else {
1419 return;
1420 }
1421 } else { # all other types can't be set
1422 return;
1423 }
1424 } elsif (defined $ref) {
1425 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1426 if ($#$var <= $i) {
1427 return $self->{'_vars'}->{$ref} = $val;
1428 } else {
1429 $ref = $self->{'_vars'}->{$ref} ||= {};
1430 }
1431 }
1432
1433 while (defined $ref) {
1434
1435 ### check at each point if the returned thing was a code
1436 if (UNIVERSAL::isa($ref, 'CODE')) {
1437 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1438 if (defined $results[0]) {
1439 $ref = ($#results > 0) ? \@results : $results[0];
1440 } elsif (defined $results[1]) {
1441 die $results[1]; # TT behavior - why not just throw ?
1442 } else {
1443 return;
1444 }
1445 }
1446
1447 ### descend one chained level
1448 last if $i >= $#$var;
1449 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1450 my $name = $var->[$i++];
1451 my $args = $var->[$i++];
1452
1453 ### allow for named portions of a variable name (foo.$name.bar)
1454 if (ref $name) {
1455 if (ref($name) eq 'ARRAY') {
1456 $name = $self->play_expr($name);
1457 if (! defined($name) || $name =~ /^[_.]/) {
1458 return;
1459 }
1460 } else {
1461 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1462 }
1463 }
1464 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1465 return;
1466 }
1467
1468 ### scalar access
1469 if (! ref $ref) {
1470 return;
1471
1472 ### method calls on objects
1473 } elsif (UNIVERSAL::can($ref, 'can')) {
1474 my $lvalueish;
1475 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1476 if ($i >= $#$var) {
1477 $lvalueish = 1;
1478 push @args, $val;
1479 }
1480 my @results = eval { $ref->$name(@args) };
1481 if (! $@) {
1482 if (defined $results[0]) {
1483 $ref = ($#results > 0) ? \@results : $results[0];
1484 } elsif (defined $results[1]) {
1485 die $results[1]; # TT behavior - why not just throw ?
1486 } else {
1487 return;
1488 }
1489 return if $lvalueish;
1490 next;
1491 }
1492 my $class = ref $ref;
1493 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1494 # fall on down to "normal" accessors
1495 }
1496
1497 ### hash member access
1498 if (UNIVERSAL::isa($ref, 'HASH')) {
1499 if ($#$var <= $i) {
1500 return $ref->{$name} = $val;
1501 } else {
1502 $ref = $ref->{$name} ||= {};
1503 next;
1504 }
1505
1506 ### array access
1507 } elsif (UNIVERSAL::isa($ref, 'ARRAY')) {
1508 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1509 if ($#$var <= $i) {
1510 return $ref->[$name] = $val;
1511 } else {
1512 $ref = $ref->[$name] ||= {};
1513 next;
1514 }
1515 } else {
1516 return;
1517 }
1518
1519 }
1520
1521 }
1522
1523 return;
1524 }
1525
1526 ###----------------------------------------------------------------###
1527
1528 sub play_operator {
1529 my $self = shift;
1530 my $tree = shift;
1531
1532 if ($OP_DISPATCH->{$tree->[0]}) {
1533 local $^W;
1534 if ($OP_ASSIGN->{$tree->[0]}) {
1535 my $val = $OP_DISPATCH->{$tree->[0]}->( $self->play_expr($tree->[1]), $self->play_expr($tree->[2]) );
1536 $self->set_variable($tree->[1], $val);
1537 return $val;
1538 } else {
1539 return $OP_DISPATCH->{$tree->[0]}->( map { $self->play_expr($tree->[$_]) } 1 .. $#$tree );
1540 }
1541 }
1542
1543 my $op = $tree->[0];
1544
1545 ### do custom and short-circuitable operators
1546 if ($op eq '=') {
1547 my $val = $self->play_expr($tree->[2]);
1548 $self->set_variable($tree->[1], $val);
1549 return $val;
1550
1551 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1552 return $self->play_expr($tree->[1]) || $self->play_expr($tree->[2]) || '';
1553
1554 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1555 my $var = $self->play_expr($tree->[1]) && $self->play_expr($tree->[2]);
1556 return $var ? $var : 0;
1557
1558 } elsif ($op eq '?') {
1559 local $^W;
1560 return $self->play_expr($tree->[1]) ? $self->play_expr($tree->[2]) : $self->play_expr($tree->[3]);
1561
1562 } elsif ($op eq '++') {
1563 local $^W;
1564 my $val = 0 + $self->play_expr($tree->[1]);
1565 $self->set_variable($tree->[1], $val + 1);
1566 return $tree->[2] ? $val : $val + 1; # ->[2] is set to 1 during parsing of postfix ops
1567
1568 } elsif ($op eq '--') {
1569 local $^W;
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
1573 }
1574
1575 $self->throw('operator', "Un-implemented operation $op");
1576 }
1577
1578 ###----------------------------------------------------------------###
1579
1580 sub parse_BLOCK {
1581 my ($self, $tag_ref, $node) = @_;
1582
1583 my $block_name = '';
1584 if ($$tag_ref =~ s{ ^ (\w+ (?: :\w+)*) \s* (?! [\.\|]) }{}x
1585 || $$tag_ref =~ s{ ^ '(|.*?[^\\])' \s* (?! [\.\|]) }{}x
1586 || $$tag_ref =~ s{ ^ "(|.*?[^\\])" \s* (?! [\.\|]) }{}x
1587 ) {
1588 $block_name = $1;
1589 ### allow for nested blocks to have nested names
1590 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1591 $block_name = join("/", @names, $block_name) if scalar @names;
1592 }
1593
1594 return $block_name;
1595 }
1596
1597 sub play_BLOCK {
1598 my ($self, $block_name, $node, $out_ref) = @_;
1599
1600 ### store a named reference - but do nothing until something processes it
1601 $self->{'BLOCKS'}->{$block_name} = {
1602 _tree => $node->[4],
1603 name => $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1604 };
1605
1606 return;
1607 }
1608
1609 sub parse_CALL { $DIRECTIVES->{'GET'}->[0]->(@_) }
1610
1611 sub play_CALL { $DIRECTIVES->{'GET'}->[1]->(@_); return }
1612
1613 sub parse_CASE {
1614 my ($self, $tag_ref) = @_;
1615 return if $$tag_ref =~ s{ ^ DEFAULT \s* }{}x;
1616 return $self->parse_expr($tag_ref);
1617 }
1618
1619 sub parse_CATCH {
1620 my ($self, $tag_ref) = @_;
1621 return $self->parse_expr($tag_ref, {auto_quote => qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
1622 }
1623
1624 sub play_control {
1625 my ($self, $undef, $node) = @_;
1626 $self->throw(lc($node->[0]), 'Control exception', $node);
1627 }
1628
1629 sub play_CLEAR {
1630 my ($self, $undef, $node, $out_ref) = @_;
1631 $$out_ref = '';
1632 }
1633
1634 sub parse_DEBUG {
1635 my ($self, $tag_ref) = @_;
1636 $$tag_ref =~ s{ ^ (on | off | format) \s* }{}xi || $self->throw('parse', "Unknown DEBUG option");
1637 my $ret = [lc($1)];
1638 if ($ret->[0] eq 'format') {
1639 $$tag_ref =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* }{}xs || $self->throw('parse', "Missing format string");
1640 $ret->[1] = $2;
1641 }
1642 return $ret;
1643 }
1644
1645 sub play_DEBUG {
1646 my ($self, $ref) = @_;
1647 if ($ref->[0] eq 'on') {
1648 delete $self->{'_debug_off'};
1649 } elsif ($ref->[0] eq 'off') {
1650 $self->{'_debug_off'} = 1;
1651 } elsif ($ref->[0] eq 'format') {
1652 $self->{'_debug_format'} = $ref->[1];
1653 }
1654 }
1655
1656 sub parse_DEFAULT { $DIRECTIVES->{'SET'}->[0]->(@_) }
1657
1658 sub play_DEFAULT {
1659 my ($self, $set) = @_;
1660 foreach (@$set) {
1661 my ($op, $set, $default) = @$_;
1662 next if ! defined $set;
1663 my $val = $self->play_expr($set);
1664 if (! $val) {
1665 $default = defined($default) ? $self->play_expr($default) : '';
1666 $self->set_variable($set, $default);
1667 }
1668 }
1669 return;
1670 }
1671
1672 sub parse_DUMP {
1673 my ($self, $tag_ref) = @_;
1674 my $ref = $self->parse_expr($tag_ref);
1675 return $ref;
1676 }
1677
1678 sub play_DUMP {
1679 my ($self, $ident, $node) = @_;
1680 require Data::Dumper;
1681 my $info = $self->node_info($node);
1682 my $out;
1683 my $var;
1684 if ($ident) {
1685 $out = Data::Dumper::Dumper($self->play_expr($ident));
1686 $var = $info->{'text'};
1687 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1688 $var =~ s/\s*[+\-~=]?$//;
1689 } else {
1690 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1691 local @{ $self->{'_vars'} }{ @were_never_here };
1692 delete @{ $self->{'_vars'} }{ @were_never_here };
1693 $out = Data::Dumper::Dumper($self->{'_vars'});
1694 $var = 'EntireStash';
1695 }
1696 if ($ENV{'REQUEST_METHOD'}) {
1697 $out =~ s/</&lt;/g;
1698 $out = "<pre>$out</pre>";
1699 $out =~ s/\$VAR1/$var/;
1700 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1701 } else {
1702 $out =~ s/\$VAR1/$var/;
1703 }
1704
1705 return $out;
1706 }
1707
1708 sub parse_FILTER {
1709 my ($self, $tag_ref) = @_;
1710 my $name = '';
1711 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1712 $name = $1;
1713 }
1714
1715 my $filter = $self->parse_expr($tag_ref);
1716 $filter = '' if ! defined $filter;
1717
1718 return [$name, $filter];
1719 }
1720
1721 sub play_FILTER {
1722 my ($self, $ref, $node, $out_ref) = @_;
1723 my ($name, $filter) = @$ref;
1724
1725 return '' if ! @$filter;
1726
1727 $self->{'FILTERS'}->{$name} = $filter if length $name;
1728
1729 my $sub_tree = $node->[4];
1730
1731 ### play the block
1732 my $out = '';
1733 eval { $self->execute_tree($sub_tree, \$out) };
1734 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1735
1736 my $var = [\$out, 0, '|', @$filter]; # make a temporary var out of it
1737
1738
1739 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1740 }
1741
1742 sub parse_FOREACH {
1743 my ($self, $tag_ref) = @_;
1744 my $items = $self->parse_expr($tag_ref);
1745 my $var;
1746 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1747 $var = [@$items];
1748 $items = $self->parse_expr($tag_ref);
1749 }
1750 return [$var, $items];
1751 }
1752
1753 sub play_FOREACH {
1754 my ($self, $ref, $node, $out_ref) = @_;
1755
1756 ### get the items - make sure it is an arrayref
1757 my ($var, $items) = @$ref;
1758
1759 $items = $self->play_expr($items);
1760 return '' if ! defined $items;
1761
1762 if (ref($items) !~ /Iterator$/) {
1763 $items = $PACKAGE_ITERATOR->new($items);
1764 }
1765
1766 my $sub_tree = $node->[4];
1767
1768 local $self->{'_vars'}->{'loop'} = $items;
1769
1770 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1771 if (defined $var) {
1772 my ($item, $error) = $items->get_first;
1773 while (! $error) {
1774
1775 $self->set_variable($var, $item);
1776
1777 ### execute the sub tree
1778 eval { $self->execute_tree($sub_tree, $out_ref) };
1779 if (my $err = $@) {
1780 if (UNIVERSAL::isa($err, $PACKAGE_EXCEPTION)) {
1781 if ($err->type eq 'next') {
1782 ($item, $error) = $items->get_next;
1783 next;
1784 }
1785 last if $err->type =~ /last|break/;
1786 }
1787 die $err;
1788 }
1789
1790 ($item, $error) = $items->get_next;
1791 }
1792 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1793 ### if the FOREACH tag doesn't set a var - then everything gets localized
1794 } else {
1795
1796 ### localize variable access for the foreach
1797 my $swap = $self->{'_vars'};
1798 local $self->{'_vars'} = my $copy = {%$swap};
1799
1800 ### iterate use the iterator object
1801 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1802 my ($item, $error) = $items->get_first;
1803 while (! $error) {
1804
1805 if (ref($item) eq 'HASH') {
1806 @$copy{keys %$item} = values %$item;
1807 }
1808
1809 ### execute the sub tree
1810 eval { $self->execute_tree($sub_tree, $out_ref) };
1811 if (my $err = $@) {
1812 if (UNIVERSAL::isa($err, $PACKAGE_EXCEPTION)) {
1813 if ($err->type eq 'next') {
1814 ($item, $error) = $items->get_next;
1815 next;
1816 }
1817 last if $err->type =~ /last|break/;
1818 }
1819 die $err;
1820 }
1821
1822 ($item, $error) = $items->get_next;
1823 }
1824 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1825 }
1826
1827 return undef;
1828 }
1829
1830 sub parse_GET {
1831 my ($self, $tag_ref) = @_;
1832 my $ref = $self->parse_expr($tag_ref);
1833 $self->throw('parse', "Missing variable name") if ! defined $ref;
1834 return $ref;
1835 }
1836
1837 sub play_GET {
1838 my ($self, $ident, $node) = @_;
1839 my $var = $self->play_expr($ident);
1840 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1841 }
1842
1843 sub parse_IF {
1844 my ($self, $tag_ref) = @_;
1845 return $self->parse_expr($tag_ref);
1846 }
1847
1848 sub play_IF {
1849 my ($self, $var, $node, $out_ref) = @_;
1850
1851 my $val = $self->play_expr($var);
1852 if ($val) {
1853 my $body_ref = $node->[4] ||= [];
1854 $self->execute_tree($body_ref, $out_ref);
1855 return;
1856 }
1857
1858 while ($node = $node->[5]) { # ELSE, ELSIF's
1859 if ($node->[0] eq 'ELSE') {
1860 my $body_ref = $node->[4] ||= [];
1861 $self->execute_tree($body_ref, $out_ref);
1862 return;
1863 }
1864 my $var = $node->[3];
1865 my $val = $self->play_expr($var);
1866 if ($val) {
1867 my $body_ref = $node->[4] ||= [];
1868 $self->execute_tree($body_ref, $out_ref);
1869 return;
1870 }
1871 }
1872 return;
1873 }
1874
1875 sub parse_INCLUDE { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1876
1877 sub play_INCLUDE {
1878 my ($self, $tag_ref, $node, $out_ref) = @_;
1879
1880 ### localize the swap
1881 my $swap = $self->{'_vars'};
1882 local $self->{'_vars'} = {%$swap};
1883
1884 ### localize the blocks
1885 my $blocks = $self->{'BLOCKS'};
1886 local $self->{'BLOCKS'} = {%$blocks};
1887
1888 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1889
1890 return $str;
1891 }
1892
1893 sub parse_INSERT { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1894
1895 sub play_INSERT {
1896 my ($self, $var, $node, $out_ref) = @_;
1897 my ($names, $args) = @$var;
1898
1899 foreach my $name (@$names) {
1900 my $filename = $self->play_expr($name);
1901 $$out_ref .= $self->_insert($filename);
1902 }
1903
1904 return;
1905 }
1906
1907 sub parse_MACRO {
1908 my ($self, $tag_ref, $node) = @_;
1909 my $copy = $$tag_ref;
1910
1911 my $name = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1912 $self->throw('parse', "Missing macro name") if ! defined $name;
1913 if (! ref $name) {
1914 $name = [ $name, 0 ];
1915 }
1916
1917 my $args;
1918 if ($copy =~ s{ ^ \( \s* }{}x) {
1919 $args = $self->parse_args(\$copy, {positional_only => 1});
1920 $copy =~ s { ^ \) \s* }{}x || $self->throw('parse.missing', "Missing close ')'");
1921 }
1922
1923 $node->[6] = 1; # set a flag to keep parsing
1924 $$tag_ref = $copy;
1925 return [$name, $args];
1926 }
1927
1928 sub play_MACRO {
1929 my ($self, $ref, $node, $out_ref) = @_;
1930 my ($name, $args) = @$ref;
1931
1932 ### get the sub tree
1933 my $sub_tree = $node->[4];
1934 if (! $sub_tree || ! $sub_tree->[0]) {
1935 $self->set_variable($name, undef);
1936 return;
1937 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1938 $sub_tree = $sub_tree->[0]->[4];
1939 }
1940
1941 my $self_copy = $self;
1942 eval {require Scalar::Util; Scalar::Util::weaken($self_copy)};
1943
1944 ### install a closure in the stash that will handle the macro
1945 $self->set_variable($name, sub {
1946 ### macros localize
1947 my $copy = $self_copy->{'_vars'};
1948 local $self_copy->{'_vars'}= {%$copy};
1949
1950 ### set arguments
1951 my $named = pop(@_) if $_[-1] && UNIVERSAL::isa($_[-1],'HASH') && $#_ > $#$args;
1952 my @positional = @_;
1953 foreach my $var (@$args) {
1954 $self_copy->set_variable($var, shift(@positional));
1955 }
1956 foreach my $name (sort keys %$named) {
1957 $self_copy->set_variable([$name, 0], $named->{$name});
1958 }
1959
1960 ### finally - run the sub tree
1961 my $out = '';
1962 $self_copy->execute_tree($sub_tree, \$out);
1963 return $out;
1964 });
1965
1966 return;
1967 }
1968
1969 sub play_METADEF {
1970 my ($self, $hash) = @_;
1971 my $ref;
1972 if ($self->{'_top_level'}) {
1973 $ref = $self->{'_vars'}->{'template'} ||= {};
1974 } else {
1975 $ref = $self->{'_vars'}->{'component'} ||= {};
1976 }
1977 foreach my $key (keys %$hash) {
1978 next if $key eq 'name' || $key eq 'modtime';
1979 $ref->{$key} = $hash->{$key};
1980 }
1981 return;
1982 }
1983
1984 sub parse_PERL { shift->{'_in_perl'} = 1; return }
1985
1986 sub play_PERL {
1987 my ($self, $info, $node, $out_ref) = @_;
1988 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1989
1990 ### fill in any variables
1991 my $perl = $node->[4] || return;
1992 my $out = '';
1993 $self->execute_tree($perl, \$out);
1994 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
1995
1996 ### try the code
1997 my $err;
1998 eval {
1999 package CGI::Ex::Template::Perl;
2000
2001 my $context = $self->context;
2002 my $stash = $context->stash;
2003
2004 ### setup a fake handle
2005 local *PERLOUT;
2006 tie *PERLOUT, $CGI::Ex::Template::PACKAGE_PERL_HANDLE, $out_ref;
2007 my $old_fh = select PERLOUT;
2008
2009 eval $out;
2010 $err = $@;
2011
2012 ### put the handle back
2013 select $old_fh;
2014
2015 };
2016 $err ||= $@;
2017
2018
2019 if ($err) {
2020 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2021 die $err;
2022 }
2023
2024 return;
2025 }
2026
2027 sub parse_PROCESS {
2028 my ($self, $tag_ref) = @_;
2029 my $info = [[], []];
2030 while (defined(my $filename = $self->parse_expr($tag_ref, {
2031 auto_quote => qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2032 }))) {
2033 push @{$info->[0]}, $filename;
2034 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2035 }
2036
2037 ### allow for post process variables
2038 while (length $$tag_ref) {
2039 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2040
2041 my $var = $self->parse_expr($tag_ref);
2042 last if ! defined $var;
2043 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2044 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2045 }
2046
2047 my $val = $self->parse_expr($tag_ref);
2048 push @{$info->[1]}, [$var, $val];
2049 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2050 }
2051
2052 return $info;
2053 }
2054
2055 sub play_PROCESS {
2056 my ($self, $info, $node, $out_ref) = @_;
2057
2058 my ($files, $args) = @$info;
2059
2060 ### set passed args
2061 foreach (@$args) {
2062 my ($key, $val) = @$_;
2063 $val = $self->play_expr($val);
2064 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL::isa($val, 'HASH')) { # import ?! - whatever
2065 foreach my $key (keys %$val) {
2066 $self->set_variable([$key,0], $val->{$key});
2067 }
2068 next;
2069 }
2070 $self->set_variable($key, $val);
2071 }
2072
2073 ### iterate on any passed block or filename
2074 foreach my $ref (@$files) {
2075 next if ! defined $ref;
2076 my $filename = $self->play_expr($ref);
2077 my $out = ''; # have temp item to allow clear to correctly clear
2078
2079 ### normal blocks or filenames
2080 if (! ref $filename) {
2081 eval { $self->_process($filename, $self->{'_vars'}, \$out) }; # restart the swap - passing it our current stash
2082
2083 ### allow for $template which is used in some odd instances
2084 } else {
2085 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2086 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2087 local $self->{'_process_dollar_template'} = 1;
2088 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2089 return if ! $doc->{'_tree'};
2090
2091 ### execute and trim
2092 eval { $self->execute_tree($doc->{'_tree'}, \$out) };
2093 if ($self->{'TRIM'}) {
2094 $out =~ s{ \s+ $ }{}x;
2095 $out =~ s{ ^ \s+ }{}x;
2096 }
2097
2098 ### handle exceptions
2099 if (my $err = $@) {
2100 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2101 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2102 }
2103
2104 }
2105
2106 ### append any output
2107 $$out_ref .= $out;
2108 if (my $err = $@) {
2109 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2110 }
2111 }
2112
2113 return;
2114 }
2115
2116 sub play_RAWPERL {
2117 my ($self, $info, $node, $out_ref) = @_;
2118 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2119
2120 ### fill in any variables
2121 my $tree = $node->[4] || return;
2122 my $perl = '';
2123 $self->execute_tree($tree, \$perl);
2124 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2125
2126 ### try the code
2127 my $err;
2128 my $output = '';
2129 eval {
2130 package CGI::Ex::Template::Perl;
2131
2132 my $context = $self->context;
2133 my $stash = $context->stash;
2134
2135 eval $perl;
2136 $err = $@;
2137 };
2138 $err ||= $@;
2139
2140 $$out_ref .= $output;
2141
2142 if ($err) {
2143 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2144 die $err;
2145 }
2146
2147 return;
2148 }
2149
2150 sub parse_SET {
2151 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2152 my @SET;
2153 my $copy = $$tag_ref;
2154 my $func;
2155
2156 if ($initial_op) {
2157 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2158 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2159 $node->[6] = 1; # set a flag to keep parsing
2160 my $val = $node->[4] ||= []; # setup storage
2161 return [[$initial_op, $initial_var, $val]];
2162 } else { # get a normal variable
2163 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2164 }
2165 }
2166
2167 while (length $$tag_ref) {
2168 my $set = $self->parse_expr($tag_ref);
2169 last if ! defined $set;
2170
2171 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2172 my $op = $1;
2173 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2174 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2175 $node->[6] = 1; # set a flag to keep parsing
2176 my $val = $node->[4] ||= []; # setup storage
2177 push @SET, [$op, $set, $val];
2178 last;
2179 } else { # get a normal variable
2180 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2181 }
2182 } else {
2183 push @SET, ['=', $set, undef];
2184 }
2185 }
2186 return \@SET;
2187 }
2188
2189 sub play_SET {
2190 my ($self, $set, $node) = @_;
2191 foreach (@$set) {
2192 my ($op, $set, $val) = @$_;
2193 if (! defined $val) { # not defined
2194 $val = '';
2195 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2196 my $sub_tree = $node->[4];
2197 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2198 $val = '';
2199 $self->execute_tree($sub_tree, \$val);
2200 } else { # normal var
2201 $val = $self->play_expr($val);
2202 }
2203
2204 if ($OP_DISPATCH->{$op}) {
2205 local $^W;
2206 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2207 }
2208
2209 $self->set_variable($set, $val);
2210 }
2211 return;
2212 }
2213
2214 sub parse_SWITCH { $DIRECTIVES->{'GET'}->[0]->(@_) }
2215
2216 sub play_SWITCH {
2217 my ($self, $var, $node, $out_ref) = @_;
2218
2219 my $val = $self->play_expr($var);
2220 $val = '' if ! defined $val;
2221 ### $node->[4] is thrown away
2222
2223 my $default;
2224 while ($node = $node->[5]) { # CASES
2225 my $var = $node->[3];
2226 if (! defined $var) {
2227 $default = $node->[4];
2228 next;
2229 }
2230
2231 my $val2 = $self->play_expr($var);
2232 $val2 = [$val2] if ! UNIVERSAL::isa($val2, 'ARRAY');
2233 for my $test (@$val2) { # find matching values
2234 next if ! defined $val && defined $test;
2235 next if defined $val && ! defined $test;
2236 if ($val ne $test) { # check string-wise first - then numerical
2237 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2238 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2239 next if $val != $test;
2240 }
2241
2242 my $body_ref = $node->[4] ||= [];
2243 $self->execute_tree($body_ref, $out_ref);
2244 return;
2245 }
2246 }
2247
2248 if ($default) {
2249 $self->execute_tree($default, $out_ref);
2250 }
2251
2252 return;
2253 }
2254
2255 sub parse_THROW {
2256 my ($self, $tag_ref, $node) = @_;
2257 my $name = $self->parse_expr($tag_ref, {auto_quote => qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2258 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2259 my $args = $self->parse_args($tag_ref);
2260 return [$name, $args];
2261 }
2262
2263 sub play_THROW {
2264 my ($self, $ref, $node) = @_;
2265 my ($name, $args) = @$ref;
2266 $name = $self->play_expr($name);
2267 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2268 $self->throw($name, \@args, $node);
2269 }
2270
2271 sub play_TRY {
2272 my ($self, $foo, $node, $out_ref) = @_;
2273 my $out = '';
2274
2275 my $body_ref = $node->[4];
2276 eval { $self->execute_tree($body_ref, \$out) };
2277 my $err = $@;
2278
2279 if (! $node->[5]) { # no catch or final
2280 if (! $err) { # no final block and no error
2281 $$out_ref .= $out;
2282 return;
2283 }
2284 $self->throw('parse.missing', "Missing CATCH block", $node);
2285 }
2286 if ($err) {
2287 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2288 if ($err->type =~ /stop|return/) {
2289 $$out_ref .= $out;
2290 die $err;
2291 }
2292 }
2293
2294 ### loop through the nested catch and final blocks
2295 my $catch_body_ref;
2296 my $last_found;
2297 my $type = $err ? $err->type : '';
2298 my $final;
2299 while ($node = $node->[5]) { # CATCH
2300 if ($node->[0] eq 'FINAL') {
2301 $final = $node->[4];
2302 next;
2303 }
2304 next if ! $err;
2305 my $name = $self->play_expr($node->[3]);
2306 $name = '' if ! defined $name || lc($name) eq 'default';
2307 if ($type =~ / ^ \Q$name\E \b /x
2308 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2309 $catch_body_ref = $node->[4] || [];
2310 $last_found = $name;
2311 }
2312 }
2313
2314 ### play the best catch block
2315 if ($err) {
2316 if (! $catch_body_ref) {
2317 $$out_ref .= $out;
2318 die $err;
2319 }
2320 local $self->{'_vars'}->{'error'} = $err;
2321 local $self->{'_vars'}->{'e'} = $err;
2322 eval { $self->execute_tree($catch_body_ref, \$out) };
2323 if (my $err = $@) {
2324 $$out_ref .= $out;
2325 die $err;
2326 }
2327 }
2328
2329 ### the final block
2330 $self->execute_tree($final, \$out) if $final;
2331
2332 $$out_ref .= $out;
2333
2334 return;
2335 }
2336
2337 sub parse_UNLESS {
2338 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2339 return [ \ [ '!', $ref ], 0 ];
2340 }
2341
2342 sub play_UNLESS { return $DIRECTIVES->{'IF'}->[1]->(@_) }
2343
2344 sub parse_USE {
2345 my ($self, $tag_ref) = @_;
2346
2347 my $var;
2348 my $copy = $$tag_ref;
2349 if (defined(my $_var = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2350 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2351 $var = $_var;
2352 $$tag_ref = $copy;
2353 }
2354
2355 $copy = $$tag_ref;
2356 my $module = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2357 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2358 $module =~ s/\./::/g;
2359
2360 my $args;
2361 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2362 $args = $self->parse_args(\$copy);
2363
2364 if ($open) {
2365 $copy =~ s { ^ \) \s* $QR_COMMENTS }{}ox || $self->throw('parse.missing', "Missing close ')'");
2366 }
2367
2368 $$tag_ref = $copy;
2369 return [$var, $module, $args];
2370 }
2371
2372 sub play_USE {
2373 my ($self, $ref, $node, $out_ref) = @_;
2374 my ($var, $module, $args) = @$ref;
2375
2376 ### get the stash storage location - default to the module
2377 $var = $module if ! defined $var;
2378 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2379 pop @var; # remove the trailing '.'
2380
2381 ### look for a plugin_base
2382 my $base = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2383 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2384 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2385 : "${base}::${module}";
2386 my $require = "$package.pm";
2387 $require =~ s|::|/|g;
2388
2389 ### try and load the module - fall back to bare module if allowed
2390 my $obj;
2391 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2392 my $shape = $package->load;
2393 my $context = $self->context;
2394 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2395 $obj = $shape->new($context, @args);
2396 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2397 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2398 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base => $base}) }) {
2399 foreach my $package (@packages) {
2400 my $require = "$package.pm";
2401 $require =~ s|::|/|g;
2402 eval {require $require} || next;
2403 my $shape = $package->load;
2404 my $context = $self->context;
2405 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2406 $obj = $shape->new($context, @args);
2407 }
2408 } elsif ($self->{'LOAD_PERL'}) {
2409 my $require = "$module.pm";
2410 $require =~ s|::|/|g;
2411 if (eval {require $require}) {
2412 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2413 $obj = $module->new(@args);
2414 }
2415 }
2416 if (! defined $obj) {
2417 my $err = "$module: plugin not found";
2418 $self->throw('plugin', $err);
2419 }
2420
2421 ### all good
2422 $self->set_variable(\@var, $obj);
2423
2424 return;
2425 }
2426
2427 sub play_WHILE {
2428 my ($self, $var, $node, $out_ref) = @_;
2429 return '' if ! defined $var;
2430
2431 my $sub_tree = $node->[4];
2432
2433 ### iterate use the iterator object
2434 my $count = $WHILE_MAX;
2435 while (--$count > 0) {
2436
2437 $self->play_expr($var) || last;
2438
2439 ### execute the sub tree
2440 eval { $self->execute_tree($sub_tree, $out_ref) };
2441 if (my $err = $@) {
2442 if (UNIVERSAL::isa($err, $PACKAGE_EXCEPTION)) {
2443 next if $err->type =~ /next/;
2444 last if $err->type =~ /last|break/;
2445 }
2446 die $err;
2447 }
2448 }
2449 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2450
2451 return undef;
2452 }
2453
2454 sub parse_WRAPPER { $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2455
2456 sub play_WRAPPER {
2457 my ($self, $var, $node, $out_ref) = @_;
2458 my $sub_tree = $node->[4] || return;
2459
2460 my ($names, $args) = @$var;
2461
2462 my $out = '';
2463 $self->execute_tree($sub_tree, \$out);
2464
2465 foreach my $name (reverse @$names) {
2466 local $self->{'_vars'}->{'content'} = $out;
2467 $out = '';
2468 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \$out);
2469 }
2470
2471 $$out_ref .= $out;
2472 return;
2473 }
2474
2475 ###----------------------------------------------------------------###
2476
2477 sub _vars {
2478 my $self = shift;
2479 $self->{'_vars'} = shift if $#_ == 0;
2480 return $self->{'_vars'} ||= {};
2481 }
2482
2483 sub include_filename {
2484 my ($self, $file) = @_;
2485 if ($file =~ m|^/|) {
2486 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2487 return $file if -e $file;
2488 } elsif ($file =~ m{(^|/)\.\./}) {
2489 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2490 return $file if -e $file;
2491 }
2492
2493 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2494 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2495 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2496 $paths = $paths->() if UNIVERSAL::isa($paths, 'CODE');
2497 $paths = $self->split_paths($paths) if ! UNIVERSAL::isa($paths, 'ARRAY');
2498 $paths; # return of the do
2499 };
2500 foreach my $path (@$paths) {
2501 return "$path/$file" if -e "$path/$file";
2502 }
2503
2504 $self->throw('file', "$file: not found");
2505 }
2506
2507 sub split_paths {
2508 my ($self, $path) = @_;
2509 return $path if ref $path;
2510 my $delim = $self->{'DELIMITER'} || ':';
2511 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr|:(?!/)| : qr|\Q$delim\E|;
2512 return [split $delim, $path];
2513 }
2514
2515 sub _insert {
2516 my ($self, $file) = @_;
2517 return $self->slurp($self->include_filename($file));
2518 }
2519
2520 sub slurp {
2521 my ($self, $file) = @_;
2522 local *FH;
2523 open(FH, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2524 read FH, my $txt, -s $file;
2525 close FH;
2526 return $txt;
2527 }
2528
2529 sub process_simple {
2530 my $self = shift;
2531 my $in = shift || die "Missing input";
2532 my $swap = shift || die "Missing variable hash";
2533 my $out = shift || die "Missing output string ref";
2534
2535 eval {
2536 delete $self->{'_debug_off'};
2537 delete $self->{'_debug_format'};
2538 local $self->{'_start_top_level'} = 1;
2539 $self->_process($in, $swap, $out);
2540 };
2541 if (my $err = $@) {
2542 if ($err->type !~ /stop|return|next|last|break/) {
2543 $self->{'error'} = $err;
2544 return;
2545 }
2546 }
2547 return 1;
2548 }
2549
2550 sub process {
2551 my ($self, $in, $swap, $out, @ARGS) = @_;
2552 delete $self->{'error'};
2553
2554 my $args;
2555 $args = ($#ARGS == 0 && UNIVERSAL::isa($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2556 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2557
2558 ### get the content
2559 my $content;
2560 if (ref $in) {
2561 if (UNIVERSAL::isa($in, 'SCALAR')) { # reference to a string
2562 $content = $in;
2563 } elsif (UNIVERSAL::isa($in, 'CODE')) {
2564 $content = $in->();
2565 $content = \$content;
2566 } else { # should be a file handle
2567 local $/ = undef;
2568 $content = <$in>;
2569 $content = \$content;
2570 }
2571 } else {
2572 ### should be a filename
2573 $content = $in;
2574 }
2575
2576
2577 ### prepare block localization
2578 my $blocks = $self->{'BLOCKS'} ||= {};
2579
2580
2581 ### do the swap
2582 my $output = '';
2583 eval {
2584
2585 ### localize the stash
2586 $swap ||= {};
2587 my $var1 = $self->{'_vars'} ||= {};
2588 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2589 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2590 my $copy = {%$var2, %$var1, %$swap};
2591 local $copy->{'template'};
2592
2593 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2594
2595 delete $self->{'_debug_off'};
2596 delete $self->{'_debug_format'};
2597
2598 ### handle pre process items that go before every document
2599 if ($self->{'PRE_PROCESS'}) {
2600 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2601 my $out = '';
2602 $self->_process($name, $copy, \$out);
2603 $output = $out . $output;
2604 }
2605 }
2606
2607 ### handle the process config - which loads a template in place of the real one
2608 if (exists $self->{'PROCESS'}) {
2609 ### load the meta data for the top document
2610 my $doc = $self->load_parsed_tree($content) || {};
2611 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2612 ? $doc->{'_tree'}->[0]->[3] : {};
2613
2614 $copy->{'template'} = $doc;
2615 @{ $doc }{keys %$meta} = values %$meta;
2616
2617 ### process any other templates
2618 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2619 next if ! length $name;
2620 $self->_process($name, $copy, \$output);
2621 }
2622
2623 ### handle "normal" content
2624 } else {
2625 local $self->{'_start_top_level'} = 1;
2626 $self->_process($content, $copy, \$output);
2627 }
2628
2629
2630 ### handle post process items that go after every document
2631 if ($self->{'POST_PROCESS'}) {
2632 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2633 $self->_process($name, $copy, \$output);
2634 }
2635 }
2636
2637 };
2638 if (my $err = $@) {
2639 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2640 if ($err->type !~ /stop|return|next|last|break/) {
2641 $self->{'error'} = $err;
2642 return;
2643 }
2644 }
2645
2646
2647
2648 ### clear blocks as asked (AUTO_RESET) defaults to on
2649 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2650
2651 ### send the content back out
2652 $out ||= $self->{'OUTPUT'};
2653 if (ref $out) {
2654 if (UNIVERSAL::isa($out, 'CODE')) {
2655 $out->($output);
2656 } elsif (UNIVERSAL::can($out, 'print')) {
2657 $out->print($output);
2658 } elsif (UNIVERSAL::isa($out, 'SCALAR')) { # reference to a string
2659 $$out = $output;
2660 } elsif (UNIVERSAL::isa($out, 'ARRAY')) {
2661 push @$out, $output;
2662 } else { # should be a file handle
2663 print $out $output;
2664 }
2665 } elsif ($out) { # should be a filename
2666 my $file;
2667 if ($out =~ m|^/|) {
2668 if (! $self->{'ABSOLUTE'}) {
2669 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2670 } else {
2671 $file = $out;
2672 }
2673 } elsif ($out =~ m|^\.\.?/|) {
2674 if (! $self->{'RELATIVE'}) {
2675 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2676 } else {
2677 $file = $out;
2678 }
2679 } else {
2680 if (! $self->{'OUTPUT_PATH'}) {
2681 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2682 } else {
2683 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2684 }
2685 }
2686 if ($file) {
2687 local *FH;
2688 if (open FH, ">$file") {
2689 if (my $bm = $args->{'binmode'}) {
2690 if (+$bm == 1) { binmode FH }
2691 else { binmode FH, $bm }
2692 }
2693 print FH $output;
2694 close FH;
2695 } else {
2696 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2697 }
2698 }
2699 } else {
2700 print $output;
2701 }
2702
2703 return if $self->{'error'};
2704 return 1;
2705 }
2706
2707 sub error { shift->{'error'} }
2708
2709 sub DEBUG {
2710 my $self = shift;
2711 print STDERR "DEBUG: ", @_;
2712 }
2713
2714 ###----------------------------------------------------------------###
2715
2716 sub exception {
2717 my ($self, $type, $info, $node) = @_;
2718 return $type if ref($type) =~ /Template::Exception$/;
2719 if (ref($info) eq 'ARRAY') {
2720 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2721 if (@$info >= 2 || scalar keys %$hash) {
2722 my $i = 0;
2723 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2724 $hash->{'args'} = $info;
2725 $info = $hash;
2726 } elsif (@$info == 1) {
2727 $info = $info->[0];
2728 } else {
2729 $info = $type;
2730 $type = 'undef';
2731 }
2732 }
2733 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2734 }
2735
2736 sub throw { die shift->exception(@_) }
2737
2738 sub context {
2739 my $self = shift;
2740 return bless {_template => $self}, $PACKAGE_CONTEXT; # a fake context
2741 }
2742
2743 sub undefined_get {
2744 my ($self, $ident, $node) = @_;
2745 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2746 return '';
2747 }
2748
2749 sub undefined_any {
2750 my ($self, $ident) = @_;
2751 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2752 return;
2753 }
2754
2755 sub list_filters {
2756 my $self = shift;
2757 return $self->{'_filters'} ||= eval { require Template::Filters; $Template::Filters::FILTERS } || {};
2758 }
2759
2760 sub list_plugins {
2761 my $self = shift;
2762 my $args = shift || {};
2763 my $base = $args->{'base'} || '';
2764
2765 return $self->{'_plugins'}->{$base} ||= do {
2766 my @plugins;
2767
2768 $base =~ s|::|/|g;
2769 my @dirs = grep {-d $_} map {"$_/$base"} @INC;
2770
2771 foreach my $dir (@dirs) {
2772 require File::Find;
2773 File::Find::find(sub {
2774 my $mod = $base .'/'. ($File::Find::name =~ m|^ $dir / (.*\w) \.pm $|x ? $1 : return);
2775 $mod =~ s|/|::|g;
2776 push @plugins, $mod;
2777 }, $dir);
2778 }
2779
2780 \@plugins; # return of the do
2781 };
2782 }
2783
2784 sub debug_node {
2785 my ($self, $node) = @_;
2786 my $info = $self->node_info($node);
2787 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2788 $format =~ s{\$(file|line|text)}{$info->{$1}}g;
2789 return $format;
2790 }
2791
2792 sub node_info {
2793 my ($self, $node) = @_;
2794 my $doc = $self->{'_vars'}->{'component'};
2795 my $i = $node->[1];
2796 my $j = $node->[2] || return ''; # METADEF can be 0
2797 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \$s };
2798 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2799 $s =~ s/^\s+//;
2800 $s =~ s/\s+$//;
2801 return {
2802 file => $doc->{'name'},
2803 line => $self->get_line_number_by_index($doc, $i),
2804 text => $s,
2805 };
2806 }
2807
2808 sub get_line_number_by_index {
2809 my ($self, $doc, $index) = @_;
2810 ### get the line offsets for the doc
2811 my $lines = $doc->{'line_offsets'} ||= do {
2812 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \$s };
2813 my $i = 0;
2814 my @lines = (0);
2815 while (1) {
2816 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2817 last if $i == 0;
2818 push @lines, $i;
2819 }
2820 \@lines;
2821 };
2822 ### binary search them (this is fast even on big docs)
2823 return $#$lines + 1 if $index > $lines->[-1];
2824 my ($i, $j) = (0, $#$lines);
2825 while (1) {
2826 return $i + 1 if abs($i - $j) <= 1;
2827 my $k = int(($i + $j) / 2);
2828 $j = $k if $lines->[$k] >= $index;
2829 $i = $k if $lines->[$k] <= $index;
2830 }
2831 }
2832
2833 ###----------------------------------------------------------------###
2834 ### long virtual methods or filters
2835 ### many of these vmethods have used code from Template/Stash.pm to
2836 ### assure conformance with the TT spec.
2837
2838 sub define_vmethod {
2839 my ($self, $type, $name, $sub) = @_;
2840 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2841 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2842 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2843 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2844 else {
2845 die "Invalid type vmethod type $type";
2846 }
2847 return 1;
2848 }
2849
2850 sub vmethod_as_scalar {
2851 my ($str, $pat) = @_;
2852 $pat = '%s' if ! defined $pat;
2853 local $^W;
2854 return sprintf $pat, $str;
2855 }
2856
2857 sub vmethod_as_list {
2858 my ($ref, $pat, $sep) = @_;
2859 $pat = '%s' if ! defined $pat;
2860 $sep = ' ' if ! defined $sep;
2861 local $^W;
2862 return join($sep, map {sprintf $pat, $_} @$ref);
2863 }
2864
2865 sub vmethod_as_hash {
2866 my ($ref, $pat, $sep) = @_;
2867 $pat = "%s\t%s" if ! defined $pat;
2868 $sep = "\n" if ! defined $sep;
2869 local $^W;
2870 return join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref);
2871 }
2872
2873 sub vmethod_chunk {
2874 my $str = shift;
2875 my $size = shift || 1;
2876 my @list;
2877 if ($size < 0) { # chunk from the opposite end
2878 $str = reverse $str;
2879 $size = -$size;
2880 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2881 } else {
2882 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2883 }
2884 return \@list;
2885 }
2886
2887 sub vmethod_indent {
2888 my $str = shift; $str = '' if ! defined $str;
2889 my $pre = shift; $pre = 4 if ! defined $pre;
2890 $pre = ' ' x $pre if $pre =~ /^\d+$/;
2891 $str =~ s/^/$pre/mg;
2892 return $str;
2893 }
2894
2895 sub vmethod_format {
2896 my $str = shift; $str = '' if ! defined $str;
2897 my $pat = shift; $pat = '%s' if ! defined $pat;
2898 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2899 }
2900
2901 sub vmethod_match {
2902 my ($str, $pat, $global) = @_;
2903 return [] if ! defined $str || ! defined $pat;
2904 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2905 return (@res >= 2) ? \@res : (@res == 1) ? $res[0] : '';
2906 }
2907
2908 sub vmethod_nsort {
2909 my ($list, $field) = @_;
2910 return defined($field)
2911 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2912 : UNIVERSAL::can($_, $field) ? $_->$field()
2913 : $_)]} @$list ]
2914 : [sort {$a <=> $b} @$list];
2915 }
2916
2917 sub vmethod_repeat {
2918 my ($str, $n, $join) = @_;
2919 return if ! length $str;
2920 $n = 1 if ! defined($n) || ! length $n;
2921 $join = '' if ! defined $join;
2922 return join $join, ($str) x $n;
2923 }
2924
2925 ### This method is a combination of my submissions along
2926 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2927 sub vmethod_replace {
2928 my ($text, $pattern, $replace, $global) = @_;
2929 $text = '' unless defined $text;
2930 $pattern = '' unless defined $pattern;
2931 $replace = '' unless defined $replace;
2932 $global = 1 unless defined $global;
2933 my $expand = sub {
2934 my ($chunk, $start, $end) = @_;
2935 $chunk =~ s{ \\(\\|\$) | \$ (\d+) }{
2936 $1 ? $1
2937 : ($2 > $#$start || $2 == 0) ? ''
2938 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2939 }exg;
2940 $chunk;
2941 };
2942 if ($global) {
2943 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2944 } else {
2945 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2946 }
2947 return $text;
2948 }
2949
2950 sub vmethod_sort {
2951 my ($list, $field) = @_;
2952 return defined($field)
2953 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2954 : UNIVERSAL::can($_, $field) ? $_->$field()
2955 : $_)]} @$list ]
2956 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2957 }
2958
2959 sub vmethod_splice {
2960 my ($ref, $i, $len, @replace) = @_;
2961 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2962 if (defined $len) {
2963 return [splice @$ref, $i || 0, $len, @replace];
2964 } else {
2965 return [splice @$ref, $i || 0];
2966 }
2967 }
2968
2969 sub vmethod_split {
2970 my ($str, $pat, @args) = @_;
2971 $str = '' if ! defined $str;
2972 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2973 }
2974
2975 sub vmethod_uri {
2976 my $str = shift;
2977 utf8::encode($str) if defined &utf8::encode;
2978 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2979 return $str;
2980 }
2981
2982 sub filter_eval {
2983 my $context = shift;
2984 return sub {
2985 my $text = shift;
2986 return $context->process(\$text);
2987 };
2988 }
2989
2990 sub filter_redirect {
2991 my ($context, $file, $options) = @_;
2992 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
2993 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
2994 if $file =~ m{(^|/)\.\./};
2995
2996 return sub {
2997 my $text = shift;
2998 if (! -d $path) {
2999 require File::Path;
3000 File::Path::mkpath($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3001 }
3002 local *FH;
3003 open (FH, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3004 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3005 if (+$bm == 1) { binmode FH }
3006 else { binmode FH, $bm}
3007 }
3008 print FH $text;
3009 close FH;
3010 return '';
3011 };
3012 }
3013
3014 ###----------------------------------------------------------------###
3015
3016 sub dump_parse {
3017 my $obj = UNIVERSAL::isa($_[0], __PACKAGE__) ? shift : __PACKAGE__->new;
3018 my $str = shift;
3019 require Data::Dumper;
3020 return Data::Dumper::Dumper($obj->parse_expr(\$str));
3021 }
3022
3023 ###----------------------------------------------------------------###
3024
3025 package CGI::Ex::Template::Exception;
3026
3027 use overload
3028 '""' => \&as_string,
3029 bool => sub { defined shift },
3030 fallback => 1;
3031
3032 sub new {
3033 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3034 return bless [$type, $info, $node, $pos, $str_ref], $class;
3035 }
3036
3037 sub type { shift->[0] }
3038
3039 sub info { shift->[1] }
3040
3041 sub node {
3042 my $self = shift;
3043 $self->[2] = shift if $#_ == 0;
3044 $self->[2];
3045 }
3046
3047 sub offset { shift->[3] || 0 }
3048
3049 sub doc {
3050 my $self = shift;
3051 $self->[4] = shift if $#_ == 0;
3052 $self->[4];
3053 }
3054
3055 sub as_string {
3056 my $self = shift;
3057 my $msg = $self->type .' error - '. $self->info;
3058 if (my $node = $self->node) {
3059 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3060 }
3061 return $msg;
3062 }
3063
3064 ###----------------------------------------------------------------###
3065
3066 package CGI::Ex::Template::Iterator;
3067
3068 sub new {
3069 my ($class, $items) = @_;
3070 $items = [] if ! defined $items;
3071 if (UNIVERSAL::isa($items, 'HASH')) {
3072 $items = [ map { {key => $_, value => $items->{ $_ }} } sort keys %$items ];
3073 } elsif (UNIVERSAL::can($items, 'as_list')) {
3074 $items = $items->as_list;
3075 } elsif (! UNIVERSAL::isa($items, 'ARRAY')) {
3076 $items = [$items];
3077 }
3078 return bless [$items, 0], $class;
3079 }
3080
3081 sub get_first {
3082 my $self = shift;
3083 return (undef, 3) if ! @{ $self->[0] };
3084 return ($self->[0]->[$self->[1] = 0], undef);
3085 }
3086
3087 sub get_next {
3088 my $self = shift;
3089 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3090 return ($self->items->[$self->[1]], undef);
3091 }
3092
3093 sub items { shift->[0] }
3094
3095 sub index { shift->[1] }
3096
3097 sub max { $#{ shift->[0] } }
3098
3099 sub size { shift->max + 1 }
3100
3101 sub count { shift->index + 1 }
3102
3103 sub number { shift->index + 1 }
3104
3105 sub first { (shift->index == 0) || 0 }
3106
3107 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3108
3109 sub prev {
3110 my $self = shift;
3111 return undef if $self->index <= 0;
3112 return $self->items->[$self->index - 1];
3113 }
3114
3115 sub next {
3116 my $self = shift;
3117 return undef if $self->index >= $self->max;
3118 return $self->items->[$self->index + 1];
3119 }
3120
3121 ###----------------------------------------------------------------###
3122
3123 package CGI::Ex::Template::_Context;
3124
3125 use vars qw($AUTOLOAD);
3126
3127 sub _template { shift->{'_template'} || die "Missing _template" }
3128
3129 sub config { shift->_template }
3130
3131 sub stash {
3132 my $self = shift;
3133 return $self->{'stash'} ||= bless {_template => $self->_template}, $CGI::Ex::Template::PACKAGE_STASH;
3134 }
3135
3136 sub insert { shift->_template->_insert(@_) }
3137
3138 sub eval_perl { shift->_template->{'EVAL_PERL'} }
3139
3140 sub process {
3141 my $self = shift;
3142 my $ref = shift;
3143 my $vars = $self->_template->_vars;
3144 my $out = '';
3145 $self->_template->_process($ref, $vars, \$out);
3146 return $out;
3147 }
3148
3149 sub include {
3150 my $self = shift;
3151 my $file = shift;
3152 my $args = shift || {};
3153
3154 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3155
3156 my $out = ''; # have temp item to allow clear to correctly clear
3157 eval { $self->_template->_process($file, $self->{'_vars'}, \$out) };
3158 if (my $err = $@) {
3159 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3160 }
3161
3162 return $out;
3163 }
3164
3165 sub define_filter {
3166 my ($self, $name, $filter, $is_dynamic) = @_;
3167 $filter = [ $filter, 1 ] if $is_dynamic;
3168 $self->define_vmethod('filter', $name, $filter);
3169 }
3170
3171 sub filter {
3172 my ($self, $name, $args, $alias) = @_;
3173 my $t = $self->_template;
3174
3175 my $filter;
3176 if (! ref $name) {
3177 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex::Template::FILTER_OPS->{$name} || $CGI::Ex::Template::SCALAR_OPS->{$name};
3178 $t->throw('filter', $name) if ! $filter;
3179 } elsif (UNIVERSAL::isa($name, 'CODE') || UNIVERSAL::isa($name, 'ARRAY')) {
3180 $filter = $name;
3181 } elsif (UNIVERSAL::can($name, 'factory')) {
3182 $filter = $name->factory || $t->throw($name->error);
3183 } else {
3184 $t->throw('undef', "$name: filter not found");
3185 }
3186
3187 if (UNIVERSAL::isa($filter, 'ARRAY')) {
3188 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3189 } elsif ($args && @$args) {
3190 my $sub = $filter;
3191 $filter = sub { $sub->(shift, @$args) };
3192 }
3193
3194 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3195
3196 return $filter;
3197 }
3198
3199 sub define_vmethod { shift->_template->define_vmethod(@_) }
3200
3201 sub throw {
3202 my ($self, $type, $info) = @_;
3203
3204 if (UNIVERSAL::isa($type, $CGI::Ex::Template::PACKAGE_EXCEPTION)) {
3205 die $type;
3206 } elsif (defined $info) {
3207 $self->_template->throw($type, $info);
3208 } else {
3209 $self->_template->throw('undef', $type);
3210 }
3211 }
3212
3213 sub AUTOLOAD { shift->_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3214
3215 sub DESTROY {}
3216
3217 ###----------------------------------------------------------------###
3218
3219 package CGI::Ex::Template::_Stash;
3220
3221 use vars qw($AUTOLOAD);
3222
3223 sub _template { shift->{'_template'} || die "Missing _template" }
3224
3225 sub get {
3226 my ($self, $var) = @_;
3227 if (! ref $var) {
3228 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3229 else { $var = $self->_template->parse_expr(\$var, {no_dots => 1}) }
3230 }
3231 return $self->_template->play_expr($var, {no_dots => 1});
3232 }
3233
3234 sub set {
3235 my ($self, $var, $val) = @_;
3236 if (! ref $var) {
3237 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3238 else { $var = $self->_template->parse_expr(\$var, {no_dots => 1}) }
3239 }
3240 $self->_template->set_variable($var, $val, {no_dots => 1});
3241 return $val;
3242 }
3243
3244 sub AUTOLOAD { shift->_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3245
3246 sub DESTROY {}
3247
3248 ###----------------------------------------------------------------###
3249
3250 package CGI::Ex::Template::EvalPerlHandle;
3251
3252 sub TIEHANDLE {
3253 my ($class, $out_ref) = @_;
3254 return bless [$out_ref], $class;
3255 }
3256
3257 sub PRINT {
3258 my $self = shift;
3259 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3260 return 1;
3261 }
3262
3263 ###----------------------------------------------------------------###
3264
3265 1;
3266
3267 ### See the perldoc in CGI/Ex/Template.pod
This page took 0.292716 seconds and 4 git commands to generate.