]> git.decadent.org.uk Git - maypole.git/blob - lib/Maypole.pm
Added Maypole::Manual::Inheritance and Maypole::Manual::Terminology. Renamed Maypole...
[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 URI();
10
11 our $VERSION = '2.11';
12
13 # proposed privacy conventions:
14 # - no leading underscore     - public to custom application code and plugins
15 # - single leading underscore - private to the main Maypole stack - *not*
16 #     including plugins
17 # - double leading underscore - private to the current package
18
19 __PACKAGE__->mk_classdata($_) for qw( config init_done view_object );
20 __PACKAGE__->mk_accessors(
21     qw( params query objects model_class template_args output path
22         args action template error document_encoding content_type table
23         headers_in headers_out stash session)
24 );
25 __PACKAGE__->config( Maypole::Config->new() );
26 __PACKAGE__->init_done(0);
27
28 sub debug { 0 }
29
30 sub setup 
31 {
32     my $calling_class = shift;
33     
34     $calling_class = ref $calling_class if ref $calling_class;
35     
36     my $config = $calling_class->config;
37     
38     $config->model || $config->model('Maypole::Model::CDBI');
39     
40     $config->model->require or die sprintf 
41         "Couldn't load the model class %s: %s", $config->model, $@;
42     
43     $config->model->setup_database($config, $calling_class, @_);
44     
45     foreach my $subclass ( @{ $config->classes } ) 
46     {
47         no strict 'refs';
48         unshift @{ $subclass . "::ISA" }, $config->model;
49         $config->model->adopt($subclass)
50           if $config->model->can("adopt");
51     }
52 }
53
54 sub init 
55 {
56     my $class  = shift;
57     my $config = $class->config;
58     $config->view || $config->view("Maypole::View::TT");
59     $config->view->require;
60     die "Couldn't load the view class " . $config->view . ": $@" if $@;
61     $config->display_tables
62       || $config->display_tables( $class->config->tables );
63     $class->view_object( $class->config->view->new );
64     $class->init_done(1);
65
66 }
67
68 sub new
69 {
70     my ($class) = @_;
71     
72     my $self = bless {
73         template_args => {},
74         config        => $class->config,
75     }, $class;
76     
77     return $self;
78 }
79
80 # handler() has a method attribute so that mod_perl will invoke
81 # BeerDB->handler() as a method rather than a plain function
82 # BeerDB::handler() and so this inherited implementation will be
83 # found. See e.g. "Practical mod_perl"  by Bekman & Cholet for
84 # more information <http://modperlbook.org/html/ch25_01.html>
85 sub handler : method 
86 {
87     # See Maypole::Workflow before trying to understand this.
88     my ($class, $req) = @_;
89     
90     $class->init unless $class->init_done;
91
92     my $self = $class->new;
93     
94     # initialise the request
95     $self->headers_out(Maypole::Headers->new);
96     $self->get_request($req);
97     $self->parse_location;
98     
99     my $status = $self->handler_guts;
100     
101     # moving this here causes unit test failures - need to check why
102     # before committing the move
103     #$status = $self->__call_process_view unless $self->output;
104     
105     return $status unless $status == OK;
106     
107     $self->send_output;
108     
109     return $status;
110 }
111
112 # The root of all evil
113 sub handler_guts 
114 {
115     my ($self) = @_;
116     
117     $self->__load_model;
118
119     my $applicable = $self->is_model_applicable;
120     
121     $self->__setup_plain_template unless $applicable;
122
123     $self->session($self->call_get_session);
124     
125     my $status;
126
127     eval { $status = $self->call_authenticate };
128     
129     if ( my $error = $@ ) 
130     {
131         $status = $self->call_exception($error);
132         
133         if ( $status != OK ) 
134         {
135             warn "caught authenticate error: $error";
136             return $self->debug ? 
137                     $self->view_object->error($self, $error) : ERROR;
138         }
139     }
140     
141     if ( $self->debug and $status != OK and $status != DECLINED ) 
142     {
143         $self->view_object->error( $self,
144             "Got unexpected status $status from calling authentication" );
145     }
146     
147     return $status unless $status == OK;
148
149     # We run additional_data for every request
150     $self->additional_data;
151     
152     if ($applicable) 
153     {
154         eval { $self->model_class->process($self) };
155         
156         if ( my $error = $@ ) 
157         {
158             $status = $self->call_exception($error);
159             
160             if ( $status != OK ) 
161             {
162                 warn "caught model error: $error";
163                 return $self->debug ? 
164                     $self->view_object->error($self, $error) : ERROR;
165             }
166         }
167     }
168     
169     # less frequent path - perhaps output has been set to an error message
170     return OK if $self->output;
171     
172     # normal path - no output has been generated yet
173     return $self->__call_process_view;
174 }
175
176 # is_applicable() returned false, so set up a plain template. Model processing 
177 # will be skipped, but need to remove the model anyway so the template can't 
178 # access it. 
179 sub __setup_plain_template
180 {
181     my ($self) = @_;
182     
183     # It's just a plain template
184     $self->model_class(undef);
185     
186     my $path = $self->path;
187     $path =~ s{/$}{};    # De-absolutify
188     $self->path($path);
189     
190     $self->template($self->path);
191 }
192
193 # The model has been processed or skipped (if is_applicable returned false), 
194 # any exceptions have been handled, and there's no content in $self->output
195 sub __call_process_view
196 {
197     my ($self) = @_;
198     
199     my $status;
200     
201     eval { $status = $self->view_object->process($self) };
202     
203     if ( my $error = $@ ) 
204     {
205         $status = $self->call_exception($error);
206         
207         if ( $status != OK ) 
208         {
209             warn "caught view error: $error" if $self->debug;
210             return $self->debug ? 
211                 $self->view_object->error($self, $error) : ERROR;
212         }
213     }
214     
215     return $status;
216 }
217
218 sub __load_model
219 {
220     my ($self) = @_;
221     $self->model_class( $self->config->model->class_of($self, $self->table) );
222 }
223
224 # is_applicable() should return true or false, not OK or DECLINED, because 
225 # the return value is never used as the return value from handler(). There's 
226 # probably a lot of code out there supplying the return codes though, so
227 # instead of changing is_applicable() to return 0 or 1, the return value is
228 # passed through __to_boolean. I think it helps handler_guts() if we don't
229 # have multiple sets of return codes being checked for different things -drb.
230 sub is_model_applicable 
231 {
232     my ($self) = @_;
233     
234     # cater for applications that are using obsolete version
235     if ($self->can('is_applicable')) 
236     {
237         warn "DEPRECATION WARNING: rewrite is_applicable to the interface ".
238                 "of Maypole::is_model_applicable\n";
239         return $self->is_applicable == OK;
240     }
241
242     # Establish which tables should be processed by the model
243     my $config = $self->config;
244     
245     $config->ok_tables || $config->ok_tables( $config->display_tables );
246     
247     $config->ok_tables( { map { $_ => 1 } @{ $config->ok_tables } } )
248         if ref $config->ok_tables eq "ARRAY";
249         
250     my $ok_tables = $config->ok_tables;
251       
252     # Does this request concern a table to be processed by the model?
253     my $table = $self->table;
254     
255     my $ok = 0;
256     
257     if (exists $ok_tables->{$table}) 
258     {
259         $ok = 1;
260     } 
261 # implements tj's default_table_view(), but there's no _default_table_view()
262 # or _have_default_table_view() yet
263 #    else 
264 #    {
265 #        $ok = $self->default_table_view($self->path, $self->args)
266 #            if $self->_have_default_table_view;
267 #    }
268
269     if (not $ok) 
270     {
271         warn "We don't have that table ($table).\n"
272             . "Available tables are: "
273             . join( ",", keys %$ok_tables )
274                 if $self->debug and not $ok_tables->{$table};
275                 
276         return 0;
277     }
278     
279     # Is the action public?
280     my $action = $self->action;
281     return 1 if $self->model_class->is_public($action);
282     
283     warn "The action '$action' is not applicable to the table $table"
284         if $self->debug;
285     
286     return 0;
287 }
288
289 sub call_authenticate 
290 {
291     my ($self) = @_;
292
293     # Check if we have a model class with an authenticate() to delegate to
294     return $self->model_class->authenticate($self) 
295         if $self->model_class and $self->model_class->can('authenticate');
296     
297     # Interface consistency is a Good Thing - 
298     # the invocant and the argument may one day be different things 
299     # (i.e. controller and request), like they are when authenticate() 
300     # is called on a model class (i.e. model and request)
301     return $self->authenticate($self);   
302 }
303
304 sub call_get_session {
305    my ($self) = @_;
306    return $self->get_session($self);
307 }
308
309 sub call_exception 
310 {
311     my ($self, $error) = @_;
312
313     # Check if we have a model class with an exception() to delegate to
314     if ( $self->model_class && $self->model_class->can('exception') )
315     {
316         my $status = $self->model_class->exception( $self, $error );
317         return $status if $status == OK;
318     }
319     
320     return $self->exception($error);
321 }
322
323 sub default_table_view {
324   my ($self,$path,$args) = @_;
325   my $path_is_ok = 0;
326   my $default_table_view = __PACKAGE__->_default_table_view;
327   # (path class action field)
328   my @path = $self->{path} =~ m{([^/]+)/?}g;
329   my $search_value = shift(@path);
330   if ($default_table_view->{path}) {
331     if ($default_table_view->{path} eq $search_value) {
332       $search_value = shift(@path);
333     } else {
334       return 0;
335     }
336   }
337
338   $self->{table} = $default_table_view->{class};
339   $self->{action} = $default_table_view->{action};
340   $self->{args} = [ $search_value,@path ];
341   return $path_is_ok;
342 }
343
344 sub additional_data { }
345
346 sub authenticate { return OK }
347
348 sub get_session { }
349
350 sub exception { return ERROR }
351
352 sub preprocess_path { };
353
354 sub parse_path 
355 {
356     my ($self) = @_;
357     
358     $self->preprocess_path;
359
360     $self->path || $self->path('frontpage');
361     
362     my @pi = grep {length} split '/', $self->path;
363     
364     $self->table || $self->table(shift @pi);
365     
366     $self->action || $self->action( shift @pi or 'index' );
367     
368     $self->args || $self->args(\@pi);
369 }
370
371
372 sub make_path
373 {
374     my $r = shift;
375     
376     my %args;
377     
378     if (@_ == 1 and ref $_[0] and ref $_[0] eq 'HASH')
379     {
380         %args = %{$_[0]};
381     }
382     elsif ( @_ > 1 and @_ < 4 )
383     {
384         $args{table}      = shift;
385         $args{action}     = shift;
386         $args{additional} = shift;
387     }
388     else
389     {
390         %args = @_;
391     }
392     
393     do { die "no $_" unless $args{$_} } for qw( table action );    
394
395     my $additional = $args{additional} || $args{id};
396     
397     my @add = ();
398     
399     if ($additional)
400     {
401         # if $additional is a href, make_uri() will transform it into a query
402         @add = (ref $additional eq 'ARRAY') ? @$additional : ($additional);
403     }    
404     
405     my $uri = $r->make_uri($args{table}, $args{action}, @add);
406     
407     return $uri->as_string;
408 }
409
410 sub make_uri
411 {
412     my ($r, @segments) = @_;
413
414     my $query = (ref $segments[-1] eq 'HASH') ? pop(@segments) : undef;
415     
416     my $base = $r->config->uri_base; 
417     $base =~ s|/$||;
418     
419     my $uri = URI->new($base);
420     $uri->path_segments($uri->path_segments, grep {length} @segments);
421     
422     my $abs_uri = $uri->abs('/');
423     $abs_uri->query_form($query) if $query;
424     return $abs_uri;
425 }
426
427
428 # like CGI::param(), but read only 
429 sub param 
430
431     my ($self, $key) = @_;
432     
433     return keys %{$self->params} unless defined $key;
434     
435     return unless exists $self->params->{$key};
436     
437     my $val = $self->params->{$key};
438     
439     return ref $val ? @$val : ($val) if wantarray;
440         
441     return ref $val ? $val->[0] : $val;
442 }
443
444 sub get_template_root {'.'}
445 sub get_request       { }
446
447 sub get_protocol {
448   die "get_protocol is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
449 }
450
451 sub parse_location {
452     die "parse_location is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
453 }
454
455 sub redirect_request {
456   die "parse_location is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
457 }
458
459 sub redirect_internal_request {
460
461 }
462
463 sub send_output {
464     die "send_output is a virtual method. Do not use Maypole directly; use Apache::MVC or similar";
465 }
466
467 # Session and Repeat Submission Handling
468
469 sub make_random_id {
470     use Maypole::Session;
471     return Maypole::Session::generate_unique_id();
472 }
473
474 =head1 NAME
475
476 Maypole - MVC web application framework
477
478 =head1 SYNOPSIS
479
480 See L<Maypole::Application>.
481
482 =head1 DESCRIPTION
483
484 This documents the Maypole request object. See the L<Maypole::Manual>, for a
485 detailed guide to using Maypole.
486
487 Maypole is a Perl web application framework similar to Java's struts. It is 
488 essentially completely abstracted, and so doesn't know anything about
489 how to talk to the outside world.
490
491 To use it, you need to create a driver  package which represents your entire
492 application. In our example above, this is the C<BeerDB> package.
493
494 This needs to first use L<Maypole::Application> which will make your package
495 inherit from the appropriate platform driver such as C<Apache::MVC> or
496 C<CGI::Maypole>. Then, the driver calls C<setup>.  This sets up the model classes and
497 configures your application. The default model class for Maypole uses
498 L<Class::DBI> to map a database to classes, but this can be changed by altering
499 configuration. (B<Before> calling setup.)
500
501
502 =head1 DOCUMENTATION ROADMAP
503
504 The primary documentation is the Maypole manual. This lives in the 
505 C<Maypole::Manual> pod documents included with the distribution. 
506
507
508 =head1 DEMOS
509
510 A couple of demos are available, usually with source code and configs. 
511
512 =over4 
513
514 =item beerdb.riverside-cms.co.uk
515
516 Looks to be down at the moment. 
517
518 =item beerfb.riverside-cms.co.uk
519
520 A demo of L<Maypole::FormBuilder>. This site is running on the set of Mason 
521 templates included in the L<Maypole::FormBuilder> distribution. See the 
522 synopsis of L<Maypole::Plugin::FormBuilder> for an example driver
523
524 =head2 CLASS METHODS
525
526 =head3 config
527
528 Returns the L<Maypole::Config> object
529
530 =head3 setup
531
532     My::App->setup($data_source, $user, $password, \%attr);
533
534 Initialise the maypole application and model classes. Your application should
535 call this after setting configuration via L<"config">
536
537 =head3 init
538
539 You should not call this directly, but you may wish to override this to
540 add
541 application-specific initialisation.
542
543 =head3 new
544
545 Constructs a very minimal new Maypole request object.
546
547 =head3 view_object
548
549 Get/set the Maypole::View object
550
551 =head3 debug
552
553     sub My::App::debug {1}
554
555 Returns the debugging flag. Override this in your application class to
556 enable/disable debugging.
557
558 =head2 INSTANCE METHODS
559
560 =head3 parse_location
561
562 Turns the backend request (e.g. Apache::MVC, Maypole, CGI) into a
563 Maypole
564 request. It does this by setting the C<path>, and invoking C<parse_path>
565 and
566 C<parse_args>.
567
568 You should only need to define this method if you are writing a new
569 Maypole
570 backend.
571
572 =head3 path
573
574 Returns the request path
575
576 =head3 parse_path
577
578 Parses the request path and sets the C<args>, C<action> and C<table>
579 properties. Calls preprocess_path before parsing path and setting properties.
580
581 =head3 make_path( %args or \%args or @args )
582
583 This is the counterpart to C<parse_path>. It generates a path to use
584 in links, form actions etc. To implement your own path scheme, just override
585 this method and C<parse_path>.
586
587     %args = ( table      => $table,
588               action     => $action,        
589               additional => $additional,    # optional - generally an object ID
590               );
591               
592     \%args = as above, but a ref
593     
594     @args = ( $table, $action, $additional );   # $additional is optional
595
596 C<id> can be used as an alternative key to C<additional>.
597
598 C<$additional> can be a string, an arrayref, or a hashref. An arrayref is
599 expanded into extra path elements, whereas a hashref is translated into a query
600 string. 
601
602 =head3 preprocess_path
603
604 Sometimes when you don't want to rewrite or over-ride parse_path but
605 want to rewrite urls or extract data from them before it is parsed.
606
607 This method is called after parse_location has populated the request
608 information and before parse_path has populated the model and action
609 information, and is passed the request object.
610
611 You can set action, args or table in this method and parse_path will
612 then leave those values in place or populate them if not present
613
614 =head3 make_uri( @segments )
615
616 Make a L<URI> object given table, action etc. Automatically adds
617 the C<uri_base>. 
618
619 If the final element in C<@segments> is a hash ref, C<make_uri> will render it
620 as a query string.
621
622 =head3 table
623
624 The table part of the Maypole request path
625
626 =head3 action
627
628 The action part of the Maypole request path
629
630 =head3 args
631
632 A list of remaining parts of the request path after table and action
633 have been
634 removed
635
636 =head3 headers_in
637
638 A L<Maypole::Headers> object containing HTTP headers for the request
639
640 =head3 headers_out
641
642 A L<HTTP::Headers> object that contains HTTP headers for the output
643
644 =head3 parse_args
645
646 Turns post data and query string paramaters into a hash of C<params>.
647
648 You should only need to define this method if you are writing a new
649 Maypole
650 backend.
651
652 =head3 param
653
654 An accessor for request parameters. It behaves similarly to CGI::param() for
655 accessing CGI parameters.
656
657 =head3 params
658
659 Returns a hash of request parameters. The source of the parameters may vary
660 depending on the Maypole backend, but they are usually populated from request
661 query string and POST data.
662
663 B<Note:> Where muliple values of a parameter were supplied, the
664 C<params> 
665 value
666 will be an array reference.
667
668 =head3 get_template_root
669
670 Implementation-specific path to template root.
671
672 You should only need to define this method if you are writing a new
673 Maypole
674 backend. Otherwise, see L<Maypole::Config/"template_root">
675
676 =head3 get_request
677
678 You should only need to define this method if you are writing a new
679 Maypole backend. It should return something that looks like an Apache
680 or CGI request object, it defaults to blank.
681
682 =head3 default_table_view
683
684 =head3 is_applicable
685
686 Returns a Maypole::Constant to indicate whether the request is valid.
687
688 B<This method is deprecated> as of version 2.11. If you have overridden it,
689 please override C<is_model_applicable> instead, and change the return type
690 from Maypole:Constants to true/false.
691
692 =head3 is_model_applicable
693
694 Returns true or false to indicate whether the request is valid.
695
696 The default implementation checks that C<< $r->table >> is publicly
697 accessible and that the model class is configured to handle the
698 C<< $r->action >>.
699
700 =head3 authenticate
701
702 Returns a Maypole::Constant to indicate whether the user is
703 authenticated for
704 the Maypole request.
705
706 The default implementation returns C<OK>
707
708 =head3 model_class
709
710 Returns the perl package name that will serve as the model for the
711 request. It corresponds to the request C<table> attribute.
712
713 =head3 additional_data
714
715 Called before the model processes the request, this method gives you a
716 chance
717 to do some processing for each request, for example, manipulating
718 C<template_args>.
719
720 =head3 objects
721
722 Get/set a list of model objects. The objects will be accessible in the
723 view
724 templates.
725
726 If the first item in C<$self-E<gt>args> can be C<retrieve()>d by the model
727 class,
728 it will be removed from C<args> and the retrieved object will be added
729 to the
730 C<objects> list. See L<Maypole::Model> for more information.
731
732 =head3 template_args
733
734     $self->template_args->{foo} = 'bar';
735
736 Get/set a hash of template variables.
737
738 =head3 stash
739
740 A place to put custom application data. Not used by Maypole itself. 
741
742 =head3 template
743
744 Get/set the template to be used by the view. By default, it returns
745 C<$self-E<gt>action>
746
747 =head3 exception
748
749 This method is called if any exceptions are raised during the
750 authentication 
751 or
752 model/view processing. It should accept the exception as a parameter and 
753 return
754 a Maypole::Constant to indicate whether the request should continue to
755 be
756 processed.
757
758 =head3 error
759
760 Get/set a request error
761
762 =head3 output
763
764 Get/set the response output. This is usually populated by the view
765 class. You
766 can skip view processing by setting the C<output>.
767
768 =head3 document_encoding
769
770 Get/set the output encoding. Default: utf-8.
771
772 =head3 content_type
773
774 Get/set the output content type. Default: text/html
775
776 =head3 send_output
777
778 Sends the output and additional headers to the user.
779
780 =head3 call_authenticate
781
782 This method first checks if the relevant model class
783 can authenticate the user, or falls back to the default
784 authenticate method of your Maypole application.
785
786
787 =head3 call_exception
788
789 This model is called to catch exceptions, first after authenticate, then after
790 processing the model class, and finally to check for exceptions from the view
791 class.
792
793 This method first checks if the relevant model class
794 can handle exceptions the user, or falls back to the default
795 exception method of your Maypole application.
796
797 =head3 make_random_id
798
799 returns a unique id for this request can be used to prevent or detect repeat
800 submissions.
801
802 =head3 get_protocol
803
804 Returns the protocol the request was made with, i.e. https
805
806 =head3 redirect_request
807
808 Sets output headers to redirect based on the arguments provided
809
810 Accepts either a single argument of the full url to redirect to, or a hash of named parameters :
811
812 $r->redirect_request('http://www.example.com/path');
813
814 or
815
816 $r->redirect_request(protocol=>'https', domain=>'www.example.com', path=>'/path/file?arguments', status=>'302', url=>'..');
817
818 The named parameters are protocol, domain, path, status and url
819
820 Only 1 named parameter is required but other than url, they can be combined as required and current values (from the request) will be used in place of any missing arguments. The url argument must be a full url including protocol and can only be combined with status.
821
822 =head3 redirect_internal_request 
823
824 =head3 handler
825
826 This method sets up the class if it's not done yet, sets some
827 defaults and leaves the dirty work to handler_guts.
828
829 =head3 handler_guts
830
831 This is the main request handling method and calls various methods to handle the request/response
832 and defines the workflow within Maypole.
833
834 Currently undocumented and liable to be refactored without warning.
835
836 =head1 SEE ALSO
837
838 There's more documentation, examples, and a information on our mailing lists
839 at the Maypole web site:
840
841 L<http://maypole.perl.org/>
842
843 L<Maypole::Application>, L<Apache::MVC>, L<CGI::Maypole>.
844
845 =head1 AUTHOR
846
847 Maypole is currently maintained by Aaron Trevena
848
849 =head1 AUTHOR EMERITUS
850
851 Simon Cozens, C<simon#cpan.org>
852
853 Sebastian Riedel, C<sri#oook.de> maintained Maypole from 1.99_01 to 2.04
854
855 =head1 THANKS TO
856
857 Sebastian Riedel, Danijel Milicevic, Dave Slack, Jesse Sheidlower, Jody Belka,
858 Marcus Ramberg, Mickael Joanne, Randal Schwartz, Simon Flack, Steve Simms,
859 Veljko Vidovic and all the others who've helped.
860
861 =head1 LICENSE
862
863 You may distribute this code under the same terms as Perl itself.
864
865 =cut
866
867 1;