blib/lib/Apache/SimpleTemplate.pm untested

filter: Statementstmt 0.0% 0 / 318 Branchbran 0.0% 0 / 182 Conditioncond 0.0% 0 / 47 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 632 CC 92 SCAR 51.5
CC
92
Cov
0%
compile
552.0
render
210.0
flush
182.0
CRAP 172.7
1 package Apache::SimpleTemplate;
2 #
3 # a very simple mod_perl template parser.
4 #
5 # (c) 2001-2006 peter forty
6 #
7 # you may use this and/or distribute this under
8 # the same terms as perl itself.
9 #
10  
11 use Apache ();
12 use strict;
13  
14 our $VERSION = 0.06;
15 our %_cache;
16 our %_cache_time;
17  
18 our $DEFAULT_BLOCK_BEGIN = '<%';
19 our $DEFAULT_BLOCK_END = '%>';
20 our $DEFAULT_CACHE_FLAG = 1;
21 our $DEFAULT_CONTENT_TYPE = 'text/html';
22 our $DEFAULT_RELOAD_FLAG = 1;
23 our $DEFAULT_CASCADE_STATUS = 1;
24 our $DEFAULT_DEBUG_LEVEL = 0;
25  
26 #
27 # handler
28 #
29 # the Apache/mod_perl handler
30 #
31  
32 sub handler {
33  
34 my $r = shift;
35  
36 my $s = shift || new Apache::SimpleTemplate($r);
37 #unless ($r) { return &cgi_handler($s); }
38 $s->{_header_sent} = 0;
39  
40 print STDERR "-------- Apache::SimpleTemplate::handler REQUEST FOR $s->{file}\n" if ($s->{debug} > 1);
41  
42 if ($s->{status} == 200) { $s->render($ENV{DOCUMENT_ROOT}.$s->{file}); }
43 $s->flush(1);
44  
45 # return ($s->{debug} && $s->{_error}) ? undef : $s->{status};
46 # return ($s->{_error}) ? $s->{status} : undef;
47 return ( $s->{status} && ($s->{status} != 200) ) ? $s->{status} : undef;
48  
49  
50 }
51  
52  
53  
54 #########################################################
55 # OBJECT CREATOR/METHODS
56 #
57  
58 #
59 # new
60 #
61 # make a new instance of SimpleTemplate,
62 # given the current Apache request object ($r) or
63 # a hash with the CGI variables already parsed.
64 #
65 # new Apache::SimpleTemplate($r);
66 # new Apache::SimpleTemplate($inref);
67 #
68  
69 sub new {
70  
71 my $class = shift;
72 my $r = shift;
73 my $self = {};
74  
75 bless($self, $class);
76  
77 if (ref($r) =~ m/Apache/) {
78 $self->{file} = $r->dir_config('SimpleTemplateFile');
79 $self->{block_begin} = $r->dir_config('SimpleTemplateBlockBegin');
80 $self->{block_end} = $r->dir_config('SimpleTemplateBlockEnd');
81 $self->{content_type} = $r->dir_config('SimpleTemplateContentType');
82 $self->{cascade_status} = $r->dir_config('SimpleTemplateCascadeStatus');
83  
84 $self->{cache} = $r->dir_config('SimpleTemplateCache');
85 $self->{reload} = $r->dir_config('SimpleTemplateReload');
86 $self->{debug} = $r->dir_config('SimpleTemplateDebug');
87 }
88 if (!defined $self->{cache}) { $self->{cache} = $DEFAULT_CACHE_FLAG; }
89 if (!defined $self->{reload}) { $self->{reload} = $DEFAULT_RELOAD_FLAG; }
90 if (!defined $self->{block_begin}) { $self->{block_begin} = $DEFAULT_BLOCK_BEGIN; }
91 if (!defined $self->{block_end}) { $self->{block_end} = $DEFAULT_BLOCK_END; }
92 if (!defined $self->{file}) { $self->{file} = ($ENV{SCRIPT_NAME} . ($ENV{PATH_INFO}||'') ); }
93 if (!defined $self->{content_type}) { $self->{content_type} = $DEFAULT_CONTENT_TYPE; }
94 if (!defined $self->{cascade_status}) { $self->{cascade_status} = $DEFAULT_CASCADE_STATUS; }
95 if (!defined $self->{debug}) { $self->{debug} = $DEFAULT_DEBUG_LEVEL; }
96  
97 print STDERR "---- NEW SimpleTemplate OBJECT FOR $self->{file}\n" if ($self->{debug} > 1);
98
99 $self->{r} = $r;
100 $self->{inref} = (ref($r) eq 'HASH') ? $r : $self->parse_form($r);
101 $self->{headerref} = {};
102 $self->{status} = 200;
103  
104 return $self;
105  
106 }
107  
108  
109 # getters/setters
110 sub block_begin { my $s = shift; return $_[0] ? $s->{block_begin} = $_[0] : $s->{block_begin}; }
111 sub block_end { my $s = shift; return $_[0] ? $s->{block_end} = $_[0] : $s->{block_end}; }
112 sub file { my $s = shift; return $_[0] ? $s->{file} = $_[0] : $s->{file}; }
113 sub debug { my $s = shift; return $_[0] ? $s->{debug} = $_[0] : $s->{debug}; }
114 sub reload { my $s = shift; return $_[0] ? $s->{reload} = $_[0] : $s->{reload}; }
115 sub cache { my $s = shift; return $_[0] ? $s->{cache} = $_[0] : $s->{cache}; }
116 sub status { my $s = shift; return $_[0] ? $s->{status} = $_[0] : $s->{status}; }
117 sub content_type { my $s = shift; return $_[0] ? $s->{content_type} = $_[0] : $s->{content_type}; }
118 sub cascade_status { my $s = shift; return $_[0] ? $s->{cascade_status} = $_[0] : $s->{cascade_status}; }
119  
120  
121 #
122 # header
123 #
124 # safely add a header (without squashing an existing entry.)
125 #
126 sub header {
127 my ($s, $name, $value) = @_;
128 my $cur = $s->{headerref}->{$name};
129 if ($cur) { $s->{headerref}->{$name} = $cur . "\n" . $name . ': ' . $value; }
130 else { $s->{headerref}->{$name} = $value; }
131 }
132  
133  
134  
135 #
136 # print
137 #
138 # print out something
139 #
140 sub print {
141 my ($s) = shift;
142 ${ $s->{out} } .= join('', @_);
143 }
144  
145  
146 #
147 # flush
148 #
149 # flush the current output buffer.
150 # (changing status or content_type no longer an option.)
151 # an arg of one won't change buffering (for internal calls.)
152 #
153  
154 sub flush {
155 my ($s) = shift;
156 my $r = $s->{r};
157  
158 local $| = $_[0] ? undef : 1;
159  
160 if (!$s->{_header_sent} && ($s->{status} < 400)) {
161 # send any header stuff from headerref
162 foreach my $h (keys %{ $s->{headerref} }) {
163 if ($r) {
164 my $cur = $r->header_out($h);
165 if ($cur) { $r->header_out($h, ($cur . "\n" . $h . ': ' . $s->{headerref}->{$h})); }
166 else { $r->header_out($h, $s->{headerref}->{$h}); }
167 }
168 else {
169 print $h . ': ' . $s->{headerref}->{$h} . "\n";
170 }
171 }
172  
173 if ($r) {
174 # set my status and content_type...
175 $r->status($s->{status});
176 $r->content_type($s->{content_type});
177 $r->send_http_header;
178 }
179 else {
180 print 'Content-type: '. $s->{content_type} . "\n\n";
181 }
182  
183 $s->{_header_sent} = 1;
184  
185 print STDERR "-------- Apache::SimpleTemplate STATUS $s->{status}\n" if ($s->{debug} > 1);
186 print STDERR "-------- Apache::SimpleTemplate CTYPE $s->{content_type}\n" if ($s->{debug} > 1);
187  
188 }
189  
190 if ($r) {
191 # send the document if we're OK
192 if ($s->{status} == 200) { $r->print(${ $s->{out} }); }
193 elsif ($s->{debug} > 0) { $r->print($s->{_error}); }
194 }
195 else {
196 if ($s->{status} == 200) { print ${ $s->{out} }; }
197 elsif ($s->{debug} > 0) { print($s->{_error}); }
198 }
199  
200 ${ $s->{out} } = '';
201 }
202  
203  
204 #
205 # render
206 #
207 # takes a full path to a template
208 #
209  
210 sub render {
211  
212 my $s = shift;
213  
214 if (!defined($s->{out})) { ${ $s->{out} } = ''; }
215  
216 my $inref = $s->{inref};
217 # my $headerref = $s->{headerref};
218  
219 my $package = 'Apache::SimpleTemplate::Template'.$_[0];
220 $package =~ s/\//\:\:/g;
221 $package =~ s/[^\w\:]/_/g;
222 print STDERR "-- RENDERING ($package)\n" if ($s->{debug} > 1);
223  
224 my $fun = $_cache{$_[0]};
225 my $usecache = $fun ? 1 : $s->{cache};
226  
227 # check for updated template
228 if ($fun && ($s->{reload} > 0)) {
229 my $filetime = (stat($_[0]))[9];
230 if ($_cache_time{$_[0]} < $filetime) {
231 print STDERR "-- RELOADING ($package)\n" if ($s->{debug} > 1);
232 $fun = undef;
233 }
234 }
235  
236 # check for cache
237 if ($fun) {
238 print STDERR "-- CACHE HIT ($package)\n" if ($s->{debug} > 1);
239 }
240 else {
241 print STDERR "-- COMPILING ($package)\n" if ($s->{debug} > 1);
242  
243 $fun = $s->compile($_[0]);
244 if ($fun && ($usecache>0)) {
245 if ($s->{reload} > 0) { $_cache_time{$_[0]} = time; }
246 $_cache{$_[0]} = $fun;
247 }
248 }
249  
250 #print STDERR "-- SETTING STATUS for $s to $s->{status}\n" if $s->{debug};
251 if (!(ref $fun)) {
252 if ($fun != 200) { $s->{status} = $fun; return ''; }
253 my $packagefun = $package.'::____st_go_';
254 $fun = \&$packagefun;
255 }
256  
257 return &$fun($s);
258  
259 }
260  
261 #
262 # compile a template
263 #
264 # load from file:
265 # $s->compile('/www/myhost.com/foo.stml');
266 # pass in body:
267 # $s->compile($template, 1);
268 #
269  
270 sub compile {
271  
272 my $s = shift;
273  
274 my $template = $_[1] ? $_[0] : &load($_[0]);
275 if (!defined $template) { $s->{_error} .= "Not Found: $_[0]\n"; return 404; }
276
277 my $block_begin = $s->{block_begin} || $DEFAULT_BLOCK_BEGIN;
278 my $block_end = $s->{block_end} || $DEFAULT_BLOCK_END;
279 print STDERR "-- DELIM: $block_begin $block_end\n" if $s->{debug} > 2;
280  
281 $block_begin =~ s/([^\w])/\\$1/g;
282 $block_end =~ s/([^\w])/\\$1/g;
283
284 my $eval = '';
285 my $precode = '';
286
287 my $package = 'Apache::SimpleTemplate::Template'.$_[0];
288 $package =~ s/\//\:\:/g;
289 $package =~ s/[^\w\:]/_/g;
290 my $usepackage = 0;
291  
292 $template =~ s/($block_begin)\#(.*?)\#($block_end)/$1.'-'.&blank_lines($2).$3/gse;
293 #$template =~ s/$block_begin\-(.*?)$block_end/&blank_lines($1)/gse;
294
295 if ($template =~ s/$block_begin\!(.*?)$block_end/
296 $precode .= $1 . '; ';
297 '';
298 /gse) {
299 $usepackage = 1;
300 if ($s->{debug} > 3) {
301 print STDERR "============================INITIAL BLOCK\n";
302 print STDERR $precode . "\n";
303 print STDERR "============================/INITIAL BLOCK\n";
304 }
305 }
306
307 if ($usepackage) {
308 $eval .= "package $package; use Apache::SimpleTemplate; " . $precode;
309 }
310
311 $eval .= 'sub ' . ($usepackage?'____st_go_ ':''). '{ my ($s) = @_; ';
312 $eval .= 'my $r = $s->{r}; my $____st_out_ = $s->{out}; my $inref=$s->{inref}; ';
313
314 my @pieces = split (/$block_end/, $template);
315  
316 # fix parsing problem if code block at very end of template.
317 if (($template =~ m/$block_end$/s) && !($template =~ m/$block_end\n$/s)) { push (@pieces, ''); }
318  
319 # for (my $i=0; $i<=$#pieces; $i++) {
320 # print STDERR "==================================PIECE $i:\n";
321 # print STDERR $pieces[$i];
322 # print STDERR "\n==================================\n";
323 # }
324  
325 my $i = 0;
326 for (; $i<$#pieces; $i++) {
327  
328 if ($pieces[$i] =~
329 m/(.*?)$block_begin([\^\+\\\-\=\:]?)(.*?)\;?(\s*)$/gs) {
330 my $text = &quote_escape($1);
331 my $encode = $2;
332 my $block = $3.$4;
333  
334 if ($s->{debug} > 3) {
335 print STDERR "==================================TEXT $i:\n";
336 print STDERR "$1\n";
337 print STDERR "==================================CODE ($encode) $i:\n";
338 print STDERR "$block\n";
339 }
340  
341 $eval .= '$$____st_out_ .= \''.$text."'; ";
342
343 if (!$encode) {
344 $eval .= $block .'; ';
345 }
346 elsif ($encode eq ':') {
347 print STDERR "** Apache::SimpleTemplate: DEPRECATED ':' OPERATOR." if ($s->{debug} > 1);
348 $eval .= '{ my $out = undef; my $____st_tmp_=eval {'.$block.'}; ';
349 $eval .= '$$____st_out_ .= (defined $out) ? $out : $____st_tmp_;'.'}; ';
350 }
351 elsif ($encode eq '=') {
352 $eval .= '$$____st_out_ .= ('.$block.'); ';
353 }
354 elsif ($encode eq '+') {
355 $eval .= '$$____st_out_ .= &Apache::SimpleTemplate::encode('.$block.'); ';
356 }
357 elsif ($encode eq '^') {
358 $eval .= '$$____st_out_ .= &Apache::SimpleTemplate::escape('.$block.'); ';
359 }
360 elsif ($encode eq '\\') {
361 $eval .= '$$____st_out_ .= &Apache::SimpleTemplate::js_escape('.$block.'); ';
362 }
363 elsif ($encode eq '-') {
364 $eval .= &blank_lines($block);
365 }
366  
367 }
368  
369 else {
370 print STDERR "** Apache::SimpleTemplate $_[0]: Invalid Block in:\n";
371 print STDERR $pieces[$i].$s->{block_end}."\n";
372 $s->{_error} .= "Invalid Block: ".$pieces[$i].$s->{block_end}."\n";
373 return 500;
374 }
375
376 }
377
378 if ($s->{debug} > 3) {
379 print STDERR "==================================TEXT $i:\n";
380 print STDERR "$pieces[$i]\n";
381 print STDERR "==================================\n";
382 }
383  
384 $eval .= '$$____st_out_.=\''.&quote_escape($pieces[$i]).'\'; ';
385 $eval .= "return (\$____st_out_);\n}";
386
387 #if ($usepackage) { $eval .= "1;\n"; }
388  
389 if ($s->{debug} > 2) {
390 print STDERR "===================================================EVAL\n";
391 print STDERR "$eval\n";
392 print STDERR "===================================================/EVAL\n";
393 }
394
395 my $fun = eval($eval);
396 if ($@) { print STDERR "** Apache::SimpleTemplate $_[0]: $@\n"; $s->{_error} .= $@; return 500; }
397  
398 if ($usepackage) { return 200; }
399 return $fun;
400  
401 }
402  
403 sub blank_lines {
404 my ($string) = @_;
405 $string =~ s/[^\n]//g;
406 return $string;
407 }
408  
409 #
410 # include
411 #
412 # for use in templates, so they can include other templates/files.
413 # takes a path relative to the document root.
414 # $s->include('/path/relative/to/docroot.stml');
415 #
416  
417 sub include {
418  
419 my $s = shift;
420
421 print STDERR "---- Apache::SimpleTemplate::include FROM $s->{file} FOR $_[0]\n" if ($s->{debug} > 1);
422 my $tmp = $s->{status};
423 $s->render($ENV{DOCUMENT_ROOT}.$_[0]);
424 $s->status($tmp) if ($s->{cascade_status} == 0);
425  
426 }
427  
428  
429  
430 #
431 # preload a template into memory
432 # takes a full path
433 #
434  
435 sub preload {
436  
437 my $s = shift;
438  
439 $_cache{$_[0]} = $s->compile($_[0]);
440  
441 }
442  
443  
444  
445 #########################################################
446 # OTHER FUNCTIONS (callable as methods, too.)
447 #
448  
449  
450 # url-encode a string
451 sub encode {
452  
453 my $s = shift;
454 if (ref $s) { $s = shift; }
455 return undef unless defined($s);
456  
457 $s =~ s/([^a-zA-Z0-9_\.\-\ ])/uc sprintf("%%%02x",ord($1))/eg;
458 $s =~ s/\ /\+/g;
459  
460 return $s;
461  
462 }
463  
464 # url-decode a string
465 sub decode {
466  
467 my $s = shift;
468 if (ref $s) { $s = shift; }
469 return undef unless defined($s);
470  
471 $s =~ s/\+/ /g;
472 $s =~ s/\%([0-9a-fA-F]{2})/chr(hex($1))/eg;
473  
474 return $s;
475  
476 }
477  
478 # html-escape a string ('<tag> & " ' becomes '&lt;tag&gt; &amp; &quot;')
479 sub escape {
480  
481 my $s = shift;
482 if (ref $s) { $s = shift; }
483 return undef unless defined($s);
484  
485 $s =~ s/\&/&amp;/g;
486 $s =~ s/\</&lt;/g;
487 $s =~ s/\>/&gt;/g;
488 $s =~ s/\"/&quot;/g;
489  
490 return $s;
491 }
492  
493 # escape single quotes (') and backslashes (\) with \' and \\
494 sub quote_escape {
495  
496 my $s = shift;
497 if (ref $s) { $s = shift; }
498 return undef unless defined($s);
499  
500 $s =~ s/([\'\\])/\\$1/gs;
501  
502 return $s;
503 }
504  
505 # escape single quotes (') and backslashes (\) with \' and \\, newlines and cr's with \n \r
506 sub js_escape {
507  
508 my $s = shift;
509 if (ref $s) { $s = shift; }
510 return undef unless defined($s);
511  
512 $s =~ s/([\'\\])/\\$1/gs;
513 $s =~ s/\n/\\n/g;
514 $s =~ s/\r/\\r/g;
515  
516 return $s;
517 }
518  
519  
520 #
521 # parse_form
522 #
523 # try to get the form data every which way..
524 # %form = $r->args; loses multiple checkboxes....
525 # and doesn't parse a QUERY STRING in a POST. :(
526 #
527  
528 sub parse_form {
529  
530 my $s = shift;
531 my ($r) = @_;
532  
533 #print STDERR "PARSE FORM! $r\n";
534  
535 my (%form, @form);
536  
537 if ($r && $r->args && ref($r->args)) {
538 @form = $r->args;
539 }
540 # elsif ($ENV{QUERY_STRING}) {
541 # foreach my $pair (split('&', $ENV{QUERY_STRING})) {
542 elsif (($r && $r->args) || $ENV{QUERY_STRING}) {
543 foreach my $pair (split('&', (($r && $r->args) ? $r->args : $ENV{QUERY_STRING}))) {
544 my ($k, $v) = split('=', $pair);
545 push (@form, &decode($k), &decode($v));
546 }
547 }
548  
549 if (($r) && ($r->method() eq 'POST') && ($r->header_in('Content-Length') > 0)) {
550  
551 # handle upload posts
552 if ($r->header_in('Content-Type') =~ m/multipart\/form-data/i) {
553 use CGI;
554 $CGI::DISABLE_UPLOADS = 0;
555 my $cgi = CGI->new();
556 foreach my $k (keys %{$cgi->Vars}) { $form{$k} = $cgi->param($k); }
557 use CGI::Upload;
558 my $upload = CGI::Upload->new({ query => $cgi });
559 $s->{upload} = $upload;
560 }
561  
562 # handle other posts
563 else {
564 push @form, $r->content();
565 }
566  
567 # blank this so we don't think there's more to read
568 $r->header_in('Content-Length', 0);
569 }
570  
571 for (my $i = 0; $i < $#form; $i += 2) {
572 ## $r->content returns empty things
573 ## as undefs instead of as empty strings...
574 unless (defined $form[$i+1]) { $form[$i+1] = ''; }
575  
576 # print STDERR " GOT: $form[$i] = "+$form[$i+1]+"\n";
577 $form{$form[$i]} = $form{$form[$i]} ?
578 $form{$form[$i]}."\0".$form[$i+1] : $form[$i+1];
579 }
580  
581 return \%form;
582  
583 }
584  
585  
586 #
587 # load()
588 #
589 # given a full path/filename,
590 # return the file as a string.
591 #
592  
593 sub load {
594
595 my ($filename) = @_;
596 my $ret;
597  
598 local $/ = undef;
599  
600 unless (open FILE, $filename) {
601 print STDERR "** Apache::SimpleTemplate: Unable to load $filename: $!\n";
602 return undef;
603 }
604 while(<FILE>) { $ret .= $_; }
605
606 return ($ret);
607  
608 }
609  
610 1;
611  
612 __END__