XML/Template/Process.pm untested

filter: Statementstmt 0.0% 0 / 205 Branchbran 0.0% 0 / 100 Conditioncond 0.0% 0 / 35 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 365 SCAR 78.8
CC
51
Cov
0%
process
306.0
_init
182.0
set_load
56.0
CRAP 2652.0
1 ###############################################################################
2 # XML::Template::Process
3 #
4 # Copyright (c) 2002-2003 Jonathan A. Waxman <jowaxman@law.upenn.edu>
5 # All rights reserved.
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the same terms as Perl itself.
9 ###############################################################################
10 package XML::Template::Process;
11 use base qw(XML::Template::Base);
12  
13 use strict;
14 use CGI qw(header);
15 use IO::String; # XXX
16 use Mail::Mailer; # XXX
17 use Data::Dumper;
18 use XML::SAX::ParserFactory;
19 use XML::Template::Exception;
20  
21  
22 =pod
23  
24 =head1 NAME
25  
26 XML::Template::Process - The main XML::Template document processing
27 module.
28  
29 =head1 SYNOPSIS
30  
31 This module is the main XML::Template document processing module. It
32 loads, compiles, stores (and caches), and evaluates XML documents. In
33 addition is contains many useful subroutines for processing documents.
34  
35 =head1 CONSTRUCTOR
36  
37 A constructor method C<new> is provided by L<XML::Template::Base>. A list
38 of named configuration parameters may be passed to the constructor. The
39 constructor returns a reference to a new parser object or under if an
40 error occurred. If undef is returned, you can use the method C<error> to
41 retrieve the error. For instance:
42  
43 my $parser = XML::Template::Process->new (%config)
44 || die XML::Template::Process->error;
45  
46 The following named configuration parameters may be passed to the
47 constructor:
48  
49 =over 4
50  
51 =item CGIHeader
52  
53 Whether to print a CGI header. The default is 1.
54  
55 =item Cache
56  
57 A blessed object that handles caching compiled XML documents to memory.
58 This value will override the default value C<$CACHE> in
59 L<XML::Template::Config>. The default cache object is of the class
60 L<XML::Template::Cache>.
61  
62 =item NoCache
63  
64 Whether to cache compiled XML documents to memory. If 1, a Cache object
65 is prepended to the load and put chains of responsibility. The default is
66 1.
67  
68 =item FileCache
69  
70 A blessed object that handles caching compiled XML documents to files.
71 This value will override the default value C<$FILE_CACHE> in
72 L<XML::Template::Config>. The default file cache object is of the class
73 L<XML::Template::Cache::File>.
74  
75 =item NoFileCache
76  
77 Whether to cache compiled XML documents to files. If 1, a FileCache
78 object is prepended to the load and put chains of responsibility. The
79 default is 1.
80  
81 =item Load
82  
83 A single object or reference to an array of objects to be added to the
84 load chain of responsibility.
85  
86 =item Handler
87  
88 A blessed XML::SAX handler object used to parse XML document. This value
89 will override the default value C<$HANDLER> in L<XML::Template::Config>.
90 The default parser handler is of the class L<XML::Template::Parser>.
91  
92 =item Subroutine
93  
94 A blessed object for default XML::Template subroutine handling. This
95 value will override the default value C<$SUBROUTINE> in
96 L<XML::Template::Config>. The default subroutine object is of the class
97 L<XML::Template::Subroutine>.
98  
99 =item Put
100  
101 A single object or reference to an array of objects to be added to the
102 put chain of responsibility.
103  
104 =item Vars
105  
106 A blessed object for XML::Template variable handling. This value will
107 override the default value C<$VARS> in L<XML::Template::Config>. The
108 default vars object is of the class L<XML::Template::Vars>.
109  
110 =back
111  
112 =head1 PRIVATE METHODS
113  
114 =head2 _init
115  
116 This method is the internal initialization function called from
117 L<XML::Template::Base> when a new process object is created.
118  
119 =cut
120  
121 sub _init {
122 my $self = shift;
123 my %params = @_;
124  
125 print "XML::Template::Process::_init\n" if $self->{_debug};
126  
127 # Whether to print a CGI header.
128 $self->{_cgi_header} = 1;
129 $self->{_cgi_header} = $params{CGIHeader} if defined $params{CGIHeader};
130 $self->{_cgi_header_printed} = 0;
131  
132 # Whether to print at all.
133 $self->{_print} = 1;
134  
135 # Create the load Chain of Responsibility list.
136 if (defined $params{Load}) {
137 push (@{$self->{_load}}, ref ($params{Load}) eq 'ARRAY'
138 ? @{$params{Load}}
139 : $params{Load});
140 } else {
141 require 'XML/Template/Element/File/Load.pm';
142 $self->{_load} = [XML::Template::Element::File::Load->new ()];
143 }
144  
145 $self->{_nofilecache} = defined $params{NoFileCache}
146 ? $params{NoFileCache}
147 : 0;
148 my $file_cache;
149 if (! $self->{_nofilecache}) {
150 $file_cache = $params{FileCache}
151 || XML::Template::Config->file_cache (%params)
152 || return $self->error (XML::Template::Config->error);
153 unshift (@{$self->{_load}}, $file_cache);
154 }
155  
156 $self->{_nocache} = defined $params{NoCache}
157 ? $params{NoCache}
158 : 0;
159 my $cache;
160 if (! $self->{_nocache}) {
161 $cache = $params{Cache}
162 || XML::Template::Config->cache (%params)
163 || return $self->error (XML::Template::Config->error);
164 unshift (@{$self->{_load}}, $cache);
165 }
166  
167 # Get SAX handler.
168 $self->{_handler} = $params{Handler} || XML::Template::Config->handler (%params)
169 || return $self->error (XML::Template::Config->error);
170  
171 $self->{_subroutine} = $params{Subroutine} || XML::Template::Config->subroutine (%params)
172 || return $self->error (XML::Template::Config->error);
173  
174 # Create the put Chain of Responsibility list.
175 $self->{_put} = [];
176 push (@{$self->{_put}}, $cache) if ! $self->{_nocache};
177 push (@{$self->{_put}}, $file_cache) if ! $self->{_nofilecache};
178 push (@{$self->{_put}}, ref ($params{Put}) eq 'ARRAY'
179 ? @{$params{Put}}
180 : $params{Put}) if defined $params{Put};
181  
182 # Get vars.
183 $self->{_vars} = $params{Vars} || XML::Template::Config->vars (%params)
184 || return $self->error (XML::Template::Config->error);
185 $self->{_vars}->create_context ();
186  
187 return 1;
188 }
189  
190 =pod
191  
192 =head1 PUBLIC METHODS
193  
194 =head2 print
195  
196 my $code = "\$process->print ($text);\n";
197  
198 This method is used to print text from XML documents. Typically it will
199 be used in Perl code generated by XML::Template. A CGI header will be
200 printed if the onstructor parameter C<CGIHeader> is set to 1 and one has
201 not yet been printed.
202  
203 =cut
204  
205 sub print {
206 my $self = shift;
207 my $text = join ('', @_);
208  
209 my $print = 0;
210  
211 my $cfh = select;
212 if (ref ($cfh) ne 'IO::String'
213 && $self->{_cgi_header}
214 && ! $self->{_cgi_header_printed}) {
215 if ($text !~ /^\s*$/) {
216 $self->{_cgi_header_printed} = 1;
217 print CGI::header;
218 print $text if $self->{_print};
219 }
220 } else {
221 print $text if $self->{_print};
222 }
223  
224 return 1;
225 }
226  
227 =pod
228  
229 =head2 subroutine
230  
231 my $code = "\$process->subroutine ('$subname', $text, \@params)";
232  
233 This method is used to handle XML::Template subroutine calls. It is
234 typically not used directly, but called from Perl code generated by
235 XML::Template. The first parameter is the XML::Template subroutine name,
236 the second is the variable on which the XML::Template subroutine is being
237 called, and the remaining parameters are additional parameters that are
238 being passed to the XML::Template subroutine. If no modules is associated
239 with the XML::Template subroutine in the XML::Template configuration file,
240 the default subroutine module (specified by the constructor parameter
241 C<Subroutine>) is used.
242  
243 =cut
244  
245 sub subroutine {
246 my $self = shift;
247 my ($subroutine, $var, @params) = @_;
248  
249 my $value = $self->{_vars}->get ($var);
250  
251 my $subroutine_info = $self->get_subroutine_info ($subroutine, 'module');
252 my $module = defined $subroutine_info ? $subroutine_info->{module}
253 : $self->{_subroutine};
254  
255 eval "use $module";
256 die $@ if $@;
257 return ($module->$subroutine ($self, $var, $value, @params));
258 }
259  
260 =pod
261  
262 =head2 process
263  
264 $process->process ($name, $vars)
265 || die $process->error ();
266  
267 This is the main XML document processing subroutine. The first parameter
268 is the name of the XML document. The format of this parameter depends on
269 loader. For instance, a block loader will interpret the name as a primary
270 key in a database table. The file loader will interpret the name as a
271 file. The second parameter is a reference to a hash containing name/value
272 pairs of defined variables.
273  
274 =cut
275  
276 sub process {
277 my $self = shift;
278 my ($name, $vars) = @_;
279  
280 print ref ($self) . "::process\n" if $self->{_debug};
281  
282 # Load XML, calling each method in the load chain of command.
283 my $document;
284 foreach my $load (@{$self->{_load}}) {
285 next if ! $load->{_enabled};
286  
287 print "XML::Temoplate::Process::process : Calling " . ref ($load) . "->load.\n" if $self->{_debug};
288  
289 $document = eval { $load->load ($name) };
290 return $self->error ('Process', "Could not load document '$name': $@") if $@;
291 return $self->error ($load->error) if $load->error;
292  
293 last if defined $document;
294 }
295 return $self->error ('Process', "Could not find document '$name'") if ! defined $document;
296  
297 if (defined $document) {
298 # Add passed vars.
299 $self->{_vars}->create_context ();
300 while (my ($var, $value) = each %$vars) {
301 # XXX
302 $var =~ s/^\01//;
303 $self->{_vars}->set ($var => $value);
304 }
305  
306 # If document not yet compiled, compile.
307 if (! $document->compiled) {
308 # Create a new handler object.
309 my $module = $self->{_handler};
310 XML::Template::Config->load ($module)
311 || return $self->error ('Process', XML::Template::Config->error);
312 my $handler = $module->new ();
313  
314 # Replace variable tags with 'core:element' tag.
315 my $xml = $document->xml;
316 $xml =~ s/<\/([^\s]*\${[^}]*}[^\s>]*>)/<\/core:element>/g;
317 $xml =~ s/<([^\s>]*\${[^}]*}[^\s>]*)/<core:element core:name="$1"/g;
318  
319 # Parse XML document.
320 my $parser = XML::SAX::ParserFactory->parser (Handler => $handler);
321 my $code = eval { $parser->parse_string ("<__xml>$xml</__xml>") };
322 return $self->error ('Process', $@) if $@;
323 $document->code ($code);
324 }
325  
326 # Put code, calling each method in the put chain of command.
327 foreach my $put (@{$self->{_put}}) {
328 print "XML::Template::Process::process : Calling " . ref ($put) . "->put.\n" if $self->{_debug};
329  
330 eval { $put->put ($name, $document) };
331 return $self->error ('Process', "Could not put document '$name': $@") if $@;
332 # return $self->error ($put->error) if $put->error;
333 }
334  
335 # Run code.
336 my $code = eval $document->{_code};
337 return $self->error ('Process', "Error evaluating document code: $@") if $@;
338 eval { &$code ($self); };
339 if ($@) {
340 my ($type, $error) = ref ($@) ? ($@->type, $@->info) : ('Unknown', $@);
341 return $self->error ($type, $error);
342 }
343  
344 # Remove variable context.
345 $self->{_vars}->delete_context ();
346  
347 # Error if document is empty.
348 if (! $self->{_cgi_header_printed}) {
349 return $self->error ('Empty', "Document \"$name\" contains no content.");
350 }
351 }
352
353 return 1;
354 }
355  
356 =pod
357  
358 =head2 get_load
359  
360 my %loaded = $process->get_load ()
361  
362 This method returns a hash that contains module name / enabled flag pairs
363 that lists which loader modules are loaded and enabled. This is used with
364 the method C<set_load> to selectively dis/enable loader modules. It is
365 definately not the best way to handle this sort of thing!
366  
367 =cut
368  
369 sub get_load {
370 my $self = shift;
371 my @modules = @_;
372  
373 # Slurp current load modules into a hash indexed by module name.
374 my %modules;
375 foreach my $module (@{$self->{_load}}) {
376 $modules{ref ($module)} = $module;
377 }
378 @modules = keys %modules if ! scalar (@modules);
379  
380 my %loaded;
381 foreach my $module (@modules) {
382 $loaded{$module} = defined $modules{$module} ? $modules{$module}->{_enabled}
383 : undef;
384 }
385  
386 return %loaded;
387 }
388  
389 =pod
390  
391 =head2 set_load
392  
393 $process->set_load (%load)
394  
395 This method is used to selectively dis/enable loader modules. It takes a
396 hash containing loader module names / enable flag pairs. For each loader
397 module listed, if the flag is set to 1, the module will be enabled,
398 otherwise it will be disabled. I would like to replace this with
399 something more sensible if it's even necessary.
400  
401 =cut
402  
403 sub set_load {
404 my $self = shift;
405 my %params = @_;
406  
407 # Slurp current load modules into a hash indexed by module name.
408 my %modules;
409 foreach my $module (@{$self->{_load}}) {
410 $modules{ref ($module)} = $module;
411 }
412  
413 my %delete;
414 while (my ($module, $loaded) = each %params) {
415 my $module_params = {};
416 ($loaded, $module_params) = @$loaded if ref ($loaded);
417  
418 if (defined $loaded) {
419 if (defined $modules{$module}) {
420 $modules{$module}->{_enabled} = $loaded;
421 } else {
422 if ($loaded) {
423 XML::Template::Config->load ($module)
424 || return $self->error (XML::Template::Config->error ());
425 push (@{$self->{_load}}, $module->new (%$module_params));
426 }
427 }
428 } else {
429 $delete{$module} = 1;
430 }
431 }
432 if (scalar (keys %delete)) {
433 my @new_load;
434 foreach my $module (@{$self->{_load}}) {
435 push (@new_load, $module) if ! $delete{ref ($module)};
436 }
437 $self->{_load} = \@new_load;
438 }
439  
440 return 1;
441 }
442  
443 =pod
444  
445 =head2 generate_where
446  
447 my $where = $self->generate_where (\%attribs, $table);
448  
449 This method returns the where clause of an SQL statement. The first
450 parameter is a reference to a hash containing attributes which are the
451 column names/values to be matched in the where clause. The second
452 parameter is the name of the default table to use for columns given in
453 C<%attribs>. If column names do not have C<.> in them, they are prepended
454 by C<$table>. If column values have C<%> in them, C<LIKE> is used for the
455 comparison test. Otherwise C<=> is used. For instance,
456  
457 my $where = $self->generate_where ({type => 'newsletter',
458 'map.num' => 5,
459 date => '2002%'},
460 'items')
461  
462 will return the following SQL where clause:
463  
464 items.type='newsletter' and map.num='5' and items.date like '2002%'
465  
466 =cut
467  
468 sub generate_where {
469 my $self = shift;
470 my ($attribs, $table) = @_;
471  
472 my $where;
473 while (my ($attrib, $value) = each %$attribs) {
474 my ($attrib_namespace, $attrib_name);
475 if ($attrib =~ /^{([^}]+)}(.*)$/) {
476 $attrib_namespace = $1;
477 $attrib_name = $2;
478 } else {
479 $attrib_namespace = '';
480 $attrib_name = $attrib;
481 }
482  
483 $where .= ' and ' if defined $where;
484 $where .= '(';
485 my $twhere;
486 foreach my $tvalue (split (/\s*,\s*/, $value)) {
487 $twhere .= ' or ' if defined $twhere;
488 $twhere .= "$table." if $attrib_name !~ /\./;
489 # xxx
490 die if $value =~ /;/;
491 $tvalue =~ s/;/\\;/g;
492 $tvalue =~ s/'/\\'/g;
493 if ($tvalue =~ /%/) {
494 $twhere .= "$attrib_name like '$tvalue'";
495 } else {
496 $twhere .= "$attrib_name='$tvalue'";
497 }
498 }
499 $where .= "$twhere)";
500 }
501  
502 return $where;
503 }
504  
505 sub load {
506 my $self = shift;
507 my @load = @_;
508  
509 my $pos = 0;
510 $pos++ if ! $self->{_nocache};
511 $pos++ if ! $self->{_nofilecache};
512 my @old_load = splice (@{$self->{_load}}, $pos);
513 push (@{$self->{_load}}, @load);
514  
515 return @old_load;
516 }
517  
518 =pod
519  
520 =head1 AUTHOR
521  
522 Jonathan Waxman
523 <jowaxman@bbl.med.upenn.edu>
524  
525 =head1 COPYRIGHT
526  
527 Copyright (c) 2002-2003 Jonathan A. Waxman
528 All rights reserved.
529  
530 This program is free software; you can redistribute it and/or
531 modify it under the same terms as Perl itself.
532  
533 =cut
534  
535  
536 1;