Apache/JAF.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Apache/JAF/Cookies.pm ↑ Summary
1 package Apache::JAF;
2  
3 1 ▶use 5.6.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use Template ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Template::Provider;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Template::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Template::Document;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 our @ISA = qw( Template::Provider );
12  
13 0 ▶use Apache ();
Subroutine BEGIN: called CC=1 SCAR=2.6
14 use Apache::Util ();
15 use Apache::JAF::Util ();
16 use JAF::Util ();
17  
18 use Apache::Request ();
19 use Apache::Constants qw( :common REDIRECT );
20 use Apache::File ();
21  
22 use Data::Dumper qw( Dumper );
23 use File::Find ();
24  
25 our $WIN32 = $^O =~ /win32/i;
26 our $RX = $WIN32 ? qr/\:(?!(?:\/|\\))/ : qr/\:/;
27 our $VERSION = do { my @r = (q$Revision: 0.21 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
28  
29 # Constructor
30 ################################################################################
31 sub new {
32 my ($ref, $r) = @_;
33 my $self = {};
34  
35 #
36 # use as template provider
37 #
38 if (ref($r) eq 'HASH') {
39 $self = $ref->SUPER::new($r);
40 bless ($self, $ref);
41 return $self;
42 }
43  
44 #
45 # use as framework
46 #
47 $r = Apache::Request->instance($r);
48 bless ($self, $ref);
49  
50 # r - request (filter-aware)
51 $self->{filter} = lc $r->dir_config('Filter') eq 'on';
52 $self->{r} = $self->{filter} ? $r->filter_register() : $r;
53 my $prefix = $r->dir_config('Apache_JAF_Prefix') || 0;
54  
55 # prefix - path|number of subdirs that must be removed from uri
56 $prefix = ($prefix =~ /^\/(.*)$/) ? scalar(my @tmp = split '/', $1) : int($prefix);
57  
58 # uri - reference to array that contains uri plitted by '/'
59 my @uri = split '/', $self->{r}->uri;
60 shift @uri if $prefix;
61 splice @uri, 0, ($prefix || 1);
62 if (@uri) {
63 $uri[-1] =~ s/\.html?$//i;
64 my $i = 0;
65 while ($i < @uri) {
66 splice @uri, $i, 2 if $uri[$i] =~ /^\w+:$/ && !$uri[$i+1];
67 $i++;
68 }
69 }
70 $self->{uri} = \@uri;
71  
72 # res - result hash, that passed to the template
73 $self->{res} = {};
74  
75 # for complex-name-handlers change '_' in handler name to '/' to provide
76 # real document tree in Templates folder
77 $self->{expand_path} = 1;
78  
79 # Level of warnings that will be written to the server's error_log
80 # every next level includes all options from previous
81 # 0: critical errors only
82 # 1: request processing line
83 # 2: client request
84 # 3: response headers
85 # 4: template variables
86 # 9: loading additional handlers
87 # 10: processed template
88 $self->{debug_level} = $self->{r}->dir_config('Apache_JAF_Debug') || 0;
89  
90 # Default response status and content-type
91 $self->{status} = NOT_FOUND;
92 $self->{type} = 'text/html';
93  
94 # Default template and includes extensions
95 $self->{template_ext} = '.html';
96 $self->{include_ext} = '.inc';
97 $self->{default_include} = 'default';
98  
99 # pre- and post-process templates (without extensions)
100 $self->{header} = 'header';
101 $self->{footer} = 'footer';
102 $self->{pre_chomp} = $self->{post_chomp} = $self->{trim} = 1;
103  
104 # Templates folder
105 $self->{templates} = $self->{r}->dir_config('Apache_JAF_Templates');
106 # Modules folder
107 $self->{modules} = $self->{r}->dir_config('Apache_JAF_Modules');
108  
109 # Compiled templates folder
110 $self->{compile_dir} = $self->{r}->dir_config('Apache_JAF_Compiled') || '/tmp';
111  
112 # This method must be implemented in derived class and must
113 # provide $self->{handler} property
114 $self->{handler} = $self->setup_handler();
115 return undef unless $self->{handler};
116  
117 # Log real and uri without prefix
118 $self->warn(1, "Starting $ref for " . $self->{r}->uri);
119 $self->warn(1, "URI: /" . join '/', @{$self->{uri}});
120 $self->warn(2, 'Request: ' . $self->{r}->as_string());
121  
122 # Load handlers if $HANDLERS_LOADED flag is unset or
123 # we are in debug mode ($self->{debug_level} > 0)
124 # reload modified templates also
125 my $package = ref $self;
126 { no strict 'refs';
127 $self->load_handlers($package, $self->{modules}) if $self->{debug_level} || !${ "${package}::HANDLERS_LOADED" };
128 $self->load_templates($package, $self->{templates}, 1) if $self->{debug_level} && ${ "${package}::SELF_PROVIDER" };
129 }
130  
131 # {page} key in result hash equals to current handler
132 $self->{res}{page} = $self->{handler};
133  
134 return $self
135 }
136  
137 # Load handlers and temlates during compile-time...
138 ################################################################################
139 sub import {
140 my ($package, %args) = @_;
141 $package = (caller())[0];
142 load_handlers(undef, $package, $args{handlers}) if $args{handlers};
143 load_templates(undef, $package, $args{templates}) if $args{templates};
144 }
145  
146 # Load handlers
147 ################################################################################
148 our (%HANDLERS, $PACKAGE);
149  
150 sub _process_as_handler {
151 return unless /\.pm$/;
152 my $text = undef;
153 if (-f && -r) {
154 open IN, $_;
155 $text = do { local $/; <IN> };
156 close IN;
157 $HANDLERS{ $_ }{TEXT} = $text;
158 }
159 }
160  
161 sub load_handlers {
162 my ($self, $package, $dir) = @_;
163 $dir ||= $self->{modules} if $self;
164  
165 if ($dir eq 'auto') {
166 $dir = $INC{ do { (my $dummy = $package) =~ s/::/\//g; "$dummy.pm"; } };
167 $dir =~ s/\.pm$/\/pages\//;
168 undef $dir unless -d $dir;
169 } else {
170 $dir .= '/' if $dir !~ /\/$/;
171 }
172  
173 if (defined $dir && -d $dir) {
174 local %HANDLERS = ();
175 File::Find::find({ wanted => \&_process_as_handler, no_chdir => 1 }, $dir);
176  
177 local $PACKAGE = qq{package $package; use strict;\n};
178 my $line = 2;
179 foreach my $file (keys %HANDLERS) {
180 my $lines = $HANDLERS{ $file }{TEXT} =~ s/(\n)/$1/sg;
181 $HANDLERS{ $file }{START} = $line;
182 $HANDLERS{ $file }{END} = $line += $lines + 1;
183 $PACKAGE .= $HANDLERS{ $file }{TEXT} . "\n";
184 }
185 $PACKAGE .= qq{\nour \$HANDLERS_LOADED=1;\n};
186  
187 $self && $self->warn(9, "Loading handlers for $package:\n $PACKAGE");
188 eval $PACKAGE;
189  
190 if ($@) {
191 (my $error = $@) =~ s/\(eval\s+\d+\)(\s+line\s+)(\d+)/
192 do {
193 my $replace = q{(can't find where...)};
194 foreach my $file (keys %HANDLERS) {
195 if ($HANDLERS{ $file }{START} <= $2 && $2 < $HANDLERS{ $file }{END}) {
196 $replace = "($file)$1" . ($2 - $HANDLERS{ $file }{START} + 1);
197 last;
198 }
199 }
200 $replace;
201 }
202 /egx;
203  
204 $self && $self->warn(0, $error) || die $error;
205 }
206 }
207 }
208  
209 # Load templates
210 ################################################################################
211 our ($TEMPLATES, $PARSER);
212  
213 sub _process_as_template {
214 if (exists $TEMPLATES->{$_} &&
215 (stat)[9] <= $TEMPLATES->{$_}{mtime} &&
216 !$TEMPLATES->{$_}{error}) {
217 return
218 }
219  
220 if (-f && -r) {
221 open IN, $_;
222 my $text = do { local $/; <IN> };
223 close IN;
224 unless ($TEMPLATES->{$_}{code} = Template::Document->new( $PARSER->parse($text) )) {
225 $TEMPLATES->{$_}{error} = $PARSER->error();
226 } else {
227 $TEMPLATES->{$_}{mtime} = (stat(_))[9];
228 }
229 }
230 }
231  
232 sub load_templates {
233 my ($self, $package, $dir, $reload) = @_;
234  
235 local $TEMPLATES = {};
236 local $PARSER = Template::Parser->new();
237  
238 if ($reload) {
239 no strict 'refs';
240 $TEMPLATES = { %${ "${package}::TEMPLATES" } };
241 }
242  
243 $dir ||= $self->{templates} if $self;
244 if ($dir eq 'auto') {
245 $dir = $INC{ do { (my $dummy = $package) =~ s/::/\//g; "$dummy.pm"; } };
246 $dir =~ s/modules\/.*$/templates\//;
247 }
248  
249 File::Find::find({ wanted => \&_process_as_template, no_chdir => 1 }, split $RX, $dir);
250  
251 { no strict 'refs';
252 ${ "${package}::SELF_PROVIDER" } ||= 1;
253 ${ "${package}::TEMPLATES" } = { ${ "${package}::TEMPLATES" } ? %${ "${package}::TEMPLATES" } : (), %${ 'TEMPLATES' } };
254 }
255 }
256  
257 sub fetch {
258 my ($self, $name) = @_;
259 my $ref;
260 my $t = "${\( ref $self )}::TEMPLATES";
261 { no strict 'refs';
262 $ref = $$t;
263 }
264 foreach my $p (@{$self->paths()}) {
265 my $full_name = "$p/$name";
266 if (exists $ref->{$full_name}) {
267 if ((stat($full_name))[9] > $ref->{$full_name}{mtime}) {
268 load_templates(undef, ref $self, $p);
269 no strict 'refs';
270 $ref = $$t;
271 }
272 return wantarray ? ($ref->{$full_name}{code}, $ref->{$full_name}{error}) : $ref->{$full_name}{code};
273 }
274 }
275 return (undef, undef);
276 }
277  
278 # ABSTRACT: setup_handler must be implemented in derived
279 # class to provide $self->{handler} property mandatory
280 ################################################################################
281 sub setup_handler { $_[0]->warn(0, 'Abstract method call!') }
282  
283 # Last modified
284 ################################################################################
285 sub last_modified { time() }
286  
287 # Cache
288 ################################################################################
289 sub cache { undef }
290  
291 # Log errors and warnings
292 ################################################################################
293 sub warn {
294 my ($self, $level, $message) = @_;
295 my $method = $level ? 'warn' : 'log_error';
296 #
297 # server_name included in warning string to distinguish different servers in
298 # overall error log... (default behavior)
299 #
300 $self->{r}->$method('[' . $self->{r}->get_server_name() . '] ' . $message) if $self->{debug_level} >= $level;
301 }
302  
303 # Check template existance
304 ################################################################################
305 sub _exists {
306 my ($self, $dir, $name, $self_provider) = @_;
307
308 return 0 unless $self_provider ? do {
309 no strict 'refs';
310 my $t = "${\( ref $self )}::TEMPLATES";
311 exists $$t->{"$dir/$name"};
312 } : -f $dir . "/$name";
313  
314 $self->warn(1, 'Template: /' . $name);
315 $self->{template} = $name;
316 return 1
317 }
318  
319 # Process template
320 ################################################################################
321 sub process_template {
322 my ($self) = @_;
323  
324 my $self_provider;
325 { no strict 'refs'; $self_provider = ${ "${\( ref $self )}::SELF_PROVIDER" }; }
326 local $Template::Config::PROVIDER = ref $self if $self_provider;
327 local $Template::Config::STASH = 'Template::Stash::XS';
328  
329 unless ($self->{template}) {
330 my $tx = "(\\$self->{template_ext})\$";
331 foreach (split $RX, $self->{templates}) {
332 my $test_name = (join '/', ($self->{handler}, @{$self->{uri}})) . $self->{template_ext};
333 last if $self->_exists($_, $test_name, $self_provider);
334 $test_name =~ s{$tx}{/index$1};
335 last if $self->_exists($_, $test_name, $self_provider);
336 }
337 $self->{template} ||= $self->{handler} . $self->{template_ext};
338 }
339 $self->warn(1, 'Ready to process template for handler: ' . $self->{handler});
340  
341 my $tt = Template->new({
342 INCLUDE_PATH => $self->{templates},
343 $self_provider ? () : (
344 PRE_CHOMP => $self->{pre_chomp},
345 POST_CHOMP => $self->{post_chomp},
346 TRIM => $self->{trim},
347 ($self->{compile_dir} ? (COMPILE_DIR => $self->{compile_dir}) : ()),
348 ),
349 ($self->{default_include} || $self->{header} ? ('PRE_PROCESS' => [$self->{default_include} && $self->{default_include} . $self->{include_ext} || (), $self->{header} && $self->{header} . $self->{include_ext} || ()]) : ()),
350 ($self->{footer} ? ('POST_PROCESS' => $self->{footer} . $self->{include_ext}) : ())
351 });
352 $self->warn(4, 'Template variables: ' . Dumper $self->{res});
353  
354 my $result;
355 $tt->process($self->{template}, $self->{res}, \$result);
356 if (my $te = $tt->error()) {
357 if ($te =~ /not found/) {
358 $self->warn(1, "Template error: $te");
359 $self->{status} = NOT_FOUND;
360 } else {
361 $self->warn(0, "Template error: $te");
362 $self->{status} = SERVER_ERROR;
363 }
364 } else {
365 $self->warn(1, 'Template processed');
366 $self->warn(10, $result);
367 }
368  
369 undef $tt;
370 return \$result;
371 }
372  
373 # Reduce stat calls (only dynamic content from mod_perl-powered server)
374 ################################################################################
375 sub trans_handler ($$) { OK }
376  
377 # Actual Apache handler
378 ################################################################################
379 sub handler ($$) {
380 my ($self, $r) = @_;
381 my $time;
382 eval "use Time::HiRes ()";
383 $time = Time::HiRes::time() unless $@;
384  
385 if (-f $r->document_root() . $r->uri() && -r _) {
386 $r->filename($r->document_root() . $r->uri());
387 $r->warn('Static file request: ' . $r->filename());
388 return DECLINED;
389 }
390  
391 $self = $self->new($r) unless ref($self);
392 unless ($self) {
393 $self->warn(0, "Can't create handler object!");
394 return SERVER_ERROR;
395 }
396  
397 my $result;
398 $self->{status} = $self->site_handler();
399 $result = $self->process_template() if $self->{status} == OK && $self->{type} =~ /^text/ && !$self->{r}->header_only;
400  
401 if ($self->{status} == OK) {
402 $self->{r}->send_http_header($self->{type});
403 return $self->{status} if $self->{r}->header_only;
404  
405 if ($self->{type} =~ /^text/) {
406 #
407 # Apache::Filter->print() must(?) be patched for printing referenced scalars
408 #
409 $self->{r}->print($self->{filter} ? $$result : $result);
410 } else {
411 #
412 # if handler set $self->{type} other than text/(html|plain)
413 # then data must be send to the client by on_send_..._data method
414 #
415 my $method = "on_send_${\($self->{handler})}_data";
416 $self->$method(@{$self->{uri}}) if $self->can($method);
417 }
418 }
419  
420 $self->warn(3, 'Response headers: ' . Dumper {($self->{status} == OK) ? $self->{r}->headers_out() : $self->{r}->err_headers_out()});
421 $self->warn(1, sprintf 'Request processed in %0.3f sec', Time::HiRes::time() - $time) if $time;
422  
423 my $status = $self->{status};
424 undef $result;
425 undef $self;
426  
427 return $status
428 }
429  
430 # Global Apache::JAF handler. If you want some stuff before (and|or) after
431 # running handler you must override it like that:
432 #
433 # sub site_handler {
434 # my $self = shift;
435 #
436 # [before stuff goes here]
437 #
438 # $self->{status} = $self->SUPER::site_handler(@_);
439 #
440 # [after stuff goes here]
441 #
442 # return $self->{status}
443 # }
444 ################################################################################
445 sub site_handler {
446 my ($self) = @_;
447  
448 my ($method, $last_modified, $cache, $mtime);
449 foreach (($method, $last_modified, $cache) = map { $_ . $self->{handler} } qw(do_ last_modified_ cache_)) {
450 $_ =~ tr{/}{_} if $self->{expand_path};
451 }
452  
453 $self->warn(1, "Handler method: $method");
454  
455 $mtime = $self->last_modified(@{$self->{uri}});
456 $mtime = $self->$last_modified(@{$self->{uri}}) if $self->can($last_modified);
457 if ($mtime) {
458 $self->{r}->update_mtime($mtime);
459 $self->{r}->set_last_modified;
460 $self->{status} = $self->{r}->meets_conditions;
461 return $self->{status} unless $self->{status} == OK;
462 }
463  
464 if ($self->can($method)) {
465 #
466 # process template with handler
467 #
468 $self->warn(1, "Can do $method: Y");
469  
470 my $cstat = $self->cache(@{$self->{uri}});
471 $cstat = $self->$cache(@{$self->{uri}}) if $self->can($cache);
472 if ($cstat) {
473 $self->{status} = $cstat;
474 } else {
475 $self->{status} = $self->$method(@{$self->{uri}})
476 }
477 $self->{handler} =~ tr{_}{/} if $self->{expand_path} && $self->{type} =~ /^text/;
478 $self->warn(1, 'Content-type: ' . $self->{type});
479 } else {
480 #
481 # process template without handler (defaults variables only, header and footer)
482 #
483 $self->warn(1, "Can do $method: N");
484 $self->{status} = OK unless $self->{status} == SERVER_ERROR;
485 }
486  
487 return $self->{status};
488 }
489  
490 ### Additional utility methods for getting params
491  
492 sub param {
493 my ($self, $p) = @_;
494 my @params = map { $_ = JAF::Util::trim($_); length > 0 ? $_ : undef} ($self->{r}->param($p));
495 return $params[0];
496 }
497  
498 sub upload_fh {
499 my ($self, $p) = @_;
500 if($self->param($p)) {
501 my $upl = $self->{r}->upload($p);
502 return $upl->fh if($upl && $upl->fh)
503 }
504 return undef
505 }
506  
507 ### Methods for simplify handlers for download content instead of viewing it
508  
509 sub disable_header { undef $_[0]->{header} }
510 sub disable_footer { undef $_[0]->{footer} }
511 sub disable_header_footer { $_[0]->disable_header(); $_[0]->disable_footer(); }
512 sub download_type { $_[0]->{type} = 'application/x-force-download'; }
513 sub download_it { $_[0]->disable_header_footer(); $_[0]->download_type(); }
514  
515 ### methods for JAF database editing
516  
517 sub default_record_edit {
518 my ($self, $tbl, $options) = @_;
519  
520 if ($self->{r}->method() eq 'POST' && $self->param('act') eq 'edit') {
521 $tbl->update({
522 $tbl->{key} => $self->param($tbl->{key}),
523 map {defined $self->{r}->param($_) ? ($_ => $self->param($_)) : $options->{checkbox} && exists $options->{checkbox}{$_} ? ($_ => $options->{checkbox}{$_}) : ()} @{$tbl->{cols}}
524 }, $options);
525 }
526 }
527  
528 sub default_table_edit {
529 my ($self, $tbl, $options) = @_;
530  
531 if ($self->{r}->method() eq 'POST' && $self->param('act') eq 'edit') {
532 for (my $i=1; defined $self->param("$tbl->{key}_$i"); $i++) {
533 $tbl->delete({
534 $tbl->{key} => $self->param("$tbl->{key}_$i")
535 }, $options) if $self->param("dowhat_$i") eq 'del';
536 $tbl->update({
537 $tbl->{key} => $self->param("$tbl->{key}_$i"),
538 map {defined $self->{r}->param("${_}_$i") ? ($_ => $self->param("${_}_$i")) : $options->{checkbox} && exists $options->{checkbox}{$_} ? ($_ => $options->{checkbox}{$_}) : ()} @{$tbl->{cols}}
539 }, $options) if $self->param("dowhat_$i") eq 'upd';
540 }
541 } elsif ($self->param('act') eq 'add') {
542 unless ($tbl->insert({
543 map {defined $self->{r}->param($_) ? ($_ => $self->param($_)) : $options->{checkbox} && exists $options->{checkbox}{$_} ? ($_ => $options->{checkbox}{$_}) : ()} @{$tbl->{cols}}
544 }, $options)) {
545 foreach (@{$tbl->{cols}}) {
546 $self->{res}{$_} = $self->param($_);
547 }
548 }
549 }
550 }
551  
552 sub default_messages {
553 my ($self, $modeller) = @_;
554
555 %{$self->{cookies}} = Apache::Cookie->fetch() unless $self->{cookies};
556 if ($self->{status} == REDIRECT) {
557 my $messages = $modeller->messages();
558 if ($messages) {
559 Apache::Cookie->new($self->{r},
560 -name => 'messages',
561 -path => '/',
562 -value => Data::Dumper::Dumper $messages)->bake();
563 }
564 } elsif ($self->{status} == OK && $self->{type} =~ /^text/ && !$self->{r}->header_only) {
565 my $VAR1;
566 if (exists $self->{cookies}{messages} && eval $self->{cookies}{messages}->value) {
567 $self->{res}{messages} = $VAR1;
568 Apache::Cookie->new($self->{r},
569 -name => $self->{res}{messages} ? 'messages' : 'error',
570 -path => '/',
571 -value => '')->bake();
572 } else {
573 $self->{res}{messages} = $modeller->messages();
574 }
575 }
576 }
577  
578 =head1 NAME
579  
580 Apache::JAF -- mod_perl and Template-Toolkit web applications framework
581  
582 =head1 SYNOPSIS
583  
584 =over 4
585  
586 =item controller -- a mod_perl module that drives your application
587  
588 package Apache::JAF::MyJAF;
589 use strict;
590 use JAF::MyJAF; # optional
591 # loading mini-handlers & templates during compilation time
592 use Apache::JAF (
593 handlers => '/examples/site/modules/Apache/JAF/MyJAF/pages/', # 'auto' if you want to use suggested file structure
594 templates => '/examples/site/templates/' # the same comment
595 );
596 our @ISA = qw(Apache::JAF);
597  
598 # determine handler to call
599 sub setup_handler {
600 my ($self) = @_;
601 # the page handler for each URI of sample site is 'do_index'
602 # you should swap left and right ||-parts for real application
603 my $handler = 'index' || shift @{$self->{uri}};
604 return $handler;
605 }
606  
607 sub site_handler {
608 my ($self) = @_;
609 # common stuff before handler is called
610 $self->{m} = JAF::MyJAF->new(); # create modeller -- if needed
611 $self->SUPER::site_handler();
612 # common stuff after handler is called
613 return $self->{status}
614 }
615 1;
616  
617 =item page handler -- controller's method that makes one (or more) pages
618  
619 sub do_index {
620 my ($self) = @_;
621 # page handler must fill $self->{res} hash that process with template
622 $self->{res}{test} = __PACKAGE__ . 'test';
623 # and return Apache constant according it's logic
624 return OK;
625 }
626  
627 =item modeller -- a module that encapsulates application business-logic
628  
629 package JAF::MyJAF;
630 use strict;
631 use DBI;
632 use base qw( JAF );
633  
634 sub new {
635 my ($class, $self) = @_;
636 $self->{dbh} = DBI->connect(...);
637 return bless $self, $class;
638 }
639 1;
640  
641 =item Apache configuration (F<httpd.conf>)
642  
643 DocumentRoot /examples/site/data
644 <Location />
645 <Perl>
646 use lib qw(/examples/site/modules);
647 use Apache::JAF::MyJAF;
648 </Perl>
649 SetHandler perl-script
650 PerlHandler Apache::JAF::MyJAF
651 PerlSetVar Apache_JAF_Templates /examples/site/templates
652 # optional or can be specified in Apache::JAF descendant (default value is used in example)
653 PerlSetVar Apache_JAF_Modules /examples/site/modules/Apache/JAF/MyJAF/pages
654 # optional or can be specified in Apache::JAF descendant (default value is used in example)
655 PerlSetVar Apache_JAF_Compiled /tmp
656 </Location>
657  
658 =back
659  
660 =head1 DESCRIPTION
661  
662 =head2 Introduction
663  
664 Apache::JAF is designed for creation web applications based on MVC (Model-View-Controller)
665 concept.
666  
667 =over 4
668  
669 =item *
670  
671 I<Modeller> is JAF descendant
672  
673 =item *
674  
675 I<Controller> is Apache::JAF descendant
676  
677 =item *
678  
679 and the I<Viewer> is set of the templates using Template-Toolkit markup syntax
680  
681 =back
682  
683 This separation hardly simplifies the dynamic development of sites by designers and programmers.
684 Each programmer works on own part of the project writing separate controller's parts.
685 Designers have to work only on visual performance of templates.
686  
687 =head2 Suggested file structure
688  
689 Suggested site's on-disk structure is:
690  
691 site
692 |
693 +-- data
694 |
695 +-- modules
696 |
697 +-- templates
698  
699 =over 4
700  
701 =item I<data>
702  
703 document_root of site. All static files (e.g. JavaScripts, pictures, CSSs etc)
704 must be placed here
705  
706 =item I<modules>
707  
708 Storage place for site modules -- must be in C<@INC>'s
709  
710 =item I<templates>
711  
712 The place of your site's templates. Framework is designed to reproduce
713 site's structure in this folder. It's just like document_root for static site.
714  
715 =back
716  
717 =head2 Request processing pipeline
718  
719 The C<Apache::JAF::handler> intercepts every request for specified location, and
720 process it's own way:
721  
722 =over 4
723  
724 =item 1
725  
726 If requested file exists then nothing happens. The handle declines request with C<DECLINE>.
727  
728 =item 2
729  
730 Otherwise the instance of Apache::JAF's descendant is created and C<setup_handler> method is called.
731 You B<must override> this method and return determined handler's name. Usually it's the first part of
732 URI or just C<index>. Also handlers from C<Apache_JAF_Modules> folder is loaded into package's
733 namespace if C<$self-E<gt>{debug_level}> E<gt> 0 or handlers were not loaded during module
734 compilation.
735  
736 =item 3
737  
738 Then goes C<site_handler> calling. If you have common tasks for each handler you can
739 override it. C<site_handler> calls your own handler. It's name is returned by C<setup_handler>.
740 Usually this "mini-handler" is I<very> simple. It have to be implemented as package method with
741 C<do_I<E<lt>handler nameE<gt>>> name. You have to fill C<$self-E<gt>{res}> hash with
742 result and return Apache constant according to handler's logic (C<OK>, C<NOT_FOUND>,
743 C<FORBIDDEN> and so on). The sample is shown in L<"SYNOPSIS">.
744  
745 =item 4
746  
747 If the previous step fulfills correctly, and C<$self-E<gt>{type}> property is C<text/*> then
748 result of processing template returns to client. If type of result is not
749 like text, one more method is needed to implement: C<on_send_I<E<lt>handeler nameE<gt>>_data>.
750 It must return binary data to client. This way you may create handlers for
751 dynamic generation of images, M$ Excel workbooks and any other type of data.
752  
753 =back
754  
755 =head2 Apache::JAF methods
756  
757 =over 4
758  
759 =item setup_handler
760  
761 This method you must override in your Apache::JAF descendant. You must return handler's
762 name (that will be called as I<do_E<lt>handler nameE<gt>> method later) from it depending
763 on URI requested by user. You may set site-wide properties such as I<debug_level>, I<header>
764 or I<footer>, templates and includes extensions and so on. If handler name depends on
765 application logic implemented in modeller then you have to create modeller in this method
766 and store it in I<m> property for later use.
767 The primary I<setup_handler> is shown in L<"SYNOPSIS">.
768  
769 =item site_handler
770  
771 You can override this method to provide common tasks for each of your page-handlers. For
772 example you may create instance of modeller class, provide some custom
773 authorization/authentication or sessions handling and so on. You must call
774 C<$selfE<gt>SUPER::site_handler> and return C<$self-E<gt>{status}> from it.
775  
776 =back
777  
778 =head2 Apache::JAF properties
779  
780 =over 4
781  
782 =item r
783  
784 Current C<Apache::Request> object.
785  
786 =item filter
787  
788 Using C<Apache::Filter> flag.
789  
790 =item uri
791  
792 Reference to the array of current URI (splitted by slash). Usually you need to modify
793 it in L<"setup_handler"> method to determine page's handler name. Remained array will be passed
794 to the page-handler method as a list of parameters.
795  
796 =item res
797  
798 Hash reference that holds page-handler results.
799  
800 =item expand_path
801  
802 Boolean flag for complex-name-handlers changes '_' to '/' in handler's name.
803 It provides real-like document tree in the templates folder.
804  
805 =item debug_level
806  
807 Look at B<Apache_JAF_Debug> in L<"CONFIGURATION"> section.
808  
809 =item status
810  
811 Default handler status is C<NOT_FOUND>.
812  
813 =item type
814  
815 Default content-type is C<text/html>. You can call C<$self-E<gt>download_type()>
816 for set unexisting MIME-type to force browser download content instead of viewing it.
817  
818 =item template_ext, include_ext
819  
820 Default template extension is C<.html>.
821 Default include template extension is C<.inc>.
822  
823 =item default_include
824  
825 Site-wide include template. Default value is... C<default>.
826  
827 =item header, footer
828  
829 Site-wide pre- and post-include templates. Defalut values are C<header> and C<footer>.
830 I<Note:>You must undef this properies if you want create page-template without it. For
831 example for page in pop-up window (C<disable_header>, C<disable_footer>, and
832 C<disable_header_footer> methods).
833  
834 =item templates
835  
836 Path to the templates folder. You may have different sets of templates for different
837 views of results generated by your page-handlers.
838  
839 =item handler
840  
841 Result of C<setup_handler> method is stored here for later use.
842  
843 =item I<other properites>
844  
845 For internal use only.
846  
847 =back
848  
849 =head2 Implementing handlers
850  
851 Page handlers are simple.
852 Their methods are with C<do_E<lt>handler nameE<gt>> name. You have to
853 analyse given parameters, fill out C<$self-E<gt>{res}> hash with handler results that will
854 be processed with template and return one of C<Apache::Constants>. Usually it's C<OK>,
855 but may be C<NOT_FOUND> if parameters passed to handlers are invalid for some reason.
856  
857 Look into F<examples/*> folder in the distribution package for some guidelines.
858  
859 =head2 Templates structure and syntax
860  
861 Template for a specific handler consists of:
862  
863 =over 4
864  
865 =item 1 default.inc
866  
867 Common C<[% BLOCK %]>s for all site templates. Processed before header and main tamplate.
868  
869 =item 2 header.inc
870  
871 Header template. Processed before main handler's template.
872  
873 =item 3 I<E<lt>handler nameE<gt>>.html
874  
875 Main handler's template.
876  
877 =item 4 footer.inc
878  
879 Footer template. Processed after main handler's template.
880  
881 =back
882  
883 Default names and extensions are shown. All of them are configurable in processing
884 handler methods. For example you have to disable processing header and footer for
885 handler that produces not C<text/*> content.
886  
887 Templates syntax is described at L<http://www.template-toolkit.org/docs/plain/Manual/>.
888  
889 =head1 CONFIGURATION
890  
891 =over 4
892  
893 =item Apache_JAF_Prefix
894  
895 Number of URI parts (between slashes) or path that must be removed from request URI.
896 Useful for implementing dynamic part of almost static site. It simplifies names of page handlers.
897  
898  
899 =item Apache_JAF_Templates
900  
901 Path to templates folder. Several paths may be separated by semicolon.
902 I<Win32 note>:
903 This separator works too. Don't get confused with full paths with drive
904 letters.
905  
906 =item Apache_JAF_Modules
907  
908 Path to page handlers folder. By default it's controller location plus C</pages>.
909  
910 =item Apache_JAF_Compiled
911  
912 Path to compiled templates folder. Default is C</tmp>.
913 Saving compiled templates on disk dramatically improves overall site performance.
914  
915 =item Apache_JAF_Debug
916  
917 Application's debug level. The amount of debug info written to the Apache error_log.
918 Ranges from 0 to 10.
919  
920 0: critical errors only
921 1: request processing line
922 2: client request
923 3: response headers
924 4: template variables
925 5-8: not used (for future enchancements)
926 9: loading additional handlers
927 10: processed template
928  
929 Also this setting affecting page-handlers loading. If debug level is 0 -- handlers
930 are loaded only on server-start. Else handlers loaded on every request. That simplifies
931 development process but increases request processing time. So it's not good to set
932 debug level greater than 0 in production environment.
933  
934 I<Note:>
935 This setting is overrided by setting C<$self-E<gt>{debug_level}>.
936  
937 =back
938  
939 =head1 SEE ALSO
940  
941 =over 4
942  
943 =item *
944  
945 B<mod_perl> -- Perl and Apache integration project (L<http://perl.apache.org>)
946  
947 =item *
948  
949 B<Template-Toolkit> -- template processing system (L<http://www.tt2.org>)
950  
951 =item *
952  
953 F<examples/*> -- sample site driven by Apache::JAF
954  
955 =item *
956  
957 L<http://jaf.webzavod.ru> -- Apache::JAF companion website
958  
959 =back
960  
961 =head1 AUTHOR
962  
963 Greg "Grishace" Belenky <greg@webzavod.ru>
964  
965 =head1 COPYRIGHT
966  
967 Copyright (C) 2001-2003 Greg Belenky
968 Copyright (C) 2002-2003 WebZavod (http://www.webzavod.ru) programming team
969  
970 This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
971  
972 =cut
973  
974 'Grishace';
« Apache/JAF/Cookies.pm ↑ Summary