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