ASP/ASPPage.pm untested

filter: Statementstmt 0.0% 0 / 249 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 414 CC 31 SCAR 27.7
CC
31
Cov
0%
_build_dom
56.0
new
42.0
_assemble_code
30.0
CRAP 15.9
1  
2 package Apache2::ASP::ASPPage;
3  
4 use strict;
5 use warnings 'all';
6 use Carp 'confess';
7 use base 'Apache2::ASP::HTTPHandler';
8 use vars __PACKAGE__->VARS;
9 use Apache2::ASP::ASPDOM::Node;
10 use Apache2::ASP::ASPDOM::Document;
11 use HTTP::Date 'time2iso';
12 use Scalar::Util 'weaken';
13  
14 use Data::Dumper;
15  
16  
17 #==============================================================================
18 sub new
19 {
20 my ($class, %args) = @_;
21
22 $class->init_asp_objects( $class->context );
23
24 foreach(qw/ virtual_path /)
25 {
26 confess "Required param '$_' was not provided"
27 unless defined($args{$_});
28 }# end foreach()
29
30 # Just so we don't end up with an injection of some kind one day:
31 delete($args{file_contents});
32
33 my $s = bless \%args, $class;
34
35 $s->{physical_path} = $s->context->server->MapPath( $s->virtual_path );
36 confess "File not found: '@{[ $s->physical_path ]}'"
37 unless -f $s->physical_path;
38
39 my $pm_folder = $s->context->config->web->page_cache_root . '/' . $s->context->config->web->application_name;
40
41 # Build out the folder structure to the Page Cache:
42 my @parts = grep { length($_) } split /\//, $pm_folder;
43 my $dir = '';
44 foreach( @parts )
45 {
46 $dir .= "/$_";
47 mkdir($dir) unless -d $dir;
48 }# end foreach()
49
50 my $pkg = $s->virtual_path;
51 $pkg =~ s/^\///;
52 $pkg =~ s/[^a-z0-9_]/_/ig;
53 $s->{package_name} = $s->context->config->web->application_name . '::' . $pkg;
54 $s->{pm_path} = $pm_folder . '/' . $pkg . '.pm';
55 my $pm_inc = $s->context->config->web->application_name . '/' . $pkg . '.pm';
56
57 # Determine age of ASP and PM:
58 my $asp_age = (stat($s->context->server->MapPath($s->virtual_path)))[9];
59 no strict 'refs';
60 my $timestamp = ${$s->package_name . "::TIMESTAMP"} || 0;
61 my $pm_age = (stat($s->pm_path))[9] || 0;
62  
63 if( ( ! $pm_age ) || ( $asp_age > $pm_age ) )
64 {
65 #warn "(Re)compiling $pkg";
66 delete( $INC{$pm_inc} );
67 $s->_init_source_code();
68 $s->parse;
69 require $pm_inc;
70 }
71 elsif( $asp_age > $timestamp )
72 {
73 #warn "(Re)loading $pkg";
74 delete( $INC{$pm_inc} );
75 require $pm_inc;
76 }# end if()
77
78 return $s;
79 }# end new()
80  
81  
82 #==============================================================================
83 # Public read-only properties:
84 sub physical_path { $_[0]->{physical_path} }
85 sub virtual_path { $_[0]->{virtual_path} }
86 sub context { $Apache2::ASP::HTTPContext::ClassName->current }
87 sub package_name { $_[0]->{package_name} }
88 sub pm_path { $_[0]->{pm_path} }
89 sub directives { my $s = shift; @_ ? $s->{directives} = shift : $s->{directives} || { } }
90 sub source_code { $_[0]->{source_code} }
91 sub file_contents { $_[0]->{file_contents} }
92 sub is_masterpage { $_[0]->{is_masterpage} || 0 > 0 }
93 sub masterpage { $_[0]->{masterpage} or return; $_[0]->{masterpage} }
94 sub placeholders { my $s = shift; @_ ? $s->{placeholders} = shift : $s->{placeholders} || { } }
95 sub placeholder_contents { $_[0]->{placeholder_contents} || { } }
96  
97  
98 #==============================================================================
99 # Public read-write properties:
100 sub childpage
101 {
102 my $s = shift;
103
104 @_ ? $s->{childpage} = shift : $s->{childpage};
105 }# end childpage()
106  
107  
108 #==============================================================================
109 sub _init_source_code
110 {
111 my ($s) = @_;
112
113 return $s->{file_contents} if defined($s->{file_contents});
114
115 open my $ifh, '<', $s->physical_path
116 or confess "Cannot open '@{[ $s->physical_path ]}' for reading: $!";
117 local $/;
118 my $data = <$ifh>;
119 $s->{source_code} = \"$data";
120 $s->{file_contents} = \$data;
121 }# end _init_source_code()
122  
123  
124 #==============================================================================
125 sub parse
126 {
127 my ($s) = @_;
128
129 $s->{directives} = $s->_get_directives( );
130
131 if( exists($s->directives->{Page}->{UseMasterPage}) )
132 {
133 my $master = Apache2::ASP::ASPPage->new(
134 virtual_path => $s->directives->{Page}->{UseMasterPage},
135 childpage => $s,
136 );
137 $s->{masterpage} = $master->package_name->new(
138 virtual_path => $s->directives->{Page}->{UseMasterPage},
139 childpage => $s,
140 );
141 $s->{masterpage} = $s->masterpage->_initialize_page;
142 }# end if()
143
144 if( exists($s->directives->{MasterPage}) )
145 {
146 $s->{is_masterpage} = 1;
147 }# end if()
148
149 # Do the <%# %> tags:
150 $s->_eval_compile_tags;
151
152 # Setup the scriptlet <% %> tags:
153 $s->_parse_scriptlet_tags;
154
155 # Do the <!-- #include --> tags:
156 $s->_parse_include_tags;
157
158 # XXX: Make DOM
159 $s->_build_dom;
160
161 # Write the code to disk:
162 $s->_assemble_code;
163 }# end parse()
164  
165  
166 #==============================================================================
167 sub _read_cache
168 {
169 my ($s) = @_;
170
171 return unless $s->context->application->can('db_Main');
172
173 if( my $cache_args = $s->{directives}->{OutputCache} )
174 {
175 use Digest::MD5 'md5_hex';
176
177 # Get the key:
178 my $cache_id = $s->_cache_key;
179
180 my $range_start = time2iso( time() - $cache_args->{Duration} );
181 my $sth = $s->context->application->db_Main->prepare(<<"SQL");
182 SELECT pagecache_data
183 FROM asp_pagecache
184 WHERE pagecache_id = ?
185 AND created_on BETWEEN ? AND ?
186 SQL
187 $sth->execute( $cache_id, $range_start, time2iso() );
188 if( my ($cache_data) = $sth->fetchrow )
189 {
190 # We got cache:
191 return $cache_data;
192 }# end if()
193 }# end if()
194 }# end _read_cache()
195  
196  
197 #==============================================================================
198 sub _cache_key
199 {
200 my $s = shift;
201
202 my $cache_args = $s->directives->{OutputCache};
203  
204 # Make the key:
205 my %key = ( );
206 if( my $field = $cache_args->{VaryBySession} )
207 {
208 $key{"Session:$field"} = $s->context->session->{$field};
209 }# end if()
210 if( my $field = $cache_args->{VaryByParam} )
211 {
212 $key{"Param:$field"} = $s->context->request->Form->{$field};
213 }# end if()
214 no warnings 'uninitialized';
215 my $key = md5_hex( $s->virtual_path . ':' .
216 join ':', map { "$_:$key{$_}" } sort keys(%key)
217 );
218
219 return $key;
220 }# end _cache_key()
221  
222  
223 #==============================================================================
224 sub _write_cache
225 {
226 my ($s, $data) = @_;
227  
228 return unless $s->context->application->can('db_Main');
229  
230 my $key = $s->_cache_key;
231 #warn "Storing cache...";
232 my $sth = $s->context->application->db_Main->prepare(<<"SQL");
233 DELETE FROM asp_pagecache WHERE pagecache_id = ?;
234 SQL
235 $sth->execute( $key );
236 $sth->finish();
237
238 $sth = $s->context->application->db_Main->prepare(<<"SQL");
239 INSERT INTO asp_pagecache ( pagecache_id, created_on, pagecache_data )
240 VALUES ( ?, ?, ? )
241 SQL
242 $sth->execute(
243 $key, time2iso(), $$data
244 );
245 $sth->finish;
246 }# end _write_cache()
247  
248  
249 #==============================================================================
250 sub _build_dom
251 {
252 my ($s) = @_;
253
254 my $ref = $s->source_code;
255
256 my %ids = ( );
257 my $doc = Apache2::ASP::ASPDOM::Document->new();
258
259 # Do <asp:TagName>...</asp:TagName> tags:
260 my @lines = split /\r?\n/, ${ $s->file_contents };
261 while(
262 my ( $chunk, $tagName, $prefix, $tag, $attrs, $contents ) =
263 $$ref =~ m{
264 (<(([a-z_]+)\:([a-z0-9_:]+))\s*(.*?)\>(.*?)\<\/\2\>)
265 }ixs
266 )
267 {
268 # Parse the attributes:
269 my $attrs = $s->_parse_tag_attrs( $attrs );
270
271 local $_ = $tagName;
272 if( m/^asp:ContentPlaceHolder$/i )
273 {
274 confess "Only MasterPages can contain $tagName elements"
275 unless $s->is_masterpage;
276 $s->{placeholders}->{ $attrs->{id} } = $contents;
277
278 # Remove the chunk of code:
279 my $subname = "\$__self->" . $attrs->{id} . "(\$__context, \$__args);";
280 $$ref =~ s/\Q$chunk\E/~); $subname \$Response->Write(q~/;
281 }
282 elsif( m/^asp:Content$/i )
283 {
284 confess "$tagName found but no UseMasterPage defined"
285 unless $s->masterpage;
286
287 confess $s->masterpage->virtual_path . " does not define an asp:ContentPlaceHolder '" . $attrs->{PlaceHolderID} . "'"
288 unless exists( $s->masterpage->{placeholders}->{ $attrs->{PlaceHolderID} } )
289 or $s->masterpage->can( $attrs->{PlaceHolderID} );
290
291 while( my ( $chunk, $tagName, $prefix, $tag, $attrs, $contents2 ) =
292 $contents =~ m{
293 (<((asp)\:(ContentPlaceHolder))\s*(.*?)\>(.*?)\<\/\2\>)
294 }ixs
295 )
296 {
297 # We have a nested master page:
298 # Parse the attributes:
299 my $attrs = $s->_parse_tag_attrs( $attrs );
300 $s->{placeholders}->{ $attrs->{id} } = $contents2;
301
302 # Remove the chunk of code:
303 my $subname = "\$__self->" . $attrs->{id} . "(\$__context, \$__args);";
304 $contents =~ s/\Q$chunk\E/~); $subname \$Response->Write(q~/;
305 }# end while()
306
307 # Find the line on which this tag occurs:
308 my $line = 0;
309 $line++ until $lines[$line] =~ m/\<$tagName\s+/s;
310 $lines[$line] = '';
311
312 # Remove the chunk of code:
313 my $fixed_contents = '$Response->Write(q~' . $contents . '~);';
314 my $code_chunk = <<"CODE";
315 sub @{[ $attrs->{PlaceHolderID} ]} {
316 my (\$__self, \$__context, \$__args) = \@_;
317 \$__self->init_asp_objects( \$__context )
318 unless \$__self->{__did_init}++;
319 #line @{[ $line + 3 ]}
320 $fixed_contents
321 }
322 CODE
323 $s->{placeholder_contents}->{ $attrs->{PlaceHolderID} } = $code_chunk;
324 $$ref =~ s/\Q$chunk\E//;
325 }
326 else
327 {
328 # Unhandled tag:
329 # Find the line on which this tag occurs:
330 my $line = 0;
331 $line++ until $lines[$line] =~ m/\<$tagName\s+/s;
332 confess "Unhandled tag '$tagName' in '@{[ $s->virtual_path ]}' line @{[ $line + 1 ]}\n";
333 }# end if()
334 }# end while()
335  
336 # Do <asp:TagName /> tags:
337 while(
338 my ( $chunk, $tagName, $prefix, $tag, $attrs ) =
339 $$ref =~ m{
340 (<(([a-z_]+)\:([a-z0-9_:]+))\s*(.*?)\/>)
341 }ix
342 )
343 {
344 # Parse the attributes:
345 my $attrs = $s->_parse_tag_attrs( $attrs );
346
347 local $_ = $tagName;
348 if( m/^some:tagName$/ )
349 {
350 # It's a some:tagName - handle it:
351 }
352 else
353 {
354 # Unhandled tag:
355 # Find the line on which this tag occurs:
356 my $line = 0;
357 $line++ until $lines[$line] =~ m/\<$tagName\s+/s;
358 confess "Unhandled tag '$tagName' in '@{[ $s->virtual_path ]}' line @{[ $line + 1 ]}\n";
359 }# end if()
360
361 # Remove the chunk of code
362 $$ref =~ s/\Q$chunk\E//;
363 }# end while()
364  
365 }# end _build_dom()
366  
367  
368 #==============================================================================
369 sub _parse_include_tags
370 {
371 my ($s) = @_;
372
373 my $ref = $s->source_code;
374
375 $$ref =~ s{
376 \<\!\-\-\s*\#include\s+virtual\="(.*?)"\s*\-\-\>
377 }{~); \$Response->Include(\$Server->MapPath("$1")); \$Response->Write(q~}xsg;
378 }# end _parse_include_tags()
379  
380  
381 #==============================================================================
382 sub _parse_scriptlet_tags
383 {
384 my ($s) = @_;
385
386 my $ref = $s->source_code;
387
388 # Parse <% %> items:
389 $$ref =~ s{
390 <%\=(.*?)%>
391 }{
392 '~);$Response->Write(' . $1 . ');$Response->Write(q~'
393 }xgse;
394  
395 $$ref =~ s{
396 <%\s*([^\@\#\=]?.*?)%>
397 }{
398 my $txt = $1; '~);' . $txt . ';$Response->Write(q~'
399 }gxse;
400
401 $$ref =~ s/(\$Response\->End)/return $1/gs;
402
403 $$ref = ';$Response->Write(q~' . $$ref . '~);';
404
405 # Now do the final ~ substitution:
406 $$ref =~ s{(\(q~)(.*?)(~\);)}{
407 my $pre = $1;
408 my $post = $3;
409 (my $txt = $2) =~ s/~/\\~/g;
410 "$pre$txt$post"
411 }xsge;
412 }# end _parse_scriptlet_tags()
413  
414  
415 #==============================================================================
416 sub _eval_compile_tags
417 {
418 my ($s) = @_;
419
420 my $ref = $s->source_code;
421 no warnings 'uninitialized';
422 while( $$ref =~ m/(<%\#\s*(.*?)\s*%>)/ )
423 {
424 my $tag = $1;
425 my $var = $2;
426 $$ref =~ s/\Q$tag\E/$var/ee;
427 }# end while()
428 }# end _eval_compile_tags()
429  
430  
431 #==============================================================================
432 sub _assemble_code
433 {
434 my ($s) = @_;
435
436 local $s->{childpage} = undef;
437
438 my $copy = bless {%$s}, ref($s);
439 unless( ref($copy) eq $copy->package_name )
440 {
441 $copy = bless { %$copy }, $copy->package_name;
442 }# end unless()
443 local $copy->{masterpage} = ref($copy->{masterpage});
444 local $copy->{source_code} = \'';
445 local $copy->{file_contents} = \'';
446 my $dump = Dumper( $copy );
447 $dump =~ s/^\$VAR1\s+\=//;
448 my $virtual_path = $s->masterpage ? $s->masterpage->virtual_path : '';
449
450 # Preamble:
451 my $code = <<"CODE";
452 package @{[ $s->package_name ]};
453  
454 use strict;
455 use warnings 'all';
456 no warnings 'redefine';
457 our \$TIMESTAMP = @{[ time() ]};
458  
459 sub _initialize_page {
460 eval { \$_[0]->SUPER::_initialize_page };
461 \$_[0]->init_asp_objects( \$_[0]->context );
462 \$_[0] = $dump;
463 \$_[0]->{masterpage} = \$_[0]->{masterpage}->new( virtual_path => '$virtual_path' ) if \$_[0]->{masterpage};
464 \$_[0];
465 }
466  
467 CODE
468
469 # Things work differently if we have/don't have a master page:
470 if( $s->masterpage )
471 {
472 # Sub-class the master page:
473 $code .= <<"CODE";
474 BEGIN {
475 (my \$pkg = '@{[ ref($s->masterpage) ]}.pm') =~ s/::/\\\\/g;
476 use Apache2::ASP::ASPPage;
477 #eval { require \$pkg; 1 } or
478 Apache2::ASP::ASPPage->new(
479 virtual_path => '@{[ $s->masterpage->virtual_path ]}'
480 );
481 }
482 use base '@{[ ref($s->masterpage) ]}';
483 use vars ( '\$Master', __PACKAGE__->VARS );
484 @{[ join "\n\n", map { $s->placeholder_contents->{$_} } keys(%{ $s->placeholder_contents }) ]}
485 @{[ join "\n\n", map { "sub $_ {\$Response->Write(q~$s->{placeholders}->{$_}~);}" } keys(%{$s->placeholders}) ]}
486  
487 CODE
488 }
489 else
490 {
491 # Just sub-class this class:
492 $code .= <<"CODE";
493 use base 'Apache2::ASP::ASPPage';
494 use vars __PACKAGE__->VARS;
495  
496 sub run {
497 my (\$__self,\$__context, \$__args) = \@_;
498 \$__self->_initialize_page;
499 if( my \$cached = \$__self->_read_cache )
500 {
501 \$__self->{directives}->{OutputCache} = undef;
502 \$Response->Write( \$cached );
503 return;
504 }# end if()
505
506 \$__context->{page} = \$__self unless \$__self->is_masterpage;
507 #line 1
508 @{[ ${$s->source_code} ]}
509 @{[ join "\n\n", map { "sub $_ {\$Response->Write(q~$s->{placeholders}->{$_}~);}" } keys(%{$s->placeholders}) ]}
510 }
511 CODE
512 }# end if()
513
514
515 # Finally:
516 $code .= <<"CODE";
517 1;# return true:
518 CODE
519
520 unlink( $s->pm_path ) if -f $s->pm_path;
521 open my $ofh, '>', $s->pm_path
522 or die "Cannot open '" . $s->pm_path . "' for writing: $!";
523 print $ofh $code;
524 close($ofh);
525 chmod( 0666, $s->pm_path );
526 }# end _assemble_code()
527  
528  
529 #==============================================================================
530 sub _get_directives
531 {
532 my ($s) = @_;
533
534 my $ref = $s->source_code;
535 my %directives = ( );
536 while( my ($tag, $directive, $attr_str) = $$ref =~ m/(<%@\s*(.*?)\s+(.*?)\s*%>)/ )
537 {
538 my $attrs = $s->_parse_tag_attrs( $attr_str );
539 $$ref =~ s/\Q$tag\E//;
540 $directives{$directive} = $attrs;
541 }# end while()
542
543 return \%directives;
544 }# end _get_directives()
545  
546
547 #==============================================================================
548 sub _parse_tag_attrs
549 {
550 my ($s, $str) = @_;
551
552 my $attr = { };
553 while( $str =~ m@([^\s\=\"\']+)(\s*=\s*(?:(")(.*?)"|(')(.*?)'|([^'"\s=]+)['"]*))?@sg ) #@
554 {
555 my $key = $1;
556 my $test = $2;
557 my $val = ( $3 ? $4 : ( $5 ? $6 : $7 ));
558 if( $test )
559 {
560 $attr->{$key} = $val;
561 }
562 else
563 {
564 $attr->{$key} = $key;
565 }# end if()
566 }# end while()
567
568 return $attr;
569 }# end _parse_tag_attrs()
570  
571 1;# return true:
572  
573 =pod
574  
575 =head1 NAME
576  
577 Apache2::ASP::ASPPage - base class for all *.asp scripts
578  
579 =head1 SYNOPSIS
580  
581 Internal use only.
582  
583 =head1 DESCRIPTION
584  
585 All C<*.asp> scripts are 'compiled' down to their respective C<*.pm> files. The
586 package definition within those C<*.pm> files all begin with this code:
587  
588 use base 'Apache2::ASP::ASPPage';
589  
590 After that, you will find your code, just a little uglier than you wrote it.
591  
592 This package is only used internally.
593
594 =head1 BUGS
595
596 It's possible that some bugs have found their way into this release.
597
598 Use RT L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Apache2-ASP> to submit bug reports.
599
600 =head1 HOMEPAGE
601
602 Please visit the Apache2::ASP homepage at L<http://www.devstack.com/> to see examples
603 of Apache2::ASP in action.
604
605 =head1 AUTHOR
606
607 John Drago L<mailto:jdrago_999@yahoo.com>
608
609 =head1 COPYRIGHT AND LICENSE
610
611 Copyright 2007 John Drago, All rights reserved.
612
613 This software is free software. It may be used and distributed under the
614 same terms as Perl itself.
615
616 =cut
617