HeavyCGI.pm untested

filter: Statementstmt 0.0% 0 / 291 Branchbran 0.0% 0 / 140 Conditioncond 0.0% 0 / 85 MC/DCmcdc 0.0% 0 / 45 Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 639 CC 71 SCAR 36.6
CC
71
Cov
0%
radio_group
156.0
dispatch
72.0
scrolling_list
72.0
CRAP 39.0
1 package Apache::HeavyCGI;
2 use 5.005; # for fields support and package-named exceptions
3 use Apache::Constants qw(:common);
4 use Apache::HeavyCGI::Date;
5 use Apache::HeavyCGI::Exception;
6 use strict;
7 use vars qw($VERSION $DEBUG);
8  
9 $VERSION = "0.013302";
10  
11 sub can_gzip {
12 my Apache::HeavyCGI $self = shift;
13 return $self->{CAN_GZIP} if defined $self->{CAN_GZIP};
14 my $acce = $self->{R}->header_in('Accept-Encoding') || "";
15 return $self->{CAN_GZIP} = 0 unless $acce;
16 $self->{CAN_GZIP} = $acce =~ /\bgzip\b/;
17 }
18  
19 sub can_png {
20 my Apache::HeavyCGI $self = shift;
21 return $self->{CAN_PNG} if defined $self->{CAN_PNG};
22 my $acce = $self->{R}->header_in("Accept") || "";
23 return $self->{CAN_PNG} = 0 unless $acce;
24 $self->{CAN_PNG} = $acce =~ m|image/png|i;
25 }
26  
27 sub can_utf8 {
28 my Apache::HeavyCGI $self = shift;
29 return $self->{CAN_UTF8} if defined $self->{CAN_UTF8};
30  
31 # From chapter 14.2. HTTP/1.1
32  
33 ## If no Accept-Charset header is present, the default is that any
34 ## character set is acceptable. If an Accept-Charset header is present,
35 ## and if the server cannot send a response which is acceptable
36 ## according to the Accept-Charset header, then the server SHOULD send
37 ## an error response with the 406 (not acceptable) status code, though
38 ## the sending of an unacceptable response is also allowed.
39  
40 my $acce = $self->{R}->header_in("Accept-Charset") || "";
41 if (defined $acce){
42 if ($acce =~ m|\butf-8\b|i){
43 $self->{CAN_UTF8} = 1;
44 } else {
45 $self->{CAN_UTF8} = 0;
46 }
47 return $self->{CAN_UTF8};
48 }
49 my $protocol = $self->{R}->protocol || "";
50 my($major,$minor) = $protocol =~ m|HTTP/(\d+)\.(\d+)|;
51 $self->{CAN_UTF8} = $major >= 1 && $minor >= 1;
52 }
53  
54 sub deliver {
55 my Apache::HeavyCGI $self = shift;
56 my $r = $self->{R};
57 # warn "Going to send_http_header";
58 $r->send_http_header;
59 return OK if $r->method eq "HEAD";
60 # warn "Going to print content";
61 $r->print($self->{CONTENT});
62 DONE; # we've sent the headers and the body, apache shouldn't talk
63 # to the browser anymore
64 }
65  
66 sub handler {
67 warn "The handler of the request hasn't defined a handler subroutine.";
68 __PACKAGE__->new( R => shift )->dispatch;
69 }
70  
71 sub dispatch {
72 my Apache::HeavyCGI $self = shift;
73 $self->init;
74 eval { $self->prepare; };
75 if ($@) {
76 if (UNIVERSAL::isa($@,"Apache::HeavyCGI::Exception")) {
77 if ($@->{ERROR}) {
78 warn "\$\@ ERROR[$@->{ERROR}]";
79 $@->{ERROR} = [ $@->{ERROR} ] unless ref $@->{ERROR};
80 warn "\$\@ ERROR[$@->{ERROR}]";
81 push @{$self->{ERROR}}, @{$@->{ERROR}};
82 warn "self ERROR[$self->{ERROR}]";
83 } elsif ($@->{HTTP_STATUS}) {
84 return $@->{HTTP_STATUS};
85 }
86 } else {
87 # this is not a known error type, we need to handle it anon
88 if ($self->{ERRORS_TO_BROWSER}) {
89 push @{$self->{ERROR}}, " ", $@;
90 } else {
91 $self->{R}->log_error($@);
92 return SERVER_ERROR;
93 }
94 }
95 }
96 return $self->{DONE} if $self->{DONE}; # backwards comp now, will go away
97 $self->{CONTENT} = $self->layout->as_string($self);
98 $self->finish;
99 $self->deliver;
100 }
101  
102 sub expires {
103 my Apache::HeavyCGI $self = shift;
104 my($set) = @_;
105 $set = Apache::HeavyCGI::Date->new(unix => $set)
106 if defined($set) and not ref($set); # allow setting to a number
107 $self->{EXPIRES} = $set if defined $set;
108 return $self->{EXPIRES}; # even if not defined $self->{EXPIRES};
109 }
110  
111 sub finish {
112 my Apache::HeavyCGI $self = shift;
113  
114 my $r = $self->{R};
115 my $content_type = "text/html";
116 $content_type .= "; charset=$self->{CHARSET}" if defined $self->{CHARSET};
117 $r->content_type($content_type);
118  
119 eval { require Compress::Zlib; };
120 $self->{CAN_GZIP} = 0 if $@; # we cannot compress anyway :-)
121  
122 if ($self->can_gzip) {
123 $r->header_out('Content-Encoding', 'gzip');
124 $self->{CONTENT} = Compress::Zlib::memGzip($self->{CONTENT});
125 }
126  
127 $r->header_out('Vary', join ", ", 'accept-encoding');
128 $r->header_out('Expires', $self->expires->http) if $self->expires;
129 $r->header_out('Last-Modified',$self->last_modified->http);
130 $r->header_out('Content-Length', length($self->{CONTENT}));
131 }
132  
133 sub init {
134 return;
135 }
136  
137 sub instance_of {
138 my($self,$class) = @_;
139 return $class->instance if $class->can("instance");
140 my $requirefile = $class;
141 $requirefile =~ s/::/\//g;
142 $requirefile .= ".pm";
143 # warn "requiring[$requirefile]";
144 require $requirefile;
145 $class->instance;
146 }
147  
148 sub layout {
149 my Apache::HeavyCGI $self = shift;
150 require Apache::HeavyCGI::Layout;
151 my @l;
152 push @l, qq{<html><head><title>Apache::HeavyCGI default page</title>
153 </head><body><pre>};
154 push @l, $self->instance_of("Apache::HeavyCGI::Debug");
155 push @l, qq{</pre></body></html>};
156 Apache::HeavyCGI::Layout->new(@l);
157 }
158  
159 sub last_modified {
160 my Apache::HeavyCGI $self = shift;
161 my($set) = @_;
162 $set = Apache::HeavyCGI::Date->new(unix => $set)
163 if defined($set) and not ref($set); # allow setting to a number
164 $self->{LAST_MODIFIED} = $set if defined $set;
165 return $self->{LAST_MODIFIED} if defined $self->{LAST_MODIFIED};
166 $self->{LAST_MODIFIED} =
167 Apache::HeavyCGI::Date->new(unix => $self->time);
168 }
169  
170 sub myurl {
171 my Apache::HeavyCGI $self = shift;
172 return $self->{MYURL} if defined $self->{MYURL};
173 require URI::URL;
174 my $r = $self->{R} or
175 return URI::URL->new("http://localhost");
176 my $script_name = substr(
177 $r->uri,
178 0,
179 length($r->uri)-length($r->path_info)
180 );
181 my $port = $r->server->port || 80;
182 my $protocol = $port == 443 ? "https" : "http";
183 my $explicit_port = ($port == 80 || $port == 443) ? "" : ":$port";
184 $self->{MYURL} = URI::URL->new(
185 "$protocol://" .
186 $r->server->server_hostname .
187 $explicit_port .
188 $script_name);
189 }
190  
191 sub new {
192 my($class,%opt) = @_;
193 no strict "refs";
194 my $self = bless {}, $class;
195 while (my($k,$v) = each %opt) {
196 $self->{$k} = $v;
197 }
198 $self;
199 }
200  
201 sub prepare {
202 my Apache::HeavyCGI $self = shift;
203 if (my $ep = $self->{EXECUTION_PLAN}) {
204 $ep->walk($self);
205 } else {
206 die "No execution plan!";
207 }
208 }
209  
210 sub serverroot_url {
211 my Apache::HeavyCGI $self = shift;
212 return $self->{SERVERROOT_URL} if $self->{SERVERROOT_URL};
213 require URI::URL;
214 my $r = $self->{R} or
215 return URI::URL->new("http://localhost");
216 my $host = $r->server->server_hostname;
217 my $port = $r->server->port || 80;
218 my $protocol = $port == 443 ? "https" : "http";
219 my $explicit_port = ($port == 80 || $port == 443) ? "" : ":$port";
220 $self->{SERVERROOT_URL} = URI::URL->new(
221 "$protocol\://" .
222 $host .
223 $explicit_port .
224 "/"
225 );
226 }
227  
228 sub time {
229 my Apache::HeavyCGI $self = shift;
230 $self->{TIME} ||= time;
231 }
232  
233 sub today {
234 my Apache::HeavyCGI $self = shift;
235 return $self->{TODAY} if defined $self->{TODAY};
236 my(@time) = localtime($self->time);
237 $time[4]++;
238 $time[5] += 1900;
239 $self->{TODAY} = sprintf "%04d-%02d-%02d", @time[5,4,3];
240 }
241  
242 # CGI form handling
243  
244 sub checkbox {
245 my($self,%arg) = @_;
246  
247 my $name = $arg{name};
248 my $value;
249 defined($value = $arg{value}) or ($value = "on");
250 my $checked;
251 my @sel = $self->{CGI}->param($name);
252 if (@sel) {
253 for my $s (@sel) {
254 if ($s eq $value) {
255 $checked = 1;
256 last;
257 }
258 }
259 } else {
260 $checked = $arg{checked};
261 }
262 sprintf(qq{<input type="checkbox" name="%s" value="%s"%s />},
263 $self->escapeHTML($name),
264 $self->escapeHTML($value),
265 $checked ? qq{ checked="checked"} : ""
266 );
267 }
268  
269 # pause_1999::main
270 sub checkbox_group {
271 my($self,%arg) = @_;
272  
273 my $name = $arg{name};
274 my @sel = $self->{CGI}->param($name);
275 unless (@sel) {
276 if (exists $arg{default}) {
277 my $default = $arg{default};
278 @sel = ref $default ? @$default : $default;
279 }
280 }
281  
282 my %sel;
283 @sel{@sel} = ();
284 my @m;
285  
286 $name = $self->escapeHTML($name);
287  
288 my $haslabels = exists $arg{labels};
289 my $linebreak = $arg{linebreak} ? "<br />" : "";
290  
291 for my $v (@{$arg{values} || []}) {
292 push(@m,
293 sprintf(
294 qq{<input type="checkbox" name="%s" value="%s"%s />%s%s},
295 $name,
296 $self->escapeHTML($v),
297 exists $sel{$v} ? qq{ checked="checked"} : "",
298 $haslabels ? $arg{labels}{$v} : $self->escapeHTML($v),
299 $linebreak,
300 )
301 );
302 }
303 join "", @m;
304 }
305  
306 sub escapeHTML {
307 my($self, $what) = @_;
308 return unless defined $what;
309 my %escapes = qw(& &amp; " &quot; > &gt; < &lt;);
310 $what =~ s[ ([&"<>]) ][$escapes{$1}]xg; # ]] cperl-mode comment
311 $what;
312 }
313  
314 sub file_field {
315 my($self) = shift;
316 $self->text_pw_field(FIELDTYPE=>"file", @_);
317 }
318  
319 sub hidden_field {
320 my($self) = shift;
321 $self->text_pw_field(FIELDTYPE=>"hidden", @_);
322 }
323  
324 sub password_field {
325 my($self) = shift;
326 $self->text_pw_field(FIELDTYPE=>"password", @_);
327 }
328  
329 # pause_1999::main
330 sub radio_group {
331 my($self,%arg) = @_;
332 my $name = $arg{name};
333 my $value;
334 my $checked;
335 my $sel = $self->{CGI}->param($name);
336 my $haslabels = exists $arg{labels};
337 my $values = $arg{values} or Carp::croak "radio_group called without values";
338 defined($checked = $arg{checked})
339 or defined($checked = $sel)
340 or defined($checked = $arg{default})
341 or $checked = "";
342 # some people like to check the first item anyway:
343 # or ($checked = $values->[0]);
344 my $escname=$self->escapeHTML($name);
345 my $linebreak = $arg{linebreak} ? "<br />" : "";
346 my @m;
347 for my $v (@$values) {
348 my $escv = $self->escapeHTML($v);
349 if ($DEBUG) {
350 warn "escname undef" unless defined $escname;
351 warn "escv undef" unless defined $escv;
352 warn "v undef" unless defined $v;
353 warn "\$arg{labels}{\$v} undef" unless defined $arg{labels}{$v};
354 warn "checked undef" unless defined $checked;
355 warn "haslabels undef" unless defined $haslabels;
356 warn "linebreak undef" unless defined $linebreak;
357 }
358 push(@m,
359 sprintf(
360 qq{<input type="radio" name="%s" value="%s"%s />%s%s},
361 $escname,
362 $escv,
363 $v eq $checked ? qq{ checked="checked"} : "",
364 $haslabels ? $arg{labels}{$v} : $escv,
365 $linebreak,
366 ));
367 }
368 join "", @m;
369 }
370  
371 # pause_1999::main
372 sub scrolling_list {
373 my($self, %arg) = @_;
374 # name values size labels
375 my $size = $arg{size} ? qq{ size="$arg{size}"} : "";
376 my $multiple = $arg{multiple} ? q{ multiple="multiple"} : "";
377 my $haslabels = exists $arg{labels};
378 my $name = $arg{name};
379 my @sel = $self->{CGI}->param($name);
380 if (!@sel && exists $arg{default} && defined $arg{default}) {
381 my $d = $arg{default};
382 @sel = ref $d ? @$d : $d;
383 }
384 my %sel;
385 @sel{@sel} = ();
386 my @m;
387 push @m, sprintf qq{<select name="%s"%s%s>}, $name, $size, $multiple;
388 $arg{values} = [$arg{value}] unless exists $arg{values};
389 for my $v (@{$arg{values} || []}) {
390 my $escv = $self->escapeHTML($v);
391 push @m, sprintf qq{<option%s value="%s">%s</option>\n},
392 exists $sel{$v} ? q{ selected="selected"} : "",
393 $escv,
394 $haslabels ? $self->escapeHTML($arg{labels}{$v}) : $escv;
395 }
396 push @m, "</select>";
397 join "", @m;
398 }
399  
400 # pause_1999::main
401 sub submit {
402 my($self,%arg) = @_;
403 my $name = $arg{name} || "";
404 my $val = $arg{value} || $name;
405 sprintf qq{<input type="submit" name="%s" value="%s" />},
406 $self->escapeHTML($name),
407 $self->escapeHTML($val);
408 }
409  
410 # pause_1999::main
411 sub textarea {
412 my($self,%arg) = @_;
413 my $req = $self->{CGI};
414 my $name = $arg{name} || "";
415 my $val = $req->param($name) || $arg{default} || $arg{value} || "";
416 my($r) = exists $arg{rows} ? qq{ rows="$arg{rows}"} : '';
417 my($c) = exists $arg{cols} ? qq{ cols="$arg{cols}"} : '';
418 my($wrap)= exists $arg{wrap} ? qq{ wrap="$arg{wrap}"} : '';
419 sprintf qq{<textarea name="%s"%s%s%s>%s</textarea>},
420 $self->escapeHTML($name),
421 $r, $c, $wrap, $self->escapeHTML($val);
422 }
423  
424 # pause_1999::main
425 sub textfield {
426 my($self) = shift;
427 $self->text_pw_field(FIELDTYPE=>"text", @_);
428 }
429  
430 sub text_pw_field {
431 my($self, %arg) = @_;
432 my $name = $arg{name} || "";
433 my $fieldtype = $arg{FIELDTYPE};
434  
435 my $req = $self->{CGI};
436 my $val;
437 if ($fieldtype eq "FILE") {
438 if ($req->can("upload")) {
439 if ($req->upload($name)) {
440 $val = $req->upload($name);
441 } else {
442 $val = $req->param($name);
443 }
444 } else {
445 $val = $req->param($name);
446 }
447 } else {
448 $val = $req->param($name);
449 }
450 defined $val or
451 defined($val = $arg{value}) or
452 defined($val = $arg{default}) or
453 ($val = "");
454  
455 sprintf qq{<input type="$fieldtype"
456 name="%s" value="%s"%s%s />},
457 $self->escapeHTML($name),
458 $self->escapeHTML($val),
459 exists $arg{size} ? " size=\"$arg{size}\"" : "",
460 exists $arg{maxlength} ? " maxlength=\"$arg{maxlength}\"" : "";
461 }
462  
463 sub uri_escape {
464 my Apache::HeavyCGI $self = shift;
465 my $string = shift;
466 return "" unless defined $string;
467 require URI::Escape;
468 my $s = URI::Escape::uri_escape($string, '^\w ');
469 $s =~ s/ /+/g;
470 $s;
471 }
472  
473 sub uri_escape_light {
474 my Apache::HeavyCGI $self = shift;
475 require URI::Escape;
476 URI::Escape::uri_escape(shift,q{<>#%"; \/\?:&=+,\$}); #"
477 }
478  
479 1;
480  
481 =head1 NAME
482  
483 Apache::HeavyCGI - Framework to run complex CGI tasks on an Apache server
484  
485 =head1 SYNOPSIS
486  
487 use Apache::HeavyCGI;
488  
489 =head1 WARNING UNSUPPORTED ALPHA CODE RELEASED FOR DEMO ONLY
490  
491 The release of this software was only for evaluation purposes to
492 people who are actively writing code that deals with Web Application
493 Frameworks. This package is probably just another Web Application
494 Framework and may be worth using or may not be worth using. As of this
495 writing (July 1999) it is by no means clear if this software will be
496 developed further in the future. The author has written it over many
497 years and is deploying it in several places. B<Update 2006-02-03:
498 Development stalled since 2001 and now discontinued.>
499  
500 There is no official support for this software. If you find it useful
501 or even if you find it useless, please mail the author directly.
502  
503 But please make sure you remember: THE RELEASE IS FOR DEMONSTRATION
504 PURPOSES ONLY.
505  
506 =head1 DESCRIPTION
507  
508 The Apache::HeavyCGI framework is intended to provide a couple of
509 simple tricks that make it easier to write complex CGI solutions. It
510 has been developed on a site that runs all requests through a single
511 mod_perl handler that in turn uses CGI.pm or Apache::Request as the
512 query interface. So Apache::HeavyCGI is -- as the name implies -- not
513 merely for multi-page CGI scripts (for which there are other
514 solutions), but it is for the integration of many different pages into
515 a single solution. The many different pages can then conveniently
516 share common tasks.
517  
518 The approach taken by Apache::HeavyCGI is a components-driven one with
519 all components being pure perl. So if you're not looking for yet
520 another embedded perl solution, and aren't intimidated by perl, please
521 read on.
522  
523 =head2 Stacked handlers suck
524  
525 If you have had a look at stacked handlers, you might have noticed
526 that the model for stacking handlers often is too primitive. The model
527 supposes that the final form of a document can be found by running
528 several passes over a single entity, each pass refining the entity,
529 manipulating some headers, maybe even passing some notes to the next
530 handler, and in the most advanced form passing pnotes between
531 handlers. A lot of Web pages may fit into that model, even complex
532 ones, but it doesn't scale well for pages that result out of a
533 structure that's more complicated than adjacent items. The more
534 complexity you add to a page, the more overhead is generated by the
535 model, because for every handler you push onto the stack, the whole
536 document has to be parsed and recomposed again and headers have to be
537 re-examined and possibly changed.
538  
539 =head2 Why not subclass Apache
540  
541 Inheritance provokes namespace conflicts. Besides this, I see little
542 reason why one should favor inheritance over a B<using> relationship.
543 The current implementation of Apache::HeavyCGI is very closely coupled
544 with the Apache class anyway, so we could do inheritance too. No big
545 deal I suppose. The downside of the current way of doing it is that we
546 have to write
547  
548 my $r = $obj->{R};
549  
550 very often, but that's about it. The upside is, that we know which
551 manpage to read for the different methods provided by C<$obj->{R}>,
552 C<$obj->{CGI}>, and C<$obj> itself.
553  
554 =head2 Composing applications
555  
556 Apache::HeavyCGI takes an approach that is more ambitious for handling
557 complex tasks. The underlying model for the production of a document
558 is that of a puzzle. An HTML (or XML or SGML or whatever) page is
559 regarded as a sequence of static and dynamic parts, each of which has
560 some influence on the final output. Typically, in today's Webpages,
561 the dynamic parts are filled into table cells, i.e. contents between
562 some C<< <TD></TD> >> tokens. But this is not necessarily so. The
563 static parts in between typically are some HTML markup, but this also
564 isn't forced by the model. The model simply expects a sequence of
565 static and dynamic parts. Static and dynamic parts can appear in
566 random order. In the extreme case of a picture you would only have one
567 part, either static or dynamic. HeavyCGI could handle this, but I
568 don't see a particular advantage of HeavyCGI over a simple single
569 handler.
570  
571 In addition to the task of generating the contents of the page, there
572 is the other task of producing correct headers. Header composition is
573 an often neglected task in the CGI world. Because pages are generated
574 dynamically, people believe that pages without a Last-Modified header
575 are fine, and that an If-Modified-Since header in the browser's
576 request can go by unnoticed. This laissez-faire principle gets in the
577 way when you try to establish a server that is entirely driven by
578 dynamic components and the number of hits is significant.
579  
580 =head2 Header Composition, Parameter Processing, and Content Creation
581  
582 The three big tasks a CGI script has to master are Headers, Parameters
583 and the Content. In general one can say, content creation SHOULD not
584 start before all parameters are processed. In complex scenarios you
585 MUST expect that the whole layout may depend on one parameter.
586 Additionally we can say that some header related data SHOULD be
587 processed very early because they might result in a shortcut that
588 saves us a lot of processing.
589  
590 Consequently, Apache::HeavyCGI divides the tasks to be done for a
591 request into four phases and distributes the four phases among an
592 arbitrary number of modules. Which modules are participating in the
593 creation of a page is the design decision of the programmer.
594  
595 The perl model that maps (at least IMHO) ideally to this task
596 description is an object oriented approach that identifies a couple of
597 phases by method names and a couple of components by class names. To
598 create an application with Apache::HeavyCGI, the programmer specifies
599 the names of all classes that are involved. All classes are singleton
600 classes, i.e. they have no identity of their own but can be used to do
601 something useful by working on an object that is passed to them.
602 Singletons have an @ISA relation to L<Class::Singleton> which can be
603 found on CPAN. As such, the classes can only have a single instance
604 which can be found by calling the C<< CLASS->instance >> method. We'll
605 call these objects after the mod_perl convention I<handlers>.
606  
607 Every request maps to exactly one Apache::HeavyCGI object. The
608 programmer uses the methods of this object by subclassing. The
609 HeavyCGI constructor creates objects of the AVHV type (pseudo-hashes).
610  
611 *** Note: after 0.0133 this was changed to an ordinary hash. ***
612  
613 If the inheriting class needs its own constructor, this needs to be an
614 AVHV compatible constructor. A description of AVHV can be found in
615 L<fields>.
616  
617 *** Note: after 0.0133 this was changed to be an ordinary hash. ***
618  
619 An Apache::HeavyCGI object usually is constructed with the
620 C<new> method and after that the programmer calls the C<dispatch>
621 method on this object. HeavyCGI will then perform various
622 initializations and then ask all nominated handlers in turn to perform
623 the I<header> method and in a second round to perform the I<parameter>
624 method. In most cases it will be the case that the availability of a
625 method can be determined at compile time of the handler. If this is
626 true, it is possible to create an execution plan at compile time that
627 determines the sequence of calls such that no runtime is lost to check
628 method availability. Such an execution plan can be created with the
629 L<Apache::HeavyCGI::ExePlan> module. All of the called methods will
630 get the HeavyCGI request object passed as the second parameter.
631  
632 There are no fixed rules as to what has to happen within the C<header>
633 and C<parameter> method. As a rule of thumb it is recommended to
634 determine and set the object attributes LAST_MODIFIED and EXPIRES (see
635 below) within the header() method. It is also recommended to inject
636 the L<Apache::HeavyCGI::IfModified> module as the last header handler,
637 so that the application can abort early with an Not Modified header. I
638 would recommend that in the header phase you do as little as possible
639 parameter processing except for those parameters that are related to
640 the last modification date of the generated page.
641  
642 =head2 Terminating the handler calls or triggering errors.
643  
644 Sometimes you want to stop calling the handlers, because you think
645 that processing the request is already done. In that case you can do a
646  
647 die Apache::HeavyCGI::Exception->new(HTTP_STATUS => status);
648  
649 at any point within prepare() and the specified status will be
650 returned to the Apache handler. This is useful for example for the
651 Apache::HeavyCGI::IfModified module which sends the response headers
652 and then dies with HTTP_STATUS set to Apache::Constants::DONE.
653 Redirectors presumably would set up their headers and set it to
654 Apache::Constants::HTTP_MOVED_TEMPORARILY.
655  
656 Another task for Perl exceptions are errors: In case of an error
657 within the prepare loop, all you need to do is
658  
659 die Apache::HeavyCGI::Exception->new(ERROR=>[array_of_error_messages]);
660  
661 The error is caught at the end of the prepare loop and the anonymous
662 array that is being passed to $@ will then be appended to
663 C<@{$self-E<gt>{ERROR}}>. You should check for $self->{ERROR} within
664 your layout method to return an appropriate response to the client.
665  
666 =head2 Layout and Text Composition
667  
668 After the header and the parameter phase, the application should have
669 set up the object that is able to characterize the complete
670 application and its status. No changes to the object should happen
671 from now on.
672  
673 In the next phase Apache::HeavyCGI will ask this object to perform the
674 C<layout> method that has the duty to generate an
675 Apache::HeavyCGI::Layout (or compatible) object. Please read more
676 about this object in L<Apache::HeavyCGI::Layout>. For our HeavyCGI
677 object it is only relevant that this Layout object can compose itself
678 as a string in the as_string() method. As a layout object can be
679 composed as an abstraction of a layout and independent of
680 request-specific contents, it is recommended to cache the most
681 important layouts. This is part of the reponsibility of the
682 programmer.
683  
684 In the next step HeavyCGI stores a string representation of current
685 request by calling the as_string() method on the layout object and
686 passing itself to it as the first argument. By passing itself to the
687 Layout object all the request-specific data get married to the
688 layout-specific data and we reach the stage where stacked handlers
689 usually start, we get at a composed content that is ready for
690 shipping.
691  
692 The last phase deals with setting up the yet unfinished headers,
693 eventually compressing, recoding and measuring the content, and
694 delivering the request to the browser. The two methods finish() and
695 deliver() are responsible for that phase. The default deliver() method
696 is pretty generic, it calls finish(), then sends the headers, and
697 sends the content only if the request method wasn't a HEAD. It then
698 returns Apache's constant DONE to the caller, so that Apache won't do
699 anything except logging on this request. The method finish is more apt
700 to being overridden. The default finish() method sets the content type
701 to text/html, compresses the content if the browser understands
702 compressed data and Compress::Zlib is available, it also sets the
703 headers Vary, Expires, Last-Modified, and Content-Length. You most
704 probably will want to override the finish method.
705  
706 head2 Summing up
707 +-------------------+
708 | sub handler {...} |
709 +--------------------+ | (sub init {...}) |
710 |Your::Class |---defines------>| |
711 |ISA Apache::HeavyCGI| | sub layout {...} |
712 +--------------------+ | sub finish {...} |
713 +-------------------+
714  
715 +-------------------+
716 | sub new {...} |
717 +--------------------+ | sub dispatch {...}|
718 |Apache::HeavyCGI |---defines------>| sub prepare {...} |
719 +--------------------+ | sub deliver {...} |
720 +-------------------+
721  
722 +----------------------+ +--------------------+
723 |Handler_1 .. Handler_N| | sub header {...} |
724 |ISA Class::Singleton |---define----->| sub parameter {...}|
725 +----------------------+ +--------------------+
726  
727 +----+
728 |Your|
729 |Duty|
730 +----------------------------+----------------------------------------+----+
731 |Apache | calls Your::Class::handler() | |
732 +----------------------------+----------------------------------------+----+
733 | | nominates the handlers, | |
734 |Your::Class::handler() | constructs $self, | ** |
735 | | and calls $self->dispatch | |
736 +----------------------------+----------------------------------------+----+
737 | | $self->init (does nothing) | ?? |
738 | | $self->prepare (see below) | |
739 |Apache::HeavyCGI::dispatch()| calls $self->layout (sets up layout)| ** |
740 | | $self->finish (headers and | ** |
741 | | gross content) | |
742 | | $self->deliver (delivers) | ?? |
743 +----------------------------+----------------------------------------+----+
744 |Apache::HeavyCGI::prepare() | calls HANDLER->instance->header($self) | ** |
745 | | and HANDLER->instance->parameter($self)| ** |
746 | | on all of your nominated handlers | |
747 +----------------------------+----------------------------------------+----+
748  
749  
750 =head1 Object Attributes
751  
752 As already mentioned, the HeavyCGI object is a pseudo-hash, i.e. can
753 be treated like a HASH, but all attributes that are being used must be
754 predeclared at compile time with a C<use fields> clause.
755  
756 The convention regarding attributes is as simple as it can be:
757 uppercase attributes are reserved for the Apache::HeavyCGI class, all
758 other attribute names are at your disposition if you write a subclass.
759  
760 The following attributes are currently defined. The module author's
761 production environment has a couple of attributes more that seem to
762 work well but most probably need more thought to be implemented in a
763 generic way.
764  
765 =over
766  
767 =item CAN_GZIP
768  
769 Set by the can_gzip method. True if client is able to handle gzipped
770 data.
771  
772 =item CAN_PNG
773  
774 Set by the can_png method. True if client is able to handle PNG.
775  
776 =item CAN_UTF8
777  
778 Set by the can_utf8 method. True if client is able to handle UTF8
779 endoded data.
780  
781 =item CGI
782  
783 An object that handles GET and POST parameters and offers the method
784 param() and upload() in a manner compatible with Apache::Request.
785 Needs to be constructed and set by the user typically in the
786 contructor.
787  
788 =item CHARSET
789  
790 Optional attribute to denote the charset in which the outgoing data
791 are being encoded. Only used within the finish method. If it is set,
792 the finish() method will set the content type to text/html with this
793 charset.
794  
795 =item CONTENT
796  
797 Scalar that contains the content that should be sent to the user
798 uncompressed. During te finish() method the content may become
799 compressed.
800  
801 =item DOCUMENT_ROOT
802  
803 Unused.
804  
805 =item ERROR
806  
807 Anonymous array that accumulates error messages. HeavyCGI doesn't
808 handle the error though. It is left to the user to set up a proper
809 response to the user.
810  
811 =item EXECUTION_PLAN
812  
813 Object of type L<Apache::HeavyCGI::ExePlan>. It is recommended to
814 compute the object at startup time and always pass the same execution
815 plan into the constructor.
816  
817 =item EXPIRES
818  
819 Optional Attribute set by the expires() method. If set, HeavyCGI will
820 send an Expires header. The EXPIRES attribute needs to contain an
821 L<Apache::HeavyCGI::Date> object.
822  
823 =item HANDLER
824  
825 If there is an EXECUTION_PLAN, this attribute is ignored. Without an
826 EXECUTION_PLAN, it must be an array of package names. HeavyCGI treats
827 the packages as Class::Singleton classes. During the prepare() method
828 HeavyCGI calls HANDLER->instance->header($self) and
829 HANDLER->instance->parameter($self) on all of your nominated handlers.
830  
831 =item LAST_MODIFIED
832  
833 Optional Attribute set by the last_modified() method. If set, HeavyCGI
834 will send a Last-Modified header of the specified time, otherwise it
835 sends a Last-Modified header of the current time. The attribute needs
836 to contain an L<Apache::HeavyCGI::Date> object.
837  
838 =item MYURL
839  
840 The URL of the running request set by the myurl() method. Contains an
841 URI::URL object.
842  
843 =item R
844  
845 The Apache Request object for the running request. Needs to be set up
846 in the constructor by the user.
847  
848 =item REFERER
849  
850 Unused.
851  
852 =item SERVERROOT_URL
853  
854 The URL of the running request's server-root set by the
855 serverroot_url() method. Contains an URI::URL object.
856  
857 =item SERVER_ADMIN
858  
859 Unused.
860  
861 =item TIME
862  
863 The time when this request started set by the time() method. Please
864 note, that the time() system call is considerable faster than the
865 method call to Apache::HeavyCGI::time. The advantage of calling using
866 the TIME attribute is that it is self-consistent (remains the same
867 during a request).
868  
869 =item TODAY
870  
871 Today's date in the format 9999-99-99 set by the today() method, based
872 on the time() method.
873  
874 =back
875  
876  
877  
878 =head2 Performance
879  
880 Don't expect Apache::HeavyCGI to serve 10 million page impressions a
881 day. The server I have developed it for is a double processor machine
882 with 233 MHz, and each request is handled by about 30 different
883 handlers: a few trigonometric, database, formatting, and recoding
884 routines. With this overhead each request takes about a tenth of a
885 second which in many environments will be regarded as slow. On the
886 other hand, the server is well respected for its excellent response
887 times. YMMV.
888  
889 =head1 BUGS
890  
891 The fields pragma doesn't mix very well with Apache::StatINC. When
892 working with HeavyCGI you have to restart your server quite often when
893 you change your main class. I believe, this could be fixed in
894 fields.pm, but I haven't tried. A workaround is to avoid changing the
895 main class, e.g. by delegating the layout() method to a different
896 class.
897  
898 *** Note: this has no meaning anymore after 0.0133 ***
899  
900 =head1 AUTHOR
901  
902 Andreas Koenig <andreas.koenig@anima.de>. Thanks to Jochen Wiedmann
903 for heavy debates about the code and crucial performance enhancement
904 suggestions. The development of this code was sponsered by
905 www.speed-link.de.
906  
907 =cut
908