]> Dogcows Code - chaz/p5-CGI-Ex/blob - lib/CGI/Ex/Template.pm
CGI::Ex 2.08
[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 2007 - 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.08';
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 local $Data::Dumper::Sortkeys = 1;
1682 my $info = $self->node_info($node);
1683 my $out;
1684 my $var;
1685 if ($ident) {
1686 $out = Data::Dumper::Dumper($self->play_expr($ident));
1687 $var = $info->{'text'};
1688 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1689 $var =~ s/\s*[+\-~=]?$//;
1690 } else {
1691 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1692 local @{ $self->{'_vars'} }{ @were_never_here };
1693 delete @{ $self->{'_vars'} }{ @were_never_here };
1694 $out = Data::Dumper::Dumper($self->{'_vars'});
1695 $var = 'EntireStash';
1696 }
1697 if ($ENV{'REQUEST_METHOD'}) {
1698 $out =~ s/</&lt;/g;
1699 $out = "<pre>$out</pre>";
1700 $out =~ s/\$VAR1/$var/;
1701 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1702 } else {
1703 $out =~ s/\$VAR1/$var/;
1704 }
1705
1706 return $out;
1707 }
1708
1709 sub parse_FILTER {
1710 my ($self, $tag_ref) = @_;
1711 my $name = '';
1712 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1713 $name = $1;
1714 }
1715
1716 my $filter = $self->parse_expr($tag_ref);
1717 $filter = '' if ! defined $filter;
1718
1719 return [$name, $filter];
1720 }
1721
1722 sub play_FILTER {
1723 my ($self, $ref, $node, $out_ref) = @_;
1724 my ($name, $filter) = @$ref;
1725
1726 return '' if ! @$filter;
1727
1728 $self->{'FILTERS'}->{$name} = $filter if length $name;
1729
1730 my $sub_tree = $node->[4];
1731
1732 ### play the block
1733 my $out = '';
1734 eval { $self->execute_tree($sub_tree, \$out) };
1735 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1736
1737 my $var = [\$out, 0, '|', @$filter]; # make a temporary var out of it
1738
1739
1740 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1741 }
1742
1743 sub parse_FOREACH {
1744 my ($self, $tag_ref) = @_;
1745 my $items = $self->parse_expr($tag_ref);
1746 my $var;
1747 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1748 $var = [@$items];
1749 $items = $self->parse_expr($tag_ref);
1750 }
1751 return [$var, $items];
1752 }
1753
1754 sub play_FOREACH {
1755 my ($self, $ref, $node, $out_ref) = @_;
1756
1757 ### get the items - make sure it is an arrayref
1758 my ($var, $items) = @$ref;
1759
1760 $items = $self->play_expr($items);
1761 return '' if ! defined $items;
1762
1763 if (ref($items) !~ /Iterator$/) {
1764 $items = $PACKAGE_ITERATOR->new($items);
1765 }
1766
1767 my $sub_tree = $node->[4];
1768
1769 local $self->{'_vars'}->{'loop'} = $items;
1770
1771 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1772 if (defined $var) {
1773 my ($item, $error) = $items->get_first;
1774 while (! $error) {
1775
1776 $self->set_variable($var, $item);
1777
1778 ### execute the sub tree
1779 eval { $self->execute_tree($sub_tree, $out_ref) };
1780 if (my $err = $@) {
1781 if (UNIVERSAL::isa($err, $PACKAGE_EXCEPTION)) {
1782 if ($err->type eq 'next') {
1783 ($item, $error) = $items->get_next;
1784 next;
1785 }
1786 last if $err->type =~ /last|break/;
1787 }
1788 die $err;
1789 }
1790
1791 ($item, $error) = $items->get_next;
1792 }
1793 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1794 ### if the FOREACH tag doesn't set a var - then everything gets localized
1795 } else {
1796
1797 ### localize variable access for the foreach
1798 my $swap = $self->{'_vars'};
1799 local $self->{'_vars'} = my $copy = {%$swap};
1800
1801 ### iterate use the iterator object
1802 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1803 my ($item, $error) = $items->get_first;
1804 while (! $error) {
1805
1806 if (ref($item) eq 'HASH') {
1807 @$copy{keys %$item} = values %$item;
1808 }
1809
1810 ### execute the sub tree
1811 eval { $self->execute_tree($sub_tree, $out_ref) };
1812 if (my $err = $@) {
1813 if (UNIVERSAL::isa($err, $PACKAGE_EXCEPTION)) {
1814 if ($err->type eq 'next') {
1815 ($item, $error) = $items->get_next;
1816 next;
1817 }
1818 last if $err->type =~ /last|break/;
1819 }
1820 die $err;
1821 }
1822
1823 ($item, $error) = $items->get_next;
1824 }
1825 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1826 }
1827
1828 return undef;
1829 }
1830
1831 sub parse_GET {
1832 my ($self, $tag_ref) = @_;
1833 my $ref = $self->parse_expr($tag_ref);
1834 $self->throw('parse', "Missing variable name") if ! defined $ref;
1835 return $ref;
1836 }
1837
1838 sub play_GET {
1839 my ($self, $ident, $node) = @_;
1840 my $var = $self->play_expr($ident);
1841 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1842 }
1843
1844 sub parse_IF {
1845 my ($self, $tag_ref) = @_;
1846 return $self->parse_expr($tag_ref);
1847 }
1848
1849 sub play_IF {
1850 my ($self, $var, $node, $out_ref) = @_;
1851
1852 my $val = $self->play_expr($var);
1853 if ($val) {
1854 my $body_ref = $node->[4] ||= [];
1855 $self->execute_tree($body_ref, $out_ref);
1856 return;
1857 }
1858
1859 while ($node = $node->[5]) { # ELSE, ELSIF's
1860 if ($node->[0] eq 'ELSE') {
1861 my $body_ref = $node->[4] ||= [];
1862 $self->execute_tree($body_ref, $out_ref);
1863 return;
1864 }
1865 my $var = $node->[3];
1866 my $val = $self->play_expr($var);
1867 if ($val) {
1868 my $body_ref = $node->[4] ||= [];
1869 $self->execute_tree($body_ref, $out_ref);
1870 return;
1871 }
1872 }
1873 return;
1874 }
1875
1876 sub parse_INCLUDE { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1877
1878 sub play_INCLUDE {
1879 my ($self, $tag_ref, $node, $out_ref) = @_;
1880
1881 ### localize the swap
1882 my $swap = $self->{'_vars'};
1883 local $self->{'_vars'} = {%$swap};
1884
1885 ### localize the blocks
1886 my $blocks = $self->{'BLOCKS'};
1887 local $self->{'BLOCKS'} = {%$blocks};
1888
1889 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1890
1891 return $str;
1892 }
1893
1894 sub parse_INSERT { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1895
1896 sub play_INSERT {
1897 my ($self, $var, $node, $out_ref) = @_;
1898 my ($names, $args) = @$var;
1899
1900 foreach my $name (@$names) {
1901 my $filename = $self->play_expr($name);
1902 $$out_ref .= $self->_insert($filename);
1903 }
1904
1905 return;
1906 }
1907
1908 sub parse_MACRO {
1909 my ($self, $tag_ref, $node) = @_;
1910 my $copy = $$tag_ref;
1911
1912 my $name = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1913 $self->throw('parse', "Missing macro name") if ! defined $name;
1914 if (! ref $name) {
1915 $name = [ $name, 0 ];
1916 }
1917
1918 my $args;
1919 if ($copy =~ s{ ^ \( \s* }{}x) {
1920 $args = $self->parse_args(\$copy, {positional_only => 1});
1921 $copy =~ s { ^ \) \s* }{}x || $self->throw('parse.missing', "Missing close ')'");
1922 }
1923
1924 $node->[6] = 1; # set a flag to keep parsing
1925 $$tag_ref = $copy;
1926 return [$name, $args];
1927 }
1928
1929 sub play_MACRO {
1930 my ($self, $ref, $node, $out_ref) = @_;
1931 my ($name, $args) = @$ref;
1932
1933 ### get the sub tree
1934 my $sub_tree = $node->[4];
1935 if (! $sub_tree || ! $sub_tree->[0]) {
1936 $self->set_variable($name, undef);
1937 return;
1938 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1939 $sub_tree = $sub_tree->[0]->[4];
1940 }
1941
1942 my $self_copy = $self;
1943 eval {require Scalar::Util; Scalar::Util::weaken($self_copy)};
1944
1945 ### install a closure in the stash that will handle the macro
1946 $self->set_variable($name, sub {
1947 ### macros localize
1948 my $copy = $self_copy->{'_vars'};
1949 local $self_copy->{'_vars'}= {%$copy};
1950
1951 ### set arguments
1952 my $named = pop(@_) if $_[-1] && UNIVERSAL::isa($_[-1],'HASH') && $#_ > $#$args;
1953 my @positional = @_;
1954 foreach my $var (@$args) {
1955 $self_copy->set_variable($var, shift(@positional));
1956 }
1957 foreach my $name (sort keys %$named) {
1958 $self_copy->set_variable([$name, 0], $named->{$name});
1959 }
1960
1961 ### finally - run the sub tree
1962 my $out = '';
1963 $self_copy->execute_tree($sub_tree, \$out);
1964 return $out;
1965 });
1966
1967 return;
1968 }
1969
1970 sub play_METADEF {
1971 my ($self, $hash) = @_;
1972 my $ref;
1973 if ($self->{'_top_level'}) {
1974 $ref = $self->{'_vars'}->{'template'} ||= {};
1975 } else {
1976 $ref = $self->{'_vars'}->{'component'} ||= {};
1977 }
1978 foreach my $key (keys %$hash) {
1979 next if $key eq 'name' || $key eq 'modtime';
1980 $ref->{$key} = $hash->{$key};
1981 }
1982 return;
1983 }
1984
1985 sub parse_PERL { shift->{'_in_perl'} = 1; return }
1986
1987 sub play_PERL {
1988 my ($self, $info, $node, $out_ref) = @_;
1989 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1990
1991 ### fill in any variables
1992 my $perl = $node->[4] || return;
1993 my $out = '';
1994 $self->execute_tree($perl, \$out);
1995 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
1996
1997 ### try the code
1998 my $err;
1999 eval {
2000 package CGI::Ex::Template::Perl;
2001
2002 my $context = $self->context;
2003 my $stash = $context->stash;
2004
2005 ### setup a fake handle
2006 local *PERLOUT;
2007 tie *PERLOUT, $CGI::Ex::Template::PACKAGE_PERL_HANDLE, $out_ref;
2008 my $old_fh = select PERLOUT;
2009
2010 eval $out;
2011 $err = $@;
2012
2013 ### put the handle back
2014 select $old_fh;
2015
2016 };
2017 $err ||= $@;
2018
2019
2020 if ($err) {
2021 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2022 die $err;
2023 }
2024
2025 return;
2026 }
2027
2028 sub parse_PROCESS {
2029 my ($self, $tag_ref) = @_;
2030 my $info = [[], []];
2031 while (defined(my $filename = $self->parse_expr($tag_ref, {
2032 auto_quote => qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2033 }))) {
2034 push @{$info->[0]}, $filename;
2035 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2036 }
2037
2038 ### allow for post process variables
2039 while (length $$tag_ref) {
2040 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2041
2042 my $var = $self->parse_expr($tag_ref);
2043 last if ! defined $var;
2044 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2045 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2046 }
2047
2048 my $val = $self->parse_expr($tag_ref);
2049 push @{$info->[1]}, [$var, $val];
2050 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2051 }
2052
2053 return $info;
2054 }
2055
2056 sub play_PROCESS {
2057 my ($self, $info, $node, $out_ref) = @_;
2058
2059 my ($files, $args) = @$info;
2060
2061 ### set passed args
2062 foreach (@$args) {
2063 my ($key, $val) = @$_;
2064 $val = $self->play_expr($val);
2065 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL::isa($val, 'HASH')) { # import ?! - whatever
2066 foreach my $key (keys %$val) {
2067 $self->set_variable([$key,0], $val->{$key});
2068 }
2069 next;
2070 }
2071 $self->set_variable($key, $val);
2072 }
2073
2074 ### iterate on any passed block or filename
2075 foreach my $ref (@$files) {
2076 next if ! defined $ref;
2077 my $filename = $self->play_expr($ref);
2078 my $out = ''; # have temp item to allow clear to correctly clear
2079
2080 ### normal blocks or filenames
2081 if (! ref $filename) {
2082 eval { $self->_process($filename, $self->{'_vars'}, \$out) }; # restart the swap - passing it our current stash
2083
2084 ### allow for $template which is used in some odd instances
2085 } else {
2086 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2087 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2088 local $self->{'_process_dollar_template'} = 1;
2089 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2090 return if ! $doc->{'_tree'};
2091
2092 ### execute and trim
2093 eval { $self->execute_tree($doc->{'_tree'}, \$out) };
2094 if ($self->{'TRIM'}) {
2095 $out =~ s{ \s+ $ }{}x;
2096 $out =~ s{ ^ \s+ }{}x;
2097 }
2098
2099 ### handle exceptions
2100 if (my $err = $@) {
2101 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2102 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2103 }
2104
2105 }
2106
2107 ### append any output
2108 $$out_ref .= $out;
2109 if (my $err = $@) {
2110 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2111 }
2112 }
2113
2114 return;
2115 }
2116
2117 sub play_RAWPERL {
2118 my ($self, $info, $node, $out_ref) = @_;
2119 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2120
2121 ### fill in any variables
2122 my $tree = $node->[4] || return;
2123 my $perl = '';
2124 $self->execute_tree($tree, \$perl);
2125 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2126
2127 ### try the code
2128 my $err;
2129 my $output = '';
2130 eval {
2131 package CGI::Ex::Template::Perl;
2132
2133 my $context = $self->context;
2134 my $stash = $context->stash;
2135
2136 eval $perl;
2137 $err = $@;
2138 };
2139 $err ||= $@;
2140
2141 $$out_ref .= $output;
2142
2143 if ($err) {
2144 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2145 die $err;
2146 }
2147
2148 return;
2149 }
2150
2151 sub parse_SET {
2152 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2153 my @SET;
2154 my $copy = $$tag_ref;
2155 my $func;
2156
2157 if ($initial_op) {
2158 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2159 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2160 $node->[6] = 1; # set a flag to keep parsing
2161 my $val = $node->[4] ||= []; # setup storage
2162 return [[$initial_op, $initial_var, $val]];
2163 } else { # get a normal variable
2164 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2165 }
2166 }
2167
2168 while (length $$tag_ref) {
2169 my $set = $self->parse_expr($tag_ref);
2170 last if ! defined $set;
2171
2172 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2173 my $op = $1;
2174 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2175 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2176 $node->[6] = 1; # set a flag to keep parsing
2177 my $val = $node->[4] ||= []; # setup storage
2178 push @SET, [$op, $set, $val];
2179 last;
2180 } else { # get a normal variable
2181 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2182 }
2183 } else {
2184 push @SET, ['=', $set, undef];
2185 }
2186 }
2187 return \@SET;
2188 }
2189
2190 sub play_SET {
2191 my ($self, $set, $node) = @_;
2192 foreach (@$set) {
2193 my ($op, $set, $val) = @$_;
2194 if (! defined $val) { # not defined
2195 $val = '';
2196 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2197 my $sub_tree = $node->[4];
2198 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2199 $val = '';
2200 $self->execute_tree($sub_tree, \$val);
2201 } else { # normal var
2202 $val = $self->play_expr($val);
2203 }
2204
2205 if ($OP_DISPATCH->{$op}) {
2206 local $^W;
2207 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2208 }
2209
2210 $self->set_variable($set, $val);
2211 }
2212 return;
2213 }
2214
2215 sub parse_SWITCH { $DIRECTIVES->{'GET'}->[0]->(@_) }
2216
2217 sub play_SWITCH {
2218 my ($self, $var, $node, $out_ref) = @_;
2219
2220 my $val = $self->play_expr($var);
2221 $val = '' if ! defined $val;
2222 ### $node->[4] is thrown away
2223
2224 my $default;
2225 while ($node = $node->[5]) { # CASES
2226 my $var = $node->[3];
2227 if (! defined $var) {
2228 $default = $node->[4];
2229 next;
2230 }
2231
2232 my $val2 = $self->play_expr($var);
2233 $val2 = [$val2] if ! UNIVERSAL::isa($val2, 'ARRAY');
2234 for my $test (@$val2) { # find matching values
2235 next if ! defined $val && defined $test;
2236 next if defined $val && ! defined $test;
2237 if ($val ne $test) { # check string-wise first - then numerical
2238 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2239 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2240 next if $val != $test;
2241 }
2242
2243 my $body_ref = $node->[4] ||= [];
2244 $self->execute_tree($body_ref, $out_ref);
2245 return;
2246 }
2247 }
2248
2249 if ($default) {
2250 $self->execute_tree($default, $out_ref);
2251 }
2252
2253 return;
2254 }
2255
2256 sub parse_THROW {
2257 my ($self, $tag_ref, $node) = @_;
2258 my $name = $self->parse_expr($tag_ref, {auto_quote => qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2259 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2260 my $args = $self->parse_args($tag_ref);
2261 return [$name, $args];
2262 }
2263
2264 sub play_THROW {
2265 my ($self, $ref, $node) = @_;
2266 my ($name, $args) = @$ref;
2267 $name = $self->play_expr($name);
2268 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2269 $self->throw($name, \@args, $node);
2270 }
2271
2272 sub play_TRY {
2273 my ($self, $foo, $node, $out_ref) = @_;
2274 my $out = '';
2275
2276 my $body_ref = $node->[4];
2277 eval { $self->execute_tree($body_ref, \$out) };
2278 my $err = $@;
2279
2280 if (! $node->[5]) { # no catch or final
2281 if (! $err) { # no final block and no error
2282 $$out_ref .= $out;
2283 return;
2284 }
2285 $self->throw('parse.missing', "Missing CATCH block", $node);
2286 }
2287 if ($err) {
2288 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2289 if ($err->type =~ /stop|return/) {
2290 $$out_ref .= $out;
2291 die $err;
2292 }
2293 }
2294
2295 ### loop through the nested catch and final blocks
2296 my $catch_body_ref;
2297 my $last_found;
2298 my $type = $err ? $err->type : '';
2299 my $final;
2300 while ($node = $node->[5]) { # CATCH
2301 if ($node->[0] eq 'FINAL') {
2302 $final = $node->[4];
2303 next;
2304 }
2305 next if ! $err;
2306 my $name = $self->play_expr($node->[3]);
2307 $name = '' if ! defined $name || lc($name) eq 'default';
2308 if ($type =~ / ^ \Q$name\E \b /x
2309 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2310 $catch_body_ref = $node->[4] || [];
2311 $last_found = $name;
2312 }
2313 }
2314
2315 ### play the best catch block
2316 if ($err) {
2317 if (! $catch_body_ref) {
2318 $$out_ref .= $out;
2319 die $err;
2320 }
2321 local $self->{'_vars'}->{'error'} = $err;
2322 local $self->{'_vars'}->{'e'} = $err;
2323 eval { $self->execute_tree($catch_body_ref, \$out) };
2324 if (my $err = $@) {
2325 $$out_ref .= $out;
2326 die $err;
2327 }
2328 }
2329
2330 ### the final block
2331 $self->execute_tree($final, \$out) if $final;
2332
2333 $$out_ref .= $out;
2334
2335 return;
2336 }
2337
2338 sub parse_UNLESS {
2339 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2340 return [ \ [ '!', $ref ], 0 ];
2341 }
2342
2343 sub play_UNLESS { return $DIRECTIVES->{'IF'}->[1]->(@_) }
2344
2345 sub parse_USE {
2346 my ($self, $tag_ref) = @_;
2347
2348 my $var;
2349 my $copy = $$tag_ref;
2350 if (defined(my $_var = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2351 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2352 $var = $_var;
2353 $$tag_ref = $copy;
2354 }
2355
2356 $copy = $$tag_ref;
2357 my $module = $self->parse_expr(\$copy, {auto_quote => qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2358 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2359 $module =~ s/\./::/g;
2360
2361 my $args;
2362 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2363 $args = $self->parse_args(\$copy);
2364
2365 if ($open) {
2366 $copy =~ s { ^ \) \s* $QR_COMMENTS }{}ox || $self->throw('parse.missing', "Missing close ')'");
2367 }
2368
2369 $$tag_ref = $copy;
2370 return [$var, $module, $args];
2371 }
2372
2373 sub play_USE {
2374 my ($self, $ref, $node, $out_ref) = @_;
2375 my ($var, $module, $args) = @$ref;
2376
2377 ### get the stash storage location - default to the module
2378 $var = $module if ! defined $var;
2379 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2380 pop @var; # remove the trailing '.'
2381
2382 ### look for a plugin_base
2383 my $BASE = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2384 my $obj;
2385
2386 foreach my $base (ref($BASE) eq 'ARRAY' ? @$BASE : $BASE) {
2387 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2388 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2389 : "${base}::${module}";
2390 my $require = "$package.pm";
2391 $require =~ s|::|/|g;
2392
2393 ### try and load the module - fall back to bare module if allowed
2394 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2395 my $shape = $package->load;
2396 my $context = $self->context;
2397 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2398 $obj = $shape->new($context, @args);
2399 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2400 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2401 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base => $base}) }) {
2402 foreach my $package (@packages) {
2403 my $require = "$package.pm";
2404 $require =~ s|::|/|g;
2405 eval {require $require} || next;
2406 my $shape = $package->load;
2407 my $context = $self->context;
2408 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2409 $obj = $shape->new($context, @args);
2410 }
2411 } elsif ($self->{'LOAD_PERL'}) {
2412 my $require = "$module.pm";
2413 $require =~ s|::|/|g;
2414 if (eval {require $require}) {
2415 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2416 $obj = $module->new(@args);
2417 }
2418 }
2419 }
2420 if (! defined $obj) {
2421 my $err = "$module: plugin not found";
2422 $self->throw('plugin', $err);
2423 }
2424
2425 ### all good
2426 $self->set_variable(\@var, $obj);
2427
2428 return;
2429 }
2430
2431 sub play_WHILE {
2432 my ($self, $var, $node, $out_ref) = @_;
2433 return '' if ! defined $var;
2434
2435 my $sub_tree = $node->[4];
2436
2437 ### iterate use the iterator object
2438 my $count = $WHILE_MAX;
2439 while (--$count > 0) {
2440
2441 $self->play_expr($var) || last;
2442
2443 ### execute the sub tree
2444 eval { $self->execute_tree($sub_tree, $out_ref) };
2445 if (my $err = $@) {
2446 if (UNIVERSAL::isa($err, $PACKAGE_EXCEPTION)) {
2447 next if $err->type =~ /next/;
2448 last if $err->type =~ /last|break/;
2449 }
2450 die $err;
2451 }
2452 }
2453 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2454
2455 return undef;
2456 }
2457
2458 sub parse_WRAPPER { $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2459
2460 sub play_WRAPPER {
2461 my ($self, $var, $node, $out_ref) = @_;
2462 my $sub_tree = $node->[4] || return;
2463
2464 my ($names, $args) = @$var;
2465
2466 my $out = '';
2467 $self->execute_tree($sub_tree, \$out);
2468
2469 foreach my $name (reverse @$names) {
2470 local $self->{'_vars'}->{'content'} = $out;
2471 $out = '';
2472 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \$out);
2473 }
2474
2475 $$out_ref .= $out;
2476 return;
2477 }
2478
2479 ###----------------------------------------------------------------###
2480
2481 sub _vars {
2482 my $self = shift;
2483 $self->{'_vars'} = shift if $#_ == 0;
2484 return $self->{'_vars'} ||= {};
2485 }
2486
2487 sub include_filename {
2488 my ($self, $file) = @_;
2489 if ($file =~ m|^/|) {
2490 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2491 return $file if -e $file;
2492 } elsif ($file =~ m{(^|/)\.\./}) {
2493 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2494 return $file if -e $file;
2495 }
2496
2497 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2498 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2499 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2500 $paths = $paths->() if UNIVERSAL::isa($paths, 'CODE');
2501 $paths = $self->split_paths($paths) if ! UNIVERSAL::isa($paths, 'ARRAY');
2502 $paths; # return of the do
2503 };
2504 foreach my $path (@$paths) {
2505 return "$path/$file" if -e "$path/$file";
2506 }
2507
2508 $self->throw('file', "$file: not found");
2509 }
2510
2511 sub split_paths {
2512 my ($self, $path) = @_;
2513 return $path if ref $path;
2514 my $delim = $self->{'DELIMITER'} || ':';
2515 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr|:(?!/)| : qr|\Q$delim\E|;
2516 return [split $delim, $path];
2517 }
2518
2519 sub _insert {
2520 my ($self, $file) = @_;
2521 return $self->slurp($self->include_filename($file));
2522 }
2523
2524 sub slurp {
2525 my ($self, $file) = @_;
2526 local *FH;
2527 open(FH, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2528 read FH, my $txt, -s $file;
2529 close FH;
2530 return $txt;
2531 }
2532
2533 sub process_simple {
2534 my $self = shift;
2535 my $in = shift || die "Missing input";
2536 my $swap = shift || die "Missing variable hash";
2537 my $out = shift || die "Missing output string ref";
2538
2539 eval {
2540 delete $self->{'_debug_off'};
2541 delete $self->{'_debug_format'};
2542 local $self->{'_start_top_level'} = 1;
2543 $self->_process($in, $swap, $out);
2544 };
2545 if (my $err = $@) {
2546 if ($err->type !~ /stop|return|next|last|break/) {
2547 $self->{'error'} = $err;
2548 return;
2549 }
2550 }
2551 return 1;
2552 }
2553
2554 sub process {
2555 my ($self, $in, $swap, $out, @ARGS) = @_;
2556 delete $self->{'error'};
2557
2558 my $args;
2559 $args = ($#ARGS == 0 && UNIVERSAL::isa($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2560 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2561
2562 ### get the content
2563 my $content;
2564 if (ref $in) {
2565 if (UNIVERSAL::isa($in, 'SCALAR')) { # reference to a string
2566 $content = $in;
2567 } elsif (UNIVERSAL::isa($in, 'CODE')) {
2568 $content = $in->();
2569 $content = \$content;
2570 } else { # should be a file handle
2571 local $/ = undef;
2572 $content = <$in>;
2573 $content = \$content;
2574 }
2575 } else {
2576 ### should be a filename
2577 $content = $in;
2578 }
2579
2580
2581 ### prepare block localization
2582 my $blocks = $self->{'BLOCKS'} ||= {};
2583
2584
2585 ### do the swap
2586 my $output = '';
2587 eval {
2588
2589 ### localize the stash
2590 $swap ||= {};
2591 my $var1 = $self->{'_vars'} ||= {};
2592 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2593 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2594 my $copy = {%$var2, %$var1, %$swap};
2595 local $copy->{'template'};
2596
2597 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2598
2599 delete $self->{'_debug_off'};
2600 delete $self->{'_debug_format'};
2601
2602 ### handle pre process items that go before every document
2603 if ($self->{'PRE_PROCESS'}) {
2604 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2605 my $out = '';
2606 $self->_process($name, $copy, \$out);
2607 $output = $out . $output;
2608 }
2609 }
2610
2611 ### handle the process config - which loads a template in place of the real one
2612 if (exists $self->{'PROCESS'}) {
2613 ### load the meta data for the top document
2614 my $doc = $self->load_parsed_tree($content) || {};
2615 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2616 ? $doc->{'_tree'}->[0]->[3] : {};
2617
2618 $copy->{'template'} = $doc;
2619 @{ $doc }{keys %$meta} = values %$meta;
2620
2621 ### process any other templates
2622 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2623 next if ! length $name;
2624 $self->_process($name, $copy, \$output);
2625 }
2626
2627 ### handle "normal" content
2628 } else {
2629 local $self->{'_start_top_level'} = 1;
2630 $self->_process($content, $copy, \$output);
2631 }
2632
2633
2634 ### handle post process items that go after every document
2635 if ($self->{'POST_PROCESS'}) {
2636 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2637 $self->_process($name, $copy, \$output);
2638 }
2639 }
2640
2641 };
2642 if (my $err = $@) {
2643 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2644 if ($err->type !~ /stop|return|next|last|break/) {
2645 $self->{'error'} = $err;
2646 return;
2647 }
2648 }
2649
2650
2651
2652 ### clear blocks as asked (AUTO_RESET) defaults to on
2653 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2654
2655 ### send the content back out
2656 $out ||= $self->{'OUTPUT'};
2657 if (ref $out) {
2658 if (UNIVERSAL::isa($out, 'CODE')) {
2659 $out->($output);
2660 } elsif (UNIVERSAL::can($out, 'print')) {
2661 $out->print($output);
2662 } elsif (UNIVERSAL::isa($out, 'SCALAR')) { # reference to a string
2663 $$out = $output;
2664 } elsif (UNIVERSAL::isa($out, 'ARRAY')) {
2665 push @$out, $output;
2666 } else { # should be a file handle
2667 print $out $output;
2668 }
2669 } elsif ($out) { # should be a filename
2670 my $file;
2671 if ($out =~ m|^/|) {
2672 if (! $self->{'ABSOLUTE'}) {
2673 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2674 } else {
2675 $file = $out;
2676 }
2677 } elsif ($out =~ m|^\.\.?/|) {
2678 if (! $self->{'RELATIVE'}) {
2679 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2680 } else {
2681 $file = $out;
2682 }
2683 } else {
2684 if (! $self->{'OUTPUT_PATH'}) {
2685 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2686 } else {
2687 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2688 }
2689 }
2690 if ($file) {
2691 local *FH;
2692 if (open FH, ">$file") {
2693 if (my $bm = $args->{'binmode'}) {
2694 if (+$bm == 1) { binmode FH }
2695 else { binmode FH, $bm }
2696 }
2697 print FH $output;
2698 close FH;
2699 } else {
2700 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2701 }
2702 }
2703 } else {
2704 print $output;
2705 }
2706
2707 return if $self->{'error'};
2708 return 1;
2709 }
2710
2711 sub error { shift->{'error'} }
2712
2713 sub DEBUG {
2714 my $self = shift;
2715 print STDERR "DEBUG: ", @_;
2716 }
2717
2718 ###----------------------------------------------------------------###
2719
2720 sub exception {
2721 my ($self, $type, $info, $node) = @_;
2722 return $type if ref($type) =~ /Template::Exception$/;
2723 if (ref($info) eq 'ARRAY') {
2724 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2725 if (@$info >= 2 || scalar keys %$hash) {
2726 my $i = 0;
2727 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2728 $hash->{'args'} = $info;
2729 $info = $hash;
2730 } elsif (@$info == 1) {
2731 $info = $info->[0];
2732 } else {
2733 $info = $type;
2734 $type = 'undef';
2735 }
2736 }
2737 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2738 }
2739
2740 sub throw { die shift->exception(@_) }
2741
2742 sub context {
2743 my $self = shift;
2744 return bless {_template => $self}, $PACKAGE_CONTEXT; # a fake context
2745 }
2746
2747 sub undefined_get {
2748 my ($self, $ident, $node) = @_;
2749 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2750 return '';
2751 }
2752
2753 sub undefined_any {
2754 my ($self, $ident) = @_;
2755 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2756 return;
2757 }
2758
2759 sub list_filters {
2760 my $self = shift;
2761 return $self->{'_filters'} ||= eval { require Template::Filters; $Template::Filters::FILTERS } || {};
2762 }
2763
2764 sub list_plugins {
2765 my $self = shift;
2766 my $args = shift || {};
2767 my $base = $args->{'base'} || '';
2768
2769 return $self->{'_plugins'}->{$base} ||= do {
2770 my @plugins;
2771
2772 $base =~ s|::|/|g;
2773 my @dirs = grep {-d $_} map {"$_/$base"} @INC;
2774
2775 foreach my $dir (@dirs) {
2776 require File::Find;
2777 File::Find::find(sub {
2778 my $mod = $base .'/'. ($File::Find::name =~ m|^ $dir / (.*\w) \.pm $|x ? $1 : return);
2779 $mod =~ s|/|::|g;
2780 push @plugins, $mod;
2781 }, $dir);
2782 }
2783
2784 \@plugins; # return of the do
2785 };
2786 }
2787
2788 sub debug_node {
2789 my ($self, $node) = @_;
2790 my $info = $self->node_info($node);
2791 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2792 $format =~ s{\$(file|line|text)}{$info->{$1}}g;
2793 return $format;
2794 }
2795
2796 sub node_info {
2797 my ($self, $node) = @_;
2798 my $doc = $self->{'_vars'}->{'component'};
2799 my $i = $node->[1];
2800 my $j = $node->[2] || return ''; # METADEF can be 0
2801 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \$s };
2802 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2803 $s =~ s/^\s+//;
2804 $s =~ s/\s+$//;
2805 return {
2806 file => $doc->{'name'},
2807 line => $self->get_line_number_by_index($doc, $i),
2808 text => $s,
2809 };
2810 }
2811
2812 sub get_line_number_by_index {
2813 my ($self, $doc, $index) = @_;
2814 ### get the line offsets for the doc
2815 my $lines = $doc->{'line_offsets'} ||= do {
2816 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \$s };
2817 my $i = 0;
2818 my @lines = (0);
2819 while (1) {
2820 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2821 last if $i == 0;
2822 push @lines, $i;
2823 }
2824 \@lines;
2825 };
2826 ### binary search them (this is fast even on big docs)
2827 return $#$lines + 1 if $index > $lines->[-1];
2828 my ($i, $j) = (0, $#$lines);
2829 while (1) {
2830 return $i + 1 if abs($i - $j) <= 1;
2831 my $k = int(($i + $j) / 2);
2832 $j = $k if $lines->[$k] >= $index;
2833 $i = $k if $lines->[$k] <= $index;
2834 }
2835 }
2836
2837 ###----------------------------------------------------------------###
2838 ### long virtual methods or filters
2839 ### many of these vmethods have used code from Template/Stash.pm to
2840 ### assure conformance with the TT spec.
2841
2842 sub define_vmethod {
2843 my ($self, $type, $name, $sub) = @_;
2844 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2845 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2846 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2847 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2848 else {
2849 die "Invalid type vmethod type $type";
2850 }
2851 return 1;
2852 }
2853
2854 sub vmethod_as_scalar {
2855 my $str = shift; $str = '' if ! defined $str;
2856 my $pat = shift; $pat = '%s' if ! defined $pat;
2857 local $^W;
2858 return @_ ? sprintf($pat, $_[0], $str)
2859 : sprintf($pat, $str);
2860 }
2861
2862 sub vmethod_as_list {
2863 my $ref = shift || return '';
2864 my $pat = shift; $pat = '%s' if ! defined $pat;
2865 my $sep = shift; $sep = ' ' if ! defined $sep;
2866 local $^W;
2867 return @_ ? join($sep, map {sprintf $pat, $_[0], $_} @$ref)
2868 : join($sep, map {sprintf $pat, $_} @$ref);
2869 }
2870
2871 sub vmethod_as_hash {
2872 my $ref = shift || return '';
2873 my $pat = shift; $pat = "%s\t%s" if ! defined $pat;
2874 my $sep = shift; $sep = "\n" if ! defined $sep;
2875 local $^W;
2876 return ! @_ ? join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref)
2877 : @_ == 1 ? join($sep, map {sprintf $pat, $_[0], $_, $ref->{$_}} sort keys %$ref) # don't get to pick - it applies to the key
2878 : join($sep, map {sprintf $pat, $_[0], $_, $_[1], $ref->{$_}} sort keys %$ref);
2879 }
2880
2881 sub vmethod_chunk {
2882 my $str = shift;
2883 my $size = shift || 1;
2884 my @list;
2885 if ($size < 0) { # chunk from the opposite end
2886 $str = reverse $str;
2887 $size = -$size;
2888 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2889 } else {
2890 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2891 }
2892 return \@list;
2893 }
2894
2895 sub vmethod_indent {
2896 my $str = shift; $str = '' if ! defined $str;
2897 my $pre = shift; $pre = 4 if ! defined $pre;
2898 $pre = ' ' x $pre if $pre =~ /^\d+$/;
2899 $str =~ s/^/$pre/mg;
2900 return $str;
2901 }
2902
2903 sub vmethod_format {
2904 my $str = shift; $str = '' if ! defined $str;
2905 my $pat = shift; $pat = '%s' if ! defined $pat;
2906 if (@_) {
2907 return join "\n", map{ sprintf $pat, $_[0], $_ } split(/\n/, $str);
2908 } else {
2909 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2910 }
2911 }
2912
2913 sub vmethod_match {
2914 my ($str, $pat, $global) = @_;
2915 return [] if ! defined $str || ! defined $pat;
2916 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2917 return (@res >= 2) ? \@res : (@res == 1) ? $res[0] : '';
2918 }
2919
2920 sub vmethod_nsort {
2921 my ($list, $field) = @_;
2922 return defined($field)
2923 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2924 : UNIVERSAL::can($_, $field) ? $_->$field()
2925 : $_)]} @$list ]
2926 : [sort {$a <=> $b} @$list];
2927 }
2928
2929 sub vmethod_repeat {
2930 my ($str, $n, $join) = @_;
2931 return if ! length $str;
2932 $n = 1 if ! defined($n) || ! length $n;
2933 $join = '' if ! defined $join;
2934 return join $join, ($str) x $n;
2935 }
2936
2937 ### This method is a combination of my submissions along
2938 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2939 sub vmethod_replace {
2940 my ($text, $pattern, $replace, $global) = @_;
2941 $text = '' unless defined $text;
2942 $pattern = '' unless defined $pattern;
2943 $replace = '' unless defined $replace;
2944 $global = 1 unless defined $global;
2945 my $expand = sub {
2946 my ($chunk, $start, $end) = @_;
2947 $chunk =~ s{ \\(\\|\$) | \$ (\d+) }{
2948 $1 ? $1
2949 : ($2 > $#$start || $2 == 0) ? ''
2950 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2951 }exg;
2952 $chunk;
2953 };
2954 if ($global) {
2955 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2956 } else {
2957 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2958 }
2959 return $text;
2960 }
2961
2962 sub vmethod_sort {
2963 my ($list, $field) = @_;
2964 return defined($field)
2965 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2966 : UNIVERSAL::can($_, $field) ? $_->$field()
2967 : $_)]} @$list ]
2968 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2969 }
2970
2971 sub vmethod_splice {
2972 my ($ref, $i, $len, @replace) = @_;
2973 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2974 if (defined $len) {
2975 return [splice @$ref, $i || 0, $len, @replace];
2976 } else {
2977 return [splice @$ref, $i || 0];
2978 }
2979 }
2980
2981 sub vmethod_split {
2982 my ($str, $pat, @args) = @_;
2983 $str = '' if ! defined $str;
2984 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2985 }
2986
2987 sub vmethod_uri {
2988 my $str = shift;
2989 utf8::encode($str) if defined &utf8::encode;
2990 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2991 return $str;
2992 }
2993
2994 sub filter_eval {
2995 my $context = shift;
2996 return sub {
2997 my $text = shift;
2998 return $context->process(\$text);
2999 };
3000 }
3001
3002 sub filter_redirect {
3003 my ($context, $file, $options) = @_;
3004 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3005 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3006 if $file =~ m{(^|/)\.\./};
3007
3008 return sub {
3009 my $text = shift;
3010 if (! -d $path) {
3011 require File::Path;
3012 File::Path::mkpath($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3013 }
3014 local *FH;
3015 open (FH, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3016 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3017 if (+$bm == 1) { binmode FH }
3018 else { binmode FH, $bm}
3019 }
3020 print FH $text;
3021 close FH;
3022 return '';
3023 };
3024 }
3025
3026 ###----------------------------------------------------------------###
3027
3028 sub dump_parse {
3029 my $obj = UNIVERSAL::isa($_[0], __PACKAGE__) ? shift : __PACKAGE__->new;
3030 my $str = shift;
3031 require Data::Dumper;
3032 return Data::Dumper::Dumper($obj->parse_tree(\$str));
3033 }
3034
3035 sub dump_parse_expr {
3036 my $obj = UNIVERSAL::isa($_[0], __PACKAGE__) ? shift : __PACKAGE__->new;
3037 my $str = shift;
3038 require Data::Dumper;
3039 return Data::Dumper::Dumper($obj->parse_expr(\$str));
3040 }
3041
3042 ###----------------------------------------------------------------###
3043
3044 package CGI::Ex::Template::Exception;
3045
3046 use overload
3047 '""' => \&as_string,
3048 bool => sub { defined shift },
3049 fallback => 1;
3050
3051 sub new {
3052 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3053 return bless [$type, $info, $node, $pos, $str_ref], $class;
3054 }
3055
3056 sub type { shift->[0] }
3057
3058 sub info { shift->[1] }
3059
3060 sub node {
3061 my $self = shift;
3062 $self->[2] = shift if $#_ == 0;
3063 $self->[2];
3064 }
3065
3066 sub offset { shift->[3] || 0 }
3067
3068 sub doc {
3069 my $self = shift;
3070 $self->[4] = shift if $#_ == 0;
3071 $self->[4];
3072 }
3073
3074 sub as_string {
3075 my $self = shift;
3076 my $msg = $self->type .' error - '. $self->info;
3077 if (my $node = $self->node) {
3078 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3079 }
3080 return $msg;
3081 }
3082
3083 ###----------------------------------------------------------------###
3084
3085 package CGI::Ex::Template::Iterator;
3086
3087 sub new {
3088 my ($class, $items) = @_;
3089 $items = [] if ! defined $items;
3090 if (UNIVERSAL::isa($items, 'HASH')) {
3091 $items = [ map { {key => $_, value => $items->{ $_ }} } sort keys %$items ];
3092 } elsif (UNIVERSAL::can($items, 'as_list')) {
3093 $items = $items->as_list;
3094 } elsif (! UNIVERSAL::isa($items, 'ARRAY')) {
3095 $items = [$items];
3096 }
3097 return bless [$items, 0], $class;
3098 }
3099
3100 sub get_first {
3101 my $self = shift;
3102 return (undef, 3) if ! @{ $self->[0] };
3103 return ($self->[0]->[$self->[1] = 0], undef);
3104 }
3105
3106 sub get_next {
3107 my $self = shift;
3108 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3109 return ($self->items->[$self->[1]], undef);
3110 }
3111
3112 sub items { shift->[0] }
3113
3114 sub index { shift->[1] }
3115
3116 sub max { $#{ shift->[0] } }
3117
3118 sub size { shift->max + 1 }
3119
3120 sub count { shift->index + 1 }
3121
3122 sub number { shift->index + 1 }
3123
3124 sub first { (shift->index == 0) || 0 }
3125
3126 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3127
3128 sub prev {
3129 my $self = shift;
3130 return undef if $self->index <= 0;
3131 return $self->items->[$self->index - 1];
3132 }
3133
3134 sub next {
3135 my $self = shift;
3136 return undef if $self->index >= $self->max;
3137 return $self->items->[$self->index + 1];
3138 }
3139
3140 ###----------------------------------------------------------------###
3141
3142 package CGI::Ex::Template::_Context;
3143
3144 use vars qw($AUTOLOAD);
3145
3146 sub _template { shift->{'_template'} || die "Missing _template" }
3147
3148 sub config { shift->_template }
3149
3150 sub stash {
3151 my $self = shift;
3152 return $self->{'stash'} ||= bless {_template => $self->_template}, $CGI::Ex::Template::PACKAGE_STASH;
3153 }
3154
3155 sub insert { shift->_template->_insert(@_) }
3156
3157 sub eval_perl { shift->_template->{'EVAL_PERL'} }
3158
3159 sub process {
3160 my $self = shift;
3161 my $ref = shift;
3162 my $vars = $self->_template->_vars;
3163 my $out = '';
3164 $self->_template->_process($ref, $vars, \$out);
3165 return $out;
3166 }
3167
3168 sub include {
3169 my $self = shift;
3170 my $file = shift;
3171 my $args = shift || {};
3172
3173 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3174
3175 my $out = ''; # have temp item to allow clear to correctly clear
3176 eval { $self->_template->_process($file, $self->{'_vars'}, \$out) };
3177 if (my $err = $@) {
3178 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3179 }
3180
3181 return $out;
3182 }
3183
3184 sub define_filter {
3185 my ($self, $name, $filter, $is_dynamic) = @_;
3186 $filter = [ $filter, 1 ] if $is_dynamic;
3187 $self->define_vmethod('filter', $name, $filter);
3188 }
3189
3190 sub filter {
3191 my ($self, $name, $args, $alias) = @_;
3192 my $t = $self->_template;
3193
3194 my $filter;
3195 if (! ref $name) {
3196 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex::Template::FILTER_OPS->{$name} || $CGI::Ex::Template::SCALAR_OPS->{$name};
3197 $t->throw('filter', $name) if ! $filter;
3198 } elsif (UNIVERSAL::isa($name, 'CODE') || UNIVERSAL::isa($name, 'ARRAY')) {
3199 $filter = $name;
3200 } elsif (UNIVERSAL::can($name, 'factory')) {
3201 $filter = $name->factory || $t->throw($name->error);
3202 } else {
3203 $t->throw('undef', "$name: filter not found");
3204 }
3205
3206 if (UNIVERSAL::isa($filter, 'ARRAY')) {
3207 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3208 } elsif ($args && @$args) {
3209 my $sub = $filter;
3210 $filter = sub { $sub->(shift, @$args) };
3211 }
3212
3213 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3214
3215 return $filter;
3216 }
3217
3218 sub define_vmethod { shift->_template->define_vmethod(@_) }
3219
3220 sub throw {
3221 my ($self, $type, $info) = @_;
3222
3223 if (UNIVERSAL::isa($type, $CGI::Ex::Template::PACKAGE_EXCEPTION)) {
3224 die $type;
3225 } elsif (defined $info) {
3226 $self->_template->throw($type, $info);
3227 } else {
3228 $self->_template->throw('undef', $type);
3229 }
3230 }
3231
3232 sub AUTOLOAD { shift->_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3233
3234 sub DESTROY {}
3235
3236 ###----------------------------------------------------------------###
3237
3238 package CGI::Ex::Template::_Stash;
3239
3240 use vars qw($AUTOLOAD);
3241
3242 sub _template { shift->{'_template'} || die "Missing _template" }
3243
3244 sub get {
3245 my ($self, $var) = @_;
3246 if (! ref $var) {
3247 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3248 else { $var = $self->_template->parse_expr(\$var, {no_dots => 1}) }
3249 }
3250 return $self->_template->play_expr($var, {no_dots => 1});
3251 }
3252
3253 sub set {
3254 my ($self, $var, $val) = @_;
3255 if (! ref $var) {
3256 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3257 else { $var = $self->_template->parse_expr(\$var, {no_dots => 1}) }
3258 }
3259 $self->_template->set_variable($var, $val, {no_dots => 1});
3260 return $val;
3261 }
3262
3263 sub AUTOLOAD { shift->_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3264
3265 sub DESTROY {}
3266
3267 ###----------------------------------------------------------------###
3268
3269 package CGI::Ex::Template::EvalPerlHandle;
3270
3271 sub TIEHANDLE {
3272 my ($class, $out_ref) = @_;
3273 return bless [$out_ref], $class;
3274 }
3275
3276 sub PRINT {
3277 my $self = shift;
3278 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3279 return 1;
3280 }
3281
3282 ###----------------------------------------------------------------###
3283
3284 1;
3285
3286 ### See the perldoc in CGI/Ex/Template.pod
This page took 0.327989 seconds and 4 git commands to generate.