Apache2-API

 view release on metacpan or  search on metacpan

lib/Apache2/API/Request.pm  view on Meta::CPAN

    $bit = 0 + $bit;
    if( exists( $methods_bit_to_name->{ $bit } ) )
    {
        return( $methods_bit_to_name->{ $bit } );
    }
    return( $self->error( "No method name is associated with bit value ${bit}" ) );
}

sub method_number { return( shift->_try( 'request', 'method_number', @_ ) ); }

sub mod_perl { return( shift->env( 'MOD_PERL', @_ ) ); }

# example: mod_perl/2.0.11
# sub mod_perl_version { return( version->parse( ( shift->mod_perl =~ /^mod_perl\/(\d+\.[\d\.]+)/ )[0] ) ); }
sub mod_perl_version { require mod_perl2; return( version->parse( $mod_perl2::VERSION ) ); }

sub mtime { return( shift->_try( 'request', 'mtime' ) ); }

sub next { return( shift->_try( 'request', 'next' ) ); }

# Tells the client not to cache the response
sub no_cache { return( shift->_try( 'request', 'no_cache', @_ ) ); }

# Takes an APR::Table object
# There is also one available via the connection object
# It returns an APR::Table object which can be used like a hash ie foreach my $k ( sort( keys( %{$table} ) ) )
sub notes
{
    my $self = shift( @_ );
    if( @_ )
    {
        my $hash = shift( @_ );
        return( $self->error( "Value provided is not a hash reference." ) ) if( ref( $hash ) ne 'HASH' );
        #my $pool = $self->pool->new;
        #my $table = APR::Table::make( $pool, 1 );
        #foreach my $k ( sort( keys( %$hash ) ) )
        #{
        #   $table->set( $k => $hash->{ $k } );
        #}
        my $r = $self->request;
        #$r->notes( $table );
        $r->pnotes( $hash );
    }
    return( $self->request->notes );
}

sub output_filters { return( shift->_try( 'request', 'output_filters', @_ ) ); }

sub param
{
    my $self = shift( @_ );
    my $name = shift( @_ ) || return;
    my $r = Apache2::API::Request::Params->new( $self->request );
    if( @_ )
    {
        return( $r->param( $name, @_ ) );
    }
    else
    {
        my $val = $r->param( $name );
        my $up = $r->upload( $name );
        # Return the Net:::API::REST::Request::Upload object if it is one
        return( $up ) if( Scalar::Util::blessed( $up ) );
        return( $val );
    }
}

sub params
{
    my $self = shift( @_ );
    return( $self->query ) if( $self->method eq 'GET' );
    # my $r = Apache2::Request->new( $self->request );
    my $r = Apache2::API::Request::Params->new( request => $self->request );
    # https://perl.apache.org/docs/1.0/guide/snippets.html#Reusing_Data_from_POST_request
    # my %params = $r->method eq 'POST' ? $r->content : $r->args;
    # Data are in pure utf8; not perl's internal, so it is up to us to decode them
    my( @params ) = $r->param;
    my( @uploads ) = $r->upload;
    my $upload_fields = {};
    # To make it easy to check if it exists
    if( scalar( @uploads ) )
    {
        @$upload_fields{ @uploads } = ( 1 ) x scalar( @uploads );
    }
    my $form = {};
    #my $io = IO::File->new( ">/tmp/form_data.txt" );
    #my $io2 = IO::File->new( ">/tmp/form_data_after_our_decoding.txt" );
    #my $raw = IO::File->new( ">/tmp/raw_form_data.txt" );
    #$io->binmode( ':utf8' );
    #$io2->binmode( ':utf8' );
    foreach my $k ( @params )
    {
        my( @values ) = $r->param( $k );
        #$raw->print( "$k => " );
        #$io->print( "$k => " );
        my $name = utf8::is_utf8( $k ) ? $k : Encode::decode_utf8( $k );
        #$io2->print( "$name => " );
        $form->{ $name } = scalar( @values ) > 1 ? \@values : $values[0];
        if( CORE::exists( $upload_fields->{ $name } ) )
        {
            my $up = $r->upload( $name );
            if( !$up )
            {
                CORE::warn( "Error: could not get the Apache2::API::Params::Upload object for this upload field \"$name\".\n" );
                next;
            }
            else
            {
                $form->{ $name } = $up;
            }
        }
        elsif( ref( $form->{ $name } ) )
        {
            #$raw->print( "[\n" );
            #$io->print( "[\n" );
            #$io2->print( "[\n" );
            for( my $i = 0; $i < scalar( @{$form->{ $name }} ); $i++ )
            {
                #$raw->print( "\t[$i]: ", $form->{ $name }->[ $i ], "\n" );
                #$io->print( "\t[$i]: ", $form->{ $name }->[ $i ], "\n" );
                $form->{ $name }->[ $i ] = utf8::is_utf8( $form->{ $name }->[ $i ] ) ? $form->{ $name }->[ $i ] : Encode::decode_utf8( $form->{ $name }->[ $i ] );
                #$io2->print( "\t[$i]: ", $form->{ $name }->[ $i ], "\n" );
            }
            #$raw->print( "];\n" );
            #$io->print( "];\n" );
            #$io2->print( "];\n" );
        }
        else
        {
            #$raw->print( $form->{ $name }, "\n" );
            #$io->print( $form->{ $name }, "\n" );
            $form->{ $name } = utf8::is_utf8( $form->{ $name } ) ? $form->{ $name } : Encode::decode_utf8( $form->{ $name } );
            #$io2->print( $form->{ $name }, "\n" );
        }
    }
    #$raw->close;
    #$io->close;
    #$io2->close;
    return( $form );
}

# NOTE: parse_date for compatibility
sub parse_date { return( shift->datetime->parse_date( @_ ) ); }

# example: /bin:/usr/bin:/usr/local/bin
sub path { return( shift->env( 'PATH', @_ ) ); }

sub path_info { return( shift->_try( 'request', 'path_info', @_ ) ); }

sub payload { return( shift->_set_get_hash( 'payload', @_ ) ); }

sub per_dir_config { return( shift->_try( 'rquest', 'per_dir_config' ) ); }

sub pnotes { return( shift->_try( 'request', 'pnotes', @_ ) ); }

sub pool { return( shift->_try( 'connection', 'pool' ) ); }

sub preferred_language
{
    my $self = shift( @_ );
    my $ok_langs = [];
    if( @_ )
    {
        return( $self->error( "I was expecting a list of supported languages as array reference, but instead I received this '", join( "', '", @_ ), "'." ) ) if( !$self->_is_array( $_[0] ) );

lib/Apache2/API/Request.pm  view on Meta::CPAN

        {
            $error = "No ip address or block was provided to evaluate current ip against";
        }
    };
    return( $self->error( $error ) ) if( defined( $error ) );
    if( $@ )
    {
        return( $self->error( "An error occurred while trying to create a APR::IpSubnet object with ip \"$ip\" and mask \"$mask\": $@" ) );
    }
    return( $ipsub->test( $self->remote_addr ) );
}

sub subprocess_env { return( shift->_try( 'request', 'subprocess_env' ) ); }

sub temp_dir { return( shift->_try( 'apr', 'temp_dir', @_ ) ); }

sub the_request { return( shift->_try( 'request', 'the_request' ) ); }

# NOTE: time2datetime for compatibility
sub time2datetime { return( shift->datetime->time2datetime( @_ ) ); }

# NOTE: time2str for compatibility
sub time2str { return( shift->datetime->time2str( @_ ) ); }

sub type
{
    my $self = shift( @_ );
    if( @_ )
    {
        # Something like text/html, text/plain or application/json, etc...
        $self->{type} = shift( @_ );
    }
    elsif( !CORE::length( $self->{type} ) )
    {
        # Content-Type: application/json; charset=utf-8
        my $ctype_raw = $self->content_type;
        if( defined( $ctype_raw ) )
        {
            my $ctype_def = Module::Generic::HeaderValue->new_from_header( $ctype_raw ) ||
                return( $self->pass_error( Module::Generic::HeaderValue->error ) );
            # Accept: application/json; version=1.0; charset=utf-8
            my $ctype = lc( $ctype_def->value->first // '' );
            $self->{type} = $ctype if( $ctype );
            my $enc = $ctype_def->param( 'charset' );
            $enc = lc( $enc ) if( defined( $enc ) );
            $self->charset( $enc );
        }
    }
    return( $self->{type} );
}

sub unparsed_uri
{
    my $self = shift( @_ );
    my $uri = $self->uri;
    my $unparseed_path = $self->request->unparsed_uri;
    my $unparsed_uri = URI->new( $uri->scheme . '://' . $uri->host_port . $unparseed_path );
    return( $unparsed_uri );
}

sub uploads
{
    my $self = shift( @_ );
    my $r = Apache2::API::Request::Params->new( $self->request );
    my( @uploads ) = $r->upload;
    my $objs = $self->new_array;
    foreach my $name ( @uploads )
    {
        my $up = $r->upload( $name );
        if( !$up )
        {
            CORE::warn( "Error: could not get the Apache2::API::Params::Upload object for this upload field \"$name\".\n" );
        }
        else
        {
            CORE::push( @$objs, $up );
        }
    }
    return( $objs );
}

#sub uri { return( URI->new( shift->request->uri( @_ ) ) ); }
# FYI, there is also the APR::URI module, but I could not see the value of it
# https://perl.apache.org/docs/2.0/api/APR/URI.html
sub uri
{
    my $self = shift( @_ );
    my $r = $self->request;
    # my $host = $r->get_server_name;
    my $host = $r->hostname;
    my $port = $r->get_server_port;
    my $proto = ( $port == 443 ) ? 'https' : 'http';
    my $path = $r->unparsed_uri;
    # The port is superfluous, and even annoying
    # return( URI->new( "${proto}://${host}:${port}${path}" ) );
    return( URI->new( "${proto}://${host}${path}" ) );
}

sub url_decode { return( shift->decode( @_ ) ); }

sub url_encode { return( shift->encode( @_ ) ); }

sub user { return( shift->_try( 'request', 'user' ) ); }

sub user_agent { return( shift->headers->{ 'User-Agent' } ); }

sub _find_bin
{
    my $self = shift( @_ );
    my $bin  = shift( @_ ) || return( '' );
    return( File::Which::which( $bin ) );
}

sub _headers
{
    my $self = shift( @_ );
    my $type = shift( @_ ) ||
        return( $self->error({
            message => "No header type was specified.",
            want => [qw( hash )],
        }) );
    # NOTE: different from the _headers method in Apache2::API::Response, which uses _request
    my $req = $self->request ||
        return( $self->error({
            message => "No Apache2::RequestRec found!",
            want => [qw( hash )],
        }) );
    my $code = $req->can( $type ) ||
        return( $self->error({
            message => "Header type '$type' is unsupported by Apache2::RequestRec",
            want => [qw( hash )],
        }) );

lib/Apache2/API/Request.pm  view on Meta::CPAN


    my $nbytes = $req->read( $buff, 1024 );
    my $notes = $req->redirect_error_notes;
    my $qs = $req->redirect_query_string;
    my $status = $req->redirect_status;
    my $url = $req->redirect_url;
    my $referrer = $req->referer;

    # APR::SockAddr object
    my $addr = $req->remote_addr;
    my $host = $req->remote_host;
    my $string = $req->remote_ip;
    my $port = $req->remote_port;

    $req->reply( Apache2::Const::FORBIDDEN => { message => "Get away" } );

    # Apache2::RequestRec
    my $r = $req->request;
    my $scheme = $req->request_scheme;
    # DateTime::Lite object
    my $dt = $req->request_time;
    my $uri = $req->request_uri;
    my $filename = $req->script_filename;
    my $name = $req->script_name;
    my $uri = $req->script_uri;
    # Apache2::ServerUtil object
    my $server = $req->server;
    my $addr = $req->server_addr;
    my $admin = $req->server_admin;
    my $hostname = $req->server_hostname;
    my $name = $req->server_name;
    my $port = $req->server_port;
    my $proto = $req->server_protocol;
    my $sig = $req->server_signature;
    my $software = $req->server_software;
    my $vers = $req->server_version;
    $req->set_basic_credentials( $user => $password );
    $req->set_handlers( $name => $code_ref );
    my $data = $req->slurp_filename;
    # Apache2::Connection object
    my $socket = $req->socket;
    my $status = $req->status;
    my $line = $req->status_line;

    my $dt = $req->str2datetime( $http_date_string );
    my $rc = $req->subnet_of( $ip, $mask );
    # APR::Table object
    my $env = subprocess_env;

    my $dir = $req->temp_dir;

    my $r = $req->the_request;
    my $dt = $req->time2datetime( $time );
    say $req->time2str( $seconds );

    # text/plain
    my $type = $req->type;
    my $raw = $req->unparsed_uri;

    # Apache2::API::Request::Params
    my $uploads = $req->uploads;
    my $uri = $req->uri;
    my $decoded = $req->url_decode( $url );
    my $encoded = $req->url_encode( $url );
    my $user = $req->user;
    my $agent = $req->user_agent;

=head1 VERSION

    v0.4.2

=head1 DESCRIPTION

The purpose of this module is to provide an easy access to various methods designed to process and manipulate incoming requests.

This is designed to work under modperl.

Normally, one would need to know which method to access across various Apache2 mod perl modules, which makes development more time consuming and even difficult, because of the scattered documentation and even sometime outdated.

This module alleviate this problem by providing all the necessary methods in one place. Also, at the contrary of L<Apache2> modules suit, all the methods here are die safe. When an error occurs, it will always return undef() and the error will be abl...

For its alter ego to manipulate outgoing HTTP response, use the L<Apache2::API::Response> module.

Throughout this documentation, we refer to C<$r> as the L<Apache request object|Apache2::RequestRec> and C<$req> as an object from this module.

=head1 CONSTRUCTORS

=head2 new

This takes an optional hash or hash reference of options and instantiate a new object.

It takes the following parameters:

=over 4

=item * C<checkonly>

If true, it will not perform the initialisation it would usually do under modperl.

=item * C<debug>

Optional. If set with a positive integer, this will activate verbose debugging message

=item * C<max_size>

Optional. This is the maximum size of the data that can be sent to us over HTTP. By default, there is no limit.

=item * C<request>

This is a required parameter to be sent with a value set to a L<Apache2::RequestRec> object

=back

=head1 METHODS

=head2 aborted

Tells whether the connection has been aborted or not, by calling L<Apache2::Connection/aborted>

=head2 accept

lib/Apache2/API/Request.pm  view on Meta::CPAN


=over 4

=item 1. the value of an Apache constant

This would be C<Apache2::Const::OK> if the password value is set (and assured a correct value in L</user>); otherwise it returns an error code, either C<Apache2::Const::HTTP_INTERNAL_SERVER_ERROR> if things are really confused, C<Apache2::Const::HTTP...

=item 2. the password as set in the headers (decoded)

=back

Note that if C<AuthType> is not set, L<Apache2::Access/get_basic_auth_pw> first sets it to C<Basic>.

=head2 basic_auth_pw

This is an alias for L</basic_auth_passwd>

=head2 basic_auth_pwd

This is an alias for L</basic_auth_passwd>

=head2 body

Returns an L<APR::Request::Param::Table|APR::Request::Param> object containing the C<POST> data parameters of the L<Apache2::Request> object.

    my $body = $req->body;
    my @body_names = $req->body;

If there is no request body, then this would return C<undef>. So, for example, if you do a C<POST> query without any content, this would return C<undef>

An optional name parameter can be passed to return the POST (or other similar query types) data parameter associated with the given name:

    my $foo_body = $req->body("foo");

In scalar context this method fetches the first matching body param.  In list context it returns all matching body params.

This is similar to the C<param> method. The main difference is that modifications to the scalar C<< $req->body() >> table affect the underlying C<apr_table_t> attribute in C<apreq_request_t>, so their impact will be noticed by all C<libapreq2> applic...

Contrary to perl hash, this uses L<APR::Table> and the order in the hash is preserved, so you could do:

    my @body_names = $req->body;
    my @body_names = %$body;

would yield the same thing.

This will throw an L<APR::Request::Error> object whenever L</body_status> returns a non-zero value.

Check L<Apache2::Request> and L<APR::Table> for more information.

=head2 body_status

    my $int = $req->body_status; # should return 0

Returns the final status code of the body parser.

=head2 brigade_limit

    my $int = $req->brigade_limit;
    $req->brigade_limit( $int );

Get or set the brigade_limit for the current parser. This limit determines how many bytes of a file upload that the parser may spool into main memory. Uploads exceeding this limit are written directly to disk.

See also L</temp_dir>

=head2 call

Provided with an Apache2 API method name, and optionally with some additional arguments, and this will call that Apache2 method and return its result.

This is designed to allow you to call arbitrary Apache2 method that, possibly, are not covered here.

For example:

    my $bitmask = $req->call( 'allow_override_opts' );

It returns whatever value this call returns.

=head2 charset

Returns the charset, if any, found in the HTTP request received and processed upon initialisation of this module object.

So for example, if the HTTP request C<Content-type> is

    Content-Type: application/json; charset=utf-8

Then, L</charset> would return C<utf-8>

See also L</type> to retrieve only the content type, i.e without other information such as charset.

See also L</client_api_version> which would contain the requested api version, if any.

See also L<charset> for the charset provided, if any. For example C<utf-8>

=head2 checkonly

This is also an object initialisation property.

If true, this will discard the normal processing of incoming HTTP request under modperl.

This is useful and intended when testing this module offline.

=head2 child_terminate

Terminate the current worker process as soon as the current request is over, by calling L<Apache2::RequestRec/child_terminate>

This is not supported in threaded MPMs.

See L<Apache2::RequestUtil> for more information.

=head2 client_api_version

Returns the client api version requested, if provided. This is set during the object initialisation phase.

An example header to require api version C<1.0> would be:

    Accept: application/json; version=1.0; charset=utf-8

In this case, this would return C<1.0>

=head2 close

This close the client connection, by calling L<Apache2::Connection/socket>, which returns a L<APR::Socket>

lib/Apache2/API/Request.pm  view on Meta::CPAN


=head2 content_type

Retrieves the value of the C<Content-type> header value. See L<Apache2::RequestRec> for more information.

For example:

    application/json; charset=utf-8

See also L</type> to retrieve only the content type, i.e without other information such as charset.

See also L</client_api_version> which would contain the requested api version, if any.

See also L<charset> for the charset provided, if any. For example C<utf-8>

=head2 cookie

Returns the current value for the given cookie name, which may be C<undef> if nothing is found.

This works by calling the L</cookies> method, which returns a L<cookie jar object|Cookie::Jar>.

=head2 cookies

Returns a L<Cookie::Jar> object acting as a jar with various methods to access, manipulate and create cookies.

=head2 data

This method reads the data sent by the client. It can be used as an accessor, and it will return a cached data, if any, or read the data from L<APR::Bucket>, or it can be used as a mutator to artificially set a payload.

Internally it uses L<Apache2::RequestUtil/pnotes> to cache the processed request body and stores it in C<REQUEST_BODY>, and set the shared property C<REQUEST_BODY_PROCESSED> to C<1>. Thus, the processed raw request body is always for other handlers w...

It takes an optional hash or hash reference of the following options:

=over 4

=item * C<data>

When provided, this will set the request body to the value provided.

=item * C<max_size>

The maximum size of the data that can be transmitted to us over HTTP. By default, there is no limit.

=back

Finally, if a charset is specified, this will also decode it from its encoded charset into perl internal utf8.

This is specifically designed for C<JSON> payload.

It returns a string of data upon success, or sets an L<error|Module::Generic/error> and return C<undef> or an empty list depending on the context.

You can also set a maximum size to read by setting the attribute C<PAYLOAD_MAX_SIZE> in Apache configuration file.

For example:

    <Directory /home/john/www>
        PerlOptions +GlobalRequest
        SetHandler modperl
        # package inheriting from Apache2::API
        PerlResponseHandler My::API
        # 2Mb upload limit
        PerlSetVar PAYLOAD_MAX_SIZE 2097152
    </Directory>

This is just an example and not a recommandation. Your mileage may vary.

=head2 datetime

Returns a new L<Apache2::API::DateTime> object, which is used to parse and format dates for HTTP.

See L<Apache2::API/parse_datetime> and L<Apache2::API/format_datetime>

=head2 decode

Given a url-encoded string, this returns the decoded string, by calling L<APR::Request/decode>

This uses L<APR::Request> XS method.

See also L<rfc3986|https://datatracker.ietf.org/doc/html/rfc3986>

=head2 discard_request_body

    my $rc = $req->discard_request_body;

In C<HTTP/1.1>, any method can have a body. However, most C<GET> handlers would not know what to do with a request body if they received one. This helper routine tests for and reads any message body in the request, simply discarding whatever it recei...

Returns C<Apache2::Const::OK> upon success.

    use Apache2::API;
    my $rc = $req->discard_request_body;
    return( $rc ) if( $rc != Apache2::Const::OK );

This method calls L<Apache2::RequestIO/discard_request_body>

=head2 dnt

Sets or gets the environment variable C<HTTP_DNT> using L<Apache2::RequestRec/subprocess_env>. See L</env> below for more on that.

This is an abbreviation for C<Do not track>

If available, typical value is a boolean such as C<0> or C<1>

=head2 document_root

Sets or retrieve the document root for this server.

If a value is provided, it sets the document root to a new value only for the duration of the current request.

See L<Apache2::RequestUtil> for more information.

=head2 document_uri

Get the value for the environment variable C<DOCUMENT_URI>.

=head2 encode

Given a string, this returns its url-encoded version

This uses L<APR::Request> XS method.

=head2 env

lib/Apache2/API/Request.pm  view on Meta::CPAN


=head2 no_cache

Add/remove cache control headers by calling L<Apache2::RequestUtil/no_cache>. A true value sets the C<no_cache> request record member to a true value and inserts:

     Pragma: no-cache
     Cache-control: no-cache

into the response headers, indicating that the data being returned is volatile and the client should not cache it.

A false value unsets the C<no_cache> request record member and the mentioned headers if they were previously set.

This method should be invoked before any response data has been sent out.

See L<Apache2::RequestUtil> for more information.

=head2 notes

Get or sets text notes for the duration of this request by calling L<Apache2::RequestUtil/pnotes>. These notes can be passed from one module to another (not only mod_perl, but modules in any other language).

If a new value was passed, returns the previous value.

The returned value is a L<APR::Table> object by calling L<Apache2::RequestUtil/notes>

=head2 output_filters

    my $output_filters = $req->connection->output_filters();
    my $prev_output_filters = $req->output_filters( $new_output_filters );

Set or get the first filter in a linked list of request level output filters by calling L</output_filters>. It returns a L<Apache2::Filter> object.

If a new output filters was passed, returns the previous value.

According to the L<Apache2::RequestRec> documentation:

For example instead of using C<< $req->print() >> to send the response body, one could send the data directly to the first output filter. The following function C<send_response_body()> does just that:

     use APR::Brigade ();
     use APR::Bucket ();
     use Apache2::Filter ();

     sub send_response_body 
     {
         my( $req, $data ) = @_;

         my $bb = APR::Brigade->new( $req->pool,
                                     $req->connection->bucket_alloc );

         my $b = APR::Bucket->new( $bb->bucket_alloc, $data );
         $bb->insert_tail( $b );
         $req->output_filters->fflush( $bb );
         $bb->destroy;
     }

In fact that's what C<< $req->read() >> does behind the scenes. But it also knows to parse HTTP headers passed together with the data and it also implements buffering, which the above function does not.

=head2 param

Provided a name, this returns its equivalent value, using L<Apache2::API::Request::Params/param>.

If C<$name> is an upload field, ie part of a multipart post data, it returns an L<Apache2::API::Request::Upload> object instead.

If a value is provided, this calls L<Apache2::API::Request::Param/param> providing it with the name ane value. This uses L<APR::Request::Param>.

=head2 params

Get the request parameters (using case-insensitive keys) by mimicing the OO interface of L<CGI::param>.

It can take as argument, only a key and it will then retrieve the corresponding value, or it can take a key and value pair to set them using L<Apache2::API::Request::Params/param>

If the value is an array, this will set multiple entry of the key for each value provided.

This uses Apache L<APR::Table> and works for both C<POST> and C<GET> methods.

If the methods received was a C<GET> method, this method returns the value of the L</query> method instead.

=head2 parse_date

Alias to L<Apache2::API::DateTime/parse_date>

=head2 path

Get the value for the environment variable C<PATH>

See also L</env>

=head2 path_info

    my $path_info      = $req->path_info();
    my $prev_path_info = $req->path_info( $path_info );

Get or set the C<PATH_INFO>, what is left in the path after the C<< URI --> filename >> translation, by calling L<Apache2::RequestRec/path_info>

Return a string as the current value.

=head2 payload

Returns the JSON data decoded into a perl structure. This is set at object initiation phase and calls the L</data> method to read the incoming data and decoded it into perl internal utf8.

=head2 per_dir_config

Get the dir config vector, by calling L<Apache2::RequestRec/per_dir_config>. Returns a L<Apache2::ConfVector> object.

For an in-depth discussion, refer to the Apache Server Configuration Customization in Perl chapter.

=head2 pnotes

Share Perl variables between Perl HTTP handlers, using L<Apache2::RequestUtil/pnotes>.

     # to share variables by value and not reference, $val should be a lexical.
     $old_val  = $req->pnotes( $key => $val );
     $val      = $req->pnotes( $key );
     $hash_ref = $req->pnotes();

Note: sharing variables really means it. The variable is not copied.  Only its reference count is incremented. If it is changed after being put in pnotes that change also affects the stored value. The following example illustrates the effect:

     my $v = 1;                   my $v = 1;
     $req->pnotes( 'v'=> $v );    $req->pnotes->{v} = $v;
     $v++;                        $v++;
     my $x = $req->pnotes('v');   my $x = $req->pnotes->{v};

lib/Apache2/API/Request.pm  view on Meta::CPAN


Alias to L<Apache2::API::DateTime/str2time>

=head2 subnet_of

Provided with an ip address (v4 or v6), and optionally a subnet mask, and this will return a boolean value indicating if the current connection ip address is part of the provided subnet.

The mask can be a string or a number of bits.

It uses L<APR::IpSubnet> and performs the test using the object from L<APR::SockAddr> as provided with L</remote_addr>

    my $ok = $req->subnet_of( '127.0.0.1' );
    my $ok = $req->subnet_of( '::1' );
    my $ok = $req->subnet_of( '127.0.0.1', '255.0.0.0' );
    my $ok = $req->subnet_of( '127.0.0.1', 15 );

    if( !$req->subnet_of( '127.0.0.1' ) )
    {
        print( "Sorry, only local connections allowed\n" );
    }

=head2 subprocess_env

Get or sets the L<Apache2::RequestRec> C<subprocess_env> table, or optionally set the value of a named entry.

From the L<Apache2::RequestRec> documentation:

When called in void context with no arguments, it populate C<%ENV> with special variables (e.g. C<$ENV{QUERY_STRING}>) like mod_cgi does.

When called in a non-void context with no arguments, it returns an C<APR::Table object>.

When the $key argument (string) is passed, it returns the corresponding value (if such exists, or C<undef>. The following two lines are equivalent:

     $val = $req->subprocess_env( $key );
     $val = $req->subprocess_env->get( $key );

When the $key and the $val arguments (strings) are passed, the value is set. The following two lines are equivalent:

     $req->subprocess_env( $key => $val );
     $req->subprocess_env->set( $key => $val );

The C<subprocess_env> C<table> is used by L<Apache2::SubProcess>, to pass environment variables to externally spawned processes. It is also used by various Apache modules, and you should use this table to pass the environment variables. For example i...

      $req->subprocess_env( MyLanguage => "de" );

you can then deploy C<mod_include> and write in C<.shtml> document:

      <!--#if expr="$MyLanguage = en" -->
      English
      <!--#elif expr="$MyLanguage = de" -->
      Deutsch
      <!--#else -->
      Sorry
      <!--#endif -->

=head2 temp_dir

    my $dir = $req->temp_dir;
    $req->temp_dir( $dir );

Get or set the spool directory for uploads which exceed the configured brigade_limit.

=head2 the_request

    my $request = $req->the_request();
    my $old_request = $req->uri( $new_request );

Get or set the first HTTP request header as a string by calling L<Apache2::RequestRec/the_request>. For example:

    GET /foo/bar/my_path_info?args=3 HTTP/1.0

=head2 time2datetime

Alias to L<Apache2::API::DateTime/time2datetime>

=head2 time2str

Alias to L<Apache2::API::DateTime/time2str>

=head2 type

Returns the content type of the request received. This value is set at object initiation phase.

So for example, if the HTTP request C<Content-type> is

    Content-Type: application/json; charset=utf-8

Then, L</type> would return C<application/json>

=head2 unparsed_uri

The URI without any parsing performed.

If for example the request was:

     GET /foo/bar/my_path_info?args=3 HTTP/1.0

C<< $req->uri >> returns:

     /foo/bar/my_path_info

whereas C<< $req->unparsed_uri >> returns:

     /foo/bar/my_path_info?args=3

=head2 uploads

Returns an L<array object|Module::Generic::Array> of L<Apache2::API::Request::Upload> objects.

=head2 uri

Returns a L<URI> object representing the full uri of the request.

This is different from the original L<Apache2::RequestRec> which only returns the path portion of the URI.

So, to get the path portion using our L</uri> method, one would simply do C<< $req->uri->path() >>

This L<URI> object is built using L<Apache2::RequestUtil/get_server_name> for the C<host>, L<Apache2::RequestUtil/get_server_port> for the port number, and the scheme is C<https> if the port is C<443>, otherwise C<http>. It is followed then by the pa...

=head2 url_decode

This is merely a convenient pointer to L</decode>

=head2 url_encode

This is merely a convenient pointer to L</encode>

=head2 user

Get the user name, if an authentication process was successful. Or set it, by calling L<Apache2::RequestRec/user>

For example, let's print the username passed by the client:

     my( $res, $sent_pw ) = $req->get_basic_auth_pw;
     return( $res ) if( $res != Apache2::Const::OK );
     print( "User: ", $req->user );

=head2 user_agent

Returns the user agent, ie the browser signature as provided in the request headers received under the HTTP header C<User-Agent>

=head2 _find_bin( string )

Given a binary, this will search for it in the path.

=head2 _try( object type, method name, @_ )

Given an object type, a method name and optional parameters, this attempts to call it.

Apache2 methods are designed to die upon error, whereas our model is based on returning C<undef> and setting an exception with L<Module::Generic::Exception>, because we believe that only the main program should be in control of the flow and decide wh...

=head1 AUTHOR

Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>

=head1 SEE ALSO

L<Apache2::Request>, L<Apache2::RequestRec>, L<Apache2::RequestUtil>

=head1 COPYRIGHT & LICENSE

Copyright (c) 2023 DEGUEST Pte. Ltd.

You can use, copy, modify and redistribute this package and associated
files under the same terms as Perl itself.



( run in 2.271 seconds using v1.01-cache-2.11-cpan-b16cb0d3907 )