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