]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole.pm
reworked components
[maypole.git] / lib / Maypole.pm
1 package Maypole;
2 use base qw(Class::Accessor::Fast Class::Data::Inheritable);
3 use UNIVERSAL::require;
4 use strict;
5 use warnings;
6 use Maypole::Config;
7 use Maypole::Constants;
8 use Maypole::Headers;
9 use Maypole::Components;
10 use URI();
11 use URI::QueryParam;
12 use NEXT;
13 use File::MMagic::XS qw(:compat);
14
15 our $VERSION = '2.11';
16 our $mmagic = File::MMagic::XS->new();
17
18 # proposed privacy conventions:
19 # - no leading underscore     - public to custom application code and plugins
20 # - single leading underscore - private to the main Maypole stack - *not*
21 #     including plugins
22 # - double leading underscore - private to the current package
23
24 =head1 NAME
25
26 Maypole - MVC web application framework
27
28 =head1 SYNOPSIS
29
30 The canonical example used in the Maypole documentation is the beer database:
31
32     package BeerDB;
33     use strict;
34     use warnings; 
35     
36     # choose a frontend, initialise the config object, and load a plugin
37     use Maypole::Application qw/Relationship/;
38     
39     # get the empty config object created by Maypole::Application
40     my $config = __PACKAGE__->config;
41     
42     # basic settings
43     $config->uri_base("http://localhost/beerdb");
44     $config->template_root("/path/to/templates");
45     $config->rows_per_page(10);
46     $config->display_tables([qw/beer brewery pub style/]);
47
48     # table relationships
49     $config->relationships([
50         "a brewery produces beers",
51         "a style defines beers",
52         "a pub has beers on handpumps",
53         ]);
54         
55     # validation
56     BeerDB::Brewery->untaint_columns( printable => [qw/name notes url/] );
57     BeerDB::Pub->untaint_columns( printable => [qw/name notes url/] );
58     BeerDB::Style->untaint_columns( printable => [qw/name notes/] );
59     BeerDB::Beer->untaint_columns(
60         printable => [qw/abv name price notes/],
61         integer => [qw/style brewery score/],
62         date => [ qw/date/],
63     );
64
65     # set everything up
66     __PACKAGE__->setup("dbi:SQLite:t/beerdb.db");
67
68     1;    
69
70 =head1 DESCRIPTION
71
72 This documents the Maypole request object. See the L<Maypole::Manual>, for a
73 detailed guide to using Maypole.
74
75 Maypole is a Perl web application framework similar to Java's struts. It is 
76 essentially completely abstracted, and so doesn't know anything about
77 how to talk to the outside world.
78
79 To use it, you need to create a driver package which represents your entire
80 application. This is the C<BeerDB> package used as an example in the manual.
81
82 This needs to first use L<Maypole::Application> which will make your package
83 inherit from the appropriate platform driver such as C<Apache::MVC> or
84 C<CGI::Maypole>. Then, the driver calls C<setup>. This sets up the model classes
85 and configures your application. The default model class for Maypole uses
86 L<Class::DBI> to map a database to classes, but this can be changed by altering
87 configuration (B<before> calling setup.)
88
89
90 =head1 DOCUMENTATION AND SUPPORT
91
92 Note that some details in some of these resources may be out of date.
93
94 =over 4 
95
96 =item The Maypole Manual
97
98 The primary documentation is the Maypole manual. This lives in the 
99 C<Maypole::Manual> pod documents included with the distribution. 
100
101 =item Embedded POD
102
103 Individual packages within the distribution contain (more or less) detailed
104 reference documentation for their API.
105
106 =item Mailing lists
107
108 There are two mailing lists - maypole-devel and maypole-users - see
109 http://maypole.perl.org/?MailingList
110
111 =item The Maypole Wiki
112
113 The Maypole wiki provides a useful store of extra documentation -
114 http://maypole.perl.org
115
116 In particular, there's a FAQ (http://maypole.perl.org/?FAQ) and a cookbook
117 (http://maypole.perl.org/?Cookbook). Again, certain information on these pages
118 may be out of date.
119
120 =item Web applications with Maypole
121
122 A tutorial written by Simon Cozens for YAPC::EU 2005 -
123 http://www.droogs.org/perl/maypole/maypole-tutorial.pdf [228KB].
124
125 =item A Database-Driven Web Application in 18 Lines of Code
126
127 By Paul Barry, published in Linux Journal, March 2005.
128
129 http://www.linuxjournal.com/article/7937
130
131 "From zero to Web-based database application in eight easy steps".
132
133 Maypole won a 2005 Linux Journal Editor's Choice Award
134 (http://www.linuxjournal.com/article/8293) after featuring in this article. 
135
136 =item Build Web apps with Maypole
137
138 By Simon Cozens, on IBM's DeveloperWorks website, May 2004.
139
140 http://www-128.ibm.com/developerworks/linux/library/l-maypole/
141
142 =item Rapid Web Application Deployment with Maypole
143
144 By Simon Cozens, on O'Reilly's Perl website, April 2004.
145
146 http://www.perl.com/pub/a/2004/04/15/maypole.html
147
148 =item Authentication
149
150 Some notes written by Simon Cozens. A little bit out of date, but still 
151 very useful: http://www.droogs.org/perl/maypole/authentication.html
152
153 =item CheatSheet
154
155 There's a refcard for the Maypole (and Class::DBI) APIs on the wiki -
156 http://maypole.perl.org/?CheatSheet. Probably a little out of date now - it's a
157 wiki, so feel free to fix any errors!
158
159 =item Plugins and add-ons
160
161 There are a large and growing number of plugins and other add-on modules
162 available on CPAN - http://search.cpan.org/search?query=maypole&mode=module
163
164 =item del.icio.us
165
166 You can find a range of useful Maypole links, particularly to several thoughtful
167 blog entries, starting here: http://del.icio.us/search/?all=maypole
168
169 =item CPAN ratings
170
171 There are a couple of short reviews here:
172 http://cpanratings.perl.org/dist/Maypole
173
174 =back
175
176 =head1 DEMOS
177
178 A couple of demos are available, sometimes with source code and configs. 
179
180 =over 4 
181
182 =item http://maypole.perl.org/beerdb/
183
184 The standard BeerDB example, using the TT factory templates supplied in the
185 distribution.
186
187 =item beerdb.riverside-cms.co.uk
188
189 The standard BeerDB example, running on Mason, using the factory templates
190 supplied in the L<MasonX::Maypole> distribution.
191
192 =item beerfb.riverside-cms.co.uk
193
194 A demo of L<Maypole::FormBuilder>. This site is running on the set of Mason 
195 templates included in the L<Maypole::FormBuilder> distribution. See the 
196 synopsis of L<Maypole::Plugin::FormBuilder> for an example driver
197
198 =back
199
200 =cut
201
202 __PACKAGE__->mk_classdata($_) for qw( config init_done view_object model_classes_loaded);
203
204 __PACKAGE__->mk_accessors(
205     qw( params query objects model_class template_args output path
206         args action template error document_encoding content_type table
207         headers_in headers_out stash status parent)
208 );
209
210 __PACKAGE__->config( Maypole::Config->new() );
211
212 __PACKAGE__->init_done(0);
213
214 __PACKAGE__->model_classes_loaded(0);
215
216 =head1 HOOKABLE METHODS
217
218 As a framework, Maypole provides a number of B<hooks> - methods that are
219 intended to be overridden. Some of these methods come with useful default
220 behaviour, others do nothing by default. Hooks include:
221
222     Class methods
223     -------------
224     debug 
225     setup 
226     setup_model 
227     load_model_subclass
228     init
229     
230     Instance methods
231     ----------------
232     start_request_hook
233     is_model_applicable
234     get_session
235     authenticate
236     exception
237     additional_data
238     preprocess_path
239
240 =head1 CLASS METHODS
241
242 =over 4
243
244 =item debug
245
246     sub My::App::debug {1}
247
248 Returns the debugging flag. Override this in your application class to
249 enable/disable debugging.
250
251 You can also set the C<debug> flag via L<Maypole::Application>.
252
253 Some packages respond to higher debug levels, try increasing it to 2 or 3.
254
255
256 =cut
257
258 sub debug { 0 }
259
260 =item config
261
262 Returns the L<Maypole::Config> object
263
264 =item setup
265
266    My::App->setup($data_source, $user, $password, \%attr);
267
268 Initialise the Maypole application and plugins and model classes.
269 Your application should call this B<after> setting up configuration data via
270 L<"config">.
271
272 It calls the hook  C<setup_model> to setup the model. The %attr hash contains
273 options and arguments used to set up the model. See the particular model's
274 documentation. However here is the most usage of setup where
275 Maypole::Model::CDBI is the base class.
276
277  My::App->setup($data_source, $user, $password,
278        {  opitons => {  # These are DB connection options
279                AutoCommit => 0,
280                RaiseError => 1,
281                ...
282           },
283           # These are Class::DBI::Loader arguments.
284           relationships  => 1,
285           ...
286        }
287  );
288
289 Also, see  L<Maypole::Manual::Plugins>.
290
291 =cut
292
293
294 sub setup
295 {
296     my $class = shift;
297     
298     $class->setup_model(@_);    
299 }
300
301 =item setup_model
302
303 Called by C<setup>. This method builds the Maypole model hierarchy. 
304
305 A likely target for over-riding, if you need to build a customised model.
306
307 This method also ensures any code in custom model classes is loaded, so you
308 don't need to load them in the driver.
309
310 =cut
311
312 sub setup_model {
313   my $class = shift;
314   $class = ref $class if ref $class;
315   my $config = $class->config;
316   $config->model || $config->model('Maypole::Model::CDBI');
317   $config->model->require or die sprintf
318     "Couldn't load the model class %s: %s", $config->model, $@;
319
320   # among other things, this populates $config->classes
321   $config->model->setup_database($config, $class, @_);
322
323   foreach my $subclass ( @{ $config->classes } ) {
324     next if $subclass->isa("Maypole::Model::Base");
325     no strict 'refs';
326     unshift @{ $subclass . "::ISA" }, $config->model;
327   }
328
329   # Load custom model code, if it exists - nb this must happen after the
330   # unshift, to allow code attributes to work, but before adopt(),
331   # in case adopt() calls overridden methods on $subclass
332   foreach my $subclass ( @{ $config->classes } ) {
333     $class->load_model_subclass($subclass) unless ($class->model_classes_loaded());
334     $config->model->adopt($subclass) if $config->model->can("adopt");
335   }
336
337 }
338
339 =item load_model_subclass($subclass)
340
341 This method is called from C<setup_model()>. It attempts to load the
342 C<$subclass> package, if one exists. So if you make a customized C<BeerDB::Beer>
343 package, you don't need to explicitly load it. 
344
345 If automatic loading causes problems, Override load_model_subclass in your driver.
346
347 sub load_model_subclass {};
348
349 Or perhaps during development, if you don't want to load up custom classes, you 
350 can override this method and load them manually. 
351
352 =cut
353
354 sub load_model_subclass {
355   my ($class, $subclass) = @_;
356
357   my $config = $class->config;
358
359   # Load any external files for the model base class or subclasses
360   # (e.g. BeerDB/DBI.pm or BeerDB/Beer.pm) based on code borrowed from
361   # Maypole::Plugin::Loader and Class::DBI.
362   if ( $subclass->require ) {
363     warn "Loaded external module for '$subclass'\n" if $class->debug > 1;
364   } else {
365     (my $filename = $subclass) =~ s!::!/!g;
366     die "Loading '$subclass' failed: $@\n"
367       unless $@ =~ /Can\'t locate \Q$filename\E\.pm/;
368     warn "No external module for '$subclass'"
369       if $class->debug > 1;
370   }
371 }
372
373 =item init
374
375 Loads the view class and instantiates the view object.
376
377 You should not call this directly, but you may wish to override this to add
378 application-specific initialisation - see L<Maypole::Manual::Plugins>.
379
380 =cut
381
382 sub init 
383 {
384     my $class  = shift;
385     my $config = $class->config;
386     $config->view || $config->view("Maypole::View::TT");
387     $config->view->require;
388     die "Couldn't load the view class " . $config->view . ": $@" if $@;
389     $config->display_tables
390       || $config->display_tables( $class->config->tables );
391     $class->view_object( $class->config->view->new );
392     $class->init_done(1);
393 }
394
395 =item new
396
397 Constructs a very minimal new Maypole request object.
398
399 =cut
400
401 sub new
402 {
403     my ($class) = @_;
404     
405     my $self = bless {
406         template_args => {},
407         config        => $class->config,
408     }, $class;
409     
410     return $self;
411 }
412
413 =item view_object
414
415 Get/set the Maypole::View object
416
417 =back
418
419 =head1 INSTANCE METHODS
420
421 =head2 Workflow
422
423 =over 4
424
425 =item handler
426
427 This method sets up the class if it's not done yet, sets some defaults and
428 leaves the dirty work to C<handler_guts>.
429
430 =cut
431
432 # handler() has a method attribute so that mod_perl will invoke
433 # BeerDB->handler() as a method rather than a plain function
434 # BeerDB::handler() and so this inherited implementation will be
435 # found. See e.g. "Practical mod_perl" by Bekman & Cholet for
436 # more information <http://modperlbook.org/html/ch25_01.html>
437 sub handler : method  {
438   # See Maypole::Workflow before trying to understand this.
439   my ($class, $req) = @_;
440     
441   $class->init unless $class->init_done;
442
443   my $self = $class->new;
444     
445   # initialise the request
446   $self->headers_out(Maypole::Headers->new);
447   $self->get_request($req);
448   $self->parse_location;
449     
450   # hook useful for declining static requests e.g. images, or perhaps for 
451   # sanitizing request parameters
452   $self->status(Maypole::Constants::OK()); # set the default
453   $self->__call_hook('start_request_hook');
454   return $self->status unless $self->status == Maypole::Constants::OK();
455     
456   die "status undefined after start_request_hook()" unless defined
457     $self->status;
458     
459   $self->get_session;
460   $self->get_user;
461     
462   my $status = $self->handler_guts;
463   return $status unless $status == OK;
464
465   # TODO: require send_output to return a status code
466   $self->send_output;
467
468   return $status;
469 }
470
471 =back
472
473 =head2 component
474
475   Run Maypole sub-requests as components using L<Maypole::Components>
476
477   [% request.component("/beer/view_as_component/20") %]
478
479   Allows you to integrate the results of a Maypole request into an existing
480 request. You'll need to set up actions and templates
481 which return fragments of HTML rather than entire pages, but once you've
482 done that, you can use the C<component> method of the Maypole request object
483 to call those actions. You may pass a query string in the usual URL style.
484 You should not fully qualify the Maypole URLs.
485
486 =cut
487
488 sub component {
489     my ( $r, $path ) = @_;
490     my $self = bless { parent => $r }, ref $r;
491     my $url = URI->new($path);
492     $self->{path} = $url->path;
493     $self->parse_path;
494     $self->params( $url->query_form_hash );
495     $self->query( $r->params );
496     $self->handler_guts;
497     return $self->output;
498 }
499
500 sub get_template_root {
501     my $self = shift;
502     my $r    = shift;
503     return $r->parent->get_template_root if $r->{parent};
504     return $self->NEXT::DISTINCT::get_template_root( $r, @_ );
505 }
506
507 sub view_object {
508     my $self = shift;
509     my $r    = shift;
510     return $r->parent->view_object if $r->{parent};
511     return $self->NEXT::DISTINCT::view_object( $r, @_ );
512 }
513
514 # Instead of making plugin authors use the NEXT::DISTINCT hoopla to ensure other 
515 # plugins also get to call the hook, we can cycle through the application's 
516 # @ISA and call them all here. Doesn't work for setup() though, because it's 
517 # too ingrained in the stack. We could add a run_setup() method, but we'd break 
518 # lots of existing code.
519 sub __call_hook
520 {
521     my ($self, $hook) = @_;
522     
523     my @plugins;
524     {
525         my $class = ref($self);
526         no strict 'refs';
527         @plugins = @{"$class\::ISA"};
528     }
529     
530     # this is either a custom method in the driver, or the method in the 1st 
531     # plugin, or the 'null' method in the frontend (i.e. inherited from 
532     # Maypole.pm) - we need to be careful to only call it once
533     my $first_hook = $self->can($hook);
534     $self->$first_hook;  
535     
536     my %seen = ( $first_hook => 1 );
537
538     # @plugins includes the frontend
539     foreach my $plugin (@plugins)
540     {
541         next unless my $plugin_hook = $plugin->can($hook);
542         next if $seen{$plugin_hook}++;
543         $self->$plugin_hook;
544     }
545 }
546
547 =item handler_guts
548
549 This is the main request handling method and calls various methods to handle the
550 request/response and defines the workflow within Maypole.
551
552 B<Currently undocumented and liable to be refactored without warning>.
553
554 =cut
555
556 # The root of all evil
557 sub handler_guts 
558 {
559     my ($self) = @_;
560     
561     $self->__load_request_model;
562
563     my $applicable = $self->is_model_applicable == OK;
564     
565     $self->__setup_plain_template unless $applicable;
566
567     my $status;
568
569     eval { $status = $self->call_authenticate };
570     
571     if ( my $error = $@ ) 
572     {
573         $status = $self->call_exception($error, "authentication");
574         
575         if ( $status != OK ) 
576         {
577             warn "caught authenticate error: $error";
578             return $self->debug ? 
579                     $self->view_object->error($self, $error) : ERROR;
580         }
581     }
582     
583     if ( $self->debug and $status != OK and $status != DECLINED ) 
584     {
585         $self->view_object->error( $self,
586             "Got unexpected status $status from calling authentication" );
587     }
588     
589     return $status unless $status == OK;
590
591     # We run additional_data for every request
592     $self->additional_data;
593     
594     if ($applicable) 
595     {
596         eval { $self->model_class->process($self) };
597         
598         if ( my $error = $@ ) 
599         {
600             $status = $self->call_exception($error, "model");
601             
602             if ( $status != OK ) 
603             {
604                 warn "caught model error: $error";
605                 return $self->debug ? 
606                     $self->view_object->error($self, $error) : ERROR;
607             }
608         }
609     }
610     
611     # less frequent path - perhaps output has been set to an error message
612     return OK if $self->output;
613
614     # normal path - no output has been generated yet
615     my $processed_view_ok = $self->__call_process_view;
616
617     $self->{content_type}      ||= $self->__get_mime_type();
618     $self->{document_encoding} ||= "utf-8";
619
620     return $processed_view_ok;
621 }
622
623 my %filetypes = (
624                  'js' => 'text/javascript',
625                  'css' => 'text/css',
626                  'htm' => 'text/html',
627                  'html' => 'text/html',
628                 );
629
630 sub __get_mime_type {
631   my $self = shift;
632   my $type;
633   if ($self->path =~ m/.*\.(\w{3,4})$/) {
634     $type = $filetypes{$1};
635   } else {
636     $type = $mmagic->checktype_contents($self->output);
637   }
638   return $type;
639 }
640
641 sub __load_request_model
642 {
643     my ($self) = @_;
644     $self->model_class( $self->config->model->class_of($self, $self->table) );
645 }
646
647 # is_applicable() returned false, so set up a plain template. Model processing 
648 # will be skipped, but need to remove the model anyway so the template can't 
649 # access it. 
650 sub __setup_plain_template
651 {
652     my ($self) = @_;
653     
654     # It's just a plain template
655     $self->model_class(undef);
656     
657     my $path = $self->path;
658     $path =~ s{/$}{};    # De-absolutify
659     $self->path($path);
660     
661     $self->template($self->path);
662 }
663
664 # The model has been processed or skipped (if is_applicable returned false), 
665 # any exceptions have been handled, and there's no content in $self->output
666 sub __call_process_view
667 {
668     my ($self) = @_;
669     
670     my $status;
671     
672     eval { $status = $self->view_object->process($self) };
673     
674     if ( my $error = $@ ) 
675     {
676         $status = $self->call_exception($error, "view");
677         
678         if ( $status != OK ) 
679         {
680             warn "caught view error: $error" if $self->debug;
681             return $self->debug ? 
682                 $self->view_object->error($self, $error) : ERROR;
683         }
684     }
685     
686     return $status;
687 }
688
689 =item get_request
690
691 You should only need to define this method if you are writing a new
692 Maypole backend. It should return something that looks like an Apache
693 or CGI request object, it defaults to blank.
694
695 =cut
696
697 sub get_request { }
698
699 =item parse_location
700
701 Turns the backend request (e.g. Apache::MVC, Maypole, CGI) into a Maypole
702 request. It does this by setting the C<path>, and invoking C<parse_path> and
703 C<parse_args>.
704
705 You should only need to define this method if you are writing a new Maypole
706 backend.
707
708 =cut
709
710 sub parse_location 
711 {
712     die "parse_location is a virtual method. Do not use Maypole directly; " . 
713                 "use Apache::MVC or similar";
714 }
715
716 =item start_request_hook
717
718 This is called immediately after setting up the basic request. The default
719 method does nothing. 
720
721 The value of C<< $r->status >> is set to C<OK> before this hook is run. Your 
722 implementation can change the status code, or leave it alone. 
723
724 After this hook has run, Maypole will check the value of C<status>. For any
725 value other than C<OK>, Maypole returns the C<status> immediately. 
726
727 This is useful for filtering out requests for static files, e.g. images, which
728 should not be processed by Maypole or by the templating engine:
729
730     sub start_request_hook
731     {
732         my ($r) = @_;
733         
734         $r->status(DECLINED) if $r->path =~ /\.jpg$/;
735     }
736     
737 Multiple plugins, and the driver, can define this hook - Maypole will call all
738 of them. You should check for and probably not change any non-OK C<status>
739 value:
740
741     package Maypole::Plugin::MyApp::SkipFavicon;
742     
743     sub start_request_hook
744     {
745         my ($r) = @_;
746         
747         # check if a previous plugin has already DECLINED this request
748         # - probably unnecessary in this example, but you get the idea
749         return unless $r->status == OK;
750         
751         # then do our stuff
752         $r->status(DECLINED) if $r->path =~ /favicon\.ico/;
753     }        
754      
755 =cut
756
757 sub start_request_hook { }
758
759 =item is_applicable
760
761 B<This method is deprecated> as of version 2.11. If you have overridden it,
762 please override C<is_model_applicable> instead, and change the return type
763 from a Maypole:Constant to a true/false value.
764
765 Returns a Maypole::Constant to indicate whether the request is valid.
766
767 =cut
768
769 sub is_applicable { return shift->is_model_applicable(@_); }
770
771 =item is_model_applicable
772
773 Returns true or false to indicate whether the request is valid.
774
775 The default implementation checks that C<< $r->table >> is publicly
776 accessible and that the model class is configured to handle the
777 C<< $r->action >>.
778
779 =cut
780
781 sub is_model_applicable {
782     my ($self) = @_;
783
784     # Establish which tables should be processed by the model
785     my $config = $self->config;
786     
787     $config->ok_tables || $config->ok_tables( $config->display_tables );
788     
789     $config->ok_tables( { map { $_ => 1 } @{ $config->ok_tables } } )
790         if ref $config->ok_tables eq "ARRAY";
791         
792     my $ok_tables = $config->ok_tables;
793       
794     # Does this request concern a table to be processed by the model?
795     my $table = $self->table;
796     
797     my $ok = 0;
798     
799     if (exists $ok_tables->{$table}) 
800     {
801         $ok = 1;
802     } 
803
804     if (not $ok) 
805     {
806         warn "We don't have that table ($table).\n"
807             . "Available tables are: "
808             . join( ",", keys %$ok_tables )
809                 if $self->debug and not $ok_tables->{$table};
810                 
811         return DECLINED;
812     }
813     
814     # Is the action public?
815     my $action = $self->action;
816     return OK if $self->model_class->is_public($action);
817     
818     warn "The action '$action' is not applicable to the table '$table'"
819          if $self->debug;
820     
821     return DECLINED;
822 }
823
824 =item get_session
825
826 Called immediately after C<start_request_hook()>.
827
828 This method should return a session, which will be stored in the request's
829 C<session> attribute.
830
831 The default method is empty. 
832
833 =cut
834
835 sub get_session { }
836
837 =item get_user
838
839 Called immediately after C<get_session>.
840
841 This method should return a user, which will be stored in the request's C<user>
842 attribute.
843
844 The default method is empty.
845
846 =cut
847
848 sub get_user {}
849
850 =item call_authenticate
851
852 This method first checks if the relevant model class
853 can authenticate the user, or falls back to the default
854 authenticate method of your Maypole application.
855
856 =cut
857
858 sub call_authenticate 
859 {
860     my ($self) = @_;
861
862     # Check if we have a model class with an authenticate() to delegate to
863     return $self->model_class->authenticate($self) 
864         if $self->model_class and $self->model_class->can('authenticate');
865     
866     # Interface consistency is a Good Thing - 
867     # the invocant and the argument may one day be different things 
868     # (i.e. controller and request), like they are when authenticate() 
869     # is called on a model class (i.e. model and request)
870     return $self->authenticate($self);   
871 }
872
873 =item authenticate
874
875 Returns a Maypole::Constant to indicate whether the user is authenticated for
876 the Maypole request.
877
878 The default implementation returns C<OK>
879
880 =cut
881
882 sub authenticate { return OK }
883
884
885 =item call_exception
886
887 This model is called to catch exceptions, first after authenticate, then after
888 processing the model class, and finally to check for exceptions from the view
889 class.
890
891 This method first checks if the relevant model class
892 can handle exceptions the user, or falls back to the default
893 exception method of your Maypole application.
894
895 =cut
896
897 sub call_exception 
898 {
899     my ($self, $error, $when) = @_;
900
901     # Check if we have a model class with an exception() to delegate to
902     if ( $self->model_class && $self->model_class->can('exception') )
903     {
904         my $status = $self->model_class->exception( $self, $error, $when );
905         return $status if $status == OK;
906     }
907     
908     return $self->exception($error, $when);
909 }
910
911
912 =item exception
913
914 This method is called if any exceptions are raised during the authentication or
915 model/view processing. It should accept the exception as a parameter and return
916 a Maypole::Constant to indicate whether the request should continue to be
917 processed.
918
919 =cut
920
921 sub exception { 
922     my ($self, $error, $when) = @_;
923     if ($self->view_object->can("report_error") and $self->debug) {
924         $self->view_object->report_error($self, $error, $when);
925         return OK;
926     }
927     return ERROR;
928 }
929
930 =item additional_data
931
932 Called before the model processes the request, this method gives you a chance to
933 do some processing for each request, for example, manipulating C<template_args>.
934
935 =cut
936
937 sub additional_data { }
938
939 =item send_output
940
941 Sends the output and additional headers to the user.
942
943 =cut
944
945 sub send_output {
946     die "send_output is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
947 }
948
949
950
951
952 =back
953
954 =head2 Path processing and manipulation
955
956 =over 4
957
958 =item path
959
960 Returns the request path
961
962 =item parse_path
963
964 Parses the request path and sets the C<args>, C<action> and C<table>
965 properties. Calls C<preprocess_path> before parsing path and setting properties.
966
967 =cut
968
969 sub parse_path 
970 {
971     my ($self) = @_;
972     
973     # Previous versions unconditionally set table, action and args to whatever 
974     # was in @pi (or else to defaults, if @pi is empty).
975     # Adding preprocess_path(), and then setting table, action and args 
976     # conditionally, broke lots of tests, hence this:
977     $self->$_(undef) for qw/action table args/;
978     
979     $self->preprocess_path;
980     $self->path || $self->path('frontpage');
981
982     my @pi = grep {length} split '/', $self->path;
983
984
985     $self->table  || $self->table(shift @pi);
986     $self->action || $self->action( shift @pi or 'index' );
987     $self->args   || $self->args(\@pi);
988 }
989
990 =item preprocess_path
991
992 Sometimes when you don't want to rewrite or over-ride parse_path but
993 want to rewrite urls or extract data from them before it is parsed.
994
995 This method is called after parse_location has populated the request
996 information and before parse_path has populated the model and action
997 information, and is passed the request object.
998
999 You can set action, args or table in this method and parse_path will
1000 then leave those values in place or populate them if not present
1001
1002 =cut
1003
1004 sub preprocess_path { };
1005
1006 =item make_path( %args or \%args or @args )
1007
1008 This is the counterpart to C<parse_path>. It generates a path to use
1009 in links, form actions etc. To implement your own path scheme, just override
1010 this method and C<parse_path>.
1011
1012     %args = ( table      => $table,
1013               action     => $action,        
1014               additional => $additional,    # optional - generally an object ID
1015               );
1016               
1017     \%args = as above, but a ref
1018     
1019     @args = ( $table, $action, $additional );   # $additional is optional
1020
1021 C<id> can be used as an alternative key to C<additional>.
1022
1023 C<$additional> can be a string, an arrayref, or a hashref. An arrayref is
1024 expanded into extra path elements, whereas a hashref is translated into a query
1025 string. 
1026
1027 =cut
1028
1029 sub make_path
1030 {
1031     my $r = shift;
1032     
1033     my %args;
1034     
1035     if (@_ == 1 and ref $_[0] and ref $_[0] eq 'HASH')
1036     {
1037         %args = %{$_[0]};
1038     }
1039     elsif ( @_ > 1 and @_ < 4 )
1040     {
1041         $args{table}      = shift;
1042         $args{action}     = shift;
1043         $args{additional} = shift;
1044     }
1045     else
1046     {
1047         %args = @_;
1048     }
1049     
1050     do { die "no $_" unless $args{$_} } for qw( table action );    
1051
1052     my $additional = $args{additional} || $args{id};
1053     
1054     my @add = ();
1055     
1056     if ($additional)
1057     {
1058         # if $additional is a href, make_uri() will transform it into a query
1059         @add = (ref $additional eq 'ARRAY') ? @$additional : ($additional);
1060     }    
1061     
1062     my $uri = $r->make_uri($args{table}, $args{action}, @add);
1063     
1064     return $uri->as_string;
1065 }
1066
1067
1068
1069 =item make_uri( @segments )
1070
1071 Make a L<URI> object given table, action etc. Automatically adds
1072 the C<uri_base>. 
1073
1074 If the final element in C<@segments> is a hash ref, C<make_uri> will render it
1075 as a query string.
1076
1077 =cut
1078
1079 sub make_uri
1080 {
1081     my ($r, @segments) = @_;
1082
1083     my $query = (ref $segments[-1] eq 'HASH') ? pop(@segments) : undef;
1084     
1085     my $base = $r->config->uri_base; 
1086     $base =~ s|/$||;
1087     
1088     my $uri = URI->new($base);
1089     $uri->path_segments($uri->path_segments, grep {length} @segments);
1090     
1091     my $abs_uri = $uri->abs('/');
1092     $abs_uri->query_form($query) if $query;
1093     return $abs_uri;
1094 }
1095
1096 =item parse_args
1097
1098 Turns post data and query string paramaters into a hash of C<params>.
1099
1100 You should only need to define this method if you are writing a new Maypole
1101 backend.
1102
1103 =cut 
1104
1105 sub parse_args
1106 {
1107     die "parse_args() is a virtual method. Do not use Maypole directly; ".
1108             "use Apache::MVC or similar";
1109 }
1110
1111 =item get_template_root
1112
1113 Implementation-specific path to template root.
1114
1115 You should only need to define this method if you are writing a new Maypole
1116 backend. Otherwise, see L<Maypole::Config/"template_root">
1117
1118 =cut
1119
1120 =back
1121
1122 =head2 Request properties
1123
1124 =over 4
1125
1126 =item model_class
1127
1128 Returns the perl package name that will serve as the model for the
1129 request. It corresponds to the request C<table> attribute.
1130
1131
1132 =item objects
1133
1134 Get/set a list of model objects. The objects will be accessible in the view
1135 templates.
1136
1137 If the first item in C<$self-E<gt>args> can be C<retrieve()>d by the model
1138 class, it will be removed from C<args> and the retrieved object will be added to
1139 the C<objects> list. See L<Maypole::Model> for more information.
1140
1141 =item template_args
1142
1143     $self->template_args->{foo} = 'bar';
1144
1145 Get/set a hash of template variables.
1146
1147 =item stash
1148
1149 A place to put custom application data. Not used by Maypole itself. 
1150
1151 =item template
1152
1153 Get/set the template to be used by the view. By default, it returns
1154 C<$self-E<gt>action>
1155
1156
1157 =item error
1158
1159 Get/set a request error
1160
1161 =item output
1162
1163 Get/set the response output. This is usually populated by the view class. You
1164 can skip view processing by setting the C<output>.
1165
1166 =item table
1167
1168 The table part of the Maypole request path
1169
1170 =item action
1171
1172 The action part of the Maypole request path
1173
1174 =item args
1175
1176 A list of remaining parts of the request path after table and action
1177 have been
1178 removed
1179
1180 =item headers_in
1181
1182 A L<Maypole::Headers> object containing HTTP headers for the request
1183
1184 =item headers_out
1185
1186 A L<HTTP::Headers> object that contains HTTP headers for the output
1187
1188 =item document_encoding
1189
1190 Get/set the output encoding. Default: utf-8.
1191
1192 =item content_type
1193
1194 Get/set the output content type. Default: text/html
1195
1196 =item get_protocol
1197
1198 Returns the protocol the request was made with, i.e. https
1199
1200 =cut
1201
1202 sub get_protocol {
1203   die "get_protocol is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
1204 }
1205
1206 =back
1207
1208 =head2 Request parameters
1209
1210 The source of the parameters may vary depending on the Maypole backend, but they
1211 are usually populated from request query string and POST data.
1212
1213 Maypole supplies several approaches for accessing the request parameters. Note
1214 that the current implementation (via a hashref) of C<query> and C<params> is
1215 likely to change in a future version of Maypole. So avoid direct access to these
1216 hashrefs:
1217
1218     $r->{params}->{foo}      # bad
1219     $r->params->{foo}        # better
1220
1221     $r->{query}->{foo}       # bad
1222     $r->query->{foo}         # better
1223
1224     $r->param('foo')         # best
1225
1226 =over 4
1227
1228 =item param
1229
1230 An accessor (get or set) for request parameters. It behaves similarly to
1231 CGI::param() for accessing CGI parameters, i.e.
1232
1233     $r->param                   # returns list of keys
1234     $r->param($key)             # returns value for $key
1235     $r->param($key => $value)   # returns old value, sets to new value
1236
1237 =cut
1238
1239 sub param 
1240
1241     my ($self, $key) = (shift, shift);
1242     
1243     return keys %{$self->params} unless defined $key;
1244     
1245     return unless exists $self->params->{$key};
1246     
1247     my $val = $self->params->{$key};
1248     
1249     if (@_)
1250     {
1251         my $new_val = shift;
1252         $self->params->{$key} = $new_val;
1253     }
1254     
1255     return ref $val ? @$val : ($val) if wantarray;
1256         
1257     return ref $val ? $val->[0] : $val;
1258 }
1259
1260
1261 =item params
1262
1263 Returns a hashref of request parameters. 
1264
1265 B<Note:> Where muliple values of a parameter were supplied, the C<params> value
1266 will be an array reference.
1267
1268 =item query
1269
1270 Alias for C<params>.
1271
1272 =back
1273
1274 =head3 Utility methods
1275
1276 =over 4
1277
1278 =item redirect_request
1279
1280 Sets output headers to redirect based on the arguments provided
1281
1282 Accepts either a single argument of the full url to redirect to, or a hash of
1283 named parameters :
1284
1285 $r->redirect_request('http://www.example.com/path');
1286
1287 or
1288
1289 $r->redirect_request(protocol=>'https', domain=>'www.example.com', path=>'/path/file?arguments', status=>'302', url=>'..');
1290
1291 The named parameters are protocol, domain, path, status and url
1292
1293 Only 1 named parameter is required but other than url, they can be combined as
1294 required and current values (from the request) will be used in place of any
1295 missing arguments. The url argument must be a full url including protocol and
1296 can only be combined with status.
1297
1298 =cut
1299
1300 sub redirect_request {
1301   die "redirect_request is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
1302 }
1303
1304 =item redirect_internal_request 
1305
1306 =cut
1307
1308 sub redirect_internal_request {
1309
1310 }
1311
1312
1313 =item make_random_id
1314
1315 returns a unique id for this request can be used to prevent or detect repeat
1316 submissions.
1317
1318 =cut
1319
1320 # Session and Repeat Submission Handling
1321 sub make_random_id {
1322     use Maypole::Session;
1323     return Maypole::Session::generate_unique_id();
1324 }
1325
1326 =back
1327
1328 =head1 SEQUENCE DIAGRAMS
1329
1330 See L<Maypole::Manual::Workflow> for a detailed discussion of the sequence of 
1331 calls during processing of a request. This is a brief summary:
1332
1333     INITIALIZATION
1334                                Model e.g.
1335          BeerDB           Maypole::Model::CDBI
1336            |                        |
1337    setup   |                        |
1338  o-------->||                       |
1339            || setup_model           |     setup_database() creates
1340            ||------+                |      a subclass of the Model
1341            |||<----+                |        for each table
1342            |||                      |                |
1343            |||   setup_database     |                |
1344            |||--------------------->|| 'create'      *
1345            |||                      ||----------> $subclass
1346            |||                      |                  |
1347            ||| load_model_subclass  |                  |
1348  foreach   |||------+  ($subclass)  |                  |
1349  $subclass ||||<----+               |    require       |
1350            ||||--------------------------------------->|
1351            |||                      |                  |
1352            |||   adopt($subclass)   |                  |
1353            |||--------------------->||                 |
1354            |                        |                  |
1355            |                        |                  |
1356            |-----+ init             |                  |
1357            ||<---+                  |                  |
1358            ||                       |     new          |     view_object: e.g.
1359            ||---------------------------------------------> Maypole::View::TT
1360            |                        |                  |          |
1361            |                        |                  |          |
1362            |                        |                  |          |
1363            |                        |                  |          |
1364            |                        |                  |          |
1365            
1366
1367
1368     HANDLING A REQUEST
1369
1370
1371           BeerDB                                Model  $subclass  view_object
1372             |                                      |       |         |
1373     handler |                                      |       |         |
1374   o-------->| new                                  |       |         |
1375             |-----> r:BeerDB                       |       |         |
1376             |         |                            |       |         |
1377             |         |                            |       |         |
1378             |         ||                           |       |         |
1379             |         ||-----+ parse_location      |       |         |
1380             |         |||<---+                     |       |         |
1381             |         ||                           |       |         |
1382             |         ||-----+ start_request_hook  |       |         |
1383             |         |||<---+                     |       |         |
1384             |         ||                           |       |         |
1385             |         ||-----+ get_session         |       |         |
1386             |         |||<---+                     |       |         |
1387             |         ||                           |       |         |
1388             |         ||-----+ get_user            |       |         |
1389             |         |||<---+                     |       |         |
1390             |         ||                           |       |         |
1391             |         ||-----+ handler_guts        |       |         |
1392             |         |||<---+                     |       |         |
1393             |         |||     class_of($table)     |       |         |
1394             |         |||------------------------->||      |         |
1395             |         |||       $subclass          ||      |         |
1396             |         |||<-------------------------||      |         |
1397             |         |||                          |       |         |
1398             |         |||-----+ is_model_applicable|       |         |
1399             |         ||||<---+                    |       |         |
1400             |         |||                          |       |         |
1401             |         |||-----+ call_authenticate  |       |         |
1402             |         ||||<---+                    |       |         |
1403             |         |||                          |       |         |
1404             |         |||-----+ additional_data    |       |         |
1405             |         ||||<---+                    |       |         |
1406             |         |||             process      |       |         |
1407             |         |||--------------------------------->||  fetch_objects
1408             |         |||                          |       ||-----+  |
1409             |         |||                          |       |||<---+  |
1410             |         |||                          |       ||        |
1411             |         |||                          |       ||   $action
1412             |         |||                          |       ||-----+  |
1413             |         |||                          |       |||<---+  |            
1414             |         |||         process          |       |         |
1415             |         |||------------------------------------------->|| template
1416             |         |||                          |       |         ||-----+
1417             |         |||                          |       |         |||<---+
1418             |         |||                          |       |         |
1419             |         ||     send_output           |       |         |
1420             |         ||-----+                     |       |         |
1421             |         |||<---+                     |       |         |
1422    $status  |         ||                           |       |         |
1423    <------------------||                           |       |         |
1424             |         |                            |       |         |
1425             |         X                            |       |         |           
1426             |                                      |       |         |
1427             |                                      |       |         |
1428             |                                      |       |         |
1429            
1430            
1431
1432 =head1 SEE ALSO
1433
1434 There's more documentation, examples, and information on our mailing lists
1435 at the Maypole web site:
1436
1437 L<http://maypole.perl.org/>
1438
1439 L<Maypole::Application>, L<Apache::MVC>, L<CGI::Maypole>.
1440
1441 =head1 AUTHOR
1442
1443 Maypole is currently maintained by Aaron Trevena, David Baird, Dave Howorth and
1444 Peter Speltz.
1445
1446 =head1 AUTHOR EMERITUS
1447
1448 Simon Cozens, C<simon#cpan.org>
1449
1450 Simon Flack maintained Maypole from 2.05 to 2.09
1451
1452 Sebastian Riedel, C<sri#oook.de> maintained Maypole from 1.99_01 to 2.04
1453
1454 =head1 THANKS TO
1455
1456 Sebastian Riedel, Danijel Milicevic, Dave Slack, Jesse Sheidlower, Jody Belka,
1457 Marcus Ramberg, Mickael Joanne, Randal Schwartz, Simon Flack, Steve Simms,
1458 Veljko Vidovic and all the others who've helped.
1459
1460 =head1 LICENSE
1461
1462 You may distribute this code under the same terms as Perl itself.
1463
1464 =cut
1465
1466 1;
1467
1468 __END__
1469
1470  =item register_cleanup($coderef)
1471
1472 Analogous to L<Apache>'s C<register_cleanup>. If an Apache request object is
1473 available, this call simply redispatches there. If not, the cleanup is
1474 registered in the Maypole request, and executed when the request is
1475 C<DESTROY>ed.
1476
1477 This method is only useful in persistent environments, where you need to ensure
1478 that some code runs when the request finishes, no matter how it finishes (e.g.
1479 after an unexpected error). 
1480
1481  =cut
1482
1483 {
1484     my @_cleanups;
1485
1486     sub register_cleanup
1487     {
1488         my ($self, $cleanup) = @_;
1489         
1490         die "register_cleanup() is an instance method, not a class method" 
1491             unless ref $self;
1492         die "Cleanup must be a coderef" unless ref($cleanup) eq 'CODE';
1493         
1494         if ($self->can('ar') && $self->ar)
1495         {
1496             $self->ar->register_cleanup($cleanup);
1497         }
1498         else
1499         {
1500             push @_cleanups, $cleanup;
1501         }
1502     }
1503
1504     sub DESTROY
1505     {
1506         my ($self) = @_;
1507         
1508         while (my $cleanup = shift @_cleanups)
1509         {
1510             eval { $cleanup->() };
1511             if ($@)
1512             {
1513                 warn "Error during request cleanup: $@";
1514             }
1515         }        
1516     }    
1517 }
1518