home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / CGIHandler.pm < prev    next >
Encoding:
Perl POD Document  |  2003-12-12  |  18.2 KB  |  585 lines

  1. package HTML::Mason::CGIHandler;
  2.  
  3. use strict;
  4.  
  5. use HTML::Mason;
  6. use HTML::Mason::Utils;
  7. use CGI;
  8. use File::Spec;
  9. use Params::Validate qw(:all);
  10. use HTML::Mason::Exceptions;
  11. use HTML::Mason::FakeApache;
  12.  
  13. use Class::Container;
  14. use base qw(Class::Container);
  15.  
  16. use HTML::Mason::MethodMaker
  17.     ( read_write => [ qw( interp ) ] );
  18.  
  19. use vars qw($VERSION);
  20.  
  21. # Why do we have a version?  I'm glad you asked.  See, dummy me
  22. # stupidly referenced it in the Subclassing docs _and_ the book.  It's
  23. # needed in order to dynamically have a request subclass change its
  24. # parent properly to work with CGIHandler or ApacheHandler.  It
  25. # doesn't really matter what the version is, as long as it's a true
  26. # value.  - dave
  27. $VERSION = '1.00';
  28.  
  29.  
  30. __PACKAGE__->valid_params
  31.     (
  32.      interp => { isa => 'HTML::Mason::Interp' },
  33.     );
  34.  
  35. __PACKAGE__->contained_objects
  36.     (
  37.      interp => 'HTML::Mason::Interp',
  38.      cgi_request => { class   => 'HTML::Mason::FakeApache', # $r
  39.               delayed => 1 },
  40.     );
  41.  
  42.  
  43. sub new {
  44.     my $package = shift;
  45.  
  46.     my %p = @_;
  47.     my $self = $package->SUPER::new(comp_root => $ENV{DOCUMENT_ROOT},
  48.                     request_class => 'HTML::Mason::Request::CGI',
  49.                     error_mode => 'output',
  50.                     error_format => 'html',
  51.                     %p);
  52.  
  53.     # If the user passed an out_method parameter, then we don't want
  54.     # to overwrite it later.  This doesn't handle the case where the
  55.     # user creates their own Interp object with a custom out_method
  56.     # and passes that to this method, though (grrr).
  57.     $self->{has_custom_out_method} = $p{out_method} ? 1 : 0;
  58.  
  59.     $self->interp->compiler->add_allowed_globals('$r');
  60.     
  61.     return $self;
  62. }
  63.  
  64. sub handle_request {
  65.     my $self = shift;
  66.     $self->_handler( { comp => $ENV{PATH_INFO} }, @_ );
  67. }
  68.  
  69. sub handle_comp {
  70.     my ($self, $comp) = (shift, shift);
  71.     $self->_handler( { comp => $comp }, @_ );
  72. }
  73.  
  74. sub handle_cgi_object {
  75.     my ($self, $cgi) = (shift, shift);
  76.     $self->_handler( { comp => $cgi->path_info,
  77.                cgi       => $cgi },
  78.              @_);
  79. }
  80.  
  81. sub _handler {
  82.     my ($self, $p) = (shift, shift);
  83.  
  84.     my $r = $self->create_delayed_object('cgi_request', cgi => $p->{cgi});
  85.     $self->interp->set_global('$r', $r);
  86.  
  87.     # hack for testing
  88.     if (@_) {
  89.         $self->{output} = '';
  90.         $self->interp->out_method( \$self->{output} );
  91.     } elsif (! $self->{has_custom_out_method}) {
  92.         my $sent_headers = 0;
  93.  
  94.         my $out_method = sub {
  95.  
  96.             # Send headers if they have not been sent by us or by user.
  97.             # We use instance here because if we store $request we get a
  98.             # circular reference and a big memory leak.
  99.             if (!$sent_headers and HTML::Mason::Request->instance->auto_send_headers) {
  100.                 unless ($r->http_header_sent) {
  101.                     $r->send_http_header();
  102.                 }
  103.                 $sent_headers = 1;
  104.             }
  105.  
  106.             # We could perhaps install a new, faster out_method here that
  107.             # wouldn't have to keep checking whether headers have been
  108.             # sent and what the $r->method is.  That would require
  109.             # additions to the Request interface, though.
  110.  
  111.             print STDOUT grep {defined} @_;
  112.         };
  113.  
  114.         $self->interp->out_method($out_method);
  115.     }
  116.  
  117.     $self->interp->delayed_object_params('request', cgi_request => $r);
  118.  
  119.     my %args = $self->request_args($r);
  120.  
  121.     eval { $self->interp->exec($p->{comp}, %args) };
  122.  
  123.     if (my $err = $@) {
  124.  
  125.         unless ( isa_mason_exception($err, 'Abort')
  126.                  or isa_mason_exception($err, 'Decline') ) {
  127.  
  128.             rethrow_exception($err);
  129.         }
  130.     }
  131.  
  132.     if (@_) {
  133.     # This is a secret feature, and should stay secret (or go
  134.     # away) because it's just a hack for the test suite.
  135.     $_[0] .= $r->http_header . $self->{output};
  136.     }
  137. }
  138.  
  139. # This is broken out in order to make subclassing easier.
  140. sub request_args {
  141.     my ($self, $r) = @_;
  142.  
  143.     return $r->params;
  144. }
  145.  
  146.  
  147. ###########################################################
  148. package HTML::Mason::Request::CGI;
  149. # Subclass for HTML::Mason::Request object $m
  150.  
  151. use HTML::Mason::Exceptions;
  152. use HTML::Mason::Request;
  153. use base qw(HTML::Mason::Request);
  154.  
  155. use Params::Validate qw(BOOLEAN);
  156. Params::Validate::validation_options( on_fail => sub { param_error( join '', @_ ) } );
  157.  
  158. __PACKAGE__->valid_params
  159.     ( cgi_request => { isa => 'HTML::Mason::FakeApache' },
  160.  
  161.       auto_send_headers => { parse => 'boolean', type => BOOLEAN, default => 1,
  162.                              descr => "Whether HTTP headers should be auto-generated" },
  163.     );
  164.  
  165. use HTML::Mason::MethodMaker
  166.     ( read_only  => [ 'cgi_request' ],
  167.       read_write => [ 'auto_send_headers' ] );
  168.  
  169. sub cgi_object {
  170.     my $self = shift;
  171.     return $self->{cgi_request}->query(@_);
  172. }
  173.  
  174. #
  175. # Override this method to send HTTP headers if necessary.
  176. #
  177. sub exec
  178. {
  179.     my $self = shift;
  180.     my $r = $self->cgi_request;
  181.     my $retval;
  182.  
  183.     eval { $retval = $self->SUPER::exec(@_) };
  184.  
  185.     # On a success code, send headers if they have not been sent and
  186.     # if we are the top-level request. Since the out_method sends
  187.     # headers, this will typically only apply after $m->abort.
  188.     # On an error code, leave it to Apache to send the headers.
  189.     if (!$self->is_subrequest
  190.     and $self->auto_send_headers
  191.     and !$r->http_header_sent
  192.     and (!$retval or $retval==200)) {
  193.     $r->send_http_header();
  194.     }
  195. }
  196.  
  197. sub redirect {
  198.     my $self = shift;
  199.     my $url = shift;
  200.     my $status = shift || 302;
  201.  
  202.     $self->clear_buffer;
  203.  
  204.     $self->{cgi_request}->header_out( Location => $url );
  205.     $self->{cgi_request}->header_out( Status => $status );
  206.  
  207.     $self->abort;
  208. }
  209.  
  210. 1;
  211. __END__
  212.  
  213. =head1 NAME
  214.  
  215. HTML::Mason::CGIHandler - Use Mason in a CGI environment
  216.  
  217. =head1 SYNOPSIS
  218.  
  219. In httpd.conf or .htaccess:
  220.  
  221.    Action html-mason /cgi-bin/mason_handler.cgi
  222.    <LocationMatch "\.html$">
  223.     SetHandler html-mason
  224.    </LocationMatch>
  225.  
  226. A script at /cgi-bin/mason_handler.pl :
  227.  
  228.    #!/usr/bin/perl
  229.    use HTML::Mason::CGIHandler;
  230.  
  231.    my $h = HTML::Mason::CGIHandler->new
  232.     (
  233.      data_dir  => '/home/jethro/code/mason_data',
  234.      allow_globals => [qw(%session $u)],
  235.     );
  236.  
  237.    $h->handle_request;
  238.  
  239. A .html component somewhere in the web server's document root:
  240.  
  241.    <%args>
  242.     $mood => 'satisfied'
  243.    </%args>
  244.    % $r->err_header_out(Location => "http://blahblahblah.com/moodring/$mood.html");
  245.    ...
  246.  
  247. =head1 DESCRIPTION
  248.  
  249. This module lets you execute Mason components in a CGI environment.
  250. It lets you keep your top-level components in the web server's
  251. document root, using regular component syntax and without worrying
  252. about the particular details of invoking Mason on each request.
  253.  
  254. If you want to use Mason components from I<within> a regular CGI
  255. script (or any other Perl program, for that matter), then you don't
  256. need this module.  You can simply follow the directions in
  257. the L<Using Mason from a standalone script|HTML::Mason::Admin/Using Mason from a standalone script> section of the administrator's manual.
  258.  
  259. This module also provides an C<$r> request object for use inside
  260. components, similar to the Apache request object under
  261. C<HTML::Mason::ApacheHandler>, but limited in functionality.  Please
  262. note that we aim to replicate the C<mod_perl> functionality as closely
  263. as possible - if you find differences, do I<not> depend on them to
  264. stay different.  We may fix them in a future release.  Also, if you
  265. need some missing functionality in C<$r>, let us know, we might be
  266. able to provide it.
  267.  
  268. Finally, this module alters the C<HTML::Mason::Request> object C<$m> to
  269. provide direct access to the CGI query, should such access be necessary.
  270.  
  271. =head2 C<HTML::Mason::CGIHandler> Methods
  272.  
  273. =over 4
  274.  
  275. =item * new()
  276.  
  277. Creates a new handler.  Accepts any parameter that the Interpreter
  278. accepts.
  279.  
  280. If no C<comp_root> parameter is passed to C<new()>, the component root
  281. will be C<$ENV{DOCUMENT_ROOT}>.
  282.  
  283. =item * handle_request()
  284.  
  285. Handles the current request, reading input from C<$ENV{QUERY_STRING}>
  286. or C<STDIN> and sending headers and component output to C<STDOUT>.
  287. This method doesn't accept any parameters.  The initial component
  288. will be the one specified in C<$ENV{PATH_INFO}>.
  289.  
  290. =item * handle_comp()
  291.  
  292. Like C<handle_request()>, but the first (only) parameter is a
  293. component path or component object.  This is useful within a
  294. traditional CGI environment, in which you're essentially using Mason
  295. as a templating language but not an application server.
  296.  
  297. C<handle_component()> will create a CGI query object, parse the query
  298. parameters, and send the HTTP header and component output to STDOUT.
  299. If you want to handle those parts yourself, see
  300. the L<Using Mason from a standalone script|HTML::Mason::Admin/Using Mason from a standalone script> section of the administrator's manual.
  301.  
  302. =item * handle_cgi_object()
  303.  
  304. Also like C<handle_request()>, but this method takes only a CGI object
  305. as its parameter.  This can be quite useful if you want to use this
  306. module with CGI::Fast.
  307.  
  308. The component path will be the value of the CGI object's
  309. C<path_info()> method.
  310.  
  311. =item * request_args()
  312.  
  313. Given an C<HTML::Mason::FakeApache> object, this method is expected to
  314. return a hash containing the arguments to be passed to the component.
  315. It is a separate method in order to make it easily overrideable in a
  316. subclass.
  317.  
  318. =item * interp()
  319.  
  320. Returns the Mason Interpreter associated with this handler.  The
  321. Interpreter lasts for the entire lifetime of the handler.
  322.  
  323. =back
  324.  
  325. =head2 $r Methods
  326.  
  327. =over 4
  328.  
  329. =item * headers_in()
  330.  
  331. This works much like the C<Apache> method of the same name. In an array
  332. context, it will return a C<%hash> of response headers. In a scalar context,
  333. it will return a reference to the case-insensitive hash blessed into the
  334. C<HTML::Mason::FakeTable> class. The values initially populated in this hash are
  335. extracted from the CGI environment variables as best as possible. The pattern
  336. is to merely reverse the conversion from HTTP headers to CGI variables as
  337. documented here: L<http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html#6.1>.
  338.  
  339. =item * header_in()
  340.  
  341. This works much like the C<Apache> method of the same name. When passed the
  342. name of a header, returns the value of the given incoming header. When passed
  343. a name and a value, sets the value of the header. Setting the header to
  344. C<undef> will actually I<unset> the header (instead of setting its value to
  345. C<undef>), removing it from the table of headers returned from future calls to
  346. C<headers_in()> or C<header_in()>.
  347.  
  348. =item * headers_out()
  349.  
  350. This works much like the C<Apache> method of the same name. In an array
  351. context, it will return a C<%hash> of response headers. In a scalar context,
  352. it will return a reference to the case-insensitive hash blessed into the
  353. C<HTML::Mason::FakeTable> class. Changes made to this hash will be made to the
  354. headers that will eventually be passed to the C<CGI> module's C<header()>
  355. method.
  356.  
  357. =item * header_out()
  358.  
  359. This works much like the C<Apache> method of the same name.  When
  360. passed the name of a header, returns the value of the given outgoing
  361. header.  When passed a name and a value, sets the value of the header.
  362. Setting the header to C<undef> will actually I<unset> the header
  363. (instead of setting its value to C<undef>), removing it from the table
  364. of headers that will be sent to the client.
  365.  
  366. The headers are eventually passed to the C<CGI> module's C<header()>
  367. method.
  368.  
  369. =item * err_headers_out()
  370.  
  371. This works much like the C<Apache> method of the same name. In an array
  372. context, it will return a C<%hash> of error response headers. In a scalar
  373. context, it will return a reference to the case-insensitive hash blessed into
  374. the C<HTML::Mason::FakeTable> class. Changes made to this hash will be made to
  375. the error headers that will eventually be passed to the C<CGI> module's
  376. C<header()> method.
  377.  
  378. =item * err_header_out()
  379.  
  380. This works much like the C<Apache> method of the same name. When passed the
  381. name of a header, returns the value of the given outgoing error header. When
  382. passed a name and a value, sets the value of the error header. Setting the
  383. header to C<undef> will actually I<unset> the header (instead of setting its
  384. value to C<undef>), removing it from the table of headers that will be sent to
  385. the client.
  386.  
  387. The headers are eventually passed to the C<CGI> module's C<header()> method.
  388.  
  389. One header currently gets special treatment - if you set a C<Location>
  390. header, you'll cause the C<CGI> module's C<redirect()> method to be
  391. used instead of the C<header()> method.  This means that in order to
  392. do a redirect, all you need to do is:
  393.  
  394.  $r->err_header_out(Location => 'http://redirect.to/here');
  395.  
  396. You may be happier using the C<< $m->redirect >> method, though,
  397. because it hides most of the complexities of sending headers and
  398. getting the status code right.
  399.  
  400. =item * content_type()
  401.  
  402. When passed an argument, sets the content type of the current request
  403. to the value of the argument.  Use this method instead of setting a
  404. C<Content-Type> header directly with C<header_out()>.  Like
  405. C<header_out()>, setting the content type to C<undef> will remove any
  406. content type set previously.
  407.  
  408. When called without arguments, returns the value set by a previous
  409. call to C<content_type()>.  The behavior when C<content_type()> hasn't
  410. already been set is undefined - currently it returns C<undef>.
  411.  
  412. If no content type is set during the request, the default MIME type
  413. C<text/html> will be used.
  414.  
  415. =item * method()
  416.  
  417. Returns the request method used for the current request, e.g., "GET", "POST",
  418. etc.
  419.  
  420. =item * http_header()
  421.  
  422. This method returns the outgoing headers as a string, suitable for
  423. sending to the client.
  424.  
  425. =item * send_http_header()
  426.  
  427. Sends the outgoing headers to the client.
  428.  
  429. =item * notes()
  430.  
  431. This works much like the C<Apache> method of the same name. When passed
  432. a C<$key> argument, it returns the value of the note for that key. When
  433. passed a C<$value> argument, it stores that value under the key. Keys are
  434. case-insensitive, and both the key and the value must be strings. When
  435. called in a scalar context with no C<$key> argument, it returns a hash
  436. reference blessed into the C<HTML::Mason::FakeTable> class.
  437.  
  438. =item * pnotes()
  439.  
  440. Like C<notes()>, but takes any scalar as an value, and stores the
  441. values in a case-sensitive hash.
  442.  
  443. =item * subprocess_env()
  444.  
  445. Works like the C<Apache> method of the same name, but is simply populated with
  446. the current values of the environment. Still, it's useful, because values can
  447. be changed and then seen by later components, but the environment itself
  448. remains unchanged. Like the C<Apache> method, it will reset all of its values
  449. to the current environment again if it's called without a C<$key> argument.
  450.  
  451. =item * params()
  452.  
  453. This method returns a hash containing the parameters sent by the
  454. client.  Multiple parameters of the same name are represented by array
  455. references.  If both POST and query string arguments were submitted,
  456. these will be merged together.
  457.  
  458. =back
  459.  
  460. =head2 Added C<$m> methods
  461.  
  462. The C<$m> object provided in components has all the functionality of
  463. the regular C<HTML::Mason::Request> object C<$m>, and the following:
  464.  
  465. =over 4
  466.  
  467. =item * cgi_object()
  468.  
  469. Returns the current C<CGI> request object.  This is handy for
  470. processing cookies or perhaps even doing HTML generation (but is that
  471. I<really> what you want to do?).  If you pass an argument to this
  472. method, you can set the request object to the argument passed.  Use
  473. this with care, as it may affect components called after the current
  474. one (they may check the content length of the request, for example).
  475.  
  476. Note that the ApacheHandler class (for using Mason under mod_perl)
  477. also provides a C<cgi_object()> method that does the same thing as
  478. this one.  This makes it easier to write components that function
  479. equally well under CGIHandler and ApacheHandler.
  480.  
  481. =item * cgi_request()
  482.  
  483. Returns the object that is used to emulate Apache's request object.
  484. In other words, this is the object that C<$r> is set to when you use
  485. this class.
  486.  
  487. =back
  488.  
  489. =head2 C<HTML::Mason::FakeTable> Methods
  490.  
  491. This class emulates the behavior of the C<Apache::Table> class, and is
  492. used to store manage the tables of values for the following attributes
  493. of <$r>:
  494.  
  495. =over 4
  496.  
  497. =item headers_in
  498.  
  499. =item headers_out
  500.  
  501. =item err_headers_out
  502.  
  503. =item notes
  504.  
  505. =item subprocess_env
  506.  
  507. =back
  508.  
  509. C<HTML::Mason::FakeTable> is designed to behave exactly like C<Apache::Table>,
  510. and differs in only one respect. When a given key has multiple values in an
  511. C<Apache::Table> object, one can fetch each of the values for that key using
  512. Perl's C<each> operator:
  513.  
  514.   while (my ($k, $v) = each %{$r->headers_out}) {
  515.       push @cookies, $v if lc $k eq 'set-cookie';
  516.   }
  517.  
  518. If anyone knows how Apache::Table does this, let us know! In the meantime, use
  519. C<get()> or C<do()> to get at all of the values for a given key (C<get()> is
  520. much more efficient, anyway).
  521.  
  522. Since the methods named for these attributes return an
  523. C<HTML::Mason::FakeTable> object hash in a scalar reference, it seemed only
  524. fair to document its interface.
  525.  
  526. =over 4
  527.  
  528. =item * new()
  529.  
  530. Returns a new C<HTML::Mason::FakeTable> object. Any parameters passed
  531. to C<new()> will be added to the table as initial values.
  532.  
  533. =item * add()
  534.  
  535. Adds a new value to the table. If the value did not previously exist under the
  536. given key, it will be created. Otherwise, it will be added as a new value to
  537. the key.
  538.  
  539. =item * clear()
  540.  
  541. Clears the table of all values.
  542.  
  543. =item * do()
  544.  
  545. Pass a code reference to this method to have it iterate over all of the
  546. key/value pairs in the table. Keys will multiple values will trigger the
  547. execution of the code reference multiple times for each value. The code
  548. reference should expect two arguments: a key and a value. Iteration terminates
  549. when the code reference returns false, to be sure to have it return a true
  550. value if you wan it to iterate over every value in the table.
  551.  
  552. =item * get()
  553.  
  554. Gets the value stored for a given key in the table. If a key has multiple
  555. values, all will be returned when C<get()> is called in an array context, and
  556. only the first value when it is called in a scalar context.
  557.  
  558. =item * merge()
  559.  
  560. Merges a new value with an existing value by concatenating the new value onto
  561. the existing. The result is a comma-separated list of all of the values merged
  562. for a given key.
  563.  
  564. =item * set()
  565.  
  566. Takes key and value arguments and sets the value for that key. Previous values
  567. for that key will be discarded. The value must be a string, or C<set()> will
  568. turn it into one. A value of C<undef> will have the same behavior as
  569. C<unset()>.
  570.  
  571. =item * unset()
  572.  
  573. Takes a single key argument and deletes that key from the table, so that none
  574. of its values will be in the table any longer.
  575.  
  576. =back
  577.  
  578. =head1 SEE ALSO
  579.  
  580. L<HTML::Mason|HTML::Mason>,
  581. L<HTML::Mason::Admin|HTML::Mason::Admin>,
  582. L<HTML::Mason::ApacheHandler|HTML::Mason::ApacheHandler>
  583.  
  584. =cut
  585.