ASP/ASPPage.pm untested

filter: Statementstmt 0.0% 0 / 249 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 24 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 401 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 #line @{[ $line + 3 ]}
318 $fixed_contents
319 }
320 CODE
321 $s->{placeholder_contents}->{ $attrs->{PlaceHolderID} } = $code_chunk;
322 $$ref =~ s/\Q$chunk\E//;
323 }
324 else
325 {
326 # Unhandled tag:
327 # Find the line on which this tag occurs:
328 my $line = 0;
329 $line++ until $lines[$line] =~ m/\<$tagName\s+/s;
330 confess "Unhandled tag '$tagName' in '@{[ $s->virtual_path ]}' line @{[ $line + 1 ]}\n";
331 }# end if()
332 }# end while()
333  
334 # Do <asp:TagName /> tags:
335 while(
336 my ( $chunk, $tagName, $prefix, $tag, $attrs ) =
337 $$ref =~ m{
338 (<(([a-z_]+)\:([a-z0-9_:]+))\s*(.*?)\/>)
339 }ix
340 )
341 {
342 # Parse the attributes:
343 my $attrs = $s->_parse_tag_attrs( $attrs );
344
345 local $_ = $tagName;
346 if( m/^some:tagName$/ )
347 {
348 # It's a some:tagName - handle it:
349 }
350 else
351 {
352 # Unhandled tag:
353 # Find the line on which this tag occurs:
354 my $line = 0;
355 $line++ until $lines[$line] =~ m/\<$tagName\s+/s;
356 confess "Unhandled tag '$tagName' in '@{[ $s->virtual_path ]}' line @{[ $line + 1 ]}\n";
357 }# end if()
358
359 # Remove the chunk of code
360 $$ref =~ s/\Q$chunk\E//;
361 }# end while()
362  
363 }# end _build_dom()
364  
365  
366 #==============================================================================
367 sub _parse_include_tags
368 {
369 my ($s) = @_;
370
371 my $ref = $s->source_code;
372
373 $$ref =~ s{
374 \<\!\-\-\s*\#include\s+virtual\="(.*?)"\s*\-\-\>
375 }{~); \$Response->Include(\$Server->MapPath("$1")); \$Response->Write(q~}xsg;
376 }# end _parse_include_tags()
377  
378  
379 #==============================================================================
380 sub _parse_scriptlet_tags
381 {
382 my ($s) = @_;
383
384 my $ref = $s->source_code;
385
386 # Parse <% %> items:
387 $$ref =~ s{
388 <%\=(.*?)%>
389 }{
390 '~);$Response->Write(' . $1 . ');$Response->Write(q~'
391 }xgse;
392  
393 $$ref =~ s{
394 <%\s*([^\@\#\=]?.*?)%>
395 }{
396 my $txt = $1; '~);' . $txt . ';$Response->Write(q~'
397 }gxse;
398
399 $$ref =~ s/(\$Response\->End)/return $1/gs;
400
401 $$ref = ';$Response->Write(q~' . $$ref . '~);';
402
403 # Now do the final ~ substitution:
404 $$ref =~ s{(\(q~)(.*?)(~\);)}{
405 my $pre = $1;
406 my $post = $3;
407 (my $txt = $2) =~ s/~/\\~/g;
408 "$pre$txt$post"
409 }xsge;
410 }# end _parse_scriptlet_tags()
411  
412  
413 #==============================================================================
414 sub _eval_compile_tags
415 {
416 my ($s) = @_;
417
418 my $ref = $s->source_code;
419 no warnings 'uninitialized';
420 while( $$ref =~ m/(<%\#\s*(.*?)\s*%>)/ )
421 {
422 my $tag = $1;
423 my $var = $2;
424 $$ref =~ s/\Q$tag\E/$var/ee;
425 }# end while()
426 }# end _eval_compile_tags()
427  
428  
429 #==============================================================================
430 sub _assemble_code
431 {
432 my ($s) = @_;
433
434 local $s->{childpage} = undef;
435
436 my $copy = bless {%$s}, ref($s);
437 unless( ref($copy) eq $copy->package_name )
438 {
439 $copy = bless { %$copy }, $copy->package_name;
440 }# end unless()
441 local $copy->{masterpage} = ref($copy->{masterpage});
442 local $copy->{source_code} = \'';
443 local $copy->{file_contents} = \'';
444 my $dump = Dumper( $copy );
445 $dump =~ s/^\$VAR1\s+\=//;
446 my $virtual_path = $s->masterpage ? $s->masterpage->virtual_path : '';
447
448 # Preamble:
449 my $code = <<"CODE";
450 package @{[ $s->package_name ]};
451  
452 use strict;
453 use warnings 'all';
454 no warnings 'redefine';
455 our \$TIMESTAMP = @{[ time() ]};
456  
457 sub _initialize_page {
458 \$_[0]->init_asp_objects( \$_[0]->context );
459 \$_[0] = $dump;
460 \$_[0]->{masterpage} = \$_[0]->{masterpage}->new( virtual_path => '$virtual_path' ) if \$_[0]->{masterpage};
461 \$_[0];
462 }
463  
464 CODE
465
466 # Things work differently if we have/don't have a master page:
467 if( $s->masterpage )
468 {
469 # Sub-class the master page:
470 $code .= <<"CODE";
471 BEGIN {
472 (my \$pkg = '@{[ ref($s->masterpage) ]}.pm') =~ s/::/\\\\/g;
473 use Apache2::ASP::ASPPage;
474 #eval { require \$pkg; 1 } or
475 Apache2::ASP::ASPPage->new(
476 virtual_path => '@{[ $s->masterpage->virtual_path ]}'
477 );
478 }
479 use base '@{[ ref($s->masterpage) ]}';
480 use vars ( '\$Master', __PACKAGE__->VARS );
481 @{[ join "\n\n", map { $s->placeholder_contents->{$_} } keys(%{ $s->placeholder_contents }) ]}
482 @{[ join "\n\n", map { "sub $_ {\$Response->Write(q~$s->{placeholders}->{$_}~);}" } keys(%{$s->placeholders}) ]}
483  
484 CODE
485 }
486 else
487 {
488 # Just sub-class this class:
489 $code .= <<"CODE";
490 use base 'Apache2::ASP::ASPPage';
491 use vars __PACKAGE__->VARS;
492  
493 sub run {
494 my (\$__self,\$__context, \$__args) = \@_;
495 \$__self->_initialize_page;
496 if( my \$cached = \$__self->_read_cache )
497 {
498 \$__self->{directives}->{OutputCache} = undef;
499 \$Response->Write( \$cached );
500 return;
501 }# end if()
502
503 \$__context->{page} = \$__self unless \$__self->is_masterpage;
504 #line 1
505 @{[ ${$s->source_code} ]}
506 @{[ join "\n\n", map { "sub $_ {\$Response->Write(q~$s->{placeholders}->{$_}~);}" } keys(%{$s->placeholders}) ]}
507 }
508 CODE
509 }# end if()
510
511
512 # Finally:
513 $code .= <<"CODE";
514 1;# return true:
515 CODE
516
517 unlink( $s->pm_path ) if -f $s->pm_path;
518 open my $ofh, '>', $s->pm_path
519 or die "Cannot open '" . $s->pm_path . "' for writing: $!";
520 print $ofh $code;
521 close($ofh);
522 chmod( 0666, $s->pm_path );
523 }# end _assemble_code()
524  
525  
526 #==============================================================================
527 sub _get_directives
528 {
529 my ($s) = @_;
530
531 my $ref = $s->source_code;
532 my %directives = ( );
533 while( my ($tag, $directive, $attr_str) = $$ref =~ m/(<%@\s*(.*?)\s+(.*?)\s*%>)/ )
534 {
535 my $attrs = $s->_parse_tag_attrs( $attr_str );
536 $$ref =~ s/\Q$tag\E//;
537 $directives{$directive} = $attrs;
538 }# end while()
539
540 return \%directives;
541 }# end _get_directives()
542  
543
544 #==============================================================================
545 sub _parse_tag_attrs
546 {
547 my ($s, $str) = @_;
548
549 my $attr = { };
550 while( $str =~ m@([^\s\=\"\']+)(\s*=\s*(?:(")(.*?)"|(')(.*?)'|([^'"\s=]+)['"]*))?@sg ) #@
551 {
552 my $key = $1;
553 my $test = $2;
554 my $val = ( $3 ? $4 : ( $5 ? $6 : $7 ));
555 if( $test )
556 {
557 $attr->{$key} = $val;
558 }
559 else
560 {
561 $attr->{$key} = $key;
562 }# end if()
563 }# end while()
564
565 return $attr;
566 }# end _parse_tag_attrs()
567  
568 1;# return true:
569  
570 =pod
571  
572 =head1 NAME
573  
574 Apache2::ASP::ASPPage - base class for all *.asp scripts
575  
576 =head1 SYNOPSIS
577  
578 Internal use only.
579  
580 =head1 DESCRIPTION
581  
582 All C<*.asp> scripts are 'compiled' down to their respective C<*.pm> files. The
583 package definition within those C<*.pm> files all begin with this code:
584  
585 use base 'Apache2::ASP::ASPPage';
586  
587 After that, you will find your code, just a little uglier than you wrote it.
588  
589 This package is only used internally.
590
591 =head1 BUGS
592
593 It's possible that some bugs have found their way into this release.
594
595 Use RT L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Apache2-ASP> to submit bug reports.
596
597 =head1 HOMEPAGE
598
599 Please visit the Apache2::ASP homepage at L<http://www.devstack.com/> to see examples
600 of Apache2::ASP in action.
601
602 =head1 AUTHOR
603
604 John Drago L<mailto:jdrago_999@yahoo.com>
605
606 =head1 COPYRIGHT AND LICENSE
607
608 Copyright 2007 John Drago, All rights reserved.
609
610 This software is free software. It may be used and distributed under the
611 same terms as Perl itself.
612
613 =cut
614