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