X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FCatalyst%2FEngine.pm;h=67e4dab5fcc748217a74253521a8ea980be9e5ce;hb=9c4288eaedee0bba8e4a123b4664bc07a4b5c24c;hp=ff016032a30d4fdb9e9176e8498a02eb1c7fdddd;hpb=5783a9a55a3037a5907c11f8649521434c2ca92e;p=catagits%2FCatalyst-Runtime.git diff --git a/lib/Catalyst/Engine.pm b/lib/Catalyst/Engine.pm index ff01603..67e4dab 100644 --- a/lib/Catalyst/Engine.pm +++ b/lib/Catalyst/Engine.pm @@ -1,31 +1,43 @@ package Catalyst::Engine; -use strict; -use base qw/Class::Data::Inheritable Class::Accessor::Fast/; -use UNIVERSAL::require; -use Data::Dumper; +use Moose; +with 'MooseX::Emulate::Class::Accessor::Fast'; + +use CGI::Simple::Cookie; +use Data::Dump qw/dump/; +use Errno 'EWOULDBLOCK'; use HTML::Entities; +use HTTP::Body; use HTTP::Headers; -use Time::HiRes qw/gettimeofday tv_interval/; -use Catalyst::Request; -use Catalyst::Response; - -require Module::Pluggable::Fast; - -$Data::Dumper::Terse = 1; - -__PACKAGE__->mk_classdata($_) for qw/actions components/; -__PACKAGE__->mk_accessors(qw/request response/); - -__PACKAGE__->actions( - { plain => {}, regex => {}, compiled => {}, reverse => {} } ); - -*comp = \&component; -*req = \&request; -*res = \&response; - -our $COUNT = 1; -our $START = time; +use URI::QueryParam; +use Plack::Loader; +use Catalyst::EngineLoader; +use Encode (); +use utf8; + +use namespace::clean -except => 'meta'; + +# Amount of data to read from input on each pass +our $CHUNKSIZE = 64 * 1024; + +# XXX - this is only here for compat, do not use! +has env => ( is => 'rw', writer => '_set_env' ); +my $WARN_ABOUT_ENV = 0; +around env => sub { + my ($orig, $self, @args) = @_; + if(@args) { + warn "env as a writer is deprecated, you probably need to upgrade Catalyst::Engine::PSGI" + unless $WARN_ABOUT_ENV++; + return $self->_set_env(@args); + } + return $self->$orig; +}; + +# XXX - Only here for Engine::PSGI compat +sub prepare_connection { + my ($self, $ctx) = @_; + $ctx->request->prepare_connection; +} =head1 NAME @@ -37,717 +49,692 @@ See L. =head1 DESCRIPTION -=head2 METHODS - -=head3 action - -Add one or more actions. - - $c->action( '!foo' => sub { $_[1]->res->output('Foo!') } ); +=head1 METHODS -Get an action's class and coderef. - my ($class, $code) = @{ $c->action('foo') }; +=head2 $self->finalize_body($c) -Get a list of available actions. - - my @actions = $c->action; - -It also automatically calls setup() if needed. - -See L for more informations about actions. +Finalize body. Prints the response output. =cut -sub action { - my $self = shift; - $self->setup unless $self->components; - $self->actions( {} ) unless $self->actions; - my $action; - $_[1] ? ( $action = {@_} ) : ( $action = shift ); - if ( ref $action eq 'HASH' ) { - while ( my ( $name, $code ) = each %$action ) { - my $class = caller(0); - if ( $name =~ /^\/(.*)\/$/ ) { - my $regex = $1; - $self->actions->{compiled}->{qr/$regex/} = $name; - $self->actions->{regex}->{$name} = [ $class, $code ]; - } - elsif ( $name =~ /^\?(.*)$/ ) { - $name = $1; - $name = _prefix( $class, $name ); - $self->actions->{plain}->{$name} = [ $class, $code ]; - } - elsif ( $name =~ /^\!\?(.*)$/ ) { - $name = $1; - $name = _prefix( $class, $name ); - $name = "\!$name"; - $self->actions->{plain}->{$name} = [ $class, $code ]; - } - else { $self->actions->{plain}->{$name} = [ $class, $code ] } - $self->actions->{reverse}->{"$code"} = $name; - $self->log->debug(qq/"$class" defined "$name" as "$code"/) - if $self->debug; - } - } - elsif ($action) { - if ( my $p = $self->actions->{plain}->{$action} ) { return [$p] } - elsif ( my $r = $self->actions->{regex}->{$action} ) { return [$r] } - else { - for my $regex ( keys %{ $self->actions->{compiled} } ) { - my $name = $self->actions->{compiled}->{$regex}; - if ( $action =~ $regex ) { - my @snippets; - for my $i ( 1 .. 9 ) { - no strict 'refs'; - last unless ${$i}; - push @snippets, ${$i}; - } - return [ $self->actions->{regex}->{$name}, - $name, \@snippets ]; - } - } - } - return 0; +sub finalize_body { + my ( $self, $c ) = @_; + my $body = $c->response->body; + no warnings 'uninitialized'; + if ( blessed($body) && $body->can('read') or ref($body) eq 'GLOB' ) { + my $got; + do { + $got = read $body, my ($buffer), $CHUNKSIZE; + $got = 0 unless $self->write( $c, $buffer ); + } while $got > 0; + + close $body; } else { - return ( - keys %{ $self->actions->{plain} }, - keys %{ $self->actions->{regex} } - ); + $self->write( $c, $body ); } -} - -=head3 benchmark -Takes a coderef with arguments and returns elapsed time as float. + my $res = $c->response; + $res->_writer->close; + $res->_clear_writer; - my ( $elapsed, $status ) = $c->benchmark( sub { return 1 } ); - $c->log->info( sprintf "Processing took %f seconds", $elapsed ); + return; +} -=cut +=head2 $self->finalize_cookies($c) -sub benchmark { - my $c = shift; - my $code = shift; - my $time = [gettimeofday]; - my @return = &$code(@_); - my $elapsed = tv_interval $time; - return wantarray ? ( $elapsed, @return ) : $elapsed; -} +Create CGI::Simple::Cookie objects from $c->res->cookies, and set them as +response headers. -=head3 component (comp) +=cut -Get a component object by name. +sub finalize_cookies { + my ( $self, $c ) = @_; - $c->comp('MyApp::Model::MyModel')->do_stuff; + my @cookies; + my $response = $c->response; -Regex search for a component. + foreach my $name (keys %{ $response->cookies }) { - $c->comp('mymodel')->do_stuff; + my $val = $response->cookies->{$name}; -=cut + my $cookie = ( + blessed($val) + ? $val + : CGI::Simple::Cookie->new( + -name => $name, + -value => $val->{value}, + -expires => $val->{expires}, + -domain => $val->{domain}, + -path => $val->{path}, + -secure => $val->{secure} || 0, + -httponly => $val->{httponly} || 0, + ) + ); + if (!defined $cookie) { + $c->log->warn("undef passed in '$name' cookie value - not setting cookie") + if $c->debug; + next; + } -sub component { - my ( $c, $name ) = @_; - if ( my $component = $c->components->{$name} ) { - return $component; + push @cookies, $cookie->as_string; } - else { - for my $component ( keys %{ $c->components } ) { - return $c->components->{$component} if $component =~ /$name/i; - } + + for my $cookie (@cookies) { + $response->headers->push_header( 'Set-Cookie' => $cookie ); } } -=head3 errors - -Returns an arrayref containing errors messages. +=head2 $self->finalize_error($c) - my @errors = @{ $c->errors }; - -Add a new error. - - $c->errors('Something bad happened'); +Output an appropriate error message. Called if there's an error in $c +after the dispatch has finished. Will output debug messages if Catalyst +is in debug mode, or a `please come back later` message otherwise. =cut -sub errors { - my $c = shift; - my $errors = ref $_[0] eq 'ARRAY' ? $_[0] : [@_]; - push @{ $c->{errors} }, @$errors; - return $c->{errors}; +sub _dump_error_page_element { + my ($self, $i, $element) = @_; + my ($name, $val) = @{ $element }; + + # This is fugly, but the metaclass is _HUGE_ and demands waaay too much + # scrolling. Suggestions for more pleasant ways to do this welcome. + local $val->{'__MOP__'} = "Stringified: " + . $val->{'__MOP__'} if ref $val eq 'HASH' && exists $val->{'__MOP__'}; + + my $text = encode_entities( dump( $val )); + sprintf <<"EOF", $name, $text; +

%s

+
+
%s
+
+EOF } -=head3 finalize +sub finalize_error { + my ( $self, $c ) = @_; -Finalize request. + $c->res->content_type('text/html; charset=utf-8'); + my $name = ref($c)->config->{name} || join(' ', split('::', ref $c)); + + # Prevent Catalyst::Plugin::Unicode::Encoding from running. + # This is a little nasty, but it's the best way to be clean whether or + # not the user has an encoding plugin. -=cut + if ($c->can('encoding')) { + $c->{encoding} = ''; + } -sub finalize { - my $c = shift; - if ( !$c->res->output || $#{ $c->errors } >= 0 ) { - $c->res->headers->content_type('text/html'); - my $name = $c->config->{name} || 'Catalyst Application'; - my ( $title, $errors, $infos ); - if ( $c->debug ) { - $errors = join '
', @{ $c->errors }; - $errors ||= 'No output'; - $title = $name = "$name on Catalyst $Catalyst::VERSION"; - my $req = encode_entities Dumper $c->req; - my $res = encode_entities Dumper $c->res; - my $stash = encode_entities Dumper $c->stash; - $infos = <<""; -
-Request
-
$req
-Response
-
$res
-Stash
-
$stash
+ my ( $title, $error, $infos ); + if ( $c->debug ) { + # For pretty dumps + $error = join '', map { + '

' + . encode_entities($_) + . '

' + } @{ $c->error }; + $error ||= 'No output'; + $error = qq{
$error
}; + $title = $name = "$name on Catalyst $Catalyst::VERSION"; + $name = "

$name

"; + + # Don't show context in the dump + $c->req->_clear_context; + $c->res->_clear_context; + + # Don't show body parser in the dump + $c->req->_clear_body; + + my @infos; + my $i = 0; + for my $dump ( $c->dump_these ) { + push @infos, $self->_dump_error_page_element($i, $dump); + $i++; } - else { - $title = $name; - $errors = ''; - $infos = <<""; + $infos = join "\n", @infos; + } + else { + $title = $name; + $error = ''; + $infos = <<"";
 (en) Please come back later
+(fr) SVP veuillez revenir plus tard
 (de) Bitte versuchen sie es spaeter nocheinmal
-(nl) Gelieve te komen later terug
+(at) Konnten's bitt'schoen spaeter nochmal reinschauen
 (no) Vennligst prov igjen senere
-(fr) Veuillez revenir plus tard
-(es) Vuelto por favor mas adelante
-(pt) Voltado por favor mais tarde
-(it) Ritornato prego più successivamente
+(dk) Venligst prov igen senere
+(pl) Prosze sprobowac pozniej
+(pt) Por favor volte mais tarde
+(ru) Попробуйте еще раз позже
+(ua) Спробуйте ще раз пізніше
 
- $name = ''; - } - $c->res->{output} = <<""; - - - $title - - - -
-
$errors
-
$infos
-
$name
-
- + } + --> + + + + +
+
$error
+
$infos
+
$name
+
+ - } - if ( my $location = $c->res->redirect ) { - $c->log->debug(qq/Redirecting to "$location"/) if $c->debug; - $c->res->headers->header( Location => $location ); - $c->res->status(302); - } - $c->res->headers->content_length( length $c->res->output ); - my $status = $c->finalize_headers; - $c->finalize_output; - return $status; + # Trick IE. Old versions of IE would display their own error page instead + # of ours if we'd give it less than 512 bytes. + $c->res->{body} .= ( ' ' x 512 ); + + $c->res->{body} = Encode::encode("UTF-8", $c->res->{body}); + + # Return 500 + $c->res->status(500); } -=head3 finalize_headers +=head2 $self->finalize_headers($c) -Finalize headers. +Allows engines to write headers to response =cut -sub finalize_headers { } +sub finalize_headers { + my ($self, $ctx) = @_; -=head3 finalize_output + $ctx->response->finalize_headers; + return; +} + +=head2 $self->finalize_uploads($c) -Finalize output. +Clean up after uploads, deleting temp files. =cut -sub finalize_output { } +sub finalize_uploads { + my ( $self, $c ) = @_; + + # N.B. This code is theoretically entirely unneeded due to ->cleanup(1) + # on the HTTP::Body object. + my $request = $c->request; + foreach my $key (keys %{ $request->uploads }) { + my $upload = $request->uploads->{$key}; + unlink grep { -e $_ } map { $_->tempname } + (ref $upload eq 'ARRAY' ? @{$upload} : ($upload)); + } -=head3 forward +} -Forward processing to a private/public action or a method from a class. -If you define a class without method it will default to process(). +=head2 $self->prepare_body($c) - $c->forward('!foo'); - $c->forward('index.html'); - $c->forward(qw/MyApp::Model::CDBI::Foo do_stuff/); - $c->forward('MyApp::View::TT'); +sets up the L object body using L =cut -sub forward { - my $c = shift; - my $command = shift; - unless ($command) { - $c->log->debug('Nothing to forward to') if $c->debug; - return 0; - } - if ( $command =~ /^\?(.*)$/ ) { - $command = $1; - my $caller = caller(0); - $command = _prefix( $caller, $command ); - } - elsif ( $command =~ /^\!\?(.*)$/ ) { - $command = $1; - my $caller = caller(0); - $command = _prefix( $caller, $command ); - $command = "\!$command"; - } - elsif ( $command =~ /^\!(.*)$/ ) { - my $try = $1; - my $caller = caller(0); - my $prefix = _class2prefix($caller); - $try = "!$prefix/$command"; - $command = $try if $c->actions->{plain}->{$try}; - } - my ( $class, $code ); - if ( my $action = $c->action($command) ) { - if ( $action->[2] ) { - $c->log->debug(qq/Couldn't forward "$command" to regex action/) - if $c->debug; - return 0; - } - ( $class, $code ) = @{ $action->[0] }; - } - else { - $class = $command; - if ( $class =~ /[^\w\:]/ ) { - $c->log->debug(qq/Couldn't forward to "$class"/) if $c->debug; - return 0; - } - my $method = shift || 'process'; - if ( $code = $class->can($method) ) { - $c->actions->{reverse}->{"$code"} = "$class->$method"; - } - else { - $c->log->debug(qq/Couldn't forward to "$class->$method"/) - if $c->debug; - return 0; - } - } - $class = $c->components->{$class} || $class; - return $c->process( $class, $code ); +sub prepare_body { + my ( $self, $c ) = @_; + + $c->request->prepare_body; } -=head3 handler +=head2 $self->prepare_body_chunk($c) -Handles the request. +Add a chunk to the request body. =cut -sub handler { - my ( $class, $r ) = @_; - - # Always expect worst case! - my $status = -1; - eval { - my $handler = sub { - my $c = $class->prepare($r); - if ( my $action = $c->action( $c->req->action ) ) { - my ( $begin, $end ); - my $class = ${ $action->[0] }[0]; - my $prefix = _class2prefix($class); - if ($prefix) { - if ( $c->actions->{plain}->{"\!$prefix/begin"} ) { - $begin = "\!$prefix/begin"; - } - elsif ( $c->actions->{plain}->{'!begin'} ) { - $begin = '!begin'; - } - if ( $c->actions->{plain}->{"\!$prefix/end"} ) { - $end = "\!$prefix/end"; - } - elsif ( $c->actions->{plain}->{'!end'} ) { $end = '!end' } - } - else { - if ( $c->actions->{plain}->{'!begin'} ) { - $begin = '!begin'; - } - if ( $c->actions->{plain}->{'!end'} ) { $end = '!end' } - } - $c->forward($begin) if $begin; - $c->forward( $c->req->action ) if $c->req->action; - $c->forward($end) if $end; - } - else { - my $action = $c->req->path; - my $error = $action - ? qq/Unknown resource "$action"/ - : "No default action defined"; - $c->log->error($error) if $c->debug; - $c->errors($error); - } - return $c->finalize; - }; - if ( $class->debug ) { - my $elapsed; - ( $elapsed, $status ) = $class->benchmark($handler); - $elapsed = sprintf '%f', $elapsed; - my $av = sprintf '%.3f', 1 / $elapsed; - $class->log->info( "Request took $elapsed" . "s ($av/s)" ); - } - else { $status = &$handler } - }; - if ( my $error = $@ ) { - chomp $error; - $class->log->error(qq/Caught exception in engine "$error"/); - } - $COUNT++; - return $status; +# XXX - Can this be deleted? +sub prepare_body_chunk { + my ( $self, $c, $chunk ) = @_; + + $c->request->prepare_body_chunk($chunk); } -=head3 prepare +=head2 $self->prepare_body_parameters($c) -Turns the request (Apache, CGI...) into a Catalyst context. +Sets up parameters from body. =cut -sub prepare { - my ( $class, $r ) = @_; - my $c = bless { - request => Catalyst::Request->new( - { - arguments => [], - cookies => {}, - headers => HTTP::Headers->new, - parameters => {}, - snippets => [], - uploads => {} - } - ), - response => Catalyst::Response->new( - { cookies => {}, headers => HTTP::Headers->new, status => 200 } - ), - stash => {} - }, $class; - if ( $c->debug ) { - my $secs = time - $START || 1; - my $av = sprintf '%.3f', $COUNT / $secs; - $c->log->debug('********************************'); - $c->log->debug("* Request $COUNT ($av/s) [$$]"); - $c->log->debug('********************************'); - $c->res->headers->header( 'X-Catalyst' => $Catalyst::VERSION ); - } - $c->prepare_request($r); - $c->prepare_path; - $c->prepare_cookies; - $c->prepare_headers; - my $method = $c->req->method; - my $path = $c->req->path; - $c->log->debug(qq/"$method" request for "$path"/) if $c->debug; - $c->prepare_action; - $c->prepare_parameters; - $c->prepare_uploads; - return $c; +sub prepare_body_parameters { + my ( $self, $c ) = @_; + + $c->request->prepare_body_parameters; } -=head3 prepare_action +=head2 $self->prepare_parameters($c) -Prepare action. +sets up parameters from query and post parameters. =cut -sub prepare_action { - my $c = shift; - my $path = $c->req->path; - my @path = split /\//, $c->req->path; - $c->req->args( \my @args ); - while (@path) { - $path = join '/', @path; - if ( my $result = $c->action($path) ) { - - # It's a regex - if ($#$result) { - my $match = $result->[1]; - my @snippets = @{ $result->[2] }; - $c->log->debug(qq/Requested action "$path" matched "$match"/) - if $c->debug; - $c->log->debug( - 'Snippets are "' . join( ' ', @snippets ) . '"' ) - if ( $c->debug && @snippets ); - $c->req->action($match); - $c->req->snippets( \@snippets ); - } - else { - $c->req->action($path); - $c->log->debug(qq/Requested action "$path"/) if $c->debug; - } - $c->req->match($path); - last; - } - unshift @args, pop @path; - } - unless ( $c->req->action ) { - my $prefix = $c->req->args->[0]; - if ( $prefix && $c->actions->{plain}->{"\!$prefix/default"} ) { - $c->req->match(''); - $c->req->action("\!$prefix/default"); - $c->log->debug('Using prefixed default action') if $c->debug; - } - elsif ( $c->actions->{plain}->{'!default'} ) { - $c->req->match(''); - $c->req->action('!default'); - $c->log->debug('Using default action') if $c->debug; - } - } - $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' ) - if ( $c->debug && @args ); +sub prepare_parameters { + my ( $self, $c ) = @_; + + $c->request->parameters; } -=head3 prepare_cookies; +=head2 $self->prepare_path($c) -Prepare cookies. +abstract method, implemented by engines. =cut -sub prepare_cookies { } +sub prepare_path { + my ($self, $ctx) = @_; -=head3 prepare_headers + my $env = $ctx->request->env; -Prepare headers. + my $scheme = $ctx->request->secure ? 'https' : 'http'; + my $host = $env->{HTTP_HOST} || $env->{SERVER_NAME}; + my $port = $env->{SERVER_PORT} || 80; + my $base_path = $env->{SCRIPT_NAME} || "/"; -=cut + # set the request URI + my $path; + if (!$ctx->config->{use_request_uri_for_path}) { + my $path_info = $env->{PATH_INFO}; + if ( exists $env->{REDIRECT_URL} ) { + $base_path = $env->{REDIRECT_URL}; + $base_path =~ s/\Q$path_info\E$//; + } + $path = $base_path . $path_info; + $path =~ s{^/+}{}; + $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go; + $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE + } + else { + my $req_uri = $env->{REQUEST_URI}; + $req_uri =~ s/\?.*$//; + $path = $req_uri; + $path =~ s{^/+}{}; + } -sub prepare_headers { } + # Using URI directly is way too slow, so we construct the URLs manually + my $uri_class = "URI::$scheme"; -=head3 prepare_parameters + # HTTP_HOST will include the port even if it's 80/443 + $host =~ s/:(?:80|443)$//; -Prepare parameters. + if ($port !~ /^(?:80|443)$/ && $host !~ /:/) { + $host .= ":$port"; + } -=cut + my $query = $env->{QUERY_STRING} ? '?' . $env->{QUERY_STRING} : ''; + my $uri = $scheme . '://' . $host . '/' . $path . $query; -sub prepare_parameters { } + $ctx->request->uri( (bless \$uri, $uri_class)->canonical ); -=head3 prepare_path + # set the base URI + # base must end in a slash + $base_path .= '/' unless $base_path =~ m{/$}; -Prepare path and base. + my $base_uri = $scheme . '://' . $host . $base_path; -=cut + $ctx->request->base( bless \$base_uri, $uri_class ); -sub prepare_path { } + return; +} + +=head2 $self->prepare_request($c) -=head3 prepare_request +=head2 $self->prepare_query_parameters($c) -Prepare the engine request. +process the query string and extract query parameters. =cut -sub prepare_request { } +sub prepare_query_parameters { + my ($self, $c) = @_; -=head3 prepare_uploads + my $env = $c->request->env; + my $query_string = exists $env->{QUERY_STRING} + ? $env->{QUERY_STRING} + : ''; -Prepare uploads. + # Check for keywords (no = signs) + # (yes, index() is faster than a regex :)) + if ( index( $query_string, '=' ) < 0 ) { + $c->request->query_keywords( $self->unescape_uri($query_string) ); + return; + } -=cut + my %query; -sub prepare_uploads { } + # replace semi-colons + $query_string =~ s/;/&/g; -=head3 process + my @params = grep { length $_ } split /&/, $query_string; -Process a coderef in given class and catch exceptions. -Errors are available via $c->errors. + for my $item ( @params ) { -=cut + my ($param, $value) + = map { $self->unescape_uri($_) } + split( /=/, $item, 2 ); + + $param = $self->unescape_uri($item) unless defined $param; -sub process { - my ( $c, $class, $code ) = @_; - my $status; - eval { - if ( $c->debug ) - { - my $action = $c->actions->{reverse}->{"$code"} || "$code"; - my $elapsed; - ( $elapsed, $status ) = - $c->benchmark( $code, $class, $c, @{ $c->req->args } ); - $c->log->info( sprintf qq/Processing "$action" took %fs/, $elapsed ) - if $c->debug; + if ( exists $query{$param} ) { + if ( ref $query{$param} ) { + push @{ $query{$param} }, $value; + } + else { + $query{$param} = [ $query{$param}, $value ]; + } + } + else { + $query{$param} = $value; } - else { $status = &$code( $class, $c, @{ $c->req->args } ) } - }; - if ( my $error = $@ ) { - chomp $error; - $error = qq/Caught exception "$error"/; - $c->log->error($error); - $c->errors($error) if $c->debug; - return 0; } - return $status; + $c->request->query_parameters( \%query ); +} + +=head2 $self->prepare_read($c) + +prepare to read from the engine. + +=cut + +sub prepare_read { + my ( $self, $c ) = @_; + + # Initialize the amount of data we think we need to read + $c->request->_read_length; } -=head3 remove_action +=head2 $self->prepare_request(@arguments) -Remove an action. +Populate the context object from the request object. - $c->remove_action('!foo'); +=cut + +sub prepare_request { + my ($self, $ctx, %args) = @_; + $ctx->request->_set_env($args{env}); + $self->_set_env($args{env}); # Nasty back compat! + $ctx->response->_set_response_cb($args{response_cb}); +} + +=head2 $self->prepare_uploads($c) =cut -sub remove_action { - my ( $self, $action ) = @_; - if ( delete $self->actions->{regex}->{$action} ) { - while ( my ( $regex, $name ) = each %{ $self->actions->{compiled} } ) { - if ( $name eq $action ) { - delete $self->actions->{compiled}->{$regex}; - last; +sub prepare_uploads { + my ( $self, $c ) = @_; + + my $request = $c->request; + return unless $request->_body; + + my $uploads = $request->_body->upload; + my $parameters = $request->parameters; + foreach my $name (keys %$uploads) { + my $files = $uploads->{$name}; + my @uploads; + for my $upload (ref $files eq 'ARRAY' ? @$files : ($files)) { + my $headers = HTTP::Headers->new( %{ $upload->{headers} } ); + my $u = Catalyst::Request::Upload->new + ( + size => $upload->{size}, + type => scalar $headers->content_type, + headers => $headers, + tempname => $upload->{tempname}, + filename => $upload->{filename}, + ); + push @uploads, $u; + } + $request->uploads->{$name} = @uploads > 1 ? \@uploads : $uploads[0]; + + # support access to the filename as a normal param + my @filenames = map { $_->{filename} } @uploads; + # append, if there's already params with this name + if (exists $parameters->{$name}) { + if (ref $parameters->{$name} eq 'ARRAY') { + push @{ $parameters->{$name} }, @filenames; + } + else { + $parameters->{$name} = [ $parameters->{$name}, @filenames ]; } } - } - else { - delete $self->actions->{plain}->{$action}; + else { + $parameters->{$name} = @filenames > 1 ? \@filenames : $filenames[0]; + } } } -=head3 request (req) +=head2 $self->read($c, [$maxlength]) -Returns a C object. +Reads from the input stream by calling C<< $self->read_chunk >>. - my $req = $c->req; +Maintains the read_length and read_position counters as data is read. -=head3 response (res) - -Returns a C object. +=cut - my $res = $c->res; +sub read { + my ( $self, $c, $maxlength ) = @_; -=head3 setup + $c->request->read($maxlength); +} -Setup. +=head2 $self->read_chunk($c, \$buffer, $length) - MyApp->setup; +Each engine implements read_chunk as its preferred way of reading a chunk +of data. Returns the number of bytes read. A return of 0 indicates that +there is no more data to be read. =cut -sub setup { - my $self = shift; - $self->setup_components; - if ( $self->debug ) { - my $name = $self->config->{name} || 'Application'; - $self->log->info("$name powered by Catalyst $Catalyst::VERSION"); - } +sub read_chunk { + my ($self, $ctx) = (shift, shift); + return $ctx->request->read_chunk(@_); } -=head3 setup_components +=head2 $self->read_length + +The length of input data to be read. This is obtained from the Content-Length +header. + +=head2 $self->read_position -Setup components. +The amount of input data that has already been read. + +=head2 $self->run($app, $server) + +Start the engine. Builds a PSGI application and calls the +run method on the server passed in, which then causes the +engine to loop, handling requests.. =cut -sub setup_components { - my $self = shift; - - # Components - my $class = ref $self || $self; - eval <<""; - package $class; - import Module::Pluggable::Fast - name => '_components', - search => [ - '$class\::Controller', '$class\::C', - '$class\::Model', '$class\::M', - '$class\::View', '$class\::V' - ]; - - if ( my $error = $@ ) { - chomp $error; - $self->log->error( - qq/Couldn't initialize "Module::Pluggable::Fast", "$error"/); +sub run { + my ($self, $app, $psgi, @args) = @_; + # @args left here rather than just a $options, $server for back compat with the + # old style scripts which send a few args, then a hashref + + # They should never actually be used in the normal case as the Plack engine is + # passed in got all the 'standard' args via the loader in the script already. + + # FIXME - we should stash the options in an attribute so that custom args + # like Gitalist's --git_dir are possible to get from the app without stupid tricks. + my $server = pop @args if (scalar @args && blessed $args[-1]); + my $options = pop @args if (scalar @args && ref($args[-1]) eq 'HASH'); + # Back compat hack for applications with old (non Catalyst::Script) scripts to work in FCGI. + if (scalar @args && !ref($args[0])) { + if (my $listen = shift @args) { + $options->{listen} ||= [$listen]; + } } - $self->components( {} ); - for my $component ( $self->_components($self) ) { - $self->components->{ ref $component } = $component; + if (! $server ) { + $server = Catalyst::EngineLoader->new(application_name => ref($self))->auto(%$options); + # We're not being called from a script, so auto detect what backend to + # run on. This should never happen, as mod_perl never calls ->run, + # instead the $app->handle method is called per request. + $app->log->warn("Not supplied a Plack engine, falling back to engine auto-loader (are your scripts ancient?)") } - $self->log->debug( 'Initialized components "' - . join( ' ', keys %{ $self->components } ) - . '"' ) - if $self->debug; + $app->run_options($options); + $server->run($psgi, $options); } -=head3 stash +=head2 build_psgi_app ($app, @args) -Returns a hashref containing all your data. - - $c->stash->{foo} ||= 'yada'; - print $c->stash->{foo}; +Builds and returns a PSGI application closure, wrapping it in the reverse proxy +middleware if the using_frontend_proxy config setting is set. =cut -sub stash { - my $self = shift; - if ( $_[0] ) { - my $stash = $_[1] ? {@_} : $_[0]; - while ( my ( $key, $val ) = each %$stash ) { - $self->{stash}->{$key} = $val; - } - } - return $self->{stash}; +sub build_psgi_app { + my ($self, $app, @args) = @_; + + return sub { + my ($env) = @_; + + return sub { + my ($respond) = @_; + $app->handle_request(env => $env, response_cb => $respond); + }; + }; } -sub _prefix { - my ( $class, $name ) = @_; - my $prefix = _class2prefix($class); - $name = "$prefix/$name" if $prefix; - return $name; +=head2 $self->write($c, $buffer) + +Writes the buffer to the client. + +=cut + +sub write { + my ( $self, $c, $buffer ) = @_; + + $c->response->write($buffer); } -sub _class2prefix { - my $class = shift; - $class =~ /^.*::[(M)(Model)(V)(View)(C)(Controller)]+::(.*)$/; - my $prefix = lc $1 || ''; - $prefix =~ s/\:\:/_/g; - return $prefix; +=head2 $self->unescape_uri($uri) + +Unescapes a given URI using the most efficient method available. Engines such +as Apache may implement this using Apache's C-based modules, for example. + +=cut + +sub unescape_uri { + my ( $self, $str ) = @_; + + $str =~ s/(?:%([0-9A-Fa-f]{2})|\+)/defined $1 ? chr(hex($1)) : ' '/eg; + + return $str; } -=head1 AUTHOR +=head2 $self->finalize_output + +, see finalize_body + +=head2 $self->env + +Hash containing environment variables including many special variables inserted +by WWW server - like SERVER_*, REMOTE_*, HTTP_* ... + +Before accessing environment variables consider whether the same information is +not directly available via Catalyst objects $c->request, $c->engine ... + +BEWARE: If you really need to access some environment variable from your Catalyst +application you should use $c->engine->env->{VARNAME} instead of $ENV{VARNAME}, +as in some environments the %ENV hash does not contain what you would expect. + +=head1 AUTHORS -Sebastian Riedel, C +Catalyst Contributors, see Catalyst.pm =head1 COPYRIGHT -This program is free software, you can redistribute it and/or modify it under +This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. =cut