CGI-Simple-1.113000755000765000120 011506110172 12543 5ustar00andyadmin000000000000CGI-Simple-1.113/Build.PL000444000765000120 70711506110167 14164 0ustar00andyadmin000000000000use strict; use warnings; use lib 'inc'; use Module::Build; use MyBuilder; my $builder = MyBuilder->new( module_name => 'CGI::Simple', sign => 1, license => 'perl', dist_author => 'Andy Armstrong ', dist_version_from => 'lib/CGI/Simple.pm', requires => { 'Test::More' => 0, 'IO::Scalar' => 0 }, add_to_cleanup => ['CGI-Simple-*'], ); $builder->create_build_script(); CGI-Simple-1.113/Changes000555000765000120 2301011506110167 14216 0ustar00andyadmin000000000000Revision history for Perl extension CGI::Simple. 0.01 Thu Nov 1 12:21:48 2001 - original version; created by h2xs 1.21 with options -X CGI::Simple 0.02 Fri Dec 21 2001 - added cgi_error() if upload called but CONTENT_TYPE not multipart/form-data - changed inernal storage names of globals by droping $ - added mod_perl notes re Selfloader and __DATA__ token - as per suggestions from Curtis Poe 0.03 Fri Apr 12 2002 - modifed test so skipping fork() test is noted as such - allow '0' as a valid param name - renamed concur.t to concur.test so that it does not rub by default - added speed tests comparing CGI.pm to CGI::Simple in the file cgi-simple_vs_cgi-pm.html in the root dir 0.04 Sat Apr 12 2002 - test bug on Solaris reported by robc@stamps.stortek.com and fixed 0.05 Wed Nov 6 2002 - nasty upload bug reported (with solution) by Brandon Black fixed. Perl would hang if upload terminated by browser before completion - also odity with IO::file fixed (Brandon Black once again) 0.06 Fri Nov 8 2002 - finally found someone with a solaris box to work out reason for unexpected test failures. Thanks to John D. Robinson and Jeroen Latour Details available at: http://www.perlmonks.org/index.pl?node_id=211401 - Removed another new bug relating to test scripts rather than core code thanks to the combined effors of Perlmonks tommyw, grinder, Jaap, vek, erasei, jlongino and strider_corinth 0.07 Sat Aug 2 2003 - i admit to abject slackness, but anyway finally allocated a few hours to apply a number of bug fixes which are (in no particular order) - mod_perl compliant, patched by Mathew Albright - still need to comment out use Selfloader and __DATA__ token - still thinking about other solutions to this - Blessed globs now possible in the constructor thanks to chromatic - Unicode error 0xfe | ($c >> 30) -> 0xfc | ($c >>30 ) fixed thanks to Thomas L. Shinnick - s/$value ||= 0/$value = defined $value ? $value : ''/ in raw_fetch() method in Cookie.pm to allow value 0. - Added missing $VERSION to Util.pm - Added P3P support as suggested by Marc Bauer (parallels CGI.pm) - updated header() and redirect() methods in Simple.pm 0.071 Sat Aug 2 2003 - Oops, changed $VERSION to 0.007 not 0.07 so have to change to 0.071 to upload again. ;-) - no significant changes since 0.07 (aka 0.007) ;-) 0.072 Tue Sept 9 2003 - Patched issue with large POSTs where data may not be on STDIN for single read call. Bug exists in CGI.pm as well. Thanks to Jason Luther - Added tests for slow post behaviour 0.075 Tue June 1 2004 - Meant to upload 0.73 and 0.074 but just never got around to it - Fixed upload hang bug in certain circumstances - Added upload_fieldnames() method by request - Added support for $fh = upload('field_name') but this has the issue of what to do if 'field_name' is duplicated. You can only ever get one fh from this method unlike the favoured approach using param() to get the filename(s) which will let you get to all the files. - José Micó deserves plaudits as does PodMaster. 0.076 - Went missing in action. 0.077 Tue 23 Nov 2004 - Bugfix patches. - José Micó supplied patch that relates to character set allowed in headers. TAB and high ascii chars are definitivelly allowed in headers, and not accepting them prevents the upload of files with filenames like "España.txt". - José Micó also notes that some versions of IE send extra boundaries in POSTed data before real ones. New patch should be fix this IE issue. - Lars Thegler supplied some patches. - head2/head3 pod changed to head1/head2 for the benefit of some older tools that exepect this. - Resolved issue with manpages not being installed on FREEBSD via Makefile hack - Steve Purkis supplied a patch for a serious POST_MAX bug. A small modification to control flow was used instead but this was a serious bug. If you are reading this you are probably upgrading which is good. 0.078 2007-01-09 - Maintenance release by Andy Armstrong - Rewrote tests to use Test::More - Implemented mod_perl 2 support 0.080 2007-03-30 - Fixed problem parsing query args containing '='. Thanks to Ewan Edwards for the patch. 0.081 2007-05-20 - Fix for sysread under mod_perl. Thanks to Joshua N Pritikin for the patch. 0.082 2007-05-22 - Added REST support. Thanks to Mike Barry for the patch. 0.83 2007-05-22 - Big version jump to move version past badly formatted version in Cookie, Util. 1.0 2007-05-24 - Another big version jump. I think we're about ready for 1.0. - Fixed skip count under Win32 in t/40.request.t [27257]. Thanks to ISHIGAKI for the patch. 1.1 2007-07-13 - Added support for Set-Cookie as per CGI.pm patch 15065. Thanks to Patrick M. Jordan for the suggestion. 1.1.1 2007-07-31 - Removed nasty global trap of __DIE__ in CGI::Standard. Thanks to Jeremy Morton for reporting it. 1.1.2 2007-07-31 - Fixed module names in POD for CGI::Simple::Cookie, CGI::Simple::Util [#27597]. Thanks to BRICAS for reporting it. 1.103 2007-07-31 - Version number chaos continues. One tends to forget that there is a strange universe in which 1.1 > 1.1.2. 1.104 2008-05-13 - Switched from sysread to read. Fixes #35844: sysread used in CGI::Simple blocks on re-directed STDIO reads. Thanks to Damjan Pelemis. 1.105 2008-05-16 - Fixed skip count in t/040.request.t. Fixes #35945. Thanks to snaury. 1.106 2008-09-14 - Added missing Apache2 modules. Refs #39146 and #38931. Thanks to RSAVAGE. - Applied BEROV's patch for UTF-8 form data handling. Refs #12481. Thanks to BEROV. 1.107 2009-03-07 - CGI::Simple::Cookie, fixed bug when cookie had both leading and trailing white space (RT#34314, Ron Savage and Mark Stosberg) - Accept a comma as well as semi-colon as a cookie separator. This is consistent with CGI.pm as well as RFC 2965, which states: "A server SHOULD also accept comma (,) as the separator between cookie- values for future compatibility." (Mark Stosberg) - Support cookies which have an equals sign in the value. Ported from CGI.pm (Mark Stosberg) - Support cookies in which one of multiple values is empty. Ported from CGI.pm (Mark Stosberg) - Fixed bug when calling unescapeHTML on HTML that wasn't properly escaped in the first place. Thanks to M-Uchino and Mark Stosberg. - Removed bogus dependency on version.pm. - Add heuristic to upload to handle the case where no boundary is specified in CONTENT_TYPE. See #14838. 1.108 2009-03-13 - Remove bogus references to Selfloader in documenation. No functional changes. 1.109 2009-04-16 - Added support for HttpOnly to CGI::Simple::Cookie. Thanks to Scott Thomson for the patch. 1.110 2009-05-24 - Added missing test to manifest / distro. - Added a test to ensure the manifest is consistent. - Migrated to git. 1.111 2009-05-28 - Implemented Michael Nachbaur fixes for multipart form data handling. 1.112 2009-05-31 - (thanks bingos) added missing IO::Scalar dependency. 1.113 2010-12-27 - (thanks to Yamada Masahiro) randomise multipart boundary string (security). - Numerous changes from Mark Stosberg: Port max-age support from CGI.pm, to improve compatibility and RFC-compliance Correct header comment in cookie.t It claims that is a simple copy/paste/modify from CGI.pm's test by the same name, but this has not been true for some time-- CGI::Simple added httponly tests that CGI.pm lacks, for example. Sync cookie references with CGI.pm: add reference to the newer RFC 2695 "Interface to browse cookies" looks like it was typo for "browser". HTTP is more precise. Fix awkward "CGI::Simple.pm" language. It looks like it probably originated from the CGI.pm form. "CGI::Simple" is used instead. Best Practice: eliminate indirect object notation from new(), parse() and fetch() calls Security: Fix handling of embedded malicious newlines in header values This is a direct port of the same security fix that Security: use a random MIME boundary by default in multipart_init(). This is a direct port of the same issue which was addressed in CGI.pm, preventing some kinds of potential header injection attacks. Port from CGI.pm: Fix multi-line header parsing. This fix is covered by the tests in t/header.t added in the previous patch. If you run those tests without this patch, you'll see how the headers would be malformed without this fix. Port CRLF injection prevention from CGI.pm Optimize Vars(): Don't build %hash if we aren't going to use it. Micro-optimization to Vars(): Don't call "tie" unless we need to. - Numerous changes from K. Berov: Added "+" to the mime character class. Added tests for C<$mime = $q->upload_info( $filename, 'mime' );> Fixed wrong match for mimetypes. Example: matched only 'application/vnd' instead of 'application/vnd.ms-excel'. Added "\." to the mime character class CGI-Simple-1.113/MANIFEST000444000765000120 74111506110167 14017 0ustar00andyadmin000000000000Build.PL Changes inc/MyBuilder.pm lib/CGI/Simple.pm lib/CGI/Simple/Cookie.pm lib/CGI/Simple/Standard.pm lib/CGI/Simple/Util.pm Makefile.PL MANIFEST META.yml README t/000.load.t t/020.cookie.t t/030.function.t t/040.request.t t/041.multipart.t t/050.simple.t t/060.slow_post.t t/070.standard.t t/080.util.t t/090.14838.t t/100.set-cookie.t t/110.bad-upload.t t/headers.t t/manifest.t t/pod-coverage.t t/pod.t t/test_file.txt t/upload_info.t SIGNATURE Added here by Module::Build CGI-Simple-1.113/META.yml000444000765000120 154611506110167 14163 0ustar00andyadmin000000000000--- abstract: 'A Simple totally OO CGI interface that is CGI.pm compliant' author: - 'Andy Armstrong ' configure_requires: Module::Build: 0.36 generated_by: 'Module::Build version 0.3607' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: CGI-Simple provides: CGI::Simple: file: lib/CGI/Simple.pm version: 1.113 CGI::Simple::Cookie: file: lib/CGI/Simple/Cookie.pm version: 1.113 CGI::Simple::Standard: file: lib/CGI/Simple/Standard.pm version: 1.113 CGI::Simple::Util: file: lib/CGI/Simple/Util.pm version: 1.113 requires: IO::Scalar: 0 Test::More: 0 resources: bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Simple license: http://dev.perl.org/licenses/ repository: 'git://github.com/AndyA/CGI--Simple.git (fetch)' version: 1.113 CGI-Simple-1.113/Makefile.PL000444000765000120 125711506110167 14663 0ustar00andyadmin000000000000use strict; use ExtUtils::MakeMaker; WriteMakefile( ( MM->can( 'signature_target' ) ? ( SIGN => 1 ) : () ), license( 'perl' ), NAME => 'CGI::Simple', AUTHOR => 'Andy Armstrong ', VERSION_FROM => 'lib/CGI/Simple.pm', ABSTRACT_FROM => 'lib/CGI/Simple.pm', PL_FILES => {}, PREREQ_PM => { 'Test::More' => 0, 'IO::Scalar' => 0 }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'CGI-Simple-*' }, ); sub license { my $lic = shift; local $^W = 0; # Silence warning about non-numeric version return unless $ExtUtils::MakeMaker::VERSION >= '6.31'; return ( LICENSE => $lic ); } CGI-Simple-1.113/README000444000765000120 76111506110167 13550 0ustar00andyadmin000000000000CGI-Simple version 1.113 INSTALLATION To install this module, run the following commands: perl Makefile.PL make make test make install Alternatively, to install with Module::Build, you can use the following commands: perl Build.PL ./Build ./Build test ./Build install DEPENDENCIES None. COPYRIGHT AND LICENCE Copyright (C) 2007, Andy Armstrong This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. CGI-Simple-1.113/SIGNATURE000644000765000120 470711506110172 14176 0ustar00andyadmin000000000000This file contains message digests of all files listed in MANIFEST, signed via the Module::Signature module, version 0.66. To verify the content in this distribution, first make sure you have Module::Signature installed, then type: % cpansign -v It will check each file's integrity, as well as the signature's validity. If "==> Signature verified OK! <==" is not displayed, the distribution may already have been compromised, and you should not run its Makefile.PL or Build.PL. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 SHA1 e045be9cdb8db55f717cf79e924203e1414225f6 Build.PL SHA1 1bd8b94957bfd7da59ef9807a45dc2d00e788ae4 Changes SHA1 154204e3d020e794e62de630951ee023f3475876 MANIFEST SHA1 ff5c3777e70cce70c0a57013ecb116f4eadc0655 META.yml SHA1 95715f0bf53b6848943258a57e2ba3b06054b7b0 Makefile.PL SHA1 10e555a784ad648e40b199025e99b781c1b5ecfa README SHA1 8c97bbeb63b586ee9c722313c2ad7858e32ff52c inc/MyBuilder.pm SHA1 3827cb87f45b8520fd33c90c0b6fc610477bdf1f lib/CGI/Simple.pm SHA1 60b212aa1d5c324d5fd4b428a0509d7e37feb261 lib/CGI/Simple/Cookie.pm SHA1 6fce2653ddeb7dad140b54e5917021c2ae22c1ab lib/CGI/Simple/Standard.pm SHA1 407108f939abc700a7a415fc8db9ab3860882108 lib/CGI/Simple/Util.pm SHA1 029a0c2274884058f99bc339fd5bb073348c2b77 t/000.load.t SHA1 e66def005f5f56804341bbf6208d09636ce90763 t/020.cookie.t SHA1 ca2ff8ba2f9a5f68c75e8d9527af38b042067148 t/030.function.t SHA1 e8fbebb9354bcd7755bfecaa564f44467265242c t/040.request.t SHA1 3678058ca2f62b397aab7560caeec6a06c4c1117 t/041.multipart.t SHA1 1cb680ef671319e86103b7927c9d93b31d3d253b t/050.simple.t SHA1 f77e6013c2de0bcf99c73c4af2ecc6220f7ec3a1 t/060.slow_post.t SHA1 25f3447480a95a844b6f893ca47106788f8c19d8 t/070.standard.t SHA1 4a7dade2334d9e4f5b223cbb6c9ebd49cb5cf4a3 t/080.util.t SHA1 432c00d3873dd6c70998f18149ba7517ffb56602 t/090.14838.t SHA1 73ac0f1550806696461a8c356aaff53393837aa7 t/100.set-cookie.t SHA1 b068924cea067616ced5d01ce376a157caf701a1 t/110.bad-upload.t SHA1 3091c116da74659dc33651d6bf2ce2f3c96eea12 t/headers.t SHA1 8c049d1fe65af78a4c01ebcc7d81f37b65b15738 t/manifest.t SHA1 d8b34ef82d206d0e64a5298a3d311ba2d87e29b9 t/pod-coverage.t SHA1 0190346d7072d458c8a10a45c19f86db641dcc48 t/pod.t SHA1 334f18ad2bd0fb8b8757d9607f9d0089bb88a1ee t/test_file.txt SHA1 a232e5fa0fdc30997bdb22104c4b6eea45978b25 t/upload_info.t -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (Darwin) iEYEARECAAYFAk0YkHcACgkQwoknRJZQnCGcegCgxnjuy2tsQhBxwSvKPPo7t6VC 6q8AoIAfVDbHZ2OcL1e8EXTTV+CgQig1 =seUy -----END PGP SIGNATURE----- CGI-Simple-1.113/inc000755000765000120 011506110167 13320 5ustar00andyadmin000000000000CGI-Simple-1.113/inc/MyBuilder.pm000444000765000120 353111506110167 15711 0ustar00andyadmin000000000000package MyBuilder; use base qw( Module::Build ); sub create_build_script { my ( $self, @args ) = @_; $self->_auto_mm; return $self->SUPER::create_build_script( @args ); } sub _auto_mm { my $self = shift; my $mm = $self->meta_merge; my @meta = qw( homepage bugtracker MailingList repository ); for my $meta ( @meta ) { next if exists $mm->{resources}{$meta}; my $auto = "_auto_$meta"; next unless $self->can( $auto ); my $av = $self->$auto(); $mm->{resources}{$meta} = $av if defined $av; } $self->meta_merge( $mm ); } sub _auto_repository { my $self = shift; if ( -d '.svn' ) { my $info = `svn info .`; return $1 if $info =~ /^URL:\s+(.+)$/m; } elsif ( -d '.git' ) { my $info = `git remote -v`; return unless $info =~ /^origin\s+(.+)$/m; my $url = $1; # Special case: patch up github URLs $url =~ s!^git\@github\.com:!git://github.com/!; return $url; } return; } sub _auto_bugtracker { 'http://rt.cpan.org/NoAuth/Bugs.html?Dist=' . shift->dist_name; } sub ACTION_testauthor { my $self = shift; $self->test_files( 'xt/author' ); $self->ACTION_test; } sub ACTION_critic { exec qw( perlcritic -1 -q -profile perlcriticrc lib/ ), glob 't/*.t'; } sub ACTION_tags { exec( qw( ctags -f tags --recurse --totals --exclude=blib --exclude=.svn --exclude='*~' --languages=Perl t/ lib/ ) ); } sub ACTION_tidy { my $self = shift; my @extra = qw( Build.PL ); my %found_files = map { %$_ } $self->find_pm_files, $self->_find_file_by_type( 'pm', 't' ), $self->_find_file_by_type( 'pm', 'inc' ), $self->_find_file_by_type( 't', 't' ); my @files = ( keys %found_files, map { $self->localize_file_path( $_ ) } @extra ); for my $file ( @files ) { system 'perltidy', '-b', $file; unlink "$file.bak" if $? == 0; } } 1; CGI-Simple-1.113/lib000755000765000120 011506110167 13315 5ustar00andyadmin000000000000CGI-Simple-1.113/lib/CGI000755000765000120 011506110167 13717 5ustar00andyadmin000000000000CGI-Simple-1.113/lib/CGI/Simple.pm000444000765000120 36704711506110167 15724 0ustar00andyadmin000000000000package CGI::Simple; require 5.004; # this module is both strict (and warnings) compliant, but they are only used # in testing as they add an unnecessary compile time overhead in production. use strict; use Carp; use vars qw( $VERSION $USE_CGI_PM_DEFAULTS $DISABLE_UPLOADS $POST_MAX $NO_UNDEF_PARAMS $USE_PARAM_SEMICOLONS $PARAM_UTF8 $HEADERS_ONCE $NPH $DEBUG $NO_NULL $FATAL *in ); $VERSION = "1.113"; # you can hard code the global variable settings here if you want. # warning - do not delete the unless defined $VAR part unless you # want to permanently remove the ability to change the variable. sub _initialize_globals { # set this to 1 to use CGI.pm default global settings $USE_CGI_PM_DEFAULTS = 0 unless defined $USE_CGI_PM_DEFAULTS; # see if user wants old CGI.pm defaults if ( $USE_CGI_PM_DEFAULTS ) { _use_cgi_pm_global_settings(); return; } # no file uploads by default, set to 0 to enable uploads $DISABLE_UPLOADS = 1 unless defined $DISABLE_UPLOADS; # use a post max of 100K, set to -1 for no limits $POST_MAX = 102_400 unless defined $POST_MAX; # set to 1 to not include undefined params parsed from query string $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS; # separate the name=value pairs with ; rather than & $USE_PARAM_SEMICOLONS = 0 unless defined $USE_PARAM_SEMICOLONS; # return everything as utf-8 $PARAM_UTF8 ||= 0; $PARAM_UTF8 and require Encode; # only print headers once $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE; # Set this to 1 to enable NPH scripts $NPH = 0 unless defined $NPH; # 0 => no debug, 1 => from @ARGV, 2 => from STDIN $DEBUG = 0 unless defined $DEBUG; # filter out null bytes in param - value pairs $NO_NULL = 1 unless defined $NO_NULL; # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak $FATAL = -1 unless defined $FATAL; } # I happen to disagree with many of the default global settings in CGI.pm # This sub is called if you set $CGI::Simple::USE_CGI_PM_GLOBALS = 1; or # invoke the '-default' pragma via a use CGI::Simple qw(-default); sub _use_cgi_pm_global_settings { $USE_CGI_PM_DEFAULTS = 1; $DISABLE_UPLOADS = 0 unless defined $DISABLE_UPLOADS; $POST_MAX = -1 unless defined $POST_MAX; $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS; $USE_PARAM_SEMICOLONS = 1 unless defined $USE_PARAM_SEMICOLONS; $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE; $NPH = 0 unless defined $NPH; $DEBUG = 1 unless defined $DEBUG; $NO_NULL = 0 unless defined $NO_NULL; $FATAL = -1 unless defined $FATAL; $PARAM_UTF8 = 0 unless defined $PARAM_UTF8; } # this is called by new, we will never directly reference the globals again sub _store_globals { my $self = shift; $self->{'.globals'}->{'DISABLE_UPLOADS'} = $DISABLE_UPLOADS; $self->{'.globals'}->{'POST_MAX'} = $POST_MAX; $self->{'.globals'}->{'NO_UNDEF_PARAMS'} = $NO_UNDEF_PARAMS; $self->{'.globals'}->{'USE_PARAM_SEMICOLONS'} = $USE_PARAM_SEMICOLONS; $self->{'.globals'}->{'HEADERS_ONCE'} = $HEADERS_ONCE; $self->{'.globals'}->{'NPH'} = $NPH; $self->{'.globals'}->{'DEBUG'} = $DEBUG; $self->{'.globals'}->{'NO_NULL'} = $NO_NULL; $self->{'.globals'}->{'FATAL'} = $FATAL; $self->{'.globals'}->{'USE_CGI_PM_DEFAULTS'} = $USE_CGI_PM_DEFAULTS; $self->{'.globals'}->{'PARAM_UTF8'} = $PARAM_UTF8; } # use the automatic calling of the import sub to set our pragmas. CGI.pm compat sub import { my ( $self, @args ) = @_; # arguments supplied in the 'use CGI::Simple [ARGS];' will now be in @args foreach ( @args ) { $USE_CGI_PM_DEFAULTS = 1, next if m/^-default/i; $DISABLE_UPLOADS = 1, next if m/^-no.?upload/i; $DISABLE_UPLOADS = 0, next if m/^-upload/i; $HEADERS_ONCE = 1, next if m/^-unique.?header/i; $NPH = 1, next if m/^-nph/i; $DEBUG = 0, next if m/^-no.?debug/i; $DEBUG = defined $1 ? $1 : 2, next if m/^-debug(\d)?/i; $USE_PARAM_SEMICOLONS = 1, next if m/^-newstyle.?url/i; $USE_PARAM_SEMICOLONS = 0, next if m/^-oldstyle.?url/i; $NO_UNDEF_PARAMS = 1, next if m/^-no.?undef.?param/i; $FATAL = 0, next if m/^-carp/i; $FATAL = 1, next if m/^-croak/i; croak "Pragma '$_' is not defined in CGI::Simple\n"; } } # used in CGI.pm .t files sub _reset_globals { _use_cgi_pm_global_settings(); } binmode STDIN; binmode STDOUT; # use correct encoding conversion to handle non ASCII char sets. # we import and install the complex routines only if we have to. BEGIN { sub url_decode { my ( $self, $decode ) = @_; return () unless defined $decode; $decode =~ tr/+/ /; $decode =~ s/%([a-fA-F0-9]{2})/ pack "C", hex $1 /eg; return $decode; } sub url_encode { my ( $self, $encode ) = @_; return () unless defined $encode; $encode =~ s/([^A-Za-z0-9\-_.!~*'() ])/ uc sprintf "%%%02x",ord $1 /eg; $encode =~ tr/ /+/; return $encode; } if ( "\t" ne "\011" ) { eval { require CGI::Simple::Util }; if ( $@ ) { croak "Your server is using not using ASCII, you must install CGI::Simple::Util, error: $@"; } # hack the symbol table and replace simple encode/decode subs *CGI::Simple::url_encode = sub { CGI::Simple::Util::escape( $_[1] ) }; *CGI::Simple::url_decode = sub { CGI::Simple::Util::unescape( $_[1] ) }; } } ################ The Guts ################ sub new { my ( $class, $init ) = @_; $class = ref( $class ) || $class; my $self = {}; bless $self, $class; if ( $self->_mod_perl ) { if ( $init ) { $self->{'.mod_perl_request'} = $init; undef $init; # otherwise _initialize takes the wrong path } $self->_initialize_mod_perl(); } $self->_initialize_globals; $self->_store_globals; $self->_initialize( $init ); return $self; } sub _mod_perl { return ( exists $ENV{MOD_PERL} or ( $ENV{GATEWAY_INTERFACE} and $ENV{GATEWAY_INTERFACE} =~ m{^CGI-Perl/} ) ); } # Return the global request object under mod_perl. If you use mod_perl 2 # and you don't set PerlOptions +GlobalRequest then the request must be # passed in to the new() method. sub _mod_perl_request { my $self = shift; my $mp = $self->{'.mod_perl'}; return unless $mp; my $req = $self->{'.mod_perl_request'}; return $req if $req; $self->{'.mod_perl_request'} = do { if ( $mp == 2 ) { Apache2::RequestUtil->request; } else { Apache->request; } }; } sub _initialize_mod_perl { my ( $self ) = @_; eval "require mod_perl"; if ( defined $mod_perl::VERSION ) { if ( $mod_perl::VERSION >= 2.00 ) { $self->{'.mod_perl'} = 2; require Apache2::RequestRec; require Apache2::RequestIO; require Apache2::RequestUtil; require Apache2::Response; require APR::Pool; my $r = $self->_mod_perl_request(); if ( defined $r ) { $r->subprocess_env unless exists $ENV{REQUEST_METHOD}; $r->pool->cleanup_register( \&CGI::Simple::_initialize_globals ); } } else { $self->{'.mod_perl'} = 1; require Apache; my $r = $self->_mod_perl_request(); if ( defined $r ) { $r->register_cleanup( \&CGI::Simple::_initialize_globals ); } } } } sub _initialize { my ( $self, $init ) = @_; if ( !defined $init ) { # initialize from QUERY_STRING, STDIN or @ARGV $self->_read_parse(); } elsif ( ( ref $init ) =~ m/HASH/i ) { # initialize from param hash for my $param ( keys %{$init} ) { $self->_add_param( $param, $init->{$param} ); } } # chromatic's blessed GLOB patch # elsif ( (ref $init) =~ m/GLOB/i ) { # initialize from a file elsif ( UNIVERSAL::isa( $init, 'GLOB' ) ) { # initialize from a file $self->_read_parse( $init ); } elsif ( ( ref $init ) eq 'CGI::Simple' ) { # initialize from a CGI::Simple object require Data::Dumper; # avoid problems with strict when Data::Dumper returns $VAR1 my $VAR1; my $clone = eval( Data::Dumper::Dumper( $init ) ); if ( $@ ) { $self->cgi_error( "Can't clone CGI::Simple object: $@" ); } else { $_[0] = $clone; } } else { $self->_parse_params( $init ); # initialize from a query string } } sub _internal_read($*\$;$) { my ( $self, $glob, $buffer, $len ) = @_; $len = 4096 if !defined $len; if ( $self->{'.mod_perl'} ) { my $r = $self->_mod_perl_request(); $r->read( $$buffer, $len ); } else { read( $glob, $$buffer, $len ); } } sub _read_parse { my $self = shift; my $handle = shift || \*STDIN; my $data = ''; my $type = $ENV{'CONTENT_TYPE'} || 'No CONTENT_TYPE received'; my $length = $ENV{'CONTENT_LENGTH'} || 0; my $method = $ENV{'REQUEST_METHOD'} || 'No REQUEST_METHOD received'; # first check POST_MAX Steve Purkis pointed out the previous bug if ( ( $method eq 'POST' or $method eq "PUT" ) and $self->{'.globals'}->{'POST_MAX'} != -1 and $length > $self->{'.globals'}->{'POST_MAX'} ) { $self->cgi_error( "413 Request entity too large: $length bytes on STDIN exceeds \$POST_MAX!" ); # silently discard data ??? better to just close the socket ??? while ( $length > 0 ) { last unless _internal_read( $self, $handle, my $buffer ); $length -= length( $buffer ); } return; } if ( $length and $type =~ m|^multipart/form-data|i ) { my $got_length = $self->_parse_multipart( $handle ); if ( $length != $got_length ) { $self->cgi_error( "500 Bad read on multipart/form-data! wanted $length, got $got_length" ); } return; } elsif ( $method eq 'POST' or $method eq 'PUT' ) { if ( $length ) { # we may not get all the data we want with a single read on large # POSTs as it may not be here yet! Credit Jason Luther for patch # CGI.pm < 2.99 suffers from same bug _internal_read( $self, $handle, $data, $length ); while ( length( $data ) < $length ) { last unless _internal_read( $self, $handle, my $buffer ); $data .= $buffer; } unless ( $length == length $data ) { $self->cgi_error( "500 Bad read on POST! wanted $length, got " . length( $data ) ); return; } if ( $type !~ m|^application/x-www-form-urlencoded| ) { $self->_add_param( $method . "DATA", $data ); } else { $self->_parse_params( $data ); } } } elsif ( $method eq 'GET' or $method eq 'HEAD' ) { $data = $self->{'.mod_perl'} ? $self->_mod_perl_request()->args() : $ENV{'QUERY_STRING'} || $ENV{'REDIRECT_QUERY_STRING'} || ''; $self->_parse_params( $data ); } else { unless ( $self->{'.globals'}->{'DEBUG'} and $data = $self->read_from_cmdline() ) { $self->cgi_error( "400 Unknown method $method" ); return; } unless ( $data ) { # I liked this reporting but CGI.pm does not behave like this so # out it goes...... # $self->cgi_error("400 No data received via method: $method, type: $type"); return; } $self->_parse_params( $data ); } } sub _parse_params { my ( $self, $data ) = @_; return () unless defined $data; unless ( $data =~ /[&=;]/ ) { $self->{'keywords'} = [ $self->_parse_keywordlist( $data ) ]; return; } my @pairs = split /[&;]/, $data; for my $pair ( @pairs ) { my ( $param, $value ) = split /=/, $pair, 2; next unless defined $param; $value = '' unless defined $value; $self->_add_param( $self->url_decode( $param ), $self->url_decode( $value ) ); } } sub _add_param { my ( $self, $param, $value, $overwrite ) = @_; return () unless defined $param and defined $value; $param =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'}; @{ $self->{$param} } = () if $overwrite; @{ $self->{$param} } = () unless exists $self->{$param}; my @values = ref $value ? @{$value} : ( $value ); for my $value ( @values ) { next if $value eq '' and $self->{'.globals'}->{'NO_UNDEF_PARAMS'}; $value =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'}; $value = Encode::decode( utf8 => $value ) if $self->{'.globals'}->{PARAM_UTF8}; push @{ $self->{$param} }, $value; unless ( $self->{'.fieldnames'}->{$param} ) { push @{ $self->{'.parameters'} }, $param; $self->{'.fieldnames'}->{$param}++; } } return scalar @values; # for compatibility with CGI.pm request.t } sub _parse_keywordlist { my ( $self, $data ) = @_; return () unless defined $data; $data = $self->url_decode( $data ); $data =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'}; my @keywords = split /\s+/, $data; return @keywords; } sub _massage_boundary { my ( $self, $boundary ) = @_; # BUG: IE 3.01 on the Macintosh uses just the boundary, # forgetting the -- $boundary = '--' . $boundary unless exists $ENV{'HTTP_USER_AGENT'} && $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+3\.0[12];\s*Mac/i; return quotemeta $boundary; } sub _parse_multipart { my $self = shift; my $handle = shift or die "NEED A HANDLE!?"; my ( $boundary ) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/; $boundary = $self->_massage_boundary( $boundary ) if $boundary; my $got_data = 0; my $data = ''; my $length = $ENV{'CONTENT_LENGTH'} || 0; my $CRLF = $self->crlf; READ: while ( $got_data < $length ) { last READ unless _internal_read( $self, $handle, my $buffer ); $data .= $buffer; $got_data += length $buffer; unless ( $boundary ) { # If we're going to guess the boundary we need a complete line. next READ unless $data =~ /^(.*)$CRLF/o; $boundary = $1; # Still no boundary? Give up... unless ( $boundary ) { $self->cgi_error( '400 No boundary supplied for multipart/form-data' ); return 0; } $boundary = $self->_massage_boundary( $boundary ); } BOUNDARY: while ( $data =~ m/^$boundary$CRLF/ ) { ## TAB and high ascii chars are definitivelly allowed in headers. ## Not accepting them in the following regex prevents the upload of ## files with filenames like "España.txt". # next READ unless $data =~ m/^([\040-\176$CRLF]+?$CRLF$CRLF)/o; next READ unless $data =~ m/^([\x20-\x7E\x80-\xFF\x09$CRLF]+?$CRLF$CRLF)/o; my $header = $1; ( my $unfold = $1 ) =~ s/$CRLF\s+/ /og; my ( $param ) = $unfold =~ m/form-data;\s+name="?([^\";]*)"?/; my ( $filename ) = $unfold =~ m/name="?\Q$param\E"?;\s+filename="?([^\"]*)"?/; if ( defined $filename ) { my ( $mime ) = $unfold =~ m/Content-Type:\s+([-\w\+\.\/]+)/io; $data =~ s/^\Q$header\E//; ( $got_data, $data, my $fh, my $size ) = $self->_save_tmpfile( $handle, $boundary, $filename, $got_data, $data ); $self->_add_param( $param, $filename ); $self->{'.upload_fields'}->{$param} = $filename; $self->{'.filehandles'}->{$filename} = $fh if $fh; $self->{'.tmpfiles'}->{$filename} = { 'size' => $size, 'mime' => $mime } if $size; next BOUNDARY; } next READ unless $data =~ s/^\Q$header\E(.*?)$CRLF(?=$boundary)//s; $self->_add_param( $param, $1 ); } unless ( $data =~ m/^$boundary/ ) { ## In a perfect world, $data should always begin with $boundary. ## But sometimes, IE5 prepends garbage boundaries into POST(ed) data. ## Then, $data does not start with $boundary and the previous block ## never gets executed. The following fix attempts to remove those ## extra boundaries from readed $data and restart boundary parsing. ## Note about performance: with well formed data, previous check is ## executed (generally) only once, when $data value is "$boundary--" ## at end of parsing. goto BOUNDARY if ( $data =~ s/.*?$CRLF(?=$boundary$CRLF)//s ); } } return $got_data; } sub _save_tmpfile { my ( $self, $handle, $boundary, $filename, $got_data, $data ) = @_; my $fh; my $CRLF = $self->crlf; my $length = $ENV{'CONTENT_LENGTH'} || 0; my $file_size = 0; if ( $self->{'.globals'}->{'DISABLE_UPLOADS'} ) { $self->cgi_error( "405 Not Allowed - File uploads are disabled" ); } elsif ( $filename ) { eval { require IO::File }; $self->cgi_error( "500 IO::File is not available $@" ) if $@; $fh = new_tmpfile IO::File; $self->cgi_error( "500 IO::File can't create new temp_file" ) unless $fh; } # read in data until closing boundary found. buffer to catch split boundary # we do this regardless of whether we save the file or not to read the file # data from STDIN. if either uploads are disabled or no file has been sent # $fh will be undef so only do file stuff if $fh is true using $fh && syntax $fh && binmode $fh; while ( $got_data < $length ) { my $buffer = $data; last unless _internal_read( $self, \*STDIN, $data ); # fixed hanging bug if browser terminates upload part way through # thanks to Brandon Black unless ( $data ) { $self->cgi_error( '400 Malformed multipart, no terminating boundary' ); undef $fh; return $got_data; } $got_data += length $data; if ( "$buffer$data" =~ m/$boundary/ ) { $data = $buffer . $data; last; } # we do not have partial boundary so print to file if valid $fh $fh && print $fh $buffer; $file_size += length $buffer; } $data =~ s/^(.*?)$CRLF(?=$boundary)//s; $fh && print $fh $1; # print remainder of file if valid $fh $file_size += length $1; return $got_data, $data, $fh, $file_size; } # Define the CRLF sequence. You can't use a simple "\r\n" because of system # specific 'features'. On EBCDIC systems "\t" ne "\011" as the don't use ASCII sub crlf { my ( $self, $CRLF ) = @_; $self->{'.crlf'} = $CRLF if $CRLF; # allow value to be set manually unless ( $self->{'.crlf'} ) { my $OS = $^O || do { require Config; $Config::Config{'osname'} }; $self->{'.crlf'} = ( $OS =~ m/VMS/i ) ? "\n" : ( "\t" ne "\011" ) ? "\r\n" : "\015\012"; } return $self->{'.crlf'}; } ################ The Core Methods ################ sub param { my ( $self, $param, @p ) = @_; unless ( defined $param ) { # return list of all params my @params = $self->{'.parameters'} ? @{ $self->{'.parameters'} } : (); return @params; } unless ( @p ) { # return values for $param return () unless exists $self->{$param}; return wantarray ? @{ $self->{$param} } : $self->{$param}->[0]; } if ( $param =~ m/^-name$/i and @p == 1 ) { return () unless exists $self->{ $p[0] }; return wantarray ? @{ $self->{ $p[0] } } : $self->{ $p[0] }->[0]; } # set values using -name=>'foo',-value=>'bar' syntax. # also allows for $q->param( 'foo', 'some', 'new', 'values' ) syntax ( $param, undef, @p ) = @p if $param =~ m/^-name$/i; # undef represents -value token $self->_add_param( $param, ( ref $p[0] eq 'ARRAY' ? $p[0] : [@p] ), 'overwrite' ); return wantarray ? @{ $self->{$param} } : $self->{$param}->[0]; } # a new method that provides access to a new internal routine. Useage: # $q->add_param( $param, $value, $overwrite ) # $param must be a plain scalar # $value may be either a scalar or an array ref # if $overwrite is a true value $param will be overwritten with new values. sub add_param { _add_param( @_ ); } sub param_fetch { my ( $self, $param, @p ) = @_; $param = ( defined $param and $param =~ m/^-name$/i ) ? $p[0] : $param; return undef unless defined $param; $self->_add_param( $param, [] ) unless exists $self->{$param}; return $self->{$param}; } # Return a parameter in the QUERY_STRING, regardless of whether a POST or GET sub url_param { my ( $self, $param ) = @_; return () unless $ENV{'QUERY_STRING'}; $self->{'.url_param'} = {}; bless $self->{'.url_param'}, 'CGI::Simple'; $self->{'.url_param'}->_parse_params( $ENV{'QUERY_STRING'} ); return $self->{'.url_param'}->param( $param ); } sub keywords { my ( $self, @values ) = @_; $self->{'keywords'} = ref $values[0] eq 'ARRAY' ? $values[0] : [@values] if @values; my @result = defined( $self->{'keywords'} ) ? @{ $self->{'keywords'} } : (); return @result; } sub Vars { my $self = shift; $self->{'.sep'} = shift || $self->{'.sep'} || "\0"; if ( wantarray ) { my %hash; for my $param ( $self->param ) { $hash{$param} = join $self->{'.sep'}, $self->param( $param ); } return %hash; } else { my %tied; tie %tied, "CGI::Simple", $self; return \%tied; } } sub TIEHASH { $_[1] ? $_[1] : new $_[0] } sub STORE { my ( $q, $p, $v ) = @_; $q->param( $p, split $q->{'.sep'}, $v ); } sub FETCH { my ( $q, $p ) = @_; ref $q->{$p} eq "ARRAY" ? join $q->{'.sep'}, @{ $q->{$p} } : $q->{$p}; } sub FIRSTKEY { my $a = scalar keys %{ $_[0] }; each %{ $_[0] } } sub NEXTKEY { each %{ $_[0] } } sub EXISTS { exists $_[0]->{ $_[1] } } sub DELETE { $_[0]->delete( $_[1] ) } sub CLEAR { %{ $_[0] } = () } sub append { my ( $self, $param, @p ) = @_; return () unless defined $param; # set values using $q->append(-name=>'foo',-value=>'bar') syntax # also allows for $q->append( 'foo', 'some', 'new', 'values' ) syntax ( $param, undef, @p ) = @p if $param =~ m/^-name$/i; # undef represents -value token $self->_add_param( $param, ( ( defined $p[0] and ref $p[0] ) ? $p[0] : [@p] ) ); return $self->param( $param ); } sub delete { my ( $self, $param ) = @_; return () unless defined $param; $param = $param =~ m/^-name$/i ? shift : $param; # allow delete(-name=>'foo') syntax return undef unless defined $self->{$param}; delete $self->{$param}; delete $self->{'.fieldnames'}->{$param}; $self->{'.parameters'} = [ grep { $_ ne $param } @{ $self->{'.parameters'} } ]; } sub Delete { CGI::Simple::delete( @_ ) } # for method style interface sub delete_all { my $self = shift; undef %{$self}; $self->_store_globals; } sub Delete_all { $_[0]->delete_all } # as used by CGI.pm sub upload { my ( $self, $filename, $writefile ) = @_; unless ( $filename ) { $self->cgi_error( "No filename submitted for upload to $writefile" ) if $writefile; return $self->{'.filehandles'} ? keys %{ $self->{'.filehandles'} } : (); } unless ( $ENV{'CONTENT_TYPE'} =~ m|^multipart/form-data|i ) { $self->cgi_error( 'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your
tag' ); return undef; } my $fh = $self->{'.filehandles'}->{$filename}; # allow use of upload fieldname to get filehandle # this has limitation that in the event of duplicate # upload field names there can only be one filehandle # which will point to the last upload file # access by filename does not suffer from this issue. $fh = $self->{'.filehandles'}->{ $self->{'.upload_fields'}->{$filename} } if !$fh and defined $self->{'.upload_fields'}->{$filename}; if ( $fh ) { seek $fh, 0, 0; # get ready for reading return $fh unless $writefile; my $buffer; unless ( open OUT, ">$writefile" ) { $self->cgi_error( "500 Can't write to $writefile: $!\n" ); return undef; } binmode OUT; binmode $fh; print OUT $buffer while read( $fh, $buffer, 4096 ); close OUT; $self->{'.filehandles'}->{$filename} = undef; undef $fh; return 1; } else { $self->cgi_error( "No filehandle for '$filename'. Are uploads enabled (\$DISABLE_UPLOADS = 0)? Is \$POST_MAX big enough?" ); return undef; } } sub upload_fieldnames { my ( $self ) = @_; return wantarray ? ( keys %{ $self->{'.upload_fields'} } ) : [ keys %{ $self->{'.upload_fields'} } ]; } # return the file size of an uploaded file sub upload_info { my ( $self, $filename, $info ) = @_; unless ( $ENV{'CONTENT_TYPE'} =~ m|^multipart/form-data|i ) { $self->cgi_error( 'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your tag' ); return undef; } return keys %{ $self->{'.tmpfiles'} } unless $filename; return $self->{'.tmpfiles'}->{$filename}->{'mime'} if $info =~ /mime/i; return $self->{'.tmpfiles'}->{$filename}->{'size'}; } sub uploadInfo { &upload_info } # alias for CGI.pm compatibility # return all params/values in object as a query string suitable for 'GET' sub query_string { my $self = shift; my @pairs; for my $param ( $self->param ) { for my $value ( $self->param( $param ) ) { next unless defined $value; push @pairs, $self->url_encode( $param ) . '=' . $self->url_encode( $value ); } } return join $self->{'.globals'}->{'USE_PARAM_SEMICOLONS'} ? ';' : '&', @pairs; } # new method that will add QUERY_STRING data to our CGI::Simple object # if the REQUEST_METHOD was 'POST' sub parse_query_string { my $self = shift; $self->_parse_params( $ENV{'QUERY_STRING'} ) if defined $ENV{'QUERY_STRING'} and $ENV{'REQUEST_METHOD'} eq 'POST'; } ################ Save and Restore params from file ############### sub _init_from_file { use Carp qw(confess); confess "INIT_FROM_FILE called, stupid fucker!"; my ( $self, $fh ) = @_; local $/ = "\n"; while ( my $pair = <$fh> ) { chomp $pair; return if $pair eq '='; $self->_parse_params( $pair ); } } sub save { my ( $self, $fh ) = @_; local ( $,, $\ ) = ( '', '' ); unless ( $fh and fileno $fh ) { $self->cgi_error( 'Invalid filehandle' ); return undef; } for my $param ( $self->param ) { for my $value ( $self->param( $param ) ) { ; print $fh $self->url_encode( $param ), '=', $self->url_encode( $value ), "\n"; } } print $fh "=\n"; } sub save_parameters { save( @_ ) } # CGI.pm alias for save ################ Miscellaneous Methods ################ sub parse_keywordlist { _parse_keywordlist( @_ ); } # CGI.pm compatibility sub escapeHTML { my ( $self, $escape, $newlinestoo ) = @_; require CGI::Simple::Util; $escape = CGI::Simple::Util::escapeHTML( $escape ); $escape =~ s/([\012\015])/'&#'.(ord $1).';'/eg if $newlinestoo; return $escape; } sub unescapeHTML { require CGI::Simple::Util; return CGI::Simple::Util::unescapeHTML( $_[1] ); } sub put { my $self = shift; $self->print( @_ ); } # send output to browser sub print { shift; CORE::print( @_ ); } # print to standard output (for overriding in mod_perl) ################# Cookie Methods ################ sub cookie { my ( $self, @params ) = @_; require CGI::Simple::Cookie; require CGI::Simple::Util; my ( $name, $value, $path, $domain, $secure, $expires, $httponly ) = CGI::Simple::Util::rearrange( [ 'NAME', [ 'VALUE', 'VALUES' ], 'PATH', 'DOMAIN', 'SECURE', 'EXPIRES', 'HTTPONLY' ], @params ); # retrieve the value of the cookie, if no value is supplied unless ( defined( $value ) ) { $self->{'.cookies'} = CGI::Simple::Cookie->fetch unless $self->{'.cookies'}; return () unless $self->{'.cookies'}; # if no name is supplied, then retrieve the names of all our cookies. return keys %{ $self->{'.cookies'} } unless $name; # return the value of the cookie return exists $self->{'.cookies'}->{$name} ? $self->{'.cookies'}->{$name}->value : (); } # If we get here, we're creating a new cookie return undef unless $name; # this is an error @params = (); push @params, '-name' => $name; push @params, '-value' => $value; push @params, '-domain' => $domain if $domain; push @params, '-path' => $path if $path; push @params, '-expires' => $expires if $expires; push @params, '-secure' => $secure if $secure; push @params, '-httponly' => $httponly if $httponly; return CGI::Simple::Cookie->new( @params ); } sub raw_cookie { my ( $self, $key ) = @_; if ( defined $key ) { unless ( $self->{'.raw_cookies'} ) { require CGI::Simple::Cookie; $self->{'.raw_cookies'} = CGI::Simple::Cookie->raw_fetch; } return $self->{'.raw_cookies'}->{$key} || (); } return $ENV{'HTTP_COOKIE'} || $ENV{'COOKIE'} || ''; } ################# Header Methods ################ sub header { my ( $self, @params ) = @_; require CGI::Simple::Util; my @header; return undef if $self->{'.header_printed'}++ and $self->{'.globals'}->{'HEADERS_ONCE'}; my ( $type, $status, $cookie, $target, $expires, $nph, $charset, $attachment, $p3p, @other ) = CGI::Simple::Util::rearrange( [ [ 'TYPE', 'CONTENT_TYPE', 'CONTENT-TYPE' ], 'STATUS', [ 'COOKIE', 'COOKIES', 'SET-COOKIE' ], 'TARGET', 'EXPIRES', 'NPH', 'CHARSET', 'ATTACHMENT', 'P3P' ], @params ); my $CRLF = $self->crlf; # CR escaping for values, per RFC 822 for my $header ( $type, $status, $cookie, $target, $expires, $nph, $charset, $attachment, $p3p, @other ) { if ( defined $header ) { # From RFC 822: # Unfolding is accomplished by regarding CRLF immediately # followed by a LWSP-char as equivalent to the LWSP-char. $header =~ s/$CRLF(\s)/$1/g; # All other uses of newlines are invalid input. if ( $header =~ m/$CRLF/ ) { # shorten very long values in the diagnostic $header = substr( $header, 0, 72 ) . '...' if ( length $header > 72 ); die "Invalid header value contains a newline not followed by whitespace: $header"; } } } $nph ||= $self->{'.globals'}->{'NPH'}; $charset = $self->charset( $charset ) ; # get charset (and set new charset if supplied) # rearrange() was designed for the HTML portion, so we need to fix it up a little. for ( @other ) { # Don't use \s because of perl bug 21951 next unless my ( $header, $value ) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/s; ( $_ = $header ) =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e; } $type ||= 'text/html' unless defined $type; $type .= "; charset=$charset" if $type and $type =~ m!^text/! and $type !~ /\bcharset\b/; my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0'; push @header, $protocol . ' ' . ( $status || '200 OK' ) if $nph; push @header, "Server: " . server_software() if $nph; push @header, "Status: $status" if $status; push @header, "Window-Target: $target" if $target; if ( $p3p ) { $p3p = join ' ', @$p3p if ref( $p3p ) eq 'ARRAY'; push( @header, qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p") ); } # push all the cookies -- there may be several if ( $cookie ) { my @cookie = ref $cookie eq 'ARRAY' ? @{$cookie} : $cookie; for my $cookie ( @cookie ) { my $cs = ref $cookie eq 'CGI::Simple::Cookie' ? $cookie->as_string : $cookie; push @header, "Set-Cookie: $cs" if $cs; } } # if the user indicates an expiration time, then we need both an Expires # and a Date header (so that the browser is using OUR clock) $expires = 'now' if $self->no_cache; # encourage no caching via expires now push @header, "Expires: " . CGI::Simple::Util::expires( $expires, 'http' ) if $expires; push @header, "Date: " . CGI::Simple::Util::expires( 0, 'http' ) if defined $expires || $cookie || $nph; push @header, "Pragma: no-cache" if $self->cache or $self->no_cache; push @header, "Content-Disposition: attachment; filename=\"$attachment\"" if $attachment; push @header, @other; push @header, "Content-Type: $type" if $type; my $header = join $CRLF, @header; $header .= $CRLF . $CRLF; # add the statutory two CRLFs if ( $self->{'.mod_perl'} and not $nph ) { my $r = $self->_mod_perl_request(); $r->send_cgi_header( $header ); return ''; } return $header; } # Control whether header() will produce the no-cache Pragma directive. sub cache { my ( $self, $value ) = @_; $self->{'.cache'} = $value if defined $value; return $self->{'.cache'}; } # Control whether header() will produce expires now + the no-cache Pragma. sub no_cache { my ( $self, $value ) = @_; $self->{'.no_cache'} = $value if defined $value; return $self->{'.no_cache'}; } sub redirect { my ( $self, @params ) = @_; require CGI::Simple::Util; my ( $url, $target, $cookie, $nph, @other ) = CGI::Simple::Util::rearrange( [ [ 'LOCATION', 'URI', 'URL' ], 'TARGET', [ 'COOKIE', 'COOKIES' ], 'NPH' ], @params ); $url ||= $self->self_url; my @o; for ( @other ) { tr/\"//d; push @o, split "=", $_, 2; } unshift @o, '-Status' => '302 Moved', '-Location' => $url, '-nph' => $nph; unshift @o, '-Target' => $target if $target; unshift @o, '-Cookie' => $cookie if $cookie; unshift @o, '-Type' => ''; my @unescaped; unshift( @unescaped, '-Cookie' => $cookie ) if $cookie; return $self->header( ( map { $self->unescapeHTML( $_ ) } @o ), @unescaped ); } ################# Server Push Methods ################# # Return a Content-Type: style header for server-push # This has to be NPH, and it is advisable to set $| = 1 # Credit to Ed Jordan and # Andrew Benham for this section sub multipart_init { my ( $self, @p ) = @_; use CGI::Simple::Util qw(rearrange); my ( $boundary, @other ) = rearrange( ['BOUNDARY'], @p ); if ( !$boundary ) { $boundary = '------- =_'; my @chrs = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' ); for ( 1 .. 17 ) { $boundary .= $chrs[ rand( scalar @chrs ) ]; } } my $CRLF = $self->crlf; # get CRLF sequence my $warning = "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY."; $self->{'.separator'} = "$CRLF--$boundary$CRLF"; $self->{'.final_separator'} = "$CRLF--$boundary--$CRLF$warning$CRLF"; my $type = 'multipart/x-mixed-replace;boundary="' . $boundary . '"'; return $self->header( -nph => 1, -type => $type, map { split "=", $_, 2 } @other ) . $warning . $self->multipart_end; } sub multipart_start { my ( $self, @p ) = @_; use CGI::Simple::Util qw(rearrange); my ( $type, @other ) = rearrange( ['TYPE'], @p ); foreach ( @other ) { # fix return from rearange next unless my ( $header, $value ) = /([^\s=]+)=\"?(.+?)\"?$/; $_ = ucfirst( lc $header ) . ': ' . unescapeHTML( 1, $value ); } $type = $type || 'text/html'; my @header = ( "Content-Type: $type" ); push @header, @other; my $CRLF = $self->crlf; # get CRLF sequence return ( join $CRLF, @header ) . $CRLF . $CRLF; } sub multipart_end { return $_[0]->{'.separator'} } sub multipart_final { return $_[0]->{'.final_separator'} } ################# Debugging Methods ################ sub read_from_cmdline { my @words; if ( $_[0]->{'.globals'}->{'DEBUG'} == 1 and @ARGV ) { @words = @ARGV; } elsif ( $_[0]->{'.globals'}->{'DEBUG'} == 2 ) { require "shellwords.pl"; print "(offline mode: enter name=value pairs on standard input)\n"; chomp( my @lines = ); @words = &shellwords( join " ", @lines ); } else { return ''; } @words = map { s/\\=/%3D/g; s/\\&/%26/g; $_ } @words; return "@words" =~ m/=/ ? join '&', @words : join '+', @words; } sub Dump { require Data::Dumper; # short and sweet way of doing it ( my $dump = Data::Dumper::Dumper( @_ ) ) =~ tr/\000/0/; # remove null bytes cgi-lib.pl return '
' . escapeHTML( 1, $dump ) . '
'; } sub as_string { Dump( @_ ) } # CGI.pm alias for Dump() sub cgi_error { my ( $self, $err ) = @_; if ( $err ) { $self->{'.cgi_error'} = $err; $self->{'.globals'}->{'FATAL'} == 1 ? croak $err : $self->{'.globals'}->{'FATAL'} == 0 ? carp $err : return $err; } return $self->{'.cgi_error'}; } ################# cgi-lib.pl Compatibility Methods ################# # Lightly GOLFED but the original functionality remains. You can call # them using either: # $q->MethodName or CGI::Simple::MethodName sub _shift_if_ref { shift if ref $_[0] eq 'CGI::Simple' } sub ReadParse { my $q = &_shift_if_ref || new CGI::Simple; my $pkg = caller(); no strict 'refs'; *in = @_ ? $_[0] : *{"${pkg}::in"}; # set *in to passed glob or export *in %in = $q->Vars; $in{'CGI'} = $q; return scalar %in; } sub SplitParam { &_shift_if_ref; defined $_[0] && ( wantarray ? split "\0", $_[0] : ( split "\0", $_[0] )[0] ); } sub MethGet { request_method() eq 'GET' } sub MethPost { request_method() eq 'POST' } sub MyBaseUrl { local $^W = 0; 'http://' . server_name() . ( server_port() != 80 ? ':' . server_port() : '' ) . script_name(); } sub MyURL { MyBaseUrl() } sub MyFullUrl { local $^W = 0; MyBaseUrl() . $ENV{'PATH_INFO'} . ( $ENV{'QUERY_STRING'} ? "?$ENV{'QUERY_STRING'}" : '' ); } sub PrintHeader { ref $_[0] ? $_[0]->header() : "Content-Type: text/html\n\n"; } sub HtmlTop { &_shift_if_ref; "\n\n$_[0]\n\n\n

$_[0]

\n"; } sub HtmlBot { "\n\n" } sub PrintVariables { &_shift_if_ref; &Dump } sub PrintEnv { &Dump( \%ENV ) } sub CgiDie { CgiError( @_ ); die @_ } sub CgiError { &_shift_if_ref; @_ = @_ ? @_ : ( "Error: script " . MyFullUrl() . " encountered fatal error\n" ); print PrintHeader(), HtmlTop( shift ), ( map { "

$_

\n" } @_ ), HtmlBot(); } ################ Accessor Methods ################ sub version { $VERSION } sub nph { $_[0]->{'.globals'}->{'NPH'} = $_[1] if defined $_[1]; return $_[0]->{'.globals'}->{'NPH'}; } sub all_parameters { $_[0]->param } sub charset { require CGI::Simple::Util; $CGI::Simple::Util::UTIL->charset( $_[1] ); } sub globals { my ( $self, $global, $value ) = @_; return keys %{ $self->{'.globals'} } unless $global; $self->{'.globals'}->{$global} = $value if defined $value; return $self->{'.globals'}->{$global}; } sub auth_type { $ENV{'AUTH_TYPE'} } sub content_length { $ENV{'CONTENT_LENGTH'} } sub content_type { $ENV{'CONTENT_TYPE'} } sub document_root { $ENV{'DOCUMENT_ROOT'} } sub gateway_interface { $ENV{'GATEWAY_INTERFACE'} } sub path_translated { $ENV{'PATH_TRANSLATED'} } sub referer { $ENV{'HTTP_REFERER'} } sub remote_addr { $ENV{'REMOTE_ADDR'} || '127.0.0.1' } sub remote_host { $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'} || 'localhost'; } sub remote_ident { $ENV{'REMOTE_IDENT'} } sub remote_user { $ENV{'REMOTE_USER'} } sub request_method { $ENV{'REQUEST_METHOD'} } sub script_name { $ENV{'SCRIPT_NAME'} || $0 || '' } sub server_name { $ENV{'SERVER_NAME'} || 'localhost' } sub server_port { $ENV{'SERVER_PORT'} || 80 } sub server_protocol { $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0' } sub server_software { $ENV{'SERVER_SOFTWARE'} || 'cmdline' } sub user_name { $ENV{'HTTP_FROM'} || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'}; } sub user_agent { my ( $self, $match ) = @_; return $match ? $ENV{'HTTP_USER_AGENT'} =~ /\Q$match\E/i : $ENV{'HTTP_USER_AGENT'}; } sub virtual_host { my $vh = $ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'}; $vh =~ s/:\d+$//; # get rid of port number return $vh; } sub path_info { my ( $self, $info ) = @_; if ( defined $info ) { $info = "/$info" if $info !~ m|^/|; $self->{'.path_info'} = $info; } elsif ( !defined( $self->{'.path_info'} ) ) { $self->{'.path_info'} = defined( $ENV{'PATH_INFO'} ) ? $ENV{'PATH_INFO'} : ''; # hack to fix broken path info in IIS source CGI.pm $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if defined( $ENV{'SERVER_SOFTWARE'} ) && $ENV{'SERVER_SOFTWARE'} =~ /IIS/; } return $self->{'.path_info'}; } sub accept { my ( $self, $search ) = @_; my %prefs; for my $accept ( split ',', $ENV{'HTTP_ACCEPT'} ) { ( my $pref ) = $accept =~ m|q=([\d\.]+)|; ( my $type ) = $accept =~ m|(\S+/[^;]+)|; next unless $type; $prefs{$type} = $pref || 1; } return keys %prefs unless $search; return $prefs{$search} if $prefs{$search}; # Didn't get it, so try pattern matching. for my $pref ( keys %prefs ) { next unless $pref =~ m/\*/; # not a pattern match ( my $pat = $pref ) =~ s/([^\w*])/\\$1/g; # escape meta characters $pat =~ s/\*/.*/g; # turn it into a pattern return $prefs{$pref} if $search =~ /$pat/; } } sub Accept { my $self = shift; $self->accept( @_ ) } sub http { my ( $self, $parameter ) = @_; if ( defined $parameter ) { ( $parameter = uc $parameter ) =~ tr/-/_/; return $ENV{$parameter} if $parameter =~ m/^HTTP/; return $ENV{"HTTP_$parameter"} if $parameter; } return grep { /^HTTP/ } keys %ENV; } sub https { my ( $self, $parameter ) = @_; return $ENV{'HTTPS'} unless $parameter; ( $parameter = uc $parameter ) =~ tr/-/_/; return $ENV{$parameter} if $parameter =~ /^HTTPS/; return $ENV{"HTTPS_$parameter"}; } sub protocol { local ( $^W ) = 0; my $self = shift; return 'https' if uc $ENV{'HTTPS'} eq 'ON'; return 'https' if $self->server_port == 443; my ( $protocol, $version ) = split '/', $self->server_protocol; return lc $protocol; } sub url { my ( $self, @p ) = @_; use CGI::Simple::Util 'rearrange'; my ( $relative, $absolute, $full, $path_info, $query, $base ) = rearrange( [ 'RELATIVE', 'ABSOLUTE', 'FULL', [ 'PATH', 'PATH_INFO' ], [ 'QUERY', 'QUERY_STRING' ], 'BASE' ], @p ); my $url; $full++ if $base || !( $relative || $absolute ); my $path = $self->path_info; my $script_name = $self->script_name; if ( $full ) { my $protocol = $self->protocol(); $url = "$protocol://"; my $vh = $self->http( 'host' ); if ( $vh ) { $url .= $vh; } else { $url .= server_name(); my $port = $self->server_port; $url .= ":" . $port unless ( lc( $protocol ) eq 'http' && $port == 80 ) or ( lc( $protocol ) eq 'https' && $port == 443 ); } return $url if $base; $url .= $script_name; } elsif ( $relative ) { ( $url ) = $script_name =~ m#([^/]+)$#; } elsif ( $absolute ) { $url = $script_name; } $url .= $path if $path_info and defined $path; $url .= "?" . $self->query_string if $query and $self->query_string; $url = '' unless defined $url; $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/uc sprintf("%%%02x",ord($1))/eg; return $url; } sub self_url { my ( $self, @params ) = @_; return $self->url( '-path_info' => 1, '-query' => 1, '-full' => 1, @params ); } sub state { self_url( @_ ) } # CGI.pm synonym routine 1; =head1 NAME CGI::Simple - A Simple totally OO CGI interface that is CGI.pm compliant =head1 VERSION This document describes CGI::Simple version 1.113. =head1 SYNOPSIS use CGI::Simple; $CGI::Simple::POST_MAX = 1024; # max upload via post default 100kB $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads $q = new CGI::Simple; $q = new CGI::Simple( { 'foo'=>'1', 'bar'=>[2,3,4] } ); $q = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' ); $q = new CGI::Simple( \*FILEHANDLE ); $q->save( \*FILEHANDLE ); # save current object to a file as used by new @params = $q->param; # return all param names as a list $value = $q->param('foo'); # return the first value supplied for 'foo' @values = $q->param('foo'); # return all values supplied for foo %fields = $q->Vars; # returns untied key value pair hash $hash_ref = $q->Vars; # or as a hash ref %fields = $q->Vars("|"); # packs multiple values with "|" rather than "\0"; @keywords = $q->keywords; # return all keywords as a list $q->param( 'foo', 'some', 'new', 'values' ); # set new 'foo' values $q->param( -name=>'foo', -value=>'bar' ); $q->param( -name=>'foo', -value=>['bar','baz'] ); $q->param( 'foo', 'some', 'new', 'values' ); # append values to 'foo' $q->append( -name=>'foo', -value=>'bar' ); $q->append( -name=>'foo', -value=>['some', 'new', 'values'] ); $q->delete('foo'); # delete param 'foo' and all its values $q->delete_all; # delete everything $files = $q->upload() # number of files uploaded @files = $q->upload(); # names of all uploaded files $filename = $q->param('upload_file') # filename of uploaded file $mime = $q->upload_info($filename,'mime'); # MIME type of uploaded file $size = $q->upload_info($filename,'size'); # size of uploaded file my $fh = $q->upload($filename); # get filehandle to read from while ( read( $fh, $buffer, 1024 ) ) { ... } # short and sweet upload $ok = $q->upload( $q->param('upload_file'), '/path/to/write/file.name' ); print "Uploaded ".$q->param('upload_file')." and wrote it OK!" if $ok; $decoded = $q->url_decode($encoded); $encoded = $q->url_encode($unencoded); $escaped = $q->escapeHTML('<>"&'); $unescaped = $q->unescapeHTML('<>"&'); $qs = $q->query_string; # get all data in $q as a query string OK for GET $q->no_cache(1); # set Pragma: no-cache + expires print $q->header(); # print a simple header # get a complex header $header = $q->header( -type => 'image/gif' -nph => 1, -status => '402 Payment required', -expires =>'+24h', -cookie => $cookie, -charset => 'utf-7', -attachment => 'foo.gif', -Cost => '$2.00' ); # a p3p header (OK for redirect use as well) $header = $q->header( -p3p => 'policyref="http://somesite.com/P3P/PolicyReferences.xml' ); @cookies = $q->cookie(); # get names of all available cookies $value = $q->cookie('foo') # get first value of cookie 'foo' @value = $q->cookie('foo') # get all values of cookie 'foo' # get a cookie formatted for header() method $cookie = $q->cookie( -name => 'Password', -values => ['superuser','god','my dog woofie'], -expires => '+3d', -domain => '.nowhere.com', -path => '/cgi-bin/database', -secure => 1 ); print $q->header( -cookie=>$cookie ); # set cookie print $q->redirect('http://go.away.now'); # print a redirect header dienice( $q->cgi_error ) if $q->cgi_error; =head1 DESCRIPTION CGI::Simple provides a relatively lightweight drop in replacement for CGI.pm. It shares an identical OO interface to CGI.pm for parameter parsing, file upload, cookie handling and header generation. This module is entirely object oriented, however a complete functional interface is available by using the CGI::Simple::Standard module. Essentially everything in CGI.pm that relates to the CGI (not HTML) side of things is available. There are even a few new methods and additions to old ones! If you are interested in what has gone on under the hood see the Compatibility with CGI.pm section at the end. In practical testing this module loads and runs about twice as fast as CGI.pm depending on the precise task. =head1 CALLING CGI::Simple ROUTINES USING THE OBJECT INTERFACE Here is a very brief rundown on how you use the interface. Full details follow. =head2 First you need to initialize an object Before you can call a CGI::Simple method you must create a CGI::Simple object. You do that by using the module and then calling the new() constructor: use CGI::Simple; my $q = new CGI::Simple; It is traditional to call your object $q for query or perhaps $cgi. =head2 Next you call methods on that object Once you have your object you can call methods on it using the -> arrow syntax For example to get the names of all the parameters passed to your script you would just write: @names = $q->param(); Many methods are sensitive to the context in which you call them. In the example above the B method returns a list of all the parameter names when called without any arguments. When you call B with a single argument it assumes you want to get the value(s) associated with that argument (parameter). If you ask for an array it gives you an array of all the values associated with it's argument: @values = $q->param('foo'); # get all the values for 'foo' whereas if you ask for a scalar like this: $value = $q->param('foo'); # get only the first value for 'foo' then it returns only the first value (if more than one value for 'foo' exists). Most CGI::Simple routines accept several arguments, sometimes as many as 10 optional ones! To simplify this interface, all routines use a named argument calling style that looks like this: print $q->header( -type=>'image/gif', -expires=>'+3d' ); Each argument name is preceded by a dash. Neither case nor order matters in the argument list. -type, -Type, and -TYPE are all acceptable. Several routines are commonly called with just one argument. In the case of these routines you can provide the single argument without an argument name. B happens to be one of these routines. In this case, the single argument is the document type. print $q->header('text/html'); Sometimes methods expect a scalar, sometimes a reference to an array, and sometimes a reference to a hash. Often, you can pass any type of argument and the routine will do whatever is most appropriate. For example, the B method can be used to set a CGI parameter to a single or a multi-valued value. The two cases are shown below: $q->param(-name=>'veggie',-value=>'tomato'); $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']); =head1 CALLING CGI::Simple ROUTINES USING THE FUNCTION INTERFACE For convenience a functional interface is provided by the CGI::Simple::Standard module. This hides the OO details from you and allows you to simply call methods. You may either use AUTOLOADING of methods or import specific method sets into you namespace. Here are the first few examples again using the function interface. use CGI::Simple::Standard qw(-autoload); @names = param(); @values = param('foo'); $value = param('foo'); print header(-type=>'image/gif',-expires=>'+3d'); print header('text/html'); Yes that's it. Not a $q-> in sight. You just use the module and select how/which methods to load. You then just call the methods you want exactly as before but without the $q-> notation. When (if) you read the following docs and are using the functional interface just pretend the $q-> is not there. =head2 Selecting which methods to load When you use the functional interface Perl needs to be able to find the functions you call. The simplest way of doing this is to use autoloading as shown above. When you use CGI::Simple::Standard with the '-autoload' pragma it exports a single AUTOLOAD sub into you namespace. Every time you call a non existent function AUTOLOAD is called and will load the required function and install it in your namespace. Thus only the AUTOLOAD sub and those functions you specifically call will be imported. Alternatively CGI::Simple::Standard provides a range of function sets you can import or you can just select exactly what you want. You do this using the familiar use CGI::Simple::Standard qw( :func_set some_func); notation. This will import the ':func_set' function set and the specific function 'some_func'. =head2 To Autoload or not to Autoload, that is the question. If you do not have a AUTOLOAD sub in you script it is generally best to use the '-autoload' option. Under autoload you can use any method you want but only import and compile those functions you actually use. If you do not use autoload you must specify what functions to import. You can only use functions that you have imported. For comvenience functions are grouped into related sets. If you choose to import one or more ':func_set' you may have potential namespace collisions so check out the docs to see what gets imported. Using the ':all' tag is pretty slack but it is there if you want. Full details of the function sets are provided in the CGI::Simple::Standard docs If you just want say the param and header methods just load these two. use CGI::Simple::Standard qw(param header); =head2 Setting globals using the functional interface Where you see global variables being set using the syntax: $CGI::Simple::DEBUG = 1; You use exactly the same syntax when using CGI::Simple::Standard. =cut ################ The Core Methods ################ =head1 THE CORE METHODS =head2 new() Creating a new query object The first step in using CGI::Simple is to create a new query object using the B constructor: $q = new CGI::Simple; This will parse the input (from both POST and GET methods) and store it into an object called $q. If you provide a file handle to the B method, it will read parameters from the file (or STDIN, or whatever). open FH, "test.in" or die $!; $q = new CGI::Simple(\*FH); open $fh, "test.in" or die $!; $q = new CGI::Simple($fh); The file should be a series of newline delimited TAG=VALUE pairs. Conveniently, this type of file is created by the B method (see below). Multiple records can be saved and restored. IO::File objects work fine. If you are using the function-oriented interface provided by CGI::Simple::Standard and want to initialize from a file handle, the way to do this is with B. This will (re)initialize the default CGI::Simple object from the indicated file handle. restore_parameters(\*FH); In fact for all intents and purposes B is identical to B Note that B does not exist in CGI::Simple itself so you can't use it. You can also initialize the query object from an associative array reference: $q = new CGI::Simple( { 'dinosaur' => 'barney', 'song' => 'I love you', 'friends' => [qw/Jessica George Nancy/] } ); or from a properly formatted, URL-escaped query string: $q = new CGI::Simple( 'dinosaur=barney&color=purple' ); or from a previously existing CGI::Simple object (this generates an identical clone including all global variable settings, etc that are stored in the object): $old_query = new CGI::Simple; $new_query = new CGI::Simple($old_query); To create an empty query, initialize it from an empty string or hash: $empty_query = new CGI::Simple(""); -or- $empty_query = new CGI::Simple({}); =head2 keywords() Fetching a list of keywords from a query @keywords = $q->keywords; If the script was invoked as the result of an search, the parsed keywords can be obtained as an array using the B method. =head2 param() Fetching the names of all parameters passed to your script @names = $q->param; If the script was invoked with a parameter list (e.g. "name1=value1&name2=value2&name3=value3"), the B method will return the parameter names as a list. If the script was invoked as an script and contains a string without ampersands (e.g. "value1+value2+value3") , there will be a single parameter named "keywords" containing the "+"-delimited keywords. NOTE: The array of parameter names returned will be in the same order as they were submitted by the browser. Usually this order is the same as the order in which the parameters are defined in the form (however, this isn't part of the spec, and so isn't guaranteed). =head2 param() Fetching the value or values of a simple named parameter @values = $q->param('foo'); -or- $value = $q->param('foo'); Pass the B method a single argument to fetch the value of the named parameter. If the parameter is multi-valued (e.g. from multiple selections in a scrolling list), you can ask to receive an array. Otherwise the method will return a single value. If a value is not given in the query string, as in the queries "name1=&name2=" or "name1&name2", it will be returned by default as an empty string. If you set the global variable: $CGI::Simple::NO_UNDEF_PARAMS = 1; Then value-less parameters will be ignored, and will not exist in the query object. If you try to access them via param you will get an undef return value. =head2 param() Setting the values of a named parameter $q->param('foo','an','array','of','values'); This sets the value for the named parameter 'foo' to an array of values. This is one way to change the value of a field. B also recognizes a named parameter style of calling described in more detail later: $q->param(-name=>'foo',-values=>['an','array','of','values']); -or- $q->param(-name=>'foo',-value=>'the value'); =head2 param() Retrieving non-application/x-www-form-urlencoded data If POSTed or PUTed data is not of type application/x-www-form-urlencoded or multipart/form-data, then the data will not be processed, but instead be returned as-is in a parameter named POSTDATA or PUTDATA. To retrieve it, use code like this: my $data = $q->param( 'POSTDATA' ); -or- my $data = $q->param( 'PUTDATA' ); (If you don't know what the preceding means, don't worry about it. It only affects people trying to use CGI::Simple for REST webservices) =head2 add_param() Setting the values of a named parameter You nay also use the new method B to add parameters. This is an alias to the _add_param() internal method that actually does all the work. You can call it like this: $q->add_param('foo', 'new'); $q->add_param('foo', [1,2,3,4,5]); $q->add_param( 'foo', 'bar', 'overwrite' ); The first argument is the parameter, the second the value or an array ref of values and the optional third argument sets overwrite mode. If the third argument is absent of false the values will be appended. If true the values will overwrite any existing ones =head2 append() Appending values to a named parameter $q->append(-name=>'foo',-values=>['yet','more','values']); This adds a value or list of values to the named parameter. The values are appended to the end of the parameter if it already exists. Otherwise the parameter is created. Note that this method only recognizes the named argument calling syntax. =head2 import_names() Importing all parameters into a namespace. This method was silly, non OO and has been deleted. You can get all the params as a hash using B or via all the other accessors. =head2 delete() Deleting a parameter completely $q->delete('foo'); This completely clears a parameter. If you are using the function call interface, use B instead to avoid conflicts with Perl's built-in delete operator. If you are using the function call interface, use B instead to avoid conflicts with Perl's built-in delete operator. =head2 delete_all() Deleting all parameters $q->delete_all(); This clears the CGI::Simple object completely. For CGI.pm compatibility B is provided however there is no reason to use this in the function call interface other than symmetry. For CGI.pm compatibility B is provided as an alias for B however there is no reason to use this, even in the function call interface. =head2 param_fetch() Direct access to the parameter list This method is provided for CGI.pm compatibility only. It returns an array ref to the values associated with a named param. It is deprecated. =head2 Vars() Fetching the entire parameter list as a hash $params = $q->Vars; # as a tied hash ref print $params->{'address'}; @foo = split "\0", $params->{'foo'}; %params = $q->Vars; # as a plain hash print $params{'address'}; @foo = split "\0", $params{'foo'}; %params = $q->Vars(','); # specifying a different separator than "\0" @foo = split ',', $params{'foo'}; Many people want to fetch the entire parameter list as a hash in which the keys are the names of the CGI parameters, and the values are the parameters' values. The B method does this. Called in a scalar context, it returns the parameter list as a tied hash reference. Because this hash ref is tied changing a key/value changes the underlying CGI::Simple object. Called in a list context, it returns the parameter list as an ordinary hash. Changing this hash will not change the underlying CGI::Simple object When using B, the thing you must watch out for are multi-valued CGI parameters. Because a hash cannot distinguish between scalar and list context, multi-valued parameters will be returned as a packed string, separated by the "\0" (null) character. You must split this packed string in order to get at the individual values. This is the convention introduced long ago by Steve Brenner in his cgi-lib.pl module for Perl version 4. You can change the character used to do the multiple value packing by passing it to B as an argument as shown. =head2 url_param() Access the QUERY_STRING regardless of 'GET' or 'POST' The B method makes the QUERY_STRING data available regardless of whether the REQUEST_METHOD was 'GET' or 'POST'. You can do anything with B that you can do with B, however the data set is completely independent. Technically what happens if you use this method is that the QUERY_STRING data is parsed into a new CGI::Simple object which is stored within the current object. B then just calls B on this new object. =head2 parse_query_string() Add QUERY_STRING data to 'POST' requests When the REQUEST_METHOD is 'POST' the default behavior is to ignore name/value pairs or keywords in the $ENV{'QUERY_STRING'}. You can override this by calling B which will add the QUERY_STRING data to the data already in our CGI::Simple object if the REQUEST_METHOD was 'POST' $q = new CGI::Simple; $q->parse_query_string; # add $ENV{'QUERY_STRING'} data to our $q object If the REQUEST_METHOD was 'GET' then the QUERY_STRING will already be stored in our object so B will be ignored. This is a new method in CGI::Simple that is not available in CGI.pm =head2 save() Saving the state of an object to file $q->save(\*FILEHANDLE) This will write the current state of the form to the provided filehandle. You can read it back in by providing a filehandle to the B method. The format of the saved file is: NAME1=VALUE1 NAME1=VALUE1' NAME2=VALUE2 NAME3=VALUE3 = Both name and value are URL escaped. Multi-valued CGI parameters are represented as repeated names. A session record is delimited by a single = symbol. You can write out multiple records and read them back in with several calls to B. open FH, "test.in" or die $!; $q1 = new CGI::Simple(\*FH); # get the first record $q2 = new CGI::Simple(\*FH); # get the next record Note: If you wish to use this method from the function-oriented (non-OO) interface, the exported name for this method is B. Also if you want to initialize from a file handle, the way to do this is with B. This will (re)initialize the default CGI::Simple object from the indicated file handle. restore_parameters(\*FH); =cut ################ Uploading Files ################### =head1 FILE UPLOADS File uploads are easy with CGI::Simple. You use the B method. Assuming you have the following in your HTML: Note that the ENCTYPE is "multipart/form-data". You must specify this or the browser will default to "application/x-www-form-urlencoded" which will result in no files being uploaded although on the surface things will appear OK. When the user submits this form any supplied files will be spooled onto disk and saved in temporary files. These files will be deleted when your script.cgi exits so if you want to keep them you will need to proceed as follows. =head2 upload() The key file upload method The B method is quite versatile. If you call B without any arguments it will return a list of uploaded files in list context and the number of uploaded files in scalar context. $number_of_files = $q->upload; @list_of_files = $q->upload; Having established that you have uploaded files available you can get the browser supplied filename using B like this: $filename1 = $q->param('upload_file1'); You can then get a filehandle to read from by calling B and supplying this filename as an argument. Warning: do not modify the value you get from B in any way - you don't need to untaint it. $fh = $q->upload( $filename1 ); Now to save the file you would just do something like: $save_path = '/path/to/write/file.name'; open FH, ">$save_path" or die "Oops $!\n"; binmode FH; print FH $buffer while read( $fh, $buffer, 4096 ); close FH; By utilizing a new feature of the upload method this process can be simplified to: $ok = $q->upload( $q->param('upload_file1'), '/path/to/write/file.name' ); if ($ok) { print "Uploaded and wrote file OK!"; } else { print $q->cgi_error(); } As you can see upload will accept an optional second argument and will write the file to this file path. It will return 1 for success and undef if it fails. If it fails you can get the error from B You can also use just the fieldname as an argument to upload ie: $fh = $q->upload( 'upload_field_name' ); or $ok = $q->upload( 'upload_field_name', '/path/to/write/file.name' ); BUT there is a catch. If you have multiple upload fields, all called 'upload_field_name' then you will only get the last uploaded file from these fields. =head2 upload_info() Get the details about uploaded files The B method is a new method. Called without arguments it returns the number of uploaded files in scalar context and the names of those files in list context. $number_of_upload_files = $q->upload_info(); @filenames_of_all_uploads = $q->upload_info(); You can get the MIME type of an uploaded file like this: $mime = $q->upload_info( $filename1, 'mime' ); If you want to know how big a file is before you copy it you can get that information from B which will return the file size in bytes. $file_size = $q->upload_info( $filename1, 'size' ); The size attribute is optional as this is the default value returned. Note: The old CGI.pm B method has been deleted. =head2 $POST_MAX and $DISABLE_UPLOADS CGI.pm has a default setting that allows infinite size file uploads by default. In contrast file uploads are disabled by default in CGI::Simple to discourage Denial of Service attacks. You must enable them before you expect file uploads to work. When file uploads are disabled the file name and file size details will still be available from B and B respectively but the upload filehandle returned by B will be undefined - not surprising as the underlying temp file will not exist either. You can enable uploads using the '-upload' pragma. You do this by specifying this in you use statement: use CGI::Simple qw(-upload); Alternatively you can enable uploads via the $DISABLE_UPLOADS global like this: use CGI::Simple; $CGI::Simple::DISABLE_UPLOADS = 0; $q = new CGI::Simple; If you wish to set $DISABLE_UPLOADS you must do this *after* the use statement and *before* the new constructor call as shown above. The maximum acceptable data via post is capped at 102_400kB rather than infinity which is the CGI.pm default. This should be ample for most tasks but you can set this to whatever you want using the $POST_MAX global. use CGI::Simple; $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads $CGI::Simple::POST_MAX = 1_048_576; # allow 1MB uploads $q = new CGI::Simple; If you set to -1 infinite size uploads will be permitted, which is the CGI.pm default. $CGI::Simple::POST_MAX = -1; # infinite size upload Alternatively you can specify all the CGI.pm default values which allow file uploads of infinite size in one easy step by specifying the '-default' pragma in your use statement. use CGI::Simple qw( -default ..... ); =head2 binmode() and Win32 If you are using CGI::Simple be sure to call B on any handle that you create to write the uploaded file to disk. Calling B will do no harm on other systems anyway. =cut ################ Miscellaneous Methods ################ =head1 MISCELANEOUS METHODS =head2 escapeHTML() Escaping HTML special characters In HTML the < > " and & chars have special meaning and need to be escaped to < > " and & respectively. $escaped = $q->escapeHTML( $string ); $escaped = $q->escapeHTML( $string, 'new_lines_too' ); If the optional second argument is supplied then newlines will be escaped to. =head2 unescapeHTML() Unescape HTML special characters This performs the reverse of B. $unescaped = $q->unescapeHTML( $HTML_escaped_string ); =head2 url_decode() Decode a URL encoded string This method will correctly decode a url encoded string. $decoded = $q->url_decode( $encoded ); =head2 url_encode() URL encode a string This method will correctly URL encode a string. $encoded = $q->url_encode( $string ); =head2 parse_keywordlist() Parse a supplied keyword list @keywords = $q->parse_keywordlist( $keyword_list ); This method returns a list of keywords, correctly URL escaped and split out of the supplied string =head2 put() Send output to browser CGI.pm alias for print. $q->put('Hello World!') will print the usual =head2 print() Send output to browser CGI.pm alias for print. $q->print('Hello World!') will print the usual =cut ################# Cookie Methods ################ =head1 HTTP COOKIES CGI.pm has several methods that support cookies. A cookie is a name=value pair much like the named parameters in a CGI query string. CGI scripts create one or more cookies and send them to the browser in the HTTP header. The browser maintains a list of cookies that belong to a particular Web server, and returns them to the CGI script during subsequent interactions. In addition to the required name=value pair, each cookie has several optional attributes: =over 4 =item 1. an expiration time This is a time/date string (in a special GMT format) that indicates when a cookie expires. The cookie will be saved and returned to your script until this expiration date is reached if the user exits the browser and restarts it. If an expiration date isn't specified, the cookie will remain active until the user quits the browser. =item 2. a domain This is a partial or complete domain name for which the cookie is valid. The browser will return the cookie to any host that matches the partial domain name. For example, if you specify a domain name of ".capricorn.com", then the browser will return the cookie to Web servers running on any of the machines "www.capricorn.com", "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names must contain at least two periods to prevent attempts to match on top level domains like ".edu". If no domain is specified, then the browser will only return the cookie to servers on the host the cookie originated from. =item 3. a path If you provide a cookie path attribute, the browser will check it against your script's URL before returning the cookie. For example, if you specify the path "/cgi-bin", then the cookie will be returned to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl", but not to the script "/cgi-private/site_admin.pl". By default, path is set to "/", which causes the cookie to be sent to any CGI script on your site. =item 4. a "secure" flag If the "secure" attribute is set, the cookie will only be sent to your script if the CGI request is occurring on a secure channel, such as SSL. =back =head2 cookie() A simple access method to cookies The interface to HTTP cookies is the B method: $cookie = $q->cookie( -name => 'sessionID', -value => 'xyzzy', -expires => '+1h', -path => '/cgi-bin/database', -domain => '.capricorn.org', -secure => 1 ); print $q->header(-cookie=>$cookie); B creates a new cookie. Its parameters include: =over 4 =item B<-name> The name of the cookie (required). This can be any string at all. Although browsers limit their cookie names to non-whitespace alphanumeric characters, CGI.pm removes this restriction by escaping and unescaping cookies behind the scenes. =item B<-value> The value of the cookie. This can be any scalar value, array reference, or even associative array reference. For example, you can store an entire associative array into a cookie this way: $cookie=$q->cookie( -name => 'family information', -value => \%childrens_ages ); =item B<-path> The optional partial path for which this cookie will be valid, as described above. =item B<-domain> The optional partial domain for which this cookie will be valid, as described above. =item B<-expires> The optional expiration date for this cookie. The format is as described in the section on the B method: "+1h" one hour from now =item B<-secure> If set to true, this cookie will only be used within a secure SSL session. =back The cookie created by B must be incorporated into the HTTP header within the string returned by the B method: print $q->header(-cookie=>$my_cookie); To create multiple cookies, give B an array reference: $cookie1 = $q->cookie( -name => 'riddle_name', -value => "The Sphynx's Question" ); $cookie2 = $q->cookie( -name => 'answers', -value => \%answers ); print $q->header( -cookie => [ $cookie1, $cookie2 ] ); To retrieve a cookie, request it by name by calling B method without the B<-value> parameter: use CGI::Simple; $q = new CGI::Simple; $riddle = $q->cookie('riddle_name'); %answers = $q->cookie('answers'); Cookies created with a single scalar value, such as the "riddle_name" cookie, will be returned in that form. Cookies with array and hash values can also be retrieved. The cookie and CGI::Simple namespaces are separate. If you have a parameter named 'answers' and a cookie named 'answers', the values retrieved by B and B are independent of each other. However, it's simple to turn a CGI parameter into a cookie, and vice-versa: # turn a CGI parameter into a cookie $c = $q->cookie( -name=>'answers', -value=>[$q->param('answers')] ); # vice-versa $q->param( -name=>'answers', -value=>[$q->cookie('answers')] ); =head2 raw_cookie() Returns the HTTP_COOKIE variable. Cookies have a special format, and this method call just returns the raw form (?cookie dough). See B for ways of setting and retrieving cooked cookies. Called with no parameters, B returns the packed cookie structure. You can separate it into individual cookies by splitting on the character sequence "; ". Called with the name of a cookie, retrieves the B form of the cookie. You can use the regular B method to get the names, or use the raw_fetch() method from the CGI::Simmple::Cookie module. =cut ################# Header Methods ################ =head1 CREATING HTTP HEADERS Normally the first thing you will do in any CGI script is print out an HTTP header. This tells the browser what type of document to expect, and gives other optional information, such as the language, expiration date, and whether to cache the document. The header can also be manipulated for special purposes, such as server push and pay per view pages. =head2 header() Create simple or complex HTTP headers print $q->header; -or- print $q->header('image/gif'); -or- print $q->header('text/html','204 No response'); -or- print $q->header( -type => 'image/gif', -nph => 1, -status => '402 Payment required', -expires => '+3d', -cookie => $cookie, -charset => 'utf-7', -attachment => 'foo.gif', -Cost => '$2.00' ); B returns the Content-type: header. You can provide your own MIME type if you choose, otherwise it defaults to text/html. An optional second parameter specifies the status code and a human-readable message. For example, you can specify 204, "No response" to create a script that tells the browser to do nothing at all. The last example shows the named argument style for passing arguments to the CGI methods using named parameters. Recognized parameters are B<-type>, B<-status>, B<-cookie>, B<-target>, B<-expires>, B<-nph>, B<-charset> and B<-attachment>. Any other named parameters will be stripped of their initial hyphens and turned into header fields, allowing you to specify any HTTP header you desire. For example, you can produce non-standard HTTP header fields by providing them as named arguments: print $q->header( -type => 'text/html', -nph => 1, -cost => 'Three smackers', -annoyance_level => 'high', -complaints_to => 'bit bucket' ); This will produce the following non-standard HTTP header: HTTP/1.0 200 OK Cost: Three smackers Annoyance-level: high Complaints-to: bit bucket Content-type: text/html Note that underscores are translated automatically into hyphens. This feature allows you to keep up with the rapidly changing HTTP "standards". The B<-type> is a key element that tell the browser how to display your document. The default is 'text/html'. Common types are: text/html text/plain image/gif image/jpg image/png application/octet-stream The B<-status> code is the HTTP response code. The default is 200 OK. Common status codes are: 200 OK 204 No Response 301 Moved Permanently 302 Found 303 See Other 307 Temporary Redirect 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 405 Not Allowed 408 Request Timed Out 500 Internal Server Error 503 Service Unavailable 504 Gateway Timed Out The B<-expires> parameter lets you indicate to a browser and proxy server how long to cache pages for. When you specify an absolute or relative expiration interval with this parameter, some browsers and proxy servers will cache the script's output until the indicated expiration date. The following forms are all valid for the -expires field: +30s 30 seconds from now +10m ten minutes from now +1h one hour from now -1d yesterday (i.e. "ASAP!") now immediately +3M in three months +10y in ten years time Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date The B<-cookie> parameter generates a header that tells the browser to provide a "magic cookie" during all subsequent transactions with your script. Netscape cookies have a special format that includes interesting attributes such as expiration time. Use the B method to create and retrieve session cookies. The B<-target> is for frames use The B<-nph> parameter, if set to a true value, will issue the correct headers to work with a NPH (no-parse-header) script. This is important to use with certain servers that expect all their scripts to be NPH. The B<-charset> parameter can be used to control the character set sent to the browser. If not provided, defaults to ISO-8859-1. As a side effect, this sets the charset() method as well. The B<-attachment> parameter can be used to turn the page into an attachment. Instead of displaying the page, some browsers will prompt the user to save it to disk. The value of the argument is the suggested name for the saved file. In order for this to work, you may have to set the B<-type> to 'application/octet-stream'. =head2 no_cache() Preventing browser caching of scripts Most browsers will not cache the output from CGI scripts. Every time the browser reloads the page, the script is invoked anew. However some browsers do cache pages. You can discourage this behavior using the B function. $q->no_cache(1); # turn caching off by sending appropriate headers $q->no_cache(1); # do not send cache related headers. $q->no_cache(1); print header (-type=>'image/gif', -nph=>1); This will produce a header like the following: HTTP/1.0 200 OK Server: Apache - accept no substitutes Expires: Thu, 15 Nov 2001 03:37:50 GMT Date: Thu, 15 Nov 2001 03:37:50 GMT Pragma: no-cache Content-Type: image/gif Both the Pragma: no-cache header field and an Expires header that corresponds to the current time (ie now) will be sent. =head2 cache() Preventing browser caching of scripts The somewhat ill named B method is a legacy from CGI.pm. It operates the same as the new B method. The difference is/was that when set it results only in the Pragma: no-cache line being printed. Expires time data is not sent. =head2 redirect() Generating a redirection header print $q->redirect('http://somewhere.else/in/movie/land'); Sometimes you don't want to produce a document yourself, but simply redirect the browser elsewhere, perhaps choosing a URL based on the time of day or the identity of the user. The B function redirects the browser to a different URL. If you use redirection like this, you should B print out a header as well. One hint I can offer is that relative links may not work correctly when you generate a redirection to another document on your site. This is due to a well-intentioned optimization that some servers use. The solution to this is to use the full URL (including the http: part) of the document you are redirecting to. You can also use named arguments: print $q->redirect( -uri=>'http://somewhere.else/in/movie/land', -nph=>1 ); The B<-nph> parameter, if set to a true value, will issue the correct headers to work with a NPH (no-parse-header) script. This is important to use with certain servers, such as Microsoft ones, which expect all their scripts to be NPH. =cut =head1 PRAGMAS There are a number of pragmas that you can specify in your use CGI::Simple statement. Pragmas, which are always preceded by a hyphen, change the way that CGI::Simple functions in various ways. You can generally achieve exactly the same results by setting the underlying $GLOBAL_VARIABLES. For example the '-upload' pargma will enable file uploads: use CGI::Simple qw(-upload); In CGI::Simple::Standard Pragmas, function sets , and individual functions can all be imported in the same use() line. For example, the following use statement imports the standard set of functions and enables debugging mode (pragma -debug): use CGI::Simple::Standard qw(:standard -debug); The current list of pragmas is as follows: =over 4 =item -no_undef_params If a value is not given in the query string, as in the queries "name1=&name2=" or "name1&name2", by default it will be returned as an empty string. If you specify the '-no_undef_params' pragma then CGI::Simple ignores parameters with no values and they will not appear in the query object. =item -nph This makes CGI.pm produce a header appropriate for an NPH (no parsed header) script. You may need to do other things as well to tell the server that the script is NPH. See the discussion of NPH scripts below. =item -newstyle_urls Separate the name=value pairs in CGI parameter query strings with semicolons rather than ampersands. For example: ?name=fred;age=24;favorite_color=3 Semicolon-delimited query strings are always accepted, but will not be emitted by self_url() and query_string() unless the -newstyle_urls pragma is specified. =item -oldstyle_urls Separate the name=value pairs in CGI parameter query strings with ampersands rather than semicolons. This is the default. ?name=fred&age=24&favorite_color=3 =item -autoload This is only available for CGI::Simple::Standard and uses AUTOLOAD to load functions on demand. See the CGI::Simple::Standard docs for details. =item -no_debug This turns off the command-line processing features. This is the default. =item -debug1 and debug2 This turns on debugging. At debug level 1 CGI::Simple will read arguments from the command-line. At debug level 2 CGI.pm will produce the prompt "(offline mode: enter name=value pairs on standard input)" and wait for input on STDIN. If no number is specified then a debug level of 2 is used. See the section on debugging for more details. =item -default This sets the default global values for CGI.pm which will enable infinite size file uploads, and specify the '-newstyle_urls' and '-debug1' pragmas =item -no_upload Disable uploads - the default setting =item - upload Enable uploads - the CGI.pm default =item -unique_header Only allows headers to be generated once per script invocation =item -carp Carp when B called, default is to do nothing =item -croak Croak when B called, default is to do nothing =back =cut ############### NPH Scripts ################ =head1 USING NPH SCRIPTS NPH, or "no-parsed-header", scripts bypass the server completely by sending the complete HTTP header directly to the browser. This has slight performance benefits, but is of most use for taking advantage of HTTP extensions that are not directly supported by your server, such as server push and PICS headers. Servers use a variety of conventions for designating CGI scripts as NPH. Many Unix servers look at the beginning of the script's name for the prefix "nph-". The Macintosh WebSTAR server and Microsoft's Internet Information Server, in contrast, try to decide whether a program is an NPH script by examining the first line of script output. CGI.pm supports NPH scripts with a special NPH mode. When in this mode, CGI.pm will output the necessary extra header information when the B and B methods are called. You can set NPH mode in any of the following ways: =over 4 =item In the B statement Simply add the "-nph" pragma to the use: use CGI::Simple qw(-nph) =item By calling the B method: Call B with a non-zero parameter at any point after using CGI.pm in your program. $q->nph(1) =item By using B<-nph> parameters in the B and B statements: print $q->header(-nph=>1); =back The Microsoft Internet Information Server requires NPH mode. CGI::Simple will automatically detect when the script is running under IIS and put itself into this mode. You do not need to do this manually, although it won't hurt anything if you do. However, note that if you have applied Service Pack 6, much of the functionality of NPH scripts, including the ability to redirect while setting a cookie, b on IIS without a special patch from Microsoft. See http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP: Non-Parsed Headers Stripped From CGI Applications That Have nph- Prefix in Name. =cut ################# Server Push Methods ################# =head1 SERVER PUSH CGI.pm provides four simple functions for producing multipart documents of the type needed to implement server push. These functions were graciously provided by Ed Jordan with additions from Andrew Benham You are also advised to put the script into NPH mode and to set $| to 1 to avoid buffering problems. Browser support for server push is variable. Here is a simple script that demonstrates server push: #!/usr/local/bin/perl use CGI::Simple::Standard qw/:push -nph/; $| = 1; print multipart_init(-boundary=>'----here we go!'); foreach (0 .. 4) { print multipart_start(-type=>'text/plain'), "The current time is ",scalar(localtime),"\n"; if ($_ < 4) { print multipart_end; } else { print multipart_final; } sleep 1; } This script initializes server push by calling B. It then enters a loop in which it begins a new multipart section by calling B, prints the current local time, and ends a multipart section with B. It then sleeps a second, and begins again. On the final iteration, it ends the multipart section with B rather than with B. =head2 multipart_init() Initialize the multipart system multipart_init(-boundary=>$boundary); Initialize the multipart system. The -boundary argument specifies what MIME boundary string to use to separate parts of the document. If not provided, CGI.pm chooses a reasonable boundary for you. =head2 multipart_start() Start a new part of the multipart document multipart_start(-type=>$type) Start a new part of the multipart document using the specified MIME type. If not specified, text/html is assumed. =head2 multipart_end() End a multipart part multipart_end() End a part. You must remember to call B once for each B, except at the end of the last part of the multipart document when B should be called instead of B. =head2 multipart_final() multipart_final() End all parts. You should call B rather than B at the end of the last part of the multipart document. =head2 CGI::Push Users interested in server push applications should also have a look at the B module. =cut ################# Debugging Methods ################ =head1 DEBUGGING If you are running the script from the command line or in the perl debugger, you can pass the script a list of keywords or parameter=value pairs on the command line or from standard input (you don't have to worry about tricking your script into reading from environment variables). Before you do this you will need to change the debug level from the default level of 0 (no debug) to either 1 if you want to debug from @ARGV (the command line) of 2 if you want to debug from STDIN. You can do this using the debug pragma like this: use CGI::Simple qw(-debug2); # set debug to level 2 => from STDIN or this: $CGI::Simple::DEBUG = 1; # set debug to level 1 => from @ARGV At debug level 1 you can pass keywords and name=value pairs like this: your_script.pl keyword1 keyword2 keyword3 or this: your_script.pl keyword1+keyword2+keyword3 or this: your_script.pl name1=value1 name2=value2 or this: your_script.pl name1=value1&name2=value2 At debug level 2 you can feed newline-delimited name=value pairs to the script on standard input. You will be presented with the following prompt: (offline mode: enter name=value pairs on standard input) You end the input with your system dependent end of file character. You should try ^Z ^X ^D and ^C if all else fails. The ^ means hold down the [Ctrl] button while you press the other key. When debugging, you can use quotes and backslashes to escape characters in the familiar shell manner, letting you place spaces and other funny characters in your parameter=value pairs: your_script.pl "name1='I am a long value'" "name2=two\ words" =head2 Dump() Dumping the current object details The B method produces a string consisting of all the query's object attributes formatted nicely as a nested list. This dump includes the name/value pairs and a number of other details. This is useful for debugging purposes: print $q->Dump The actual result of this is HTML escaped formatted text wrapped in
 tags
so if you send it straight to the browser it produces something that looks
like:

    $VAR1 = bless( {
         '.parameters' => [
                            'name',
                            'color'
                          ],
         '.globals' => {
                         'FATAL' => -1,
                         'DEBUG' => 0,
                         'NO_NULL' => 1,
                         'POST_MAX' => 102400,
                         'USE_CGI_PM_DEFAULTS' => 0,
                         'HEADERS_ONCE' => 0,
                         'NPH' => 0,
                         'DISABLE_UPLOADS' => 1,
                         'NO_UNDEF_PARAMS' => 0,
                         'USE_PARAM_SEMICOLONS' => 0
                       },
         '.fieldnames' => {
                            'color' => '1',
                            'name' => '1'
                          },
         '.mod_perl' => '',
         'color' => [
                      'red',
                      'green',
                      'blue'
                    ],
         'name' => [
                     'JaPh,'
                   ]
        }, 'CGI::Simple' );

You may recognize this as valid Perl syntax (which it is) and/or the output
from Data::Dumper (also true). This is the actual guts of how the information
is stored in the query object. All the internal params start with a . char

Alternatively you can dump your object and the current environment using:

    print $q->Dump(\%ENV);

=head2 PrintEnv() Dumping the environment

You can get a similar browser friendly dump of the current %ENV hash using:

    print $q->PrintEnv;

This will produce something like (in the browser):

    $VAR1 = {
          'QUERY_STRING' => 'name=JaPh%2C&color=red&color=green&color=blue',
          'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
          'REGRESSION_TEST' => 'simple.t.pl',
          'VIM' => 'C:\\WINDOWS\\Desktop\\vim',
          'HTTP_REFERER' => 'xxx.sex.com',
          'HTTP_USER_AGENT' => 'LWP',
          'HTTP_ACCEPT' => 'text/html;q=1, image/gif;q=0.42, */*;q=0.001',
          'REMOTE_HOST' => 'localhost',
          'HTTP_HOST' => 'the.restaurant.at.the.end.of.the.universe',
          'GATEWAY_INTERFACE' => 'bleeding edge',
          'REMOTE_IDENT' => 'None of your damn business',
          'SCRIPT_NAME' => '/cgi-bin/foo.cgi',
          'SERVER_NAME' => 'nowhere.com',
          'HTTP_COOKIE' => '',
          'CONTENT_LENGTH' => '42',
          'HTTPS_A' => 'A',
          'HTTP_FROM' => 'spammer@nowhere.com',
          'HTTPS_B' => 'B',
          'SERVER_PROTOCOL' => 'HTTP/1.0',
          'PATH_TRANSLATED' => '/usr/local/somewhere/else',
          'SERVER_SOFTWARE' => 'Apache - accept no substitutes',
          'PATH_INFO' => '/somewhere/else',
          'REMOTE_USER' => 'Just another Perl hacker,',
          'REMOTE_ADDR' => '127.0.0.1',
          'HTTPS' => 'ON',
          'DOCUMENT_ROOT' => '/vs/www/foo',
          'REQUEST_METHOD' => 'GET',
          'REDIRECT_QUERY_STRING' => '',
          'AUTH_TYPE' => 'PGP MD5 DES rot13',
          'COOKIE' => 'foo=a%20phrase; bar=yes%2C%20a%20phrase&;I%20say;',
          'SERVER_PORT' => '8080'
        };


=head2 cgi_error() Retrieving CGI::Simple error messages

Errors can occur while processing user input, particularly when
processing uploaded files.  When these errors occur, CGI::Simple will stop
processing and return an empty parameter list.  You can test for
the existence and nature of errors using the B function.
The error messages are formatted as HTTP status codes. You can either
incorporate the error text into an HTML page, or use it as the value
of the HTTP status:

    my $error = $q->cgi_error;
    if ($error) {
        print $q->header(-status=>$error);
        print "

$error

; exit; } =cut ############### Accessor Methods ################ =head1 ACCESSOR METHODS =head2 version() Get the CGI::Simple version info $version = $q->version(); The B method returns the value of $VERSION =head2 nph() Enable/disable NPH (Non Parsed Header) mode $q->nph(1); # enable NPH mode $q->nph(0); # disable NPH mode The B method enables and disables NPH headers. See the NPH section. =head2 all_parameters() Get the names/values of all parameters @all_parameters = $q->all_parameters(); The B method is an alias for B =head2 charset() Get/set the current character set. $charset = $q->charset(); # get current charset $q->charset('utf-42'); # set the charset The B method gets the current charset value if no argument is supplied or sets it if an argument is supplied. =head2 crlf() Get the system specific line ending sequence $crlf = $q->crlf(); The B method returns the system specific line ending sequence. =head2 globals() Get/set the value of the remaining global variables $globals = $q->globals('FATAL'); # get the current value of $FATAL $globals = $q->globals('FATAL', 1 ); # set croak mode on cgi_error() The B method gets/sets the values of the global variables after the script has been invoked. For globals like $POST_MAX and $DISABLE_UPLOADS this makes no difference as they must be set prior to calling the new constructor but there might be reason the change the value of others. =head2 auth_type() Get the current authorization/verification method $auth_type = $q->auth_type(); The B method returns the value of $ENV{'AUTH_TYPE'} which should contain the authorization/verification method in use for this script, if any. =head2 content_length() Get the content length submitted in a POST $content_length = $q->content_length(); The B method returns the value of $ENV{'AUTH_TYPE'} =head2 content_type() Get the content_type of data submitted in a POST $content_type = $q->content_type(); The B method returns the content_type of data submitted in a POST, generally 'multipart/form-data' or 'application/x-www-form-urlencoded' as supplied in $ENV{'CONTENT_TYPE'} =head2 document_root() Get the document root $document_root = $q->document_root(); The B method returns the value of $ENV{'DOCUMENT_ROOT'} =head2 gateway_interface() Get the gateway interface $gateway_interface = $q->gateway_interface(); The B method returns the value of $ENV{'GATEWAY_INTERFACE'} =head2 path_translated() Get the value of path translated $path_translated = $q->path_translated(); The B method returns the value of $ENV{'PATH_TRANSLATED'} =head2 referer() Spy on your users $referer = $q->referer(); The B method returns the value of $ENV{'REFERER'} This will return the URL of the page the browser was viewing prior to fetching your script. Not available for all browsers. =head2 remote_addr() Get the remote address $remote_addr = $q->remote_addr(); The B method returns the value of $ENV{'REMOTE_ADDR'} or 127.0.0.1 (localhost) if this is not defined. =head2 remote_host() Get a value for remote host $remote_host = $q->remote_host(); The B method returns the value of $ENV{'REMOTE_HOST'} if it is defined. If this is not defined it returns $ENV{'REMOTE_ADDR'} If this is not defined it returns 'localhost' =head2 remote_ident() Get the remote identity $remote_ident = $q->remote_ident(); The B method returns the value of $ENV{'REMOTE_IDENT'} =head2 remote_user() Get the remote user $remote_user = $q->remote_user(); The B method returns the authorization/verification name used for user verification, if this script is protected. The value comes from $ENV{'REMOTE_USER'} =head2 request_method() Get the request method $request_method = $q->request_method(); The B method returns the method used to access your script, usually one of 'POST', 'GET' or 'HEAD' as supplied by $ENV{'REQUEST_METHOD'} =head2 script_name() Get the script name $script_name = $q->script_name(); The B method returns the value of $ENV{'SCRIPT_NAME'} if it is defined. Otherwise it returns Perl's script name from $0. Failing this it returns a null string '' =head2 server_name() Get the server name $server_name = $q->server_name(); The B method returns the value of $ENV{'SERVER_NAME'} if defined or 'localhost' otherwise =head2 server_port() Get the port the server is listening on $server_port = $q->server_port(); The B method returns the value $ENV{'SERVER_PORT'} if defined or 80 if not. =head2 server_protocol() Get the current server protocol $server_protocol = $q->server_protocol(); The B method returns the value of $ENV{'SERVER_PROTOCOL'} if defined or 'HTTP/1.0' otherwise =head2 server_software() Get the server software $server_software = $q->server_software(); The B method returns the value $ENV{'SERVER_SOFTWARE'} or 'cmdline' If the server software is IIS it formats your hard drive, installs Linux, FTPs to www.apache.org, installs Apache, and then restores your system from tape. Well maybe not, but it's a nice thought. =head2 user_name() Get a value for the user name. $user_name = $q->user_name(); Attempt to obtain the remote user's name, using a variety of different techniques. This only works with older browsers such as Mosaic. Newer browsers do not report the user name for privacy reasons! Technically the B method returns the value of $ENV{'HTTP_FROM'} or failing that $ENV{'REMOTE_IDENT'} or as a last choice $ENV{'REMOTE_USER'} =head2 user_agent() Get the users browser type $ua = $q->user_agent(); # return the user agent $ok = $q->user_agent('mozilla'); # return true if user agent 'mozilla' The B method returns the value of $ENV{'HTTP_USER_AGENT'} when called without an argument or true or false if the $ENV{'HTTP_USER_AGENT'} matches the passed argument. The matching is case insensitive and partial. =head2 virtual_host() Get the virtual host $virtual_host = $q->virtual_host(); The B method returns the value of $ENV{'HTTP_HOST'} if defined or $ENV{'SERVER_NAME'} as a default. Port numbers are removed. =head2 path_info() Get any extra path info set to the script $path_info = $q->path_info(); The B method returns additional path information from the script URL. E.G. fetching /cgi-bin/your_script/additional/stuff will result in $q->path_info() returning "/additional/stuff". NOTE: The Microsoft Internet Information Server is broken with respect to additional path information. If you use the Perl DLL library, the IIS server will attempt to execute the additional path information as a Perl script. If you use the ordinary file associations mapping, the path information will be present in the environment, but incorrect. The best thing to do is to avoid using additional path information in CGI scripts destined for use with IIS. =head2 Accept() Get the browser MIME types $Accept = $q->Accept(); The B method returns a list of MIME types that the remote browser accepts. If you give this method a single argument corresponding to a MIME type, as in $q->Accept('text/html'), it will return a floating point value corresponding to the browser's preference for this type from 0.0 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept list are handled correctly. =head2 accept() Alias for Accept() $accept = $q->accept(); The B Method is an alias for Accept() =head2 http() Get a range of HTTP related information $http = $q->http(); Called with no arguments the B method returns the list of HTTP or HTTPS environment variables, including such things as HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the like-named HTTP header fields in the request. Called with the name of an HTTP header field, returns its value. Capitalization and the use of hyphens versus underscores are not significant. For example, all three of these examples are equivalent: $requested_language = $q->http('Accept-language'); $requested_language = $q->http('Accept_language'); $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE'); =head2 https() Get a range of HTTPS related information $https = $q->https(); The B method is similar to the http() method except that when called without an argument it returns the value of $ENV{'HTTPS'} which will be true if a HTTPS connection is in use and false otherwise. =head2 protocol() Get the current protocol $protocol = $q->protocol(); The B method returns 'https' if a HTTPS connection is in use or the B minus version numbers ('http') otherwise. =head2 url() Return the script's URL in several formats $full_url = $q->url(); $full_url = $q->url(-full=>1); $relative_url = $q->url(-relative=>1); $absolute_url = $q->url(-absolute=>1); $url_with_path = $q->url(-path_info=>1); $url_with_path_and_query = $q->url(-path_info=>1,-query=>1); $netloc = $q->url(-base => 1); B returns the script's URL in a variety of formats. Called without any arguments, it returns the full form of the URL, including host name and port number http://your.host.com/path/to/script.cgi You can modify this format with the following named arguments: =over 4 =item B<-absolute> If true, produce an absolute URL, e.g. /path/to/script.cgi =item B<-relative> Produce a relative URL. This is useful if you want to reinvoke your script with different parameters. For example: script.cgi =item B<-full> Produce the full URL, exactly as if called without any arguments. This overrides the -relative and -absolute arguments. =item B<-path> (B<-path_info>) Append the additional path information to the URL. This can be combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info> is provided as a synonym. =item B<-query> (B<-query_string>) Append the query string to the URL. This can be combined with B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided as a synonym. =item B<-base> Generate just the protocol and net location, as in http://www.foo.com:8000 =back =head2 self_url() Get the scripts complete URL $self_url = $q->self_url(); The B method returns the value of: $self->url( '-path_info'=>1, '-query'=>1, '-full'=>1 ); =head2 state() Alias for self_url() $state = $q->state(); The B method is an alias for self_url() =cut ################# cgi-lib.pl Compatibility Methods ################# =head1 COMPATIBILITY WITH cgi-lib.pl 2.18 To make it easier to port existing programs that use cgi-lib.pl all the subs within cgi-lib.pl are available in CGI::Simple. Using the functional interface of CGI::Simple::Standard porting is as easy as: OLD VERSION require "cgi-lib.pl"; &ReadParse; print "The value of the antique is $in{'antique'}.\n"; NEW VERSION use CGI::Simple::Standard qw(:cgi-lib); &ReadParse; print "The value of the antique is $in{'antique'}.\n"; CGI:Simple's B routine creates a variable named %in, which can be accessed to obtain the query variables. Like ReadParse, you can also provide your own variable via a glob. Infrequently used features of B, such as the creation of @in and $in variables, are not supported. You can also use the OO interface of CGI::Simple and call B and other cgi-lib.pl functions like this: &CGI::Simple::ReadParse; # get hash values in %in my $q = new CGI::Simple; $q->ReadParse(); # same thing CGI::Simple::ReadParse(*field); # get hash values in %field function style my $q = new CGI::Simple; $q->ReadParse(*field); # same thing Once you use B under the functional interface , you can retrieve the query object itself this way if needed: $q = $in{'CGI'}; Either way it allows you to start using the more interesting features of CGI.pm without rewriting your old scripts from scratch. Unlike CGI.pm all the cgi-lib.pl functions from Version 2.18 are supported: ReadParse() SplitParam() MethGet() MethPost() MyBaseUrl() MyURL() MyFullUrl() PrintHeader() HtmlTop() HtmlBot() PrintVariables() PrintEnv() CgiDie() CgiError() =head1 COMPATIBILITY WITH CGI.pm I has long been suggested that the CGI and HTML parts of CGI.pm should be split into separate modules (even the author suggests this!), CGI::Simple represents the realization of this and contains the complete CGI side of CGI.pm. Code-wise it weighs in at a little under 30% of the size of CGI.pm at a little under 1000 lines. A great deal of care has been taken to ensure that the interface remains unchanged although a few tweaks have been made. The test suite is extensive and includes all the CGI.pm test scripts as well as a series of new test scripts. You may like to have a look at /t/concur.t which makes 160 tests of CGI::Simple and CGI in parallel and compares the results to ensure they are identical. This is the case as of CGI.pm 2.78. You can't make an omelet without breaking eggs. A large number of methods and global variables have been deleted as detailed below. Some pragmas are also gone. In the tarball there is a script B that will check if a script seems to be using any of these now non existent methods, globals or pragmas. You call it like this: perl check.pl If it finds any likely candidates it will print a line with the line number, problem method/global and the complete line. For example here is some output from running the script on CGI.pm: ... 3162: Problem:'$CGI::OS' local($CRLF) = "\015\012" if $CGI::OS eq 'VMS'; 3165: Problem:'fillBuffer' $self->fillBuffer($FILLUNIT); .... =head1 DIFFERENCES FROM CGI.pm CGI::Simple is strict and warnings compliant. There are 4 modules in this distribution: CGI/Simple.pm supplies all the core code. CGI/Simple/Cookie.pm supplies the cookie handling functions. CGI/Simple/Util.pm supplies a variety of utility functions CGI/Simple/Standard.pm supplies a functional interface for Simple.pm Simple.pm is the core module that provide all the essential functionality. Cookie.pm is a shortened rehash of the CGI.pm module of the same name which supplies the required cookie functionality. Util.pm has been recoded to use an internal object for data storage and supplies rarely needed non core functions and/or functions needed for the HTML side of things. Standard.pm is a wrapper module that supplies a complete functional interface to the OO back end supplied by CGI::Simple. Although a serious attempt has been made to keep the interface identical, some minor changes and tweaks have been made. They will likely be insignificant to most users but here are the gory details. =head2 Globals Variables The list of global variables has been pruned by 75%. Here is the complete list of the global variables used: $VERSION = "0.01"; # set this to 1 to use CGI.pm default global settings $USE_CGI_PM_DEFAULTS = 0 unless defined $USE_CGI_PM_DEFAULTS; # see if user wants old CGI.pm defaults do{ _use_cgi_pm_global_settings(); return } if $USE_CGI_PM_DEFAULTS; # no file uploads by default, set to 0 to enable uploads $DISABLE_UPLOADS = 1 unless defined $DISABLE_UPLOADS; # use a post max of 100K, set to -1 for no limits $POST_MAX = 102_400 unless defined $POST_MAX; # do not include undefined params parsed from query string $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS; # separate the name=value pairs with ; rather than & $USE_PARAM_SEMICOLONS = 0 unless defined $USE_PARAM_SEMICOLONS; # only print headers once $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE; # Set this to 1 to enable NPH scripts $NPH = 0 unless defined $NPH; # 0 => no debug, 1 => from @ARGV, 2 => from STDIN $DEBUG = 0 unless defined $DEBUG; # filter out null bytes in param - value pairs $NO_NULL = 1 unless defined $NO_NULL; # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak $FATAL = -1 unless defined $FATAL; Four of the default values of the old CGI.pm variables have been changed. Unlike CGI.pm which by default allows unlimited POST data and file uploads by default CGI::Simple limits POST data size to 100kB and denies file uploads by default. $USE_PARAM_SEMICOLONS is set to 0 by default so we use (old style) & rather than ; as the pair separator for query strings. Debugging is disabled by default. There are three new global variables. If $NO_NULL is true (the default) then CGI::Simple will strip null bytes out of names, values and keywords. Null bytes can do interesting things to C based code like Perl. Uploaded files are not touched. $FATAL controls the behavior when B is called. The default value of -1 makes errors silent. $USE_CGI_PM_DEFAULTS reverts the defaults to the CGI.pm standard values ie unlimited file uploads via POST for DNS attacks. You can also get the defaults back by using the '-default' pragma in the use: use CGI::Simple qw(-default); use CGI::Simple::Standard qw(-default); The values of the global variables are stored in the CGI::Simple object and can be referenced and changed using the B method like this: my $value = $q->globals( 'VARNAME' ); # get $q->globals( 'VARNAME', 'some value' ); # set As with many CGI.pm methods if you pass the optional value that will be set. The $CGI::Simple::VARNAME = 'N' syntax is only useful prior to calling the B constructor. After that all reference is to the values stored in the CGI::Simple object so you must change these using the B method. $DISABLE_UPLOADS and $POST_MAX *must* be set prior to calling the constructor if you want the changes to have any effect as they control behavior during initialization. This is the same a CGI.pm although some people seem to miss this rather important point and set these after calling the constructor which does nothing. The following globals are no longer relevant and have all been deleted: $AUTOLOADED_ROUTINES $AUTOLOAD_DEBUG $BEEN_THERE $CRLF $DEFAULT_DTD $EBCDIC $FH $FILLUNIT $IIS $IN $INITIAL_FILLUNIT $JSCRIPT $MAC $MAXTRIES $MOD_PERL $NOSTICKY $OS $PERLEX $PRIVATE_TEMPFILES $Q $QUERY_CHARSET $QUERY_PARAM $SCRATCH $SL $SPIN_LOOP_MAX $TIMEOUT $TMPDIRECTORY $XHTML %EXPORT %EXPORT_OK %EXPORT_TAGS %OVERLOAD %QUERY_FIELDNAMES %SUBS @QUERY_PARAM @TEMP Notes: CGI::Simple uses IO::File->new_tmpfile to get tempfile filehandles. These are private by default so $PRIVATE_TEMPFILES is no longer required nor is $TMPDIRECTORY. The value that were stored in $OS, $CRLF, $QUERY_CHARSET and $EBCDIC are now stored in the CGI::Simple::Util object where they find most of their use. The $MOD_PERL and $PERLEX values are now stored in our CGI::Simple object. $IIS was only used once in path_info(). $SL the system specific / \ : path delimiter is not required as we let IO::File handle our tempfile requirements. The rest of the globals are HTML related, export related, hand rolled autoload related or serve obscure purposes in CGI.pm =head2 Changes to pragmas There are some new pragmas available. See the pragmas section for details. The following CGI.pm pragmas are not available: -any -compile -nosticky -no_xhtml -private_tempfiles =head2 Filehandles Unlike CGI.pm which tries to accept all filehandle like objects only \*FH and $fh are accepted by CGI::Simple as file accessors for B and B. IO::File objects work fine. =head2 Hash interface %hash = $q->Vars(); # pack values with "\0"; %hash = $q->Vars(","); # comma separate values You may optionally pass B a string that will be used to separate multiple values when they are packed into the single hash value. If no value is supplied the default "\0" (null byte) will be used. Null bytes are dangerous things for C based code (ie Perl). =head2 cgi-lib.pl All the cgi-lib.pl 2.18 routines are supported. Unlike CGI.pm all the subroutines from cgi-lib.pl are included. They have been GOLFED down to 25 lines but they all work pretty much the same as the originals. =head1 CGI::Simple COMPLETE METHOD LIST Here is a complete list of all the CGI::Simple methods. =head2 Guts (hands off, except of course for new) _initialize_globals _use_cgi_pm_global_settings _store_globals import _reset_globals new _initialize _read_parse _parse_params _add_param _parse_keywordlist _parse_multipart _save_tmpfile _read_data =head2 Core Methods param add_param param_fetch url_param keywords Vars append delete Delete delete_all Delete_all upload upload_info query_string parse_query_string parse_keywordlist =head2 Save and Restore from File Methods _init_from_file save save_parameters =head2 Miscellaneous Methods url_decode url_encode escapeHTML unescapeHTML put print =head2 Cookie Methods cookie raw_cookie =head2 Header Methods header cache no_cache redirect =head2 Server Push Methods multipart_init multipart_start multipart_end multipart_final =head2 Debugging Methods read_from_cmdline Dump as_string cgi_error =head2 cgi-lib.pl Compatibility Routines - all 2.18 functions available _shift_if_ref ReadParse SplitParam MethGet MethPost MyBaseUrl MyURL MyFullUrl PrintHeader HtmlTop HtmlBot PrintVariables PrintEnv CgiDie CgiError =head2 Accessor Methods version nph all_parameters charset crlf # new, returns OS specific CRLF sequence globals # get/set global variables auth_type content_length content_type document_root gateway_interface path_translated referer remote_addr remote_host remote_ident remote_user request_method script_name server_name server_port server_protocol server_software user_name user_agent virtual_host path_info Accept accept http https protocol url self_url state =head1 NEW METHODS IN CGI::Simple There are a few new methods in CGI::Simple as listed below. The highlights are the B method to add the QUERY_STRING data to your object if the method was POST. The B method adds an expires now directive and the Pragma: no-cache directive to the header to encourage some browsers to do the right thing. B from the cgi-lib.pl routines will dump an HTML friendly list of the %ENV and makes a handy addition to B for use in debugging. The upload method now accepts a filepath as an optional second argument as shown in the synopsis. If this is supplied the uploaded file will be written to there automagically. =head2 Internal Routines _initialize_globals() _use_cgi_pm_global_settings() _store_globals() _initialize() _init_from_file() _read_parse() _parse_params() _add_param() _parse_keywordlist() _parse_multipart() _save_tmpfile() _read_data() =head2 New Public Methods add_param() # adds a param/value(s) pair +/- overwrite upload_info() # uploaded files MIME type and size url_decode() # decode s url encoded string url_encode() # url encode a string parse_query_string() # add QUERY_STRING data to $q object if 'POST' no_cache() # add both the Pragma: no-cache # and Expires/Date => 'now' to header =head2 cgi-lib.pl methods added for completeness _shift_if_ref() # internal hack reminiscent of self_or_default :-) MyBaseUrl() MyURL() MyFullUrl() PrintVariables() PrintEnv() CgiDie() CgiError() =head2 New Accessors crlf() # returns CRLF sequence globals() # global vars now stored in $q object - get/set content_length() # returns $ENV{'CONTENT_LENGTH'} document_root() # returns $ENV{'DOCUMENT_ROOT'} gateway_interface() # returns $ENV{'GATEWAY_INTERFACE'} =head1 METHODS IN CGI.pm NOT IN CGI::Simple Here is a complete list of what is not included in CGI::Simple. Basically all the HTML related stuff plus large redundant chunks of the guts. The check.pl script in the /misc dir will check to see if a script is using any of these. =head2 Guts - rearranged, recoded, renamed and hacked out of existence initialize_globals() compile() expand_tags() self_or_default() self_or_CGI() init() to_filehandle() save_request() parse_params() add_parameter() binmode() _make_tag_func() AUTOLOAD() _compile() _setup_symbols() new_MultipartBuffer() read_from_client() import_names() # I dislike this and left it out, so shoot me. =head2 HTML Related autoEscape() URL_ENCODED() MULTIPART() SERVER_PUSH() start_html() _style() _script() end_html() isindex() startform() start_form() end_multipart_form() start_multipart_form() endform() end_form() _textfield() textfield() filefield() password_field() textarea() button() submit() reset() defaults() comment() checkbox() checkbox_group() _tableize() radio_group() popup_menu() scrolling_list() hidden() image_button() nosticky() default_dtd() =head2 Upload Related CGI::Simple uses anonymous tempfiles supplied by IO::File to spool uploaded files to. private_tempfiles() # automatic in CGI::Simple tmpFileName() # all upload files are anonymous uploadInfo() # relied on FH access, replaced with upload_info() =head2 Really Private Subs (marked as so) previous_or_default() register_parameter() get_fields() _set_values_and_labels() _compile_all() asString() compare() =head2 Internal Multipart Parsing Routines read_multipart() readHeader() readBody() read() fillBuffer() eof() =head1 EXPORT Nothing. =head1 AUTHOR INFORMATION Originally copyright 2001 Dr James Freeman Ejfreeman@tassie.net.auE This release by Andy Armstrong This package is free software and is provided "as is" without express or implied warranty. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html) Address bug reports and comments to: andy@hexten.net. When sending bug reports, please provide the version of CGI::Simple, the version of Perl, the name and version of your Web server, and the name and version of the operating system you are using. If the problem is even remotely browser dependent, please provide information about the affected browsers as well. Address bug reports and comments to: andy@hexten.net =head1 CREDITS Lincoln D. Stein (lstein@cshl.org) and everyone else who worked on the original CGI.pm upon which this module is heavily based Brandon Black for some heavy duty testing and bug fixes John D Robinson and Jeroen Latour for helping solve some interesting test failures as well as Perlmonks: tommyw, grinder, Jaap, vek, erasei, jlongino and strider_corinth Thanks for patches to: Ewan Edwards, Joshua N Pritikin, Mike Barry, Michael Nachbaur, Chris Williams, Mark Stosberg, Krasimir Berov, Yamada Masahiro =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Andy Armstrong C<< >>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 SEE ALSO B, L, L, L, L =cut CGI-Simple-1.113/lib/CGI/Simple000755000765000120 011506110167 15150 5ustar00andyadmin000000000000CGI-Simple-1.113/lib/CGI/Simple/Cookie.pm000444000765000120 3472711506110167 17111 0ustar00andyadmin000000000000package CGI::Simple::Cookie; # Original version Copyright 1995-1999, Lincoln D. Stein. All rights reserved. # It may be used and modified freely, but I do request that this copyright # notice remain attached to the file. You may modify this module as you # wish, but if you redistribute a modified version, please attach a note # listing the modifications you have made. # This version Copyright 2001, Dr James Freeman. All rights reserved. # Renamed, strictified, and generally hacked code. Now 30% shorter. # Interface remains identical and passes all original CGI::Cookie tests use strict; use vars '$VERSION'; $VERSION = '1.113'; use CGI::Simple::Util qw(rearrange unescape escape); use overload '""' => \&as_string, 'cmp' => \&compare, 'fallback' => 1; # fetch a list of cookies from the environment and return as a hash. # the cookies are parsed as normal escaped URL data. sub fetch { my $self = shift; my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE}; return () unless $raw_cookie; return $self->parse( $raw_cookie ); } sub parse { my ( $self, $raw_cookie ) = @_; return () unless $raw_cookie; my %results; my @pairs = split "[;,] ?", $raw_cookie; for my $pair ( @pairs ) { # trim leading trailing whitespace $pair =~ s/^\s+//; $pair =~ s/\s+$//; my ( $key, $value ) = split( "=", $pair, 2 ); next if !defined( $value ); my @values = (); if ( $value ne '' ) { @values = map unescape( $_ ), split( /[&;]/, $value . '&dmy' ); pop @values; } $key = unescape( $key ); # A bug in Netscape can cause several cookies with same name to # appear. The FIRST one in HTTP_COOKIE is the most recent version. $results{$key} ||= $self->new( -name => $key, -value => \@values ); } return wantarray ? %results : \%results; } # fetch a list of cookies from the environment and return as a hash. # the cookie values are not unescaped or altered in any way. sub raw_fetch { my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE}; return () unless $raw_cookie; my %results; my @pairs = split "; ?", $raw_cookie; for my $pair ( @pairs ) { $pair =~ s/^\s+|\s+$//; # trim leading trailing whitespace my ( $key, $value ) = split "=", $pair; # fixed bug that does not allow 0 as a cookie value thanks Jose Mico # $value ||= 0; $value = defined $value ? $value : ''; $results{$key} = $value; } return wantarray ? %results : \%results; } sub new { my ( $class, @params ) = @_; $class = ref( $class ) || $class; my ( $name, $value, $path, $domain, $secure, $expires, $max_age, $httponly ) = rearrange( [ 'NAME', [ 'VALUE', 'VALUES' ], 'PATH', 'DOMAIN', 'SECURE', 'EXPIRES', 'MAX-AGE', 'HTTPONLY' ], @params ); return undef unless defined $name and defined $value; my $self = {}; bless $self, $class; $self->name( $name ); $self->value( $value ); $path ||= "/"; $self->path( $path ) if defined $path; $self->domain( $domain ) if defined $domain; $self->secure( $secure ) if defined $secure; $self->expires( $expires ) if defined $expires; $self->max_age( $expires ) if defined $max_age; $self->httponly( $httponly ) if defined $httponly; return $self; } sub as_string { my $self = shift; return "" unless $self->name; my $name = escape( $self->name ); my $value = join "&", map { escape( $_ ) } $self->value; my @cookie = ( "$name=$value" ); push @cookie, "domain=" . $self->domain if $self->domain; push @cookie, "path=" . $self->path if $self->path; push @cookie, "expires=" . $self->expires if $self->expires; push @cookie, "max-age=" . $self->max_age if $self->max_age; push @cookie, "secure" if $self->secure; push @cookie, "HttpOnly" if $self->httponly; return join "; ", @cookie; } sub compare { my ( $self, $value ) = @_; return "$self" cmp $value; } # accessors subs sub name { my ( $self, $name ) = @_; $self->{'name'} = $name if defined $name; return $self->{'name'}; } sub value { my ( $self, $value ) = @_; if ( defined $value ) { my @values = ref $value eq 'ARRAY' ? @$value : ref $value eq 'HASH' ? %$value : ( $value ); $self->{'value'} = [@values]; } return wantarray ? @{ $self->{'value'} } : $self->{'value'}->[0]; } sub domain { my ( $self, $domain ) = @_; $self->{'domain'} = $domain if defined $domain; return $self->{'domain'}; } sub secure { my ( $self, $secure ) = @_; $self->{'secure'} = $secure if defined $secure; return $self->{'secure'}; } sub expires { my ( $self, $expires ) = @_; $self->{'expires'} = CGI::Simple::Util::expires( $expires, 'cookie' ) if defined $expires; return $self->{'expires'}; } sub max_age { my ( $self, $max_age ) = @_; $self->{'max-age'} = CGI::Simple::Util::_expire_calc( $max_age ) - time() if defined $max_age; return $self->{'max-age'}; } sub path { my ( $self, $path ) = @_; $self->{'path'} = $path if defined $path; return $self->{'path'}; } sub httponly { my ( $self, $httponly ) = @_; $self->{'httponly'} = $httponly if defined $httponly; return $self->{'httponly'}; } 1; __END__ =head1 NAME CGI::Simple::Cookie - Interface to HTTP cookies =head1 SYNOPSIS use CGI::Simple::Standard qw(header); use CGI::Simple::Cookie; # Create new cookies and send them $cookie1 = CGI::Simple::Cookie->new( -name=>'ID', -value=>123456 ); $cookie2 = CGI::Simple::Cookie->new( -name=>'preferences', -value=>{ font => Helvetica, size => 12 } ); print header( -cookie=>[$cookie1,$cookie2] ); # fetch existing cookies %cookies = CGI::Simple::Cookie->fetch; $id = $cookies{'ID'}->value; # create cookies returned from an external source %cookies = CGI::Simple::Cookie->parse($ENV{COOKIE}); =head1 DESCRIPTION CGI::Simple::Cookie is an interface to HTTP/1.1 cookies, a mechanism that allows Web servers to store persistent information on the browser's side of the connection. Although CGI::Simple::Cookie is intended to be used in conjunction with CGI::Simple (and is in fact used by it internally), you can use this module independently. For full information on cookies see: http://tools.ietf.org/html/rfc2109 http://tools.ietf.org/html/rfc2965 =head1 USING CGI::Simple::Cookie CGI::Simple::Cookie is object oriented. Each cookie object has a name and a value. The name is any scalar value. The value is any scalar or array value (associative arrays are also allowed). Cookies also have several optional attributes, including: =over 4 =item B<1. expiration date> The expiration date tells the browser how long to hang on to the cookie. If the cookie specifies an expiration date in the future, the browser will store the cookie information in a disk file and return it to the server every time the user reconnects (until the expiration date is reached). If the cookie species an expiration date in the past, the browser will remove the cookie from the disk file. If the expiration date is not specified, the cookie will persist only until the user quits the browser. =item B<2. domain> This is a partial or complete domain name for which the cookie is valid. The browser will return the cookie to any host that matches the partial domain name. For example, if you specify a domain name of ".capricorn.com", then the browser will return the cookie to web servers running on any of the machines "www.capricorn.com", "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names must contain at least two periods to prevent attempts to match on top level domains like ".edu". If no domain is specified, then the browser will only return the cookie to servers on the host the cookie originated from. =item B<3. path> If you provide a cookie path attribute, the browser will check it against your script's URL before returning the cookie. For example, if you specify the path "/cgi-bin", then the cookie will be returned to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl", but not to the script "/cgi-private/site_admin.pl". By default, the path is set to "/", so that all scripts at your site will receive the cookie. =item B<4. secure flag> If the "secure" attribute is set, the cookie will only be sent to your script if the CGI request is occurring on a secure channel, such as SSL. =item B<4. HttpOnly flag> If the "httponly" attribute is set, the cookie will only be accessible through HTTP Requests. This cookie will be inaccessible via JavaScript (to prevent XSS attacks). See this URL for more information including supported browsers: L =back =head2 Creating New Cookies $c = CGI::Simple::Cookie->new( -name => 'foo', -value => 'bar', -expires => '+3M', -domain => '.capricorn.com', -path => '/cgi-bin/database', -secure => 1 ); Create cookies from scratch with the B method. The B<-name> and B<-value> parameters are required. The name must be a scalar value. The value can be a scalar, an array reference, or a hash reference. (At some point in the future cookies will support one of the Perl object serialization protocols for full generality). B<-expires> accepts any of the relative or absolute date formats recognized by CGI::Simple, for example "+3M" for three months in the future. See CGI::Simple's documentation for details. B<-max-age> accepts the same data formats as B<< -expires >>, but sets a relative value instead of an absolute like B<< -expires >>. This is intended to be more secure since a clock could be changed to fake an absolute time. In practice, as of 2011, C<< -max-age >> still does not enjoy the widespread support that C<< -expires >> has. You can set both, and browsers that support C<< -max-age >> should ignore the C<< Expires >> header. The drawback to this approach is the bit of bandwidth for sending an extra header on each cookie. B<-domain> points to a domain name or to a fully qualified host name. If not specified, the cookie will be returned only to the Web server that created it. B<-path> points to a partial URL on the current server. The cookie will be returned to all URLs beginning with the specified path. If not specified, it defaults to '/', which returns the cookie to all pages at your site. B<-secure> if set to a true value instructs the browser to return the cookie only when a cryptographic protocol is in use. B<-httponly> if set to a true value, the cookie will not be accessible via JavaScript. =head2 Sending the Cookie to the Browser Within a CGI script you can send a cookie to the browser by creating one or more Set-Cookie: fields in the HTTP header. Here is a typical sequence: $c = CGI::Simple::Cookie->new( -name => 'foo', -value => ['bar','baz'], -expires => '+3M' ); print "Set-Cookie: $c\n"; print "Content-Type: text/html\n\n"; To send more than one cookie, create several Set-Cookie: fields. Alternatively, you may concatenate the cookies together with "; " and send them in one field. If you are using CGI::Simple, you send cookies by providing a -cookie argument to the header() method: print header( -cookie=>$c ); Mod_perl users can set cookies using the request object's header_out() method: $r->header_out('Set-Cookie',$c); Internally, Cookie overloads the "" operator to call its as_string() method when incorporated into the HTTP header. as_string() turns the Cookie's internal representation into an RFC-compliant text representation. You may call as_string() yourself if you prefer: print "Set-Cookie: ",$c->as_string,"\n"; =head2 Recovering Previous Cookies %cookies = CGI::Simple::Cookie->fetch; B returns an associative array consisting of all cookies returned by the browser. The keys of the array are the cookie names. You can iterate through the cookies this way: %cookies = CGI::Simple::Cookie->fetch; foreach (keys %cookies) { do_something($cookies{$_}); } In a scalar context, fetch() returns a hash reference, which may be more efficient if you are manipulating multiple cookies. CGI::Simple uses the URL escaping methods to save and restore reserved characters in its cookies. If you are trying to retrieve a cookie set by a foreign server, this escaping method may trip you up. Use raw_fetch() instead, which has the same semantics as fetch(), but performs no unescaping. You may also retrieve cookies that were stored in some external form using the parse() class method: $COOKIES = `cat /usr/tmp/Cookie_stash`; %cookies = CGI::Simple::Cookie->parse($COOKIES); =head2 Manipulating Cookies Cookie objects have a series of accessor methods to get and set cookie attributes. Each accessor has a similar syntax. Called without arguments, the accessor returns the current value of the attribute. Called with an argument, the accessor changes the attribute and returns its new value. =over 4 =item B Get or set the cookie's name. Example: $name = $c->name; $new_name = $c->name('fred'); =item B Get or set the cookie's value. Example: $value = $c->value; @new_value = $c->value(['a','b','c','d']); B is context sensitive. In a list context it will return the current value of the cookie as an array. In a scalar context it will return the B value of a multivalued cookie. =item B Get or set the cookie's domain. =item B Get or set the cookie's path. =item B Get or set the cookie's expiration time. =item B Get or set the cookie's maximum age. =item B Get or set the cookie's secure flag. =item B Get or set the cookie's HttpOnly flag. =back =head1 AUTHOR INFORMATION Original version copyright 1997-1998, Lincoln D. Stein. All rights reserved. Originally copyright 2001 Dr James Freeman Ejfreeman@tassie.net.auE This release by Andy Armstrong This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Address bug reports and comments to: andy@hexten.net =head1 BUGS This section intentionally left blank :-) =head1 SEE ALSO L, L =cut CGI-Simple-1.113/lib/CGI/Simple/Standard.pm000444000765000120 3627111506110167 17434 0ustar00andyadmin000000000000package CGI::Simple::Standard; use strict; use CGI::Simple; use Carp; use vars qw( $VERSION $USE_CGI_PM_DEFAULTS $DISABLE_UPLOADS $POST_MAX $NO_UNDEF_PARAMS $USE_PARAM_SEMICOLONS $HEADERS_ONCE $NPH $DEBUG $NO_NULL $FATAL *in %EXPORT_TAGS $AUTOLOAD ); $VERSION = "1.113"; %EXPORT_TAGS = ( ':html' => [qw(:misc)], ':standard' => [qw(:core :access)], ':cgi' => [qw(:core :access)], ':all' => [ qw(:core :misc :cookie :header :push :debug :cgi-lib :access :internal) ], ':core' => [ qw(param add_param param_fetch url_param keywords append Delete delete_all Delete_all upload query_string parse_query_string parse_keywordlist Vars save_parameters restore_parameters) ], ':misc' => [qw(url_decode url_encode escapeHTML unescapeHTML put)], ':cookie' => [qw(cookie raw_cookie)], ':header' => [qw(header cache no_cache redirect)], ':push' => [ qw(multipart_init multipart_start multipart_end multipart_final) ], ':debug' => [qw(Dump as_string cgi_error _cgi_object)], ':cgi-lib' => [ qw(ReadParse SplitParam MethGet MethPost MyBaseUrl MyURL MyFullUrl PrintHeader HtmlTop HtmlBot PrintVariables PrintEnv CgiDie CgiError Vars) ], ':ssl' => [qw(https)], ':access' => [ qw(version nph all_parameters charset crlf globals auth_type content_length content_type document_root gateway_interface path_translated referer remote_addr remote_host remote_ident remote_user request_method script_name server_name server_port server_protocol server_software user_name user_agent virtual_host path_info Accept http https protocol url self_url state) ], ':internal' => [ qw(_initialize_globals _use_cgi_pm_global_settings _store_globals _reset_globals) ] ); # BEGIN { # $SIG{__DIE__} = sub { croak "Undefined Method : @_\n" } # } sub import { my ( $self, @args ) = @_; my $package = caller(); my ( %exports, %pragmas ); for my $arg ( @args ) { $exports{$arg}++, next if $arg =~ m/^\w+$/; $pragmas{$arg}++, next if $arg =~ m/^-\w+$/; if ( $arg =~ m/^:[-\w]+$/ ) { if ( exists $EXPORT_TAGS{$arg} ) { my @tags = @{ $EXPORT_TAGS{$arg} }; for my $tag ( @tags ) { my @expanded = exists $EXPORT_TAGS{$tag} ? @{ $EXPORT_TAGS{$tag} } : ( $tag ); $exports{$_}++ for @expanded; } } else { croak "No '$arg' tag set available for export from CGI::Simple::Standard!\n"; } } } my @exports = keys %exports; my %valid_exports; for my $tag ( @{ $EXPORT_TAGS{':all'} } ) { $valid_exports{$_}++ for @{ $EXPORT_TAGS{$tag} }; } for ( @exports ) { croak "'$_' is not an available export method from CGI::Simple::Standard!\n" unless exists $valid_exports{$_}; } no strict 'refs'; if ( exists $pragmas{'-autoload'} ) { # hack symbol table to export our AUTOLOAD sub *{"${package}::AUTOLOAD"} = sub { my ( $caller, $sub ) = $AUTOLOAD =~ m/(.*)::(\w+)$/; &CGI::Simple::Standard::loader( $caller, $sub, @_ ); }; delete $pragmas{'-autoload'}; } my @pragmas = keys %pragmas; CGI::Simple->import( @pragmas ) if @pragmas; # export subroutine stubs for all the desired export functions # we will replace them in the symbol table with the real thing # if and when they are first called for my $i ( 0 .. $#exports ) { *{"${package}::$exports[$i]"} = sub { my $caller = caller; &CGI::Simple::Standard::loader( $caller, $exports[$i], @_ ); } } } # loader() may be called either via our exported AUTOLOAD sub or by the # subroutine stubs we exported on request. It has three functions: # 1) to initialize and store (via a closure) our CGI::Simple object # 2) to overwrite the exported subroutine stubs with calls to the real ones # 3) to provide two 'virtual' methods - _cgi_object() and restore_parameters() # restore_parameters effectively functions like new() for the OO interface. { my $q; sub loader { my $package = shift; my $sub = shift; if ( $sub eq '_cgi_object' ) { # for debugging get at the object $q = new CGI::Simple( @_ ) unless $q; return $q; } if ( !$q or $sub eq 'restore_parameters' ) { if ( $sub eq 'restore_parameters' ) { $q = new CGI::Simple( @_ ); return; } else { $q = new CGI::Simple; } } # hack the symbol table and insert the sub so we only use loader once # get strict to look the other way while we use sym refs no strict 'refs'; # stop warnings screaming about redefined subs local $^W = 0; # hack to ensure %in ends in right package when exported by ReadParse @_ = ( *{"${package}::in"} ) if $sub eq 'ReadParse' and !@_; # write the required sub to the callers symbol table *{"${package}::$sub"} = sub { $q->$sub( @_ ) }; # now we have inserted the sub let's call it and return the results :-) return &{"${package}::$sub"}; } } 1; =head1 NAME CGI::Simple::Standard - a wrapper module for CGI::Simple that provides a function style interface =head1 SYNOPSIS use CGI::Simple::Standard qw( -autoload ); use CGI::Simple::Standard qw( :core :cookie :header :misc ); use CGI::Simple::Standard qw( param upload ); $CGI::Simple::Standard::POST_MAX = 1024; # max upload via post 1kB $CGI::Simple::Standard::DISABLE_UPLOADS = 0; # enable uploads @params = param(); # return all param names as a list $value = param('foo'); # return the first value supplied for 'foo' @values = param('foo'); # return all values supplied for foo %fields = Vars(); # returns untied key value pair hash $hash_ref = Vars(); # or as a hash ref %fields = Vars("|"); # packs multiple values with "|" rather than "\0"; @keywords = keywords(); # return all keywords as a list param( 'foo', 'some', 'new', 'values' ); # set new 'foo' values param( -name=>'foo', -value=>'bar' ); param( -name=>'foo', -value=>['bar','baz'] ); append( -name=>'foo', -value=>'bar' ); # append values to 'foo' append( -name=>'foo', -value=>['some', 'new', 'values'] ); Delete('foo'); # delete param 'foo' and all its values Delete_all(); # delete everything $files = upload() # number of files uploaded @files = upload(); # names of all uploaded files $filename = param('upload_file') # filename of 'upload_file' field $mime = upload_info($filename,'mime'); # MIME type of uploaded file $size = upload_info($filename,'size'); # size of uploaded file my $fh = $q->upload($filename); # open filehandle to read from while ( read( $fh, $buffer, 1024 ) ) { ... } # short and sweet upload $ok = upload( param('upload_file'), '/path/to/write/file.name' ); print "Uploaded ".param('upload_file')." and wrote it OK!" if $ok; $decoded = url_decode($encoded); $encoded = url_encode($unencoded); $escaped = escapeHTML('<>"&'); $unescaped = unescapeHTML('<>"&'); $qs = query_string(); # get all data in $q as a query string OK for GET no_cache(1); # set Pragma: no-cache + expires print header(); # print a simple header # get a complex header $header = header( -type => 'image/gif' -nph => 1, -status => '402 Payment required', -expires =>'+24h', -cookie => $cookie, -charset => 'utf-7', -attachment => 'foo.gif', -Cost => '$2.00'); @cookies = cookie(); # get names of all available cookies $value = cookie('foo') # get first value of cookie 'foo' @value = cookie('foo') # get all values of cookie 'foo' # get a cookie formatted for header() method $cookie = cookie( -name => 'Password', -values => ['superuser','god','my dog woofie'], -expires => '+3d', -domain => '.nowhere.com', -path => '/cgi-bin/database', -secure => 1 ); print header( -cookie=>$cookie ); # set cookie print redirect('http://go.away.now'); # print a redirect header dienice( cgi_error() ) if cgi_error(); =head1 DESCRIPTION This module is a wrapper for the completely object oriented CGI::Simple module and provides a simple functional style interface. It provides two different methods to import function names into your namespace. =head2 Autoloading If you specify the '-autoload' pragma like this: use CGI::Simple::Standard qw( -autoload ); Then it will use AUTOLOAD and a symbol table trick to export only those subs you actually call into your namespace. When you specify the '-autoload' pragma this module exports a single AUTOLOAD subroutine into you namespace. This will clash with any AUTOLOAD sub that exists in the calling namespace so if you are using AUTOLOAD for something else don't use this pragma. Anyway, when you call a subroutine that is not defined in your script this AUTOLOAD sub will be called. The first time this happens it will initialize a CGI::Simple object and then apply the requested method (if it exists) to it. A fatal exception will be thrown if you try to use an undefined method (function). =head2 Specified Export Alternatively you can specify the functions you wish to import. You can do this on a per function basis like this: use CGI::Simple::Standard qw( param upload query_string Dump ); or utilize the %EXPORT_TAGS that group functions into related groups. Here are the groupings: %EXPORT_TAGS = ( ':html' => [ qw(:misc) ], ':standard' => [ qw(:core :access) ], ':cgi' => [ qw(:core :access) ], ':all' => [ qw(:core :misc :cookie :header :push :debug :cgi-lib :access :internal) ], ':core' => [ qw(param add_param param_fetch url_param keywords append Delete delete_all Delete_all upload query_string parse_query_string parse_keywordlist Vars save_parameters restore_parameters) ], ':misc' => [ qw(url_decode url_encode escapeHTML unescapeHTML put) ], ':cookie' => [ qw(cookie raw_cookie) ], ':header' => [ qw(header cache no_cache redirect) ], ':push' => [ qw(multipart_init multipart_start multipart_end multipart_final) ], ':debug' => [ qw(Dump as_string cgi_error _cgi_object) ], ':cgi-lib' => [ qw(ReadParse SplitParam MethGet MethPost MyBaseUrl MyURL MyFullUrl PrintHeader HtmlTop HtmlBot PrintVariables PrintEnv CgiDie CgiError Vars) ], ':ssl' => [ qw(https) ], ':access' => [ qw(version nph all_parameters charset crlf globals auth_type content_length content_type document_root gateway_interface path_translated referer remote_addr remote_host remote_ident remote_user request_method script_name server_name server_port server_protocol server_software user_name user_agent virtual_host path_info Accept http https protocol url self_url state) ], ':internal' => [ qw(_initialize_globals _use_cgi_pm_global_settings _store_globals _reset_globals) ] ); The familiar CGI.pm tags are available but do not include the HTML functionality. You specify the import of some function groups like this: use CGI::Simple::Standard qw( :core :cookie :header ); Note that the function groups all start with a : char. =head2 Mix and Match You can use the '-autoload' pragma, specifically named function imports and tag group imports together if you desire. =head1 $POST_MAX and $DISABLE_UPLOADS If you wish to set $POST_MAX or $DISABLE_UPLOADS you must do this *after* the use statement and *before* the first function call as shown in the synopsis. Unlike CGI.pm uploads are disabled by default and the maximum acceptable data via post is capped at 102_400kB rather than infinity. This is specifically to avoid denial of service attacks by default. To enable uploads and to allow them to be of infinite size you simply: $CGI::Simple::Standard::POST_MAX = -1; # infinite size upload $CGI::Simple::Standard::$DISABLE_UPLOADS = 0; # enable uploads Alternatively you can specify the CGI.pm default values as shown above by specifying the '-default' pragma in your use statement. use CGI::Simple::Standard qw( -default ..... ); =head1 EXPORT Nothing by default. Under the '-autoload' pragma the AUTOLOAD subroutine is exported into the calling namespace. Additional subroutines are only imported into this namespace if you physically call them. They are installed in the symbol table the first time you use them to save repeated calls to AUTOLOAD. If you specifically request a function or group of functions via an EXPORT_TAG then stubs of these functions are exported into the calling namespace. These stub functions will be replaced with the real functions only if you actually call them saving wasted compilation effort. =head1 FUNCTION DETAILS This is a wrapper module for CGI::Simple. Virtually all the methods available in the OO interface are available via the functional interface. Several method names are aliased to prevent namespace conflicts: $q->delete('foo') => Delete('foo') $q->delete_all => Delete_all() or delete_all() $q->save(\*FH) => save_parameters(\*FH) $q->accept() => Accept() Although you could use the new() function to genrate new OO CGI::Simple objects the restore_parameters() function is a better choice as it operates like new but on the correct underlying CGI::Simple object for the functional interface. restore_parameters() can be used exactly as you might use new() in that you can supply arguments to it such as query strings, hashes and file handles to re-initialize your underlying object. $q->new CGI::Simple() => restore_parameters() $q->new CGI::Simple({foo=>'bar'}) => restore_parameters({foo=>'bar'}) $q->new CGI::Simple($query_string) => restore_parameters($query_string) $q->new CGI::Simple(\*FH) => restore_parameters(\*FH) For full details of the available functions see the CGI::Simple docs. Just remove the $q-> part and use the method name directly. =head1 BUGS As this is 0.01 there are almost bound to be some. =head1 AUTHOR Dr James Freeman Ejfreeman@tassie.net.auE This release by Andy Armstrong This package is free software and is provided "as is" without express or implied warranty. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html) Address bug reports and comments to: andy@hexten.net =head1 CREDITS The interface and key sections of the CGI::Simple code come from CGI.pm by Lincoln Stein. =head1 SEE ALSO L which is the back end for this module, B =cut CGI-Simple-1.113/lib/CGI/Simple/Util.pm000444000765000120 3261711506110167 16611 0ustar00andyadmin000000000000package CGI::Simple::Util; use strict; use vars qw( $VERSION @EXPORT_OK @ISA $UTIL ); $VERSION = '1.113'; require Exporter; @ISA = qw( Exporter ); @EXPORT_OK = qw( rearrange make_attributes expires escapeHTML unescapeHTML escape unescape ); sub rearrange { my ( $order, @params ) = @_; my ( %pos, @result, %leftover ); return () unless @params; if ( ref $params[0] eq 'HASH' ) { @params = %{ $params[0] }; } else { return @params unless $params[0] =~ m/^-/; } # map parameters into positional indices my $i = 0; for ( @$order ) { for ( ref( $_ ) eq 'ARRAY' ? @$_ : $_ ) { $pos{ lc( $_ ) } = $i; } $i++; } $#result = $#$order; # preextend while ( @params ) { my $key = lc( shift( @params ) ); $key =~ s/^\-//; if ( exists $pos{$key} ) { $result[ $pos{$key} ] = shift( @params ); } else { $leftover{$key} = shift( @params ); } } push @result, make_attributes( \%leftover, 1 ) if %leftover; return @result; } sub make_attributes { my $attref = shift; my $escape = shift || 0; return () unless $attref && ref $attref eq 'HASH'; my @attrib; for my $key ( keys %{$attref} ) { ( my $mod_key = $key ) =~ s/^-//; # get rid of initial - if present $mod_key = lc $mod_key; # parameters are lower case $mod_key =~ tr/_/-/; # use dashes my $value = $escape ? escapeHTML( $attref->{$key} ) : $attref->{$key}; push @attrib, defined $value ? qq/$mod_key="$value"/ : $mod_key; } return @attrib; } # This internal routine creates date strings suitable for use in # cookies and HTTP headers. (They differ, unfortunately.) # Thanks to Mark Fisher for this. sub expires { my ( $time, $format ) = @_; $format ||= 'http'; my @MON = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my @WDAY = qw( Sun Mon Tue Wed Thu Fri Sat ); # pass through preformatted dates for the sake of expire_calc() $time = _expire_calc( $time ); return $time unless $time =~ /^\d+$/; # make HTTP/cookie date string from GMT'ed time # (cookies use '-' as date separator, HTTP uses ' ') my $sc = $format eq 'cookie' ? '-' : ' '; my ( $sec, $min, $hour, $mday, $mon, $year, $wday ) = gmtime( $time ); $year += 1900; return sprintf( "%s, %02d$sc%s$sc%04d %02d:%02d:%02d GMT", $WDAY[$wday], $mday, $MON[$mon], $year, $hour, $min, $sec ); } # This internal routine creates an expires time exactly some number of # hours from the current time. It incorporates modifications from Mark Fisher. # format for time can be in any of the forms... # "now" -- expire immediately # "+180s" -- in 180 seconds # "+2m" -- in 2 minutes # "+12h" -- in 12 hours # "+1d" -- in 1 day # "+3M" -- in 3 months # "+2y" -- in 2 years # "-3m" -- 3 minutes ago(!) # If you don't supply one of these forms, we assume you are specifying # the date yourself sub _expire_calc { my ( $time ) = @_; my %mult = ( 's' => 1, 'm' => 60, 'h' => 60 * 60, 'd' => 60 * 60 * 24, 'M' => 60 * 60 * 24 * 30, 'y' => 60 * 60 * 24 * 365 ); my $offset; if ( !$time or lc $time eq 'now' ) { $offset = 0; } elsif ( $time =~ /^\d+/ ) { return $time; } elsif ( $time =~ /^([+-]?(?:\d+|\d*\.\d*))([mhdMy]?)/ ) { $offset = ( $mult{$2} || 1 ) * $1; } else { return $time; } my $cur_time = time; return ( $cur_time + $offset ); } sub escapeHTML { my ( $escape, $text ) = @_; return undef unless defined $escape; $escape =~ s/&/&/g; $escape =~ s/"/"/g; $escape =~ s//>/g; # these next optional escapes make text look the same when rendered in HTML if ( $text ) { $escape =~ s/\t/ /g; # tabs to 4 spaces $escape =~ s/( {2,})/" " x length $1/eg; # whitespace escapes $escape =~ s/\n/
\n/g; # newlines to
} return $escape; } sub unescapeHTML { my ( $unescape ) = @_; return undef unless defined( $unescape ); my $latin = $UTIL->{'charset'} =~ /^(?:ISO-8859-1|WINDOWS-1252)$/i; my $ebcdic = $UTIL->{'ebcdic'}; # credit to Randal Schwartz for original version of this $unescape =~ s[&(.*?);]{ local $_ = $1; /^amp$/i ? "&" : /^quot$/i ? '"' : /^gt$/i ? ">" : /^lt$/i ? "<" : /^#(\d+)$/ && $latin ? chr($1) : /^#(\d+)$/ && $ebcdic ? chr($UTIL->{'a2e'}->[$1]) : /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) : /^#x([0-9a-f]+)$/i && $ebcdic ? chr($UTIL->{'a2e'}->[hex $1]) : "\&$_;" }gex; return $unescape; } # URL-encode data sub escape { my ( $toencode ) = @_; return undef unless defined $toencode; if ( $UTIL->{'ebcdic'} ) { $toencode =~ s/([^a-zA-Z0-9_.-])/uc sprintf "%%%02x", $UTIL->{'e2a'}->[ord $1]/eg; } else { $toencode =~ s/([^a-zA-Z0-9_.-])/uc sprintf "%%%02x", ord $1 /eg; } return $toencode; } # unescape URL-encoded data sub unescape { my ( $todecode ) = @_; return undef unless defined $todecode; $todecode =~ tr/+/ /; if ( $UTIL->{'ebcdic'} ) { $todecode =~ s/%([0-9a-fA-F]{2})/chr $UTIL->{'a2e'}->[hex $1]/ge; } else { $todecode =~ s/%(?:([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/ defined($1)? chr hex($1) : utf8_chr(hex($2))/ge; } return $todecode; } sub utf8_chr ($) { my $c = shift; if ( $c < 0x80 ) { return sprintf( "%c", $c ); } elsif ( $c < 0x800 ) { return sprintf( "%c%c", 0xc0 | ( $c >> 6 ), 0x80 | ( $c & 0x3f ) ); } elsif ( $c < 0x10000 ) { return sprintf( "%c%c%c", 0xe0 | ( $c >> 12 ), 0x80 | ( ( $c >> 6 ) & 0x3f ), 0x80 | ( $c & 0x3f ) ); } elsif ( $c < 0x200000 ) { return sprintf( "%c%c%c%c", 0xf0 | ( $c >> 18 ), 0x80 | ( ( $c >> 12 ) & 0x3f ), 0x80 | ( ( $c >> 6 ) & 0x3f ), 0x80 | ( $c & 0x3f ) ); } elsif ( $c < 0x4000000 ) { return sprintf( "%c%c%c%c%c", 0xf8 | ( $c >> 24 ), 0x80 | ( ( $c >> 18 ) & 0x3f ), 0x80 | ( ( $c >> 12 ) & 0x3f ), 0x80 | ( ( $c >> 6 ) & 0x3f ), 0x80 | ( $c & 0x3f ) ); } elsif ( $c < 0x80000000 ) { return sprintf( "%c%c%c%c%c%c", 0xfc | ( $c >> 30 ), # was 0xfe patch Thomas L. Shinnick 0x80 | ( ( $c >> 24 ) & 0x3f ), 0x80 | ( ( $c >> 18 ) & 0x3f ), 0x80 | ( ( $c >> 12 ) & 0x3f ), 0x80 | ( ( $c >> 6 ) & 0x3f ), 0x80 | ( $c & 0x3f ) ); } else { return utf8( 0xfffd ); } } # We need to define a number of things about the operating environment so # we do this on first initialization and store the results in in an object BEGIN { $UTIL = new CGI::Simple::Util; # initialize our $UTIL object sub new { my $class = shift; $class = ref( $class ) || $class; my $self = {}; bless $self, $class; $self->init; return $self; } sub init { my $self = shift; $self->charset; $self->os; $self->ebcdic; } sub charset { my ( $self, $charset ) = @_; $self->{'charset'} = $charset if $charset; $self->{'charset'} ||= 'ISO-8859-1'; # set to the safe ISO-8859-1 if not defined return $self->{'charset'}; } sub os { my ( $self, $OS ) = @_; $self->{'os'} = $OS if $OS; # allow value to be set manually $OS = $self->{'os'}; unless ( $OS ) { unless ( $OS = $^O ) { require Config; $OS = $Config::Config{'osname'}; } if ( $OS =~ /Win/i ) { $OS = 'WINDOWS'; } elsif ( $OS =~ /vms/i ) { $OS = 'VMS'; } elsif ( $OS =~ /bsdos/i ) { $OS = 'UNIX'; } elsif ( $OS =~ /dos/i ) { $OS = 'DOS'; } elsif ( $OS =~ /^MacOS$/i ) { $OS = 'MACINTOSH'; } elsif ( $OS =~ /os2/i ) { $OS = 'OS2'; } else { $OS = 'UNIX'; } } return $self->{'os'} = $OS; } sub ebcdic { my $self = shift; return $self->{'ebcdic'} if exists $self->{'ebcdic'}; $self->{'ebcdic'} = "\t" ne "\011" ? 1 : 0; if ( $self->{'ebcdic'} ) { # (ord('^') == 95) for codepage 1047 as on os390, vmesa my @A2E = ( 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31, 64, 90, 127, 123, 91, 108, 80, 125, 77, 93, 92, 78, 107, 96, 75, 97, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 122, 94, 76, 126, 110, 111, 124, 193, 194, 195, 196, 197, 198, 199, 200, 201, 209, 210, 211, 212, 213, 214, 215, 216, 217, 226, 227, 228, 229, 230, 231, 232, 233, 173, 224, 189, 95, 109, 121, 129, 130, 131, 132, 133, 134, 135, 136, 137, 145, 146, 147, 148, 149, 150, 151, 152, 153, 162, 163, 164, 165, 166, 167, 168, 169, 192, 79, 208, 161, 7, 32, 33, 34, 35, 36, 37, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27, 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62, 255, 65, 170, 74, 177, 159, 178, 106, 181, 187, 180, 154, 138, 176, 202, 175, 188, 144, 143, 234, 250, 190, 160, 182, 179, 157, 218, 155, 139, 183, 184, 185, 171, 100, 101, 98, 102, 99, 103, 158, 104, 116, 113, 114, 115, 120, 117, 118, 119, 172, 105, 237, 238, 235, 239, 236, 191, 128, 253, 254, 251, 252, 186, 174, 89, 68, 69, 66, 70, 67, 71, 156, 72, 84, 81, 82, 83, 88, 85, 86, 87, 140, 73, 205, 206, 203, 207, 204, 225, 112, 221, 222, 219, 220, 141, 142, 223 ); my @E2A = ( 0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, 16, 17, 18, 19, 157, 10, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, 128, 129, 130, 131, 132, 133, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, 144, 145, 22, 147, 148, 149, 150, 4, 152, 153, 154, 155, 20, 21, 158, 26, 32, 160, 226, 228, 224, 225, 227, 229, 231, 241, 162, 46, 60, 40, 43, 124, 38, 233, 234, 235, 232, 237, 238, 239, 236, 223, 33, 36, 42, 41, 59, 94, 45, 47, 194, 196, 192, 193, 195, 197, 199, 209, 166, 44, 37, 95, 62, 63, 248, 201, 202, 203, 200, 205, 206, 207, 204, 96, 58, 35, 64, 39, 61, 34, 216, 97, 98, 99, 100, 101, 102, 103, 104, 105, 171, 187, 240, 253, 254, 177, 176, 106, 107, 108, 109, 110, 111, 112, 113, 114, 170, 186, 230, 184, 198, 164, 181, 126, 115, 116, 117, 118, 119, 120, 121, 122, 161, 191, 208, 91, 222, 174, 172, 163, 165, 183, 169, 167, 182, 188, 189, 190, 221, 168, 175, 93, 180, 215, 123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 173, 244, 246, 242, 243, 245, 125, 74, 75, 76, 77, 78, 79, 80, 81, 82, 185, 251, 252, 249, 250, 255, 92, 247, 83, 84, 85, 86, 87, 88, 89, 90, 178, 212, 214, 210, 211, 213, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 179, 219, 220, 217, 218, 159 ); if ( ord( '^' ) == 106 ) { # as in the BS2000 posix-bc coded character set $A2E[91] = 187; $A2E[92] = 188; $A2E[94] = 106; $A2E[96] = 74; $A2E[123] = 251; $A2E[125] = 253; $A2E[126] = 255; $A2E[159] = 95; $A2E[162] = 176; $A2E[166] = 208; $A2E[168] = 121; $A2E[172] = 186; $A2E[175] = 161; $A2E[217] = 224; $A2E[219] = 221; $A2E[221] = 173; $A2E[249] = 192; $E2A[74] = 96; $E2A[95] = 159; $E2A[106] = 94; $E2A[121] = 168; $E2A[161] = 175; $E2A[173] = 221; $E2A[176] = 162; $E2A[186] = 172; $E2A[187] = 91; $E2A[188] = 92; $E2A[192] = 249; $E2A[208] = 166; $E2A[221] = 219; $E2A[224] = 217; $E2A[251] = 123; $E2A[253] = 125; $E2A[255] = 126; } elsif ( ord( '^' ) == 176 ) { # as in codepage 037 on os400 $A2E[10] = 37; $A2E[91] = 186; $A2E[93] = 187; $A2E[94] = 176; $A2E[133] = 21; $A2E[168] = 189; $A2E[172] = 95; $A2E[221] = 173; $E2A[21] = 133; $E2A[37] = 10; $E2A[95] = 172; $E2A[173] = 221; $E2A[176] = 94; $E2A[186] = 91; $E2A[187] = 93; $E2A[189] = 168; } $self->{'a2e'} = \@A2E; $self->{'e2a'} = \@E2A; } } } 1; __END__ =head1 NAME CGI::Simple::Util - Internal utilities used by CGI::Simple module =head1 SYNOPSIS $escaped = escapeHTML('In HTML you need to escape < > " and & chars'); $unescaped = unescapeHTML('<>"&'); $url_encoded = escape($string); $decoded = unescape($url_encoded); =head1 DESCRIPTION CGI::Simple::Util contains essentially non public subroutines used by CGI::Simple. There are HTML and URL escape and unescape routines that may be of some use. An internal object is used to store a number of system specific details to enable the escape routines to be accurate. =head1 AUTHOR INFORMATION Original version copyright 1995-1998, Lincoln D. Stein. All rights reserved. Originally copyright 2001 Dr James Freeman Ejfreeman@tassie.net.auE This release by Andy Armstrong This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Address bug reports and comments to: andy@hexten.net =head1 SEE ALSO L =cut CGI-Simple-1.113/t000755000765000120 011506110167 13012 5ustar00andyadmin000000000000CGI-Simple-1.113/t/000.load.t000444000765000120 16711506110167 14535 0ustar00andyadmin000000000000use Test::More tests => 1; BEGIN { use_ok( 'CGI::Simple' ); } diag( "Testing CGI::Simple $CGI::Simple::VERSION" ); CGI-Simple-1.113/t/020.cookie.t000555000765000120 3376211506110167 15143 0ustar00andyadmin000000000000# This was forked from the original cookie.t file distributed with CGI.pm 2.78 # Originally, only modification is to change CGI::Cookie to CGI::Simple::Cookie # whenever it appeared. Since then the tests suites for CGI.pm and CGI::Simple # have not been kept in sync. # to have a consistent baseline, we nail the current time # to 100 seconds after the epoch BEGIN { *CORE::GLOBAL::time = sub { 100 }; } use Test::More tests => 98; use strict; use CGI::Simple::Util qw(escape unescape); use POSIX qw(strftime); #----------------------------------------------------------------------------- # make sure module loaded #----------------------------------------------------------------------------- BEGIN { use_ok( 'CGI::Simple::Cookie' ); } my @test_cookie = ( 'foo=123, bar=qwerty; baz=wib=ble ; qux=1&2&', 'foo=123; bar=qwerty; baz=wibble;', 'foo=vixen; bar=cow; baz=bitch; qux=politician', 'foo=a%20phrase; bar=yes%2C%20a%20phrase; baz=%5Ewibble; qux=%27', ); #----------------------------------------------------------------------------- # Test parse #----------------------------------------------------------------------------- { my $result = CGI::Simple::Cookie->parse( $test_cookie[0] ); is( ref( $result ), 'HASH', "Hash ref returned in scalar context" ); my @result = CGI::Simple::Cookie->parse( $test_cookie[0] ); is( @result, 8, "returns correct number of fields" ); @result = CGI::Simple::Cookie->parse( $test_cookie[1] ); is( @result, 6, "returns correct number of fields" ); my %result = CGI::Simple::Cookie->parse( $test_cookie[0] ); is( $result{foo}->value, '123', "cookie foo is correct" ); is( $result{bar}->value, 'qwerty', "cookie bar is correct" ); is( $result{baz}->value, 'wib=ble', "cookie baz is correct" ); my @values = $result{qux}->value; is_deeply( \@values, [ 1, 2, '' ], "multiple values are supported including empty values." ); } #----------------------------------------------------------------------------- # Test fetch #----------------------------------------------------------------------------- { # make sure there are no cookies in the environment delete $ENV{HTTP_COOKIE}; delete $ENV{COOKIE}; my %result = CGI::Simple::Cookie->fetch(); ok( keys %result == 0, "No cookies in environment, returns empty list" ); # now set a cookie in the environment and try again $ENV{HTTP_COOKIE} = $test_cookie[2]; %result = CGI::Simple::Cookie->fetch(); ok( eq_set( [ keys %result ], [qw(foo bar baz qux)] ), "expected cookies extracted" ); is( ref( $result{foo} ), 'CGI::Simple::Cookie', 'Type of objects returned is correct' ); is( $result{foo}->value, 'vixen', "cookie foo is correct" ); is( $result{bar}->value, 'cow', "cookie bar is correct" ); is( $result{baz}->value, 'bitch', "cookie baz is correct" ); is( $result{qux}->value, 'politician', "cookie qux is correct" ); # Delete that and make sure it goes away delete $ENV{HTTP_COOKIE}; %result = CGI::Simple::Cookie->fetch(); ok( keys %result == 0, "No cookies in environment, returns empty list" ); # try another cookie in the other environment variable thats supposed to work $ENV{COOKIE} = $test_cookie[3]; %result = CGI::Simple::Cookie->fetch(); ok( eq_set( [ keys %result ], [qw(foo bar baz qux)] ), "expected cookies extracted" ); is( ref( $result{foo} ), 'CGI::Simple::Cookie', 'Type of objects returned is correct' ); is( $result{foo}->value, 'a phrase', "cookie foo is correct" ); is( $result{bar}->value, 'yes, a phrase', "cookie bar is correct" ); is( $result{baz}->value, '^wibble', "cookie baz is correct" ); is( $result{qux}->value, "'", "cookie qux is correct" ); } #----------------------------------------------------------------------------- # Test raw_fetch #----------------------------------------------------------------------------- { # make sure there are no cookies in the environment delete $ENV{HTTP_COOKIE}; delete $ENV{COOKIE}; my %result = CGI::Simple::Cookie->raw_fetch(); ok( keys %result == 0, "No cookies in environment, returns empty list" ); # now set a cookie in the environment and try again $ENV{HTTP_COOKIE} = $test_cookie[2]; %result = CGI::Simple::Cookie->raw_fetch(); ok( eq_set( [ keys %result ], [qw(foo bar baz qux)] ), "expected cookies extracted" ); is( ref( $result{foo} ), '', 'Plain scalar returned' ); is( $result{foo}, 'vixen', "cookie foo is correct" ); is( $result{bar}, 'cow', "cookie bar is correct" ); is( $result{baz}, 'bitch', "cookie baz is correct" ); is( $result{qux}, 'politician', "cookie qux is correct" ); # Delete that and make sure it goes away delete $ENV{HTTP_COOKIE}; %result = CGI::Simple::Cookie->raw_fetch(); ok( keys %result == 0, "No cookies in environment, returns empty list" ); # try another cookie in the other environment variable thats supposed to work $ENV{COOKIE} = $test_cookie[3]; %result = CGI::Simple::Cookie->raw_fetch(); ok( eq_set( [ keys %result ], [qw(foo bar baz qux)] ), "expected cookies extracted" ); is( ref( $result{foo} ), '', 'Plain scalar returned' ); is( $result{foo}, 'a%20phrase', "cookie foo is correct" ); is( $result{bar}, 'yes%2C%20a%20phrase', "cookie bar is correct" ); is( $result{baz}, '%5Ewibble', "cookie baz is correct" ); is( $result{qux}, '%27', "cookie qux is correct" ); } #----------------------------------------------------------------------------- # Test new #----------------------------------------------------------------------------- { # Try new with full information provided my $c = CGI::Simple::Cookie->new( -name => 'foo', -value => 'bar', -expires => '+3M', -domain => '.capricorn.com', -path => '/cgi-bin/database', -secure => 1, -httponly => 1 ); is( ref( $c ), 'CGI::Simple::Cookie', 'new returns objects of correct type' ); is( $c->name, 'foo', 'name is correct' ); is( $c->value, 'bar', 'value is correct' ); like( $c->expires, '/^[a-z]{3},\s*\d{2}-[a-z]{3}-\d{4}/i', 'expires in correct format' ); is( $c->domain, '.capricorn.com', 'domain is correct' ); is( $c->path, '/cgi-bin/database', 'path is correct' ); ok( $c->secure, 'secure attribute is set' ); ok( $c->httponly, 'httponly attribute is set' ); # now try it with the only two manditory values (should also set the default path) $c = CGI::Simple::Cookie->new( -name => 'baz', -value => 'qux', ); is( ref( $c ), 'CGI::Simple::Cookie', 'new returns objects of correct type' ); is( $c->name, 'baz', 'name is correct' ); is( $c->value, 'qux', 'value is correct' ); ok( !defined $c->expires, 'expires is not set' ); ok( !defined $c->domain, 'domain attributeis not set' ); is( $c->path, '/', 'path atribute is set to default' ); ok( !defined $c->secure, 'secure attribute is not set' ); ok( !defined $c->httponly, 'httponly attribute is not set' ); # I'm really not happy about the restults of this section. You pass # the new method invalid arguments and it just merilly creates a # broken object :-) # I've commented them out because they currently pass but I don't # think they should. I think this is testing broken behaviour :-( # # This shouldn't work # $c = CGI::Simple::Cookie->new(-name => 'baz' ); # # is(ref($c), 'CGI::Simple::Cookie', 'new returns objects of correct type'); # is($c->name , 'baz', 'name is correct'); # ok(!defined $c->value, "Value is undefined "); # ok(!defined $c->expires, 'expires is not set'); # ok(!defined $c->domain , 'domain attributeis not set'); # is($c->path , '/', 'path atribute is set to default'); # ok(!defined $c->secure , 'secure attribute is set'); } #----------------------------------------------------------------------------- # Test as_string #----------------------------------------------------------------------------- { my $c = CGI::Simple::Cookie->new( -name => 'Jam', -value => 'Hamster', -expires => '+3M', -domain => '.pie-shop.com', -path => '/', -secure => 1, -httponly => 1 ); my $name = $c->name; like( $c->as_string, "/$name/", "Stringified cookie contains name" ); my $value = $c->value; like( $c->as_string, "/$value/", "Stringified cookie contains value" ); my $expires = $c->expires; like( $c->as_string, "/$expires/", "Stringified cookie contains expires" ); my $domain = $c->domain; like( $c->as_string, "/$domain/", "Stringified cookie contains domain" ); my $path = $c->path; like( $c->as_string, "/$path/", "Stringified cookie contains path" ); like( $c->as_string, '/secure/', "Stringified cookie contains secure" ); like( $c->as_string, '/HttpOnly/', "Stringified cookie contains HttpOnly" ); $c = CGI::Simple::Cookie->new( -name => 'Hamster-Jam', -value => 'Tulip', ); $name = $c->name; like( $c->as_string, "/$name/", "Stringified cookie contains name" ); $value = $c->value; like( $c->as_string, "/$value/", "Stringified cookie contains value" ); ok( $c->as_string !~ /expires/, "Stringified cookie has no expires field" ); ok( $c->as_string !~ /domain/, "Stringified cookie has no domain field" ); $path = $c->path; like( $c->as_string, "/$path/", "Stringified cookie contains path" ); ok( $c->as_string !~ /secure/, "Stringified cookie does not contain secure" ); ok( $c->as_string !~ /HttpOnly/, "Stringified cookie does not contain HttpOnly" ); } #----------------------------------------------------------------------------- # Test compare #----------------------------------------------------------------------------- { my $c1 = CGI::Simple::Cookie->new( -name => 'Jam', -value => 'Hamster', -expires => '+3M', -domain => '.pie-shop.com', -path => '/', -secure => 1, -httponly => 1 ); # have to use $c1->expires because the time will occasionally be # different between the two creates causing spurious failures. my $c2 = CGI::Simple::Cookie->new( -name => 'Jam', -value => 'Hamster', -expires => $c1->expires, -domain => '.pie-shop.com', -path => '/', -secure => 1, -httponly => 1 ); # This looks titally whacked, but it does the -1, 0, 1 comparison # thing so 0 means they match is( $c1->compare( "$c1" ), 0, "Cookies are identical" ); is( $c1->compare( "$c2" ), 0, "Cookies are identical" ); $c1 = CGI::Simple::Cookie->new( -name => 'Jam', -value => 'Hamster', -domain => '.foo.bar.com' ); # have to use $c1->expires because the time will occasionally be # different between the two creates causing spurious failures. $c2 = CGI::Simple::Cookie->new( -name => 'Jam', -value => 'Hamster', ); # This looks titally whacked, but it does the -1, 0, 1 comparison # thing so 0 (i.e. false) means they match is( $c1->compare( "$c1" ), 0, "Cookies are identical" ); ok( $c1->compare( "$c2" ), "Cookies are not identical" ); $c2->domain( '.foo.bar.com' ); is( $c1->compare( "$c2" ), 0, "Cookies are identical" ); } #----------------------------------------------------------------------------- # Test name, value, domain, secure, expires and path #----------------------------------------------------------------------------- { my $c = CGI::Simple::Cookie->new( -name => 'Jam', -value => 'Hamster', -expires => '+3M', -domain => '.pie-shop.com', -path => '/', -secure => 1, -httponly => 1 ); is( $c->name, 'Jam', 'name is correct' ); is( $c->name( 'Clash' ), 'Clash', 'name is set correctly' ); is( $c->name, 'Clash', 'name now returns updated value' ); # this is insane! it returns a simple scalar but can't accept one as # an argument, you have to give it an arrary ref. It's totally # inconsitent with these other methods :-( is( $c->value, 'Hamster', 'value is correct' ); is( $c->value( ['Gerbil'] ), 'Gerbil', 'value is set correctly' ); is( $c->value, 'Gerbil', 'value now returns updated value' ); my $exp = $c->expires; like( $c->expires, '/^[a-z]{3},\s*\d{2}-[a-z]{3}-\d{4}/i', 'expires is correct' ); like( $c->expires( '+12h' ), '/^[a-z]{3},\s*\d{2}-[a-z]{3}-\d{4}/i', 'expires is set correctly' ); like( $c->expires, '/^[a-z]{3},\s*\d{2}-[a-z]{3}-\d{4}/i', 'expires now returns updated value' ); isnt( $c->expires, $exp, "Expiry time has changed" ); is( $c->domain, '.pie-shop.com', 'domain is correct' ); is( $c->domain( '.wibble.co.uk' ), '.wibble.co.uk', 'domain is set correctly' ); is( $c->domain, '.wibble.co.uk', 'domain now returns updated value' ); is( $c->path, '/', 'path is correct' ); is( $c->path( '/basket/' ), '/basket/', 'path is set correctly' ); is( $c->path, '/basket/', 'path now returns updated value' ); ok( $c->secure, 'secure attribute is set' ); ok( !$c->secure( 0 ), 'secure attribute is cleared' ); ok( !$c->secure, 'secure attribute is cleared' ); ok( $c->httponly, 'httponly attribute is set' ); ok( !$c->httponly( 0 ), 'httponly attribute is cleared' ); ok( !$c->httponly, 'httponly attribute is cleared' ); } #---------------------------------------------------------------------------- # Max-age #---------------------------------------------------------------------------- MAX_AGE: { { my $cookie = CGI::Simple::Cookie->new( -name => 'a', value => 'b', '-expires' => 'now', ); is $cookie->expires, 'Thu, 01-Jan-1970 00:01:40 GMT'; is $cookie->max_age => undef, 'max-age is undefined when setting expires'; } { my $cookie = CGI::Simple::Cookie->new( -name => 'a', 'value' => 'b' ); $cookie->max_age( '+4d' ); is $cookie->expires, undef, 'expires is undef when setting max_age'; is $cookie->max_age => 4 * 24 * 60 * 60, 'setting via max-age'; $cookie->max_age( '113' ); is $cookie->max_age => 13, 'max_age(num) as delta'; } } CGI-Simple-1.113/t/030.function.t000555000765000120 1051211506110167 15504 0ustar00andyadmin000000000000use Test::More tests => 27; use strict; use Config; use CGI::Simple::Standard qw(:all -default); # Makes forked test work OK Test::More->builder->no_ending( 1 ); my $CRLF = "\015\012"; # A peculiarity of sending "\n" through MBX|Socket|web-server on VMS # is that a CR character gets inserted automatically in the web server # case but not internal to perl's double quoted strings "\n". This # test would need to be modified to use the "\015\012" on VMS if it # were actually run through a web server. # Thanks to Peter Prymmer for this if ( $^O eq 'VMS' ) { $CRLF = "\n"; } # Web servers on EBCDIC hosts are typically set up to do an EBCDIC -> ASCII # translation hence CRLF is used as \r\n within CGI.pm on such machines. if ( ord( "\t" ) != 9 ) { $CRLF = "\r\n"; } # Set up a CGI environment $ENV{REQUEST_METHOD} = 'GET'; $ENV{QUERY_STRING} = 'game=chess&game=checkers&weather=dull'; $ENV{PATH_INFO} = '/somewhere/else'; $ENV{PATH_TRANSLATED} = '/usr/local/somewhere/else'; $ENV{SCRIPT_NAME} = '/cgi-bin/foo.cgi'; $ENV{SERVER_PROTOCOL} = 'HTTP/1.0'; $ENV{SERVER_PORT} = 8080; $ENV{SERVER_NAME} = 'the.good.ship.lollypop.com'; $ENV{HTTP_LOVE} = 'true'; is( request_method(), 'GET', "CGI::request_method()" ); is( query_string(), 'game=chess;game=checkers;weather=dull', "CGI::query_string()" ); is( param(), 2, "CGI::param()" ); is( join( ' ', sort { $a cmp $b } param() ), 'game weather', "CGI::param()" ); is( param( 'game' ), 'chess', "CGI::param()" ); is( param( 'weather' ), 'dull', "CGI::param()" ); is( join( ' ', param( 'game' ) ), 'chess checkers', "CGI::param()" ); ok( param( -name => 'foo', -value => 'bar' ), 'CGI::param() put' ); is( param( -name => 'foo' ), 'bar', 'CGI::param() get' ); is( query_string(), 'game=chess;game=checkers;weather=dull;foo=bar', "CGI::query_string() redux" ); is( http( 'love' ), 'true', "CGI::http()" ); is( script_name(), '/cgi-bin/foo.cgi', "CGI::script_name()" ); is( url(), 'http://the.good.ship.lollypop.com:8080/cgi-bin/foo.cgi', "CGI::url()" ); is( self_url(), 'http://the.good.ship.lollypop.com:8080/cgi-bin/foo.cgi/somewhere/else' . '?game=chess;game=checkers;weather=dull;foo=bar', "CGI::url()" ); is( url( -absolute => 1 ), '/cgi-bin/foo.cgi', 'CGI::url(-absolute=>1)' ); is( url( -relative => 1 ), 'foo.cgi', 'CGI::url(-relative=>1)' ); is( url( -relative => 1, -path => 1 ), 'foo.cgi/somewhere/else', 'CGI::url(-relative=>1,-path=>1)' ); is( url( -relative => 1, -path => 1, -query => 1 ), 'foo.cgi/somewhere/else?game=chess;game=checkers;weather=dull;foo=bar', 'CGI::url(-relative=>1,-path=>1,-query=>1)' ); Delete( 'foo' ); ok( !param( 'foo' ), 'CGI::delete()' ); #CGI::_reset_globals(); $ENV{QUERY_STRING} = 'mary+had+a+little+lamb'; restore_parameters(); is( join( ' ', keywords() ), 'mary had a little lamb', 'CGI::keywords' ); is( join( ' ', param( 'keywords' ) ), 'mary had a little lamb', 'CGI::keywords' ); is( redirect( 'http://somewhere.else' ), "Status: 302 Moved${CRLF}Location: http://somewhere.else${CRLF}${CRLF}", "CGI::redirect() 1" ); my $h = redirect( -Location => 'http://somewhere.else', -Type => 'text/html' ); is( $h, "Status: 302 Moved${CRLF}Location: http://somewhere.else${CRLF}" . "Content-Type: text/html; charset=ISO-8859-1${CRLF}${CRLF}", "CGI::redirect() 2" ); is( redirect( -Location => 'http://somewhere.else/bin/foo&bar', -Type => 'text/html' ), "Status: 302 Moved${CRLF}Location: http://somewhere.else/bin/foo&bar${CRLF}" . "Content-Type: text/html; charset=ISO-8859-1${CRLF}${CRLF}", "CGI::redirect() 2" ); is( escapeHTML( 'CGI' ), 'CGI', 'escapeHTML(CGI) failing again' ); SKIP: { skip "Fork not available on this platform", 2 unless $Config{d_fork}; my $test_string = 'game=soccer&game=baseball&weather=nice'; $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_LENGTH} = length( $test_string ); $ENV{QUERY_STRING} = 'big_balls=basketball&small_balls=golf'; $ENV{CONTENT_TYPE} = 'application/x-www-form-urlencoded'; if ( open( CHILD, "|-" ) ) { # cparent print CHILD $test_string; close CHILD; exit 0; } # at this point, we're in a new (child) process restore_parameters(); # trigger a reinitialisaton is( param( 'weather' ), 'nice', "CGI::param() from POST" ); is( url_param( 'big_balls' ), 'basketball', "CGI::url_param()" ); } CGI-Simple-1.113/t/040.request.t000555000765000120 1354711506110167 15363 0ustar00andyadmin000000000000# This is the original function.t file distributed with CGI.pm 2.78 # The only change is to change the use statement and change references # from CGI to CGI::Simple use Test::More tests => 40; use strict; use Config; use CGI::Simple ( -default ); # Makes forked test work OK Test::More->builder->no_ending( 1 ); # Set up a CGI environment $ENV{REQUEST_METHOD} = 'GET'; $ENV{QUERY_STRING} = 'game=chess&game=checkers&weather=dull'; $ENV{PATH_INFO} = '/somewhere/else'; $ENV{PATH_TRANSLATED} = '/usr/local/somewhere/else'; $ENV{SCRIPT_NAME} = '/cgi-bin/foo.cgi'; $ENV{SERVER_PROTOCOL} = 'HTTP/1.0'; $ENV{SERVER_PORT} = 8080; $ENV{SERVER_NAME} = 'the.good.ship.lollypop.com'; $ENV{REQUEST_URI} = "$ENV{SCRIPT_NAME}$ENV{PATH_INFO}?$ENV{QUERY_STRING}"; $ENV{HTTP_LOVE} = 'true'; my $q = new CGI::Simple; ok( $q, "CGI::Simple::new()" ); is( $q->request_method, 'GET', "CGI::Simple::request_method()" ); is( $q->query_string, 'game=chess;game=checkers;weather=dull', "CGI::Simple::query_string()" ); is( $q->param(), 2, "CGI::Simple::param()" ); is( join( ' ', sort $q->param() ), 'game weather', "CGI::Simple::param()" ); is( $q->param( 'game' ), 'chess', "CGI::Simple::param()" ); is( $q->param( 'weather' ), 'dull', "CGI::Simple::param()" ); is( join( ' ', $q->param( 'game' ) ), 'chess checkers', "CGI::Simple::param()" ); ok( $q->param( -name => 'foo', -value => 'bar' ), 'CGI::Simple::param() put' ); is( $q->param( -name => 'foo' ), 'bar', 'CGI::Simple::param() get' ); is( $q->query_string, 'game=chess;game=checkers;weather=dull;foo=bar', "CGI::Simple::query_string() redux" ); is( $q->http( 'love' ), 'true', "CGI::Simple::http()" ); is( $q->script_name, '/cgi-bin/foo.cgi', "CGI::Simple::script_name()" ); is( $q->url, 'http://the.good.ship.lollypop.com:8080/cgi-bin/foo.cgi', "CGI::Simple::url()" ); is( $q->self_url, 'http://the.good.ship.lollypop.com:8080/cgi-bin/foo.cgi/somewhere/else?' . 'game=chess;game=checkers;weather=dull;foo=bar', "CGI::Simple::url()" ); is( $q->url( -absolute => 1 ), '/cgi-bin/foo.cgi', 'CGI::Simple::url(-absolute=>1)' ); is( $q->url( -relative => 1 ), 'foo.cgi', 'CGI::Simple::url(-relative=>1)' ); is( $q->url( -relative => 1, -path => 1 ), 'foo.cgi/somewhere/else', 'CGI::Simple::url(-relative=>1,-path=>1)' ); is( $q->url( -relative => 1, -path => 1, -query => 1 ), 'foo.cgi/somewhere/else?game=chess;game=checkers;weather=dull;foo=bar', 'CGI::Simple::url(-relative=>1,-path=>1,-query=>1)' ); $q->delete( 'foo' ); ok( !$q->param( 'foo' ), 'CGI::Simple::delete()' ); $q->_reset_globals; $ENV{QUERY_STRING} = 'mary+had+a+little+lamb'; ok( $q = new CGI::Simple, "CGI::Simple::new() redux" ); is( join( ' ', $q->keywords ), 'mary had a little lamb', 'CGI::Simple::keywords' ); is( join( ' ', $q->param( 'keywords' ) ), 'mary had a little lamb', 'CGI::Simple::keywords' ); ok $q = new CGI::Simple( 'foo=bar=baz' ), 'CGI::Simple::new(), equals in value'; is $q->param( 'foo' ), 'bar=baz', 'parsed parameter containing equals'; ok( $q = new CGI::Simple( 'foo=bar&foo=baz' ), "CGI::Simple::new() redux" ); is( $q->param( 'foo' ), 'bar', 'CGI::Simple::param() redux' ); ok( $q = new CGI::Simple( { 'foo' => 'bar', 'bar' => 'froz' } ), "CGI::Simple::new() redux 2" ); is( $q->param( 'bar' ), 'froz', "CGI::Simple::param() redux 2" ); # test tied interface my $p = $q->Vars; is( $p->{bar}, 'froz', "tied interface fetch" ); $p->{bar} = join( "\0", qw(foo bar baz) ); is( join( ' ', $q->param( 'bar' ) ), 'foo bar baz', 'tied interface store' ); SKIP: { skip "Fork not available on this platform", 9 unless $Config{d_fork}; # test posting $q->_reset_globals; my $test_string = 'game=soccer&game=baseball&weather=nice'; $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_LENGTH} = length( $test_string ); $ENV{QUERY_STRING} = 'big_balls=basketball&small_balls=golf'; $ENV{CONTENT_TYPE} = 'application/x-www-form-urlencoded'; if ( open( CHILD, "|-" ) ) { # cparent print CHILD $test_string; close CHILD; exit 0; } # at this point, we're in a new (child) process ok( $q = new CGI::Simple, "CGI::Simple::new() from POST" ); is( $q->param( 'weather' ), 'nice', "CGI::Simple::param() from POST" ); is( $q->url_param( 'big_balls' ), 'basketball', "CGI::url_param()" ); # test posting POSTDATA $q->_reset_globals; $test_string = 'soccerbaseballnice'; $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_LENGTH} = length( $test_string ); $ENV{QUERY_STRING} = ''; $ENV{CONTENT_TYPE} = 'text/xml'; if ( open( CHILD, "|-" ) ) { # cparent print CHILD $test_string; close CHILD; exit 0; } ok( $q = new CGI::Simple, "CGI::Simple::new from POST" ); is( $q->param( 'POSTDATA' ), $test_string, "CGI::Simple::param('POSTDATA') from POST" ); # test posting POSTDATA with nulls $q->_reset_globals; $test_string = "some nulls \0\0\0 are better than others \0\0\0"; $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_LENGTH} = length( $test_string ); $ENV{QUERY_STRING} = ''; $ENV{CONTENT_TYPE} = 'text/plain'; if ( open( CHILD, "|-" ) ) { # cparent print CHILD $test_string; close CHILD; exit 0; } ok( $q = new CGI::Simple, "CGI::Simple::new from POST" ); is( $q->param( 'POSTDATA' ), $test_string, "CGI::Simple::param('POSTDATA') from POST w/nulls" ); # test posting PUTDATA $q->_reset_globals; $test_string = 'soccerbaseballnice'; $ENV{REQUEST_METHOD} = 'PUT'; $ENV{CONTENT_LENGTH} = length( $test_string ); $ENV{CONTENT_TYPE} = 'text/xml'; if ( open( CHILD, "|-" ) ) { # cparent print CHILD $test_string; close CHILD; exit 0; } ok( $q = new CGI::Simple, "CGI::Simple::new from PUT" ); is( $q->param( 'PUTDATA' ), $test_string, "CGI::Simple::param('POSTDATA') from POST" ); } CGI-Simple-1.113/t/041.multipart.t000444000765000120 302011506110167 15653 0ustar00andyadmin000000000000use Test::More tests => 5; use strict; use warnings; use Config; use Data::Dumper; use IO::Scalar; use CGI::Simple ( -default ); # Set up a CGI environment $ENV{REQUEST_METHOD} = 'POST'; $ENV{QUERY_STRING} = ''; $ENV{PATH_INFO} = '/somewhere/else'; $ENV{PATH_TRANSLATED} = '/usr/local/somewhere/else'; $ENV{SCRIPT_NAME} = '/cgi-bin/foo.cgi'; $ENV{SERVER_PROTOCOL} = 'HTTP/1.0'; $ENV{SERVER_PORT} = 8080; $ENV{SERVER_NAME} = 'the.good.ship.lollypop.com'; $ENV{CONTENT_TYPE} = q{multipart/form-data; boundary=---------------------------10263292819275730631136676268}; $ENV{REQUEST_URI} = "$ENV{SCRIPT_NAME}$ENV{PATH_INFO}?$ENV{QUERY_STRING}"; $ENV{HTTP_LOVE} = 'true'; my $body = <new( \$body ); my $q = new CGI::Simple( $h ); ok( $q, "CGI::Simple::new()" ); is_deeply( [ $q->param ], [qw(action body send_action)], 'list of params' ); is( $q->param( 'action' ), 'reply', 'reply param' ); is( $q->param( 'body' ), 'asdfasdf', 'body param' ); is( $q->param( 'send_action' ), 'Reply', 'send_action param' ); CGI-Simple-1.113/t/050.simple.t000555000765000120 13073311506110167 15202 0ustar00andyadmin000000000000use Test::More tests => 319; use Carp; use strict; use vars qw(%field %in); use CGI::Simple; my ( $q, $sv, @av ); my $tmpfile = './cgi-tmpfile.tmp'; $ENV{'AUTH_TYPE'} = 'PGP MD5 DES rot13'; $ENV{'CONTENT_LENGTH'} = '42'; $ENV{'CONTENT_TYPE'} = 'application/x-www-form-urlencoded'; $ENV{'COOKIE'} = 'foo=a%20phrase; bar=yes%2C%20a%20phrase&I%20say;'; $ENV{'DOCUMENT_ROOT'} = '/vs/www/foo'; $ENV{'GATEWAY_INTERFACE'} = 'bleeding edge'; $ENV{'HTTPS'} = 'ON'; $ENV{'HTTPS_A'} = 'A'; $ENV{'HTTPS_B'} = 'B'; $ENV{'HTTP_ACCEPT'} = 'text/html;q=1, text/plain;q=0.8, image/jpg, image/gif;q=0.42, */*;q=0.001'; $ENV{'HTTP_COOKIE'} = ''; $ENV{'HTTP_FROM'} = 'spammer@nowhere.com'; $ENV{'HTTP_HOST'} = 'the.vatican.org'; $ENV{'HTTP_REFERER'} = 'xxx.sex.com'; $ENV{'HTTP_USER_AGENT'} = 'LWP'; $ENV{'PATH_INFO'} = '/somewhere/else'; $ENV{'PATH_TRANSLATED'} = '/usr/local/somewhere/else'; $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; $ENV{'REDIRECT_QUERY_STRING'} = ''; $ENV{'REMOTE_ADDR'} = '127.0.0.1'; $ENV{'REMOTE_HOST'} = 'localhost'; $ENV{'REMOTE_IDENT'} = 'None of your damn business'; $ENV{'REMOTE_USER'} = 'Just another Perl hacker,'; $ENV{'REQUEST_METHOD'} = 'GET'; $ENV{'SCRIPT_NAME'} = '/cgi-bin/foo.cgi'; $ENV{'SERVER_NAME'} = 'nowhere.com'; $ENV{'SERVER_PORT'} = '8080'; $ENV{'SERVER_PROTOCOL'} = 'HTTP/1.0'; $ENV{'SERVER_SOFTWARE'} = 'Apache - accept no substitutes'; $q = new CGI::Simple; sub undef_globals { undef $CGI::Simple::USE_CGI_PM_DEFAULTS; undef $CGI::Simple::DISABLE_UPLOADS; undef $CGI::Simple::POST_MAX; undef $CGI::Simple::NO_UNDEF_PARAMS; undef $CGI::Simple::USE_PARAM_SEMICOLONS; undef $CGI::Simple::HEADERS_ONCE; undef $CGI::Simple::NPH; undef $CGI::Simple::DEBUG; undef $CGI::Simple::NO_NULL; undef $CGI::Simple::FATAL; } undef_globals(); # _initialize_globals() $q->_initialize_globals(); is( $CGI::Simple::USE_CGI_PM_DEFAULTS, 0, '_initialize_globals(), 1' ); is( $CGI::Simple::DISABLE_UPLOADS, 1, '_initialize_globals(), 2' ); is( $CGI::Simple::POST_MAX, 102_400, '_initialize_globals(), 3' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 0, '_initialize_globals(), 4' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 0, '_initialize_globals(), 5' ); is( $CGI::Simple::HEADERS_ONCE, 0, '_initialize_globals(), 6' ); is( $CGI::Simple::NPH, 0, '_initialize_globals(), 7' ); is( $CGI::Simple::DEBUG, 0, '_initialize_globals(), 8' ); is( $CGI::Simple::NO_NULL, 1, '_initialize_globals(), 9' ); is( $CGI::Simple::FATAL, -1, '_initialize_globals(), 10' ); undef_globals(); # _use_cgi_pm_global_settings() $q->_use_cgi_pm_global_settings(); is( $CGI::Simple::DISABLE_UPLOADS, 0, '_use_cgi_pm_global_settings(), 1' ); is( $CGI::Simple::POST_MAX, -1, '_use_cgi_pm_global_settings(), 2' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 0, '_use_cgi_pm_global_settings(), 3' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 1, '_use_cgi_pm_global_settings(), 4' ); is( $CGI::Simple::HEADERS_ONCE, 0, '_use_cgi_pm_global_settings(), 5' ); is( $CGI::Simple::NPH, 0, '_use_cgi_pm_global_settings(), 6' ); is( $CGI::Simple::DEBUG, 1, '_use_cgi_pm_global_settings(), 7' ); is( $CGI::Simple::NO_NULL, 0, '_use_cgi_pm_global_settings(), 8' ); is( $CGI::Simple::FATAL, -1, '_use_cgi_pm_global_settings(), 9' ); # _store_globals() undef %{$q}; ok( !defined $q->{'.globals'}->{'DISABLE_UPLOADS'}, '_store_globals(), 1' ); ok( !defined $q->{'.globals'}->{'POST_MAX'}, '_store_globals(), 2' ); ok( !defined $q->{'.globals'}->{'NO_UNDEF_PARAMS'}, '_store_globals(), 3' ); ok( !defined $q->{'.globals'}->{'USE_PARAM_SEMICOLONS'}, '_store_globals(), 4' ); ok( !defined $q->{'.globals'}->{'HEADERS_ONCE'}, '_store_globals(), 5' ); ok( !defined $q->{'.globals'}->{'NPH'}, '_store_globals(), 6' ); ok( !defined $q->{'.globals'}->{'DEBUG'}, '_store_globals(), 7' ); ok( !defined $q->{'.globals'}->{'NO_NULL'}, '_store_globals(), 8' ); ok( !defined $q->{'.globals'}->{'FATAL'}, '_store_globals(), 9' ); ok( !defined $q->{'.globals'}->{'USE_CGI_PM_DEFAULTS'}, '_store_globals(), 10' ); $q->_store_globals(); ok( defined $q->{'.globals'}->{'DISABLE_UPLOADS'}, '_store_globals(), 11' ); ok( defined $q->{'.globals'}->{'POST_MAX'}, '_store_globals(), 12' ); ok( defined $q->{'.globals'}->{'NO_UNDEF_PARAMS'}, '_store_globals(), 13' ); ok( defined $q->{'.globals'}->{'USE_PARAM_SEMICOLONS'}, '_store_globals(), 14' ); ok( defined $q->{'.globals'}->{'HEADERS_ONCE'}, '_store_globals(), 15' ); ok( defined $q->{'.globals'}->{'NPH'}, '_store_globals(), 16' ); ok( defined $q->{'.globals'}->{'DEBUG'}, '_store_globals(), 17' ); ok( defined $q->{'.globals'}->{'NO_NULL'}, '_store_globals(), 18' ); ok( defined $q->{'.globals'}->{'FATAL'}, '_store_globals(), 19' ); ok( defined $q->{'.globals'}->{'USE_CGI_PM_DEFAULTS'}, '_store_globals(), 20' ); # import() - used to set paragmas my @args = qw( -default -no_upload -unique_header -nph -no_debug -newstyle_url -no_undef_param ); undef_globals(); $q->import( @args ); is( $CGI::Simple::USE_CGI_PM_DEFAULTS, 1, 'import(), 1' ); is( $CGI::Simple::DISABLE_UPLOADS, 1, 'import(), 2' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 1, 'import(), 3' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 1, 'import(), 4' ); is( $CGI::Simple::HEADERS_ONCE, 1, 'import(), 5' ); is( $CGI::Simple::NPH, 1, 'import(), 6' ); is( $CGI::Simple::DEBUG, 0, 'import(), 7' ); undef_globals(); $q->import( qw ( -upload -oldstyle_url -debug ) ); is( $CGI::Simple::DISABLE_UPLOADS, 0, 'import(), 8' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 0, 'import(), 9' ); is( $CGI::Simple::DEBUG, 2, 'import(), 10' ); undef_globals(); # _reset_globals() $q->_reset_globals(); is( $CGI::Simple::DISABLE_UPLOADS, 0, '_reset_globals(), 1' ); is( $CGI::Simple::POST_MAX, -1, '_reset_globals(), 2' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 0, '_reset_globals(), 3' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 1, '_reset_globals(), 4' ); is( $CGI::Simple::HEADERS_ONCE, 0, '_reset_globals(), 5' ); is( $CGI::Simple::NPH, 0, '_reset_globals(), 6' ); is( $CGI::Simple::DEBUG, 1, '_reset_globals(), 7' ); is( $CGI::Simple::NO_NULL, 0, '_reset_globals(), 8' ); is( $CGI::Simple::FATAL, -1, '_reset_globals(), 9' ); undef_globals(); $q = new CGI::Simple; # url_decode() - scalar context, void argument $sv = $q->url_decode(); is( $sv, undef, 'url_decode(), 1' ); # url_decode() - scalar context, valid argument my ( $string, $enc_string ); for ( 32 .. 255 ) { $string .= chr; $enc_string .= uc sprintf "%%%02x", ord chr; } is( $q->url_decode( $enc_string ), $string, 'url_decode(\$enc_string), 1' ); # url_encode() - scalar context, void argument $sv = $q->url_encode(); is( $sv, undef, 'url_encode(), 1' ); # url_encode() - scalar context, valid argument $sv = $q->url_encode( $string ); $sv =~ tr/+/ /; $sv =~ s/%([a-fA-F0-9]{2})/ pack "C", hex $1 /eg; is( $sv, $string, 'url_encode(\$string), 1' ); # url encoding - circular test is( $q->url_decode( $q->url_encode( $string ) ), $string, 'url encoding via circular test, 1' ); # new() plain constructor $q = CGI::Simple->new; like( $q, qr/CGI::Simple/, 'new() plain constructor, 1' ); # new('') empty constructor $q = new CGI::Simple( '' ); like( $q, qr/CGI::Simple/, 'new() empty constructor, 1' ); $q = new CGI::Simple( {} ); like( $q, qr/CGI::Simple/, 'new() empty constructor, 2' ); # new() hash constructor $q = new CGI::Simple( { 'foo' => '1', 'bar' => [ 2, 3, 4 ] } ); @av = $q->param; # fix OS bug with testing is( join( ' ', sort @av ), 'bar foo', 'new() hash constructor, 1' ); is( $q->param( 'foo' ), 1, 'new() hash constructor, 2' ); is( $q->param( 'bar' ), 2, 'new() hash constructor, 3' ); @av = $q->param( 'bar' ); is( join( '', @av ), 234, 'new() hash constructor, 4' ); $q = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' ); open FH, ">$tmpfile", or carp "Can't create $tmpfile $!\n"; $q->save( \*FH ); close FH; # new() query string constructor $q = new CGI::Simple( 'foo=5&bar=6&bar=7&bar=8' ); @av = $q->param; is( join( ' ', @av ), 'foo bar', 'new() query string constructor, 1' ); is( $q->param( 'foo' ), 5, 'new() query string constructor, 2' ); is( $q->param( 'bar' ), 6, 'new() query string constructor, 3' ); @av = $q->param( 'bar' ); is( join( '', @av ), 678, 'new() query string constructor, 4' ); open FH, ">>$tmpfile", or carp "Can't append $tmpfile $!\n"; $q->save_parameters( \*FH ); close FH; # new() CGI::Simple object constructor my $q_old = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' ); my $q_new = new CGI::Simple( $q_old ); is( $q_old->query_string, 'foo=1&bar=2&bar=3&bar=4', 'new() CGI::Simple object constructor, 1' ); is( $q_new->query_string, 'foo=1&bar=2&bar=3&bar=4', 'new() CGI::Simple object constructor, 2' ); # new() \@ARGV constructor $ENV{'REQUEST_METHOD'} = ''; $CGI::Simple::DEBUG = 1; @ARGV = qw( foo=bar\=baz foo=bar\&baz ); $q = new CGI::Simple; is( join( ' ', $q->param( 'foo' ) ), 'bar=baz bar&baz', 'new() \@ARGV constructor, 1' ); $ENV{'REQUEST_METHOD'} = 'GET'; ################ The Core Methods ################ $q = new CGI::Simple; # param() - scalar and array context, void argument $sv = $q->param(); @av = $q->param(); is( $sv, '2', 'param() void argument, 1' ); is( join( ' ', @av ), 'name color', 'param() void argument, 2' ); # param() - scalar and array context, single argument (valid) $sv = $q->param( 'color' ); @av = $q->param( 'color' ); is( $sv, 'red', 'param(\'color\') single argument (valid), 1' ); is( join( ' ', @av ), 'red green blue', 'param(\'color\') single argument (valid), 2' ); # param() - scalar and array context, single argument (invalid) $sv = $q->param( 'invalid' ); @av = $q->param( 'invalid' ); is( $sv, undef, 'param(\'invalid\') single argument (invalid), 1' ); is( join( ' ', @av ), '', 'param(\'invalid\') single argument (invalid), 2' ); # param() - scalar and array context, -name=>'param' (valid) $sv = $q->param( -name => 'color' ); @av = $q->param( -name => 'color' ); is( $sv, 'red', 'param( -name=>\'color\' ) get values, 1' ); is( join( ' ', @av ), 'red green blue', 'param( -name=>\'color\' ) get values, 2' ); # param() - scalar and array context, -name=>'param' (invalid) $sv = $q->param( -name => 'invalid' ); @av = $q->param( -name => 'invalid' ); is( $sv, undef, 'param( -name=>\'invalid\' ) get values, 1' ); is( join( ' ', @av ), '', 'param( -name=>\'invalid\' ) get values, 2' ); $CGI::Simple::NO_UNDEF_PARAMS = 0; $q = new CGI::Simple( 'name=&color=' ); # param() - scalar and array context, void values void arg $sv = $q->param(); @av = $q->param(); is( $sv, '2', 'param() void values 1, 1' ); is( join( ' ', @av ), 'name color', 'param() void values 1, 2' ); # param() - scalar and array context, void values, valid arg $sv = $q->param( 'name' ); @av = $q->param( 'name' ); is( $sv, '', 'param(\'name\') void values 1, valid param, 1' ); is( join( ' ', @av ), '', 'param(\'name\') void values 1, valid param, 2' ); $q = new CGI::Simple( 'name&color' ); # param() - scalar and array context, void values void arg $sv = $q->param(); @av = $q->param(); is( $sv, '2', 'param() void values 2, 1' ); is( join( ' ', @av ), 'name color', 'param() void values 2, 2' ); # param() - scalar and array context, void values, valid arg $sv = $q->param( 'name' ); @av = $q->param( 'name' ); is( $sv, '', 'param(\'name\') void values 2 , valid param, 1' ); is( join( ' ', @av ), '', 'param(\'name\') void values 2 , valid param, 2' ); $CGI::Simple::NO_UNDEF_PARAMS = 1; $q = new CGI::Simple( 'name=&color=' ); # param() - scalar and array context, void values void arg $sv = $q->param(); @av = $q->param(); is( $sv, '0', 'param() void values 1, no undef, 1' ); is( join( ' ', @av ), '', 'param() void values 1, no undef, 2' ); # param() - scalar and array context, void values, valid arg $sv = $q->param( 'name' ); @av = $q->param( 'name' ); is( $sv, undef, 'param(\'name\') void values 1, valid param, no undef, 1' ); is( join( ' ', @av ), '', 'param(\'name\') void values 1, valid param, no undef, 2' ); $q = new CGI::Simple( 'name&color' ); # param() - scalar and array context, void values void arg $sv = $q->param(); @av = $q->param(); is( $sv, '0', 'param() void values 2, no undef, 1' ); is( join( ' ', @av ), '', 'param() void values 2, no undef, 2' ); # param() - scalar and array context, void values, valid arg $sv = $q->param( 'name' ); @av = $q->param( 'name' ); is( $sv, undef, 'param(\'name\') void values 2, valid param, no undef, 1' ); is( join( ' ', @av ), '', 'param(\'name\') void values 2, valid param, no undef, 2' ); $CGI::Simple::NO_UNDEF_PARAMS = 0; $q = new CGI::Simple; # param() - scalar and array context, set values $sv = $q->param( 'foo', 'some', 'new', 'values' ); @av = $q->param( 'foo', 'some', 'new', 'values' ); is( $sv, 'some', 'param( \'foo\', \'some\', \'new\', \'values\' ) set values, 1' ); is( join( ' ', @av ), 'some new values', 'param( \'foo\', \'some\', \'new\', \'values\' ) set values, 2' ); # param() - scalar and array context $sv = $q->param( -name => 'foo', -value => 'bar' ); @av = $q->param( -name => 'foo', -value => 'bar' ); is( $sv, 'bar', 'param( -name=>\'foo\', -value=>\'bar\' ) set values, 1' ); is( join( ' ', @av ), 'bar', 'param( -name=>\'foo\', -value=>\'bar\' ) set values, 2' ); # param() - scalar and array context $sv = $q->param( -name => 'foo', -value => [ 'bar', 'baz' ] ); @av = $q->param( -name => 'foo', -value => [ 'bar', 'baz' ] ); is( $sv, 'bar', 'param(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 1' ); is( join( ' ', @av ), 'bar baz', 'param(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 2' ); # add_param() - scalar and array context, void argument $sv = $q->add_param(); @av = $q->add_param(); is( $sv, undef, 'add_param(), 1' ); is( join( ' ', @av ), '', 'add_param(), 2' ); # add_param() - scalar and array context, existing param argument $q->add_param( 'foo', 'new' ); @av = $q->param( 'foo' ); is( join( ' ', @av ), 'bar baz new', 'add_param( \'foo\', \'new\' ), 1' ); $q->add_param( 'foo', [ 1, 2, 3, 4, 5 ] ); @av = $q->param( 'foo' ); is( join( ' ', @av ), 'bar baz new 1 2 3 4 5', 'add_param( \'foo\', \'new\' ), 2' ); # add_param() - existing param argument, overwrite $q->add_param( 'foo', 'bar', 'overwrite' ); @av = $q->param( 'foo' ); is( join( ' ', @av ), 'bar', 'add_param(\'foo\', \'bar\', \'overwrite\' ), 1' ); # add_param() - scalar and array context, existing param argument $q->add_param( 'new', 'new%2C' ); @av = $q->param( 'new' ); is( join( ' ', @av ), 'new%2C', 'add_param( \'new\', \'new\' ), 1' ); $q->add_param( 'new', [ 1, 2, 3, 4, 5 ] ); @av = $q->param( 'new' ); is( join( ' ', @av ), 'new%2C 1 2 3 4 5', 'add_param( \'new\', \'new\' ), 2' ); # param_fetch() - scalar context, void argument $sv = $q->param_fetch(); is( $sv, undef, 'param_fetch(), 1' ); # param_fetch() - scalar context, 'color' syntax $sv = $q->param_fetch( 'color' ); is( ref $sv, 'ARRAY', 'param_fetch( \'color\' ), 1' ); is( join( ' ', @$sv ), 'red green blue', 'param_fetch( \'color\' ), 2' ); # param_fetch() - scalar context, -name=>'color' syntax $sv = $q->param_fetch( -name => 'color' ); is( ref $sv, 'ARRAY', 'param_fetch( -name=>\'color\' ), 1' ); is( join( ' ', @$sv ), 'red green blue', 'param_fetch( -name=>\'color\' ), 2' ); # url_param() - scalar and array context, void argument $sv = $q->url_param(); @av = $q->url_param(); is( $sv, '2', 'url_param() void argument, 1' ); is( join( ' ', @av ), 'name color', 'url_param() void argument, 2' ); # url_param() - scalar and array context, single argument (valid) $sv = $q->url_param( 'color' ); @av = $q->url_param( 'color' ); is( $sv, 'red', 'url_param(\'color\') single argument (valid), 1' ); is( join( ' ', @av ), 'red green blue', 'url_param(\'color\') single argument (valid), 2' ); # url_param() - scalar and array context, single argument (invalid) $sv = $q->url_param( 'invalid' ); @av = $q->url_param( 'invalid' ); is( $sv, undef, 'url_param(\'invalid\') single argument (invalid), 1' ); is( join( ' ', @av ), '', 'url_param(\'invalid\') single argument (invalid), 2' ); # keywords() - scalar and array context, void argument $q = new CGI::Simple( 'here+are++++some%20keywords' ); $sv = $q->keywords; @av = $q->keywords; is( $sv, '4', 'keywords(), 1' ); is( join( ' ', @av ), 'here are some keywords', 'keywords(), 2' ); # keywords() - scalar and array context, array argument $sv = $q->keywords( 'foo', 'bar', 'baz' ); @av = $q->keywords( 'foo', 'bar', 'baz' ); is( $sv, '3', 'keywords( \'foo\', \'bar\', \'baz\' ), 1' ); is( join( ' ', @av ), 'foo bar baz', 'keywords( \'foo\', \'bar\', \'baz\' ), 2' ); # keywords() - scalar and array context, array ref argument $q = new CGI::Simple; $sv = $q->keywords( [ 'foo', 'man', 'chu' ] ); @av = $q->keywords( [ 'foo', 'man', 'chu' ] ); is( $sv, '3', 'keywords( [\'foo\', \'man\', \'chu\'] ), 1' ); is( join( ' ', @av ), 'foo man chu', 'keywords( [\'foo\', \'man\', \'chu\'] ), 2' ); $sv = $q->Vars(); is( $sv->{'color'}, "red\0green\0blue", 'Vars() - tied interface, 1' ); $sv->{'color'} = "foo\0bar\0baz"; is( join( ' ', $q->param( 'color' ) ), 'foo bar baz', 'Vars() - tied interface, 2' ); $q = new CGI::Simple; # Vars() - hash context, void argument my %hv = $q->Vars(); is( $hv{'name'}, 'JaPh,', 'Vars(), 1' ); # Vars() - hash context, "|" argument %hv = $q->Vars( ',' ); is( $hv{'color'}, 'red,green,blue', 'Vars(\',\'), 1' ); # append() - scalar and array context, void argument $sv = $q->append(); @av = $q->append(); is( $sv, undef, 'append(), 1' ); is( join( '', @av ), '', 'append(), 2' ); # append() - scalar and array context, set values, valid param $q->add_param( 'foo', 'bar', 'overwrite' ); $sv = $q->append( 'foo', 'some' ); @av = $q->append( 'foo', 'some-more' ); is( $sv, 'bar', 'append( \'foo\', \'some\' ) set values, 1' ); is( join( ' ', @av ), 'bar some some-more', 'append( \'foo\', \'some\' ) set values, 2' ); # append() - scalar and array context, set values, non-existant param $sv = $q->append( 'invalid', 'param1' ); @av = $q->append( 'invalid', 'param2' ); is( $sv, 'param1', 'append( \'invalid\', \'param\' ) set values, 1' ); is( join( ' ', @av ), 'param1 param2', 'append( \'invalid\', \'param\' ) set values, 2' ); is( join( ' ', $q->param( 'invalid' ) ), 'param1 param2', 'append( \'invalid\', \'param\' ) set values, 3' ); # append() - scalar and array context, set values $sv = $q->append( 'foo', 'some', 'new', 'values' ); @av = $q->append( 'foo', 'even', 'more', 'stuff' ); is( $sv, 'bar', 'append( \'foo\', \'some\', \'new\', \'values\' ) set values, 1' ); is( join( ' ', @av ), 'bar some some-more some new values even more stuff', 'append( \'foo\', \'some\', \'new\', \'values\' ) set values, 2' ); # append() - scalar and array context $sv = $q->append( -name => 'foo', -value => 'baz' ); @av = $q->append( -name => 'foo', -value => 'xyz' ); is( $sv, 'bar', 'append( -name=>\'foo\', -value=>\'bar\' ) set values, 1' ); is( join( ' ', @av ), 'bar some some-more some new values even more stuff baz xyz', 'append( -name=>\'foo\', -value=>\'bar\' ) set values, 2' ); # append() - scalar and array context $sv = $q->append( -name => 'foo', -value => [ 1, 2 ] ); @av = $q->append( -name => 'foo', -value => [ 3, 4 ] ); is( $sv, 'bar', 'append(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 1' ); is( join( ' ', @av ), 'bar some some-more some new values even more stuff baz xyz 1 2 3 4', 'append(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 2' ); # delete() - void/valid argument $q->delete(); is( join( ' ', $q->param ), 'name color foo invalid', 'delete(), 1' ); $q->delete( 'foo' ); is( join( ' ', $q->param ), 'name color invalid', 'delete(), 2' ); # Delete() - void/valid argument $q->Delete(); is( join( ' ', $q->param ), 'name color invalid', 'Delete(), 1' ); $q->Delete( 'invalid' ); is( join( ' ', $q->param ), 'name color', 'Delete(), 2' ); # delete_all() - scalar and array context, void/invalid/valid argument $q->delete_all(); is( join( '', $q->param ), '', 'delete_all(), 1' ); is( $q->globals, '11', 'delete_all(), 2' ); $ENV{'CONTENT_TYPE'} = 'NOT multipart/form-data'; $q = new CGI::Simple; # delete_all() - scalar and array context, void/invalid/valid argument is( join( ' ', $q->param ), 'name color', 'Delete_all(), 1' ); $q->Delete_all(); is( join( '', $q->param ), '', 'Delete_all(), 2' ); $ENV{'CONTENT_TYPE'} = 'application/x-www-form-urlencoded'; # upload() - invalid CONTENT_TYPE $sv = $q->upload( 'foo' ); is( $sv, undef, 'upload() - invalid CONTENT_TYPE, 1' ); is( $q->cgi_error(), 'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your
tag', 'upload() - invalid CONTENT_TYPE, 2' ); $ENV{'CONTENT_TYPE'} = 'multipart/form-data'; # upload() - scalar and array context, void/invalid/valid argument $sv = $q->upload(); @av = $q->upload(); is( $sv, undef, 'upload() - no files available, 1' ); is( join( ' ', @av ), '', 'upload() - no files available, 2' ); # upload() - scalar and array context, files available, void arg $q->{'.filehandles'}->{$_} = $_ for qw( File1 File2 File3 ); $sv = $q->upload(); @av = $q->upload(); is( $sv, 3, 'upload() - files available, 1' ); is( join( ' ', sort @av ), 'File1 File2 File3', 'upload() - files available, 2' ); $q->{'.filehandles'} = {}; # upload() - scalar context, valid argument open FH, $tmpfile or carp "Can't read $tmpfile $!\n"; my $data = join '', ; is( $data && 1, 1, 'upload(\'/some/path/to/myfile\') - real files, 1' ); seek FH, 0, 0; $q->{'.filehandles'}->{'/some/path/to/myfile'} = \*FH; my $handle = $q->upload( '/some/path/to/myfile' ); my $upload = join '', <$handle>; is( $upload, $data, 'upload(\'/some/path/to/myfile\') - real files, 2' ); # upload() - scalar context, invalid argument $sv = $q->upload( 'invalid' ); is( $sv, undef, 'upload(\'invalid\'), 1' ); is( $q->cgi_error, "No filehandle for 'invalid'. Are uploads enabled (\$DISABLE_UPLOADS = 0)? Is \$POST_MAX big enough?", 'upload(\'invalid\'), 2' ); my $ok = $q->upload( '/some/path/to/myfile', "$tmpfile.bak" ); is( $ok, 1, 'upload(\'invalid\'), 3' ); open $handle, "$tmpfile.bak" or carp "Can't read $tmpfile.bak $!\n"; $upload = join '', <$handle>; is( $upload, $data, 'upload(\'invalid\'), 4' ); $sv = $q->upload( '/some/path/to/myfile', "$tmpfile.bak" ); is( $sv, undef, 'upload(\'invalid\'), 5' ); unlink $tmpfile, "$tmpfile.bak"; $ENV{'CONTENT_TYPE'} = 'application/x-www-form-urlencoded'; $q = new CGI::Simple; # query_string() - scalar and array context, void/invalid/valid argument $sv = $q->query_string(); is( $sv, 'name=JaPh%2C&color=red&color=green&color=blue', 'query_string(), 1' ); # parse_query_string() $q->delete_all; is( $q->param, 0, 'parse_query_string(), 1' ); $ENV{'REQUEST_METHOD'} = 'POST'; $q->parse_query_string(); $sv = $q->query_string(); is( $sv, 'name=JaPh%2C&color=red&color=green&color=blue', 'parse_query_string(), 2' ); $ENV{'REQUEST_METHOD'} = 'GET'; # parse_keywordlist() - scalar and array context $sv = $q->parse_keywordlist( 'Just+another++Perl%20hacker%2C' ); @av = $q->parse_keywordlist( 'Just+another++Perl%20hacker%2C' ); is( $sv, '4', 'parse_keywordlist(), 1' ); is( join( ' ', @av ), 'Just another Perl hacker,', 'parse_keywordlist(), 2' ); ################ Save and Restore params from file ############### # _init_from_file() # save() - scalar and array context, void/invalid/valid argument # save_parameters() - scalar and array context, void/invalid/valid argument # all tested in constructor section ################ Miscelaneous Methods ################ $q = new CGI::Simple; # escapeHTML() $sv = $q->escapeHTML(); is( $sv, undef, 'escapeHTML(), 1' ); $sv = $q->escapeHTML( "<>&\"\012\015<>&\"\012\015", 0 ); is( $sv, "<>&"\012\015<>&"\012\015", 'escapeHTML(), 2' ); $sv = $q->escapeHTML( "<>&\"\012\015<>&\"\012\015", 'newlines too' ); is( $sv, "<>&" <>&" ", 'escapeHTML(), 3' ); # unescapeHTML() $sv = $q->unescapeHTML(); is( $sv, undef, 'unescapeHTML(), 1' ); $sv = $q->unescapeHTML( "<>&" <>&" " ); is( $sv, "<>&\"\012\015<>&\"\012\015", 'unescapeHTML(), 2' ); $sv = $q->unescapeHTML( 'Jack & Jill went up the hill; to get a pail of water' ); is( $sv, 'Jack & Jill went up the hill; to get a pail of water', 'unescapeHTML(), 3 ' ); # put() is( $q->put( '' ), 1, 'put(), 1' ); # print() is( $q->print( '' ), 1, 'print(), 1' ); ################# Cookie Methods ################ $q = new CGI::Simple; # raw_cookie() - scalar and array context, void argument $sv = $q->raw_cookie(); @av = $q->raw_cookie(); is( $sv, 'foo=a%20phrase; bar=yes%2C%20a%20phrase&I%20say;', 'raw_cookie(), 1' ); is( join( '', @av ), 'foo=a%20phrase; bar=yes%2C%20a%20phrase&I%20say;', 'raw_cookie(), 2' ); # raw_cookie() - scalar and array context, valid argument $sv = $q->raw_cookie( 'foo' ); @av = $q->raw_cookie( 'foo' ); is( $sv, 'a%20phrase', 'raw_cookie(\'foo\'), 1' ); is( join( '', @av ), 'a%20phrase', 'raw_cookie(\'foo\'), 2' ); # raw_cookie() - scalar and array context, invalid argument $sv = $q->raw_cookie( 'invalid' ); @av = $q->raw_cookie( 'invalid' ); is( $sv, undef, 'raw_cookie(\'invalid\'), 1' ); is( join( '', @av ), '', 'raw_cookie(\'invalid\'), 2' ); # cookie() - scalar and array context, void argument $sv = $q->cookie(); @av = $q->cookie(); is( $sv, '2', 'cookie(), 1' ); # fix OS perl version test bug is( join( ' ', sort @av ), 'bar foo', 'cookie(), 2' ); # cookie() - scalar and array context, valid argument, single value $sv = $q->cookie( 'foo' ); @av = $q->cookie( 'foo' ); is( $sv, 'a phrase', 'cookie(\'foo\'), 1' ); is( join( '', @av ), 'a phrase', 'cookie(\'foo\'), 2' ); # cookie() - scalar and array context, valid argument, multiple values $sv = $q->cookie( 'bar' ); @av = $q->cookie( 'bar' ); is( $sv, 'yes, a phrase', 'cookie(\'foo\'), 1' ); is( join( ' ', @av ), 'yes, a phrase I say', 'cookie(\'foo\'), 2' ); # cookie() - scalar and array context, invalid argument $sv = $q->cookie( 'invalid' ); @av = $q->cookie( 'invalid' ); is( $sv, undef, 'cookie(\'invalid\'), 1' ); is( join( '', @av ), '', 'cookie(\'invalid\'), 2' ); my @vals = ( -name => 'Password', -value => [ 'superuser', 'god', 'open sesame', 'mydog woofie' ], -expires => 'Mon, 11-Nov-2018 11:00:00 GMT', -domain => '.nowhere.com', -path => '/cgi-bin/database', -secure => 1, -httponly => 1 ); # cookie() - scalar and array context, full argument set, correct order $sv = $q->cookie( @vals ); @av = $q->cookie( @vals ); is( $sv, 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) correct order, 1' ); is( join( '', @av ), 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) correct order, 2' ); # cookie() - scalar and array context, full argument set, incorrect order $sv = $q->cookie( @vals[ 0, 1, 10, 11, 12, 13, 8, 9, 2, 3, 4, 5, 6, 7 ] ); @av = $q->cookie( @vals[ 0, 1, 10, 11, 12, 13, 8, 9, 2, 3, 4, 5, 6, 7 ] ); is( $sv, 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) incorrect order, 1' ); is( join( '', @av ), 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) incorrect order, 2' ); my $cookie = $sv; # save a cookie for header testing # cookie() - scalar and array context, partial argument set $sv = $q->cookie( -name => 'foo', -value => 'bar' ); @av = $q->cookie( -name => 'foo', -value => 'bar' ); is( $sv, 'foo=bar; path=/', 'cookie( -name=>\'foo\', -value=>\'bar\' ), 1' ); is( join( '', @av ), 'foo=bar; path=/', 'cookie( -name=>\'foo\', -value=>\'bar\' ), 2' ); ################# Header Methods ################ $q = new CGI::Simple my $CRLF = $q->crlf; # header() - scalar and array context, void argument $sv = $q->header(); @av = $q->header(); is( $sv, "Content-Type: text/html; charset=ISO-8859-1$CRLF$CRLF", 'header(), 1' ); is( join( '', @av ), "Content-Type: text/html; charset=ISO-8859-1$CRLF$CRLF", 'header(), 2' ); # header() - scalar context, single argument $sv = $q->header( 'image/gif' ); is( $sv, "Content-Type: image/gif$CRLF$CRLF", 'header(\'image/gif\'), 1' ); @vals = ( -type => 'image/gif', -nph => 1, -status => '402 Payment required', -expires => 'Mon, 11-Nov-2018 11:00:00 GMT', -cookie => $cookie, -charset => 'utf-7', -attachment => 'foo.gif', -Cost => '$2.00' ); # header() - scalar context, complex header $sv = $q->header( @vals ); my $header = <<'HEADER'; HTTP/1.0 402 Payment required Server: Apache - accept no substitutes Status: 402 Payment required Set-Cookie: Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly Expires: Mon, 11-Nov-2018 11:00:00 GMT Date: Tue, 11-Nov-2018 11:00:00 GMT Content-Disposition: attachment; filename="foo.gif" Cost: $2.00 Content-Type: image/gif HEADER $sv =~ s/[\012\015]//g; $header =~ s/[\012\015]//g; $sv =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements $header =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements is( $sv, $header, 'header(\@vals) - complex header, 1' ); # cache() - scalar and array context, void argument $sv = $q->cache(); is( $sv, undef, 'cache(), 1' ); # cache() - scalar and array context, true argument, sets no cache paragma $sv = $q->cache( 1 ); is( $sv, 1, 'cache(1), 1' ); $sv = $q->header(); is( $sv =~ /Pragma: no-cache/, 1, 'cache(1), 2' ); # no_cache() - scalar and array context, void argument $sv = $q->no_cache(); is( $sv, undef, 'cache(), 1' ); # no_cache() - scalar and array context, true argument, sets no cache paragma $sv = $q->no_cache( 1 ); is( $sv, 1, 'cache(1), 1' ); $sv = $q->header(); like( $sv, qr/Pragma: no-cache/, 'cache(1), 2' ); ok( $sv =~ /Expires:(.*?)GMT/, 'cache(1), 3' ); ok( $sv =~ /Date:$1GMT/ . 'cache(1), 4' ); # redirect() - scalar and array context, void argument $sv = $q->redirect( 'http://a.galaxy.far.away.gov' ); $header = <<'HEADER'; Status: 302 Moved Expires: Tue, 13 Nov 2001 06:45:15 GMT Date: Tue, 13 Nov 2001 06:45:15 GMT Pragma: no-cache Location: http://a.galaxy.far.away.gov HEADER $sv =~ s/[\012\015]//g; $header =~ s/[\012\015]//g; $sv =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements $header =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements is( $sv, $header, 'redirect(), 1' ); # redirect() - scalar and array context, void argument $sv = $q->redirect( -uri => 'http://a.galaxy.far.away.gov', -nph => 1 ); $header = <<'HEADER'; HTTP/1.0 302 Moved Server: Apache - accept no substitutes Status: 302 Moved Expires: Tue, 13 Nov 2001 06:49:24 GMT Date: Tue, 13 Nov 2001 06:49:24 GMT Pragma: no-cache Location: http://a.galaxy.far.away.gov HEADER $sv =~ s/[\012\015]//g; $header =~ s/[\012\015]//g; $sv =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements $header =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements is( $sv, $header, 'redirect() - nph, 1' ); ################# Server Push Methods ################# $q = CGI::Simple->new; $sv = $q->multipart_init(); like( $sv, qr|Content-Type: multipart/x-mixed-replace;boundary="------- =_[a-zA-Z0-9]{17}"|, 'multipart_init(), 1' ); like( $sv, qr/--------- =_[a-zA-Z0-9]{17}$CRLF/, 'multipart_init(), 2' ); $sv = $q->multipart_init( 'this_is_the_boundary' ); like( $sv, qr/boundary="this_is_the_boundary"/, 'multipart_init(), 3' ); { my $sv1 = $q->multipart_init; my $sv2 = $q->multipart_init; isnt( $sv1, $sv2, "due to random boundaries, multiple calls produce different results" ); } $sv = $q->multipart_init( -boundary => 'this_is_another_boundary' ); like( $sv, qr/boundary="this_is_another_boundary"/, 'multipart_init(), 4' ); # multipart_start() $sv = $q->multipart_start(); is( $sv, "Content-Type: text/html$CRLF$CRLF", 'multipart_start(), 1' ); $sv = $q->multipart_start( 'foo/bar' ); is( $sv, "Content-Type: foo/bar$CRLF$CRLF", 'multipart_start(), 2' ); $sv = $q->multipart_start( -type => 'text/plain' ); is( $sv, "Content-Type: text/plain$CRLF$CRLF", 'multipart_start(), 3' ); # multipart_end() $sv = $q->multipart_end(); is( $sv, "$CRLF--this_is_another_boundary$CRLF", 'multipart_end(), 1' ); # multipart_final() - scalar and array context, void/invalid/valid argument $sv = $q->multipart_final(); like( $sv, qr|--this_is_another_boundary--|, 'multipart_final(), 1' ); ################# Debugging Methods ################ # Dump() - scalar context, void argument $sv = $q->Dump(); like( $sv, qr/JaPh,/, 'Dump(), 1' ); # as_string() is( $q->as_string(), $q->Dump(), 'as_string(), 1' ); # cgi_error() $ENV{'REQUEST_METHOD'} = 'GET'; $ENV{'QUERY_STRING'} = ''; $q = CGI::Simple->new; # we have changes this behaviour # is( $q->cgi_error, qr/400 No data received via method: GET/ , 'cgi_error(), 1'); is( $q->cgi_error, undef, 'cgi_error(), 2' ); $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; ############## cgi-lib.pl tests ################ # ReadParse() - scalar and array context, void/invalid/valid argument CGI::Simple::ReadParse(); is( $in{'name'}, 'JaPh,', 'ReadParse(), 1' ); %in = (); $q = new CGI::Simple; $q->ReadParse(); is( $in{'name'}, 'JaPh,', 'ReadParse(), 2' ); CGI::Simple::ReadParse( *field ); is( $field{'name'}, 'JaPh,', 'ReadParse(), 3' ); %field = (); $q = new CGI::Simple; $q->ReadParse( *field ); is( $field{'name'}, 'JaPh,', 'ReadParse(), 4' ); $q = $field{'CGI'}; is( $q->param( 'name' ), 'JaPh,', 'ReadParse(), 5' ); # SplitParam() - scalar and array context, void/invalid/valid argument is( join( ' ', $q->SplitParam( $field{'color'} ) ), 'red green blue', 'SplitParam(), 1' ); is( join( ' ', CGI::Simple::SplitParam( $field{'color'} ) ), 'red green blue', 'SplitParam(), 2' ); is( scalar $q->SplitParam( $field{'color'} ), 'red', 'SplitParam(), 3' ); is( scalar CGI::Simple::SplitParam( $field{'color'} ), 'red', 'SplitParam(), 4' ); # MethGet() - scalar and array context, void/invalid/valid argument is( $q->MethGet, 1, 'MethGet(), 1' ); # MethPost() - scalar and array context, void/invalid/valid argument is( !$q->MethPost, 1, 'MethPost(), 1' ); # MyBaseUrl() - scalar and array context, void/invalid/valid argument is( $q->MyBaseUrl, 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'MyBaseUrl(), 1' ); $ENV{'SERVER_PORT'} = 80; is( $q->MyBaseUrl, 'http://nowhere.com/cgi-bin/foo.cgi', 'MyBaseUrl(), 2' ); $ENV{'SERVER_PORT'} = 8080; # MyURL() - scalar and array context, void/invalid/valid argument is( $q->MyURL, 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'MyURL(), 1' ); # MyFullUrl() - scalar and array context, void/invalid/valid argument is( $q->MyFullUrl, 'http://nowhere.com:8080/cgi-bin/foo.cgi/somewhere/else?name=JaPh%2C&color=red&color=green&color=blue', 'MyFullUrl(), 1' ); $ENV{'QUERY_STRING'} = ''; $ENV{'PATH_INFO'} = ''; is( $q->MyFullUrl, 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'MyFullUrl(), 2' ); $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; $ENV{'PATH_INFO'} = '/somewhere/else'; # PrintHeader() - scalar and array context, void/invalid/valid argument like( $q->PrintHeader, qr|Content-Type: text/html|, 'PrintHeader(), 1' ); # HtmlTop() - scalar and array context, void/invalid/valid argument is( $q->HtmlTop( '$' ), "\n\n\$\n\n\n

\$

\n", 'HtmlTop(), 1' ); is( CGI::Simple::HtmlTop( '$' ), "\n\n\$\n\n\n

\$

\n", 'HtmlTop(), 2' ); # HtmlBot() - scalar and array context, void/invalid/valid argument is( $q->HtmlBot, "\n\n", 'HtmlBot(), 1' ); # PrintVariables() - scalar and array context, void/invalid/valid argument like( $q->PrintVariables( \%field ), qr/JaPh,/, 'PrintVariables(), 1' ); # PrintEnv() - scalar and array context, void/invalid/valid argument like( $q->PrintEnv, qr/PATH_TRANSLATED/, 'PrintEnv(), 1' ); # CgiDie() - scalar and array context, void/invalid/valid argument # CgiError() - scalar and array context, void/invalid/valid argument ################ Accessor Methods ################ $q = new CGI::Simple; # version() - scalar context, void argument like( $q->version(), qr/[\d\.]+/, 'version(), 1' ); # nph() - scalar context, void argument is( $q->nph(), $q->globals( 'NPH' ), 'nph(), 1' ); # nph() - scalar context, valid argument is( $q->nph( 42 ), 42, 'nph(42), 1' ); is( $q->globals( 'NPH' ), 42, 'nph(42), 2' ); # all_parameters() - array context, void/invalid/valid argument $sv = $q->all_parameters(); @av = $q->all_parameters(); is( $sv, 2, 'all_parameters(), 1' ); is( join( ' ', @av ), 'name color', 'all_parameters(), 2' ); # charset() - scalar context, void argument $sv = $q->charset(); is( $sv, 'utf-7', 'charset(), 1' ); # charset() - scalar context, void argument $sv = $q->charset( 'Linear B' ); is( $sv, 'Linear B', 'charset(), 1' ); $sv = $q->charset(); is( $sv, 'Linear B', 'charset(), 2' ); # crlf() - scalar context, void argument $sv = $q->crlf(); like( $sv, qr/[\012\015]{1,2}/, 'crlf(), 1' ); # globals() - scalar and array context, void argument $sv = $q->globals(); is( $sv, 11, 'globals(), 1' ); @av = $q->globals(); is( join( ' ', sort @av ), 'DEBUG DISABLE_UPLOADS FATAL HEADERS_ONCE NO_NULL NO_UNDEF_PARAMS NPH PARAM_UTF8 POST_MAX USE_CGI_PM_DEFAULTS USE_PARAM_SEMICOLONS', 'globals(), 2' ); # globals() - scalar context, invalid argument $sv = $q->globals( 'FOO' ); is( $sv, undef, 'globals(\'FOO\') - invalid arg, 1' ); # globals() - scalar context, valid argument is( $q->globals( 'VERSION', '3.1415' ), '3.1415', 'globals(\'VERSION\') - valid arg, 1' ); is( $q->globals( 'VERSION' ), '3.1415', 'globals(\'VERSION\') - valid arg, 2' ); # auth_type() - scalar context, void argument $sv = $q->auth_type(); is( $sv, 'PGP MD5 DES rot13', 'auth_type(), 1' ); # content_length() - scalar context, void argument $sv = $q->content_length(); is( $sv, '42', 'content_length(), 1' ); # content_type() - scalar context, void argument $sv = $q->content_type(); is( $sv, 'application/x-www-form-urlencoded', 'content_type(), 1' ); # document_root() - scalar context, void argument $sv = $q->document_root(); is( $sv, '/vs/www/foo', 'document_root(), 1' ); # gateway_interface() - scalar context, void argument $sv = $q->gateway_interface(); is( $sv, 'bleeding edge', 'gateway_interface(), 1' ); # path_translated() - scalar context, void argument $sv = $q->path_translated(); is( $sv, '/usr/local/somewhere/else', 'path_translated(), 1' ); # referer() - scalar context, void argument $sv = $q->referer(); is( $sv, 'xxx.sex.com', 'referer(), 1' ); # remote_addr() - scalar and array context, void/invalid/valid argument $sv = $q->remote_addr(); is( $sv, '127.0.0.1', 'remote_addr(), 1' ); # remote_host() - scalar context, void argument $sv = $q->remote_host(); is( $sv, 'localhost', 'remote_host(), 1' ); # remote_ident() - scalar context, void argument $sv = $q->remote_ident(); is( $sv, 'None of your damn business', 'remote_ident(), 1' ); # remote_user() - scalar context, void argument $sv = $q->remote_user(); is( $sv, 'Just another Perl hacker,', 'remote_user(), 1' ); # request_method() - scalar context, void argument $sv = $q->request_method(); is( $sv, 'GET', 'request_method(), 1' ); # script_name() - scalar context, void argument $sv = $q->script_name(); is( $sv, '/cgi-bin/foo.cgi', 'script_name(), 1' ); # server_name() - scalar context, void argument $sv = $q->server_name(); is( $sv, 'nowhere.com', 'server_name(), 1' ); # server_port() - scalar context, void argument $sv = $q->server_port(); is( $sv, '8080', 'server_port(), 1' ); # server_protocol() - scalar context, void argument $sv = $q->server_protocol(); is( $sv, 'HTTP/1.0', 'server_protocol(), 1' ); # server_software() - scalar context, void argument $sv = $q->server_software(); is( $sv, 'Apache - accept no substitutes', 'server_software(), 1' ); # user_name() - scalar context, void argument $sv = $q->user_name(); is( $sv, 'spammer@nowhere.com', 'user_name(), 1' ); # user_agent() - scalar context, void argument $sv = $q->user_agent(); is( $sv, 'LWP', 'user_agent(), 1' ); # user_agent() - scalar context, void argument $sv = $q->user_agent( 'lwp' ); is( $sv, 1, 'user_agent(), 1' ); $sv = $q->user_agent( 'mozilla' ); is( $sv, '', 'user_agent(), 2' ); # virtual_host() - scalar context, void argument $sv = $q->virtual_host(); is( $sv, 'the.vatican.org', 'virtual_host(), 1' ); # path_info() - scalar and array context, void/valid argument $sv = $q->path_info(); is( $sv, '/somewhere/else', 'path_info(), 1' ); $sv = $q->path_info( 'somewhere/else/again' ); is( $sv, '/somewhere/else/again', 'path_info(), 2' ); $sv = $q->path_info(); is( $sv, '/somewhere/else/again', 'path_info(), 3' ); $q->path_info( '/somewhere/else' ); # Accept() - scalar and array context, void argument $sv = $q->Accept(); @av = $q->Accept(); is( $sv, 5, 'Accept(), 1' ); is( join( ' ', sort @av ), '*/* image/gif image/jpg text/html text/plain', 'Accept(), 2' ); # Accept() - scalar context, invalid argument (matches '*/*' $sv = $q->Accept( 'foo/bar' ); is( $sv, '0.001', 'Accept(\'foo/bar\'), 1' ); # Accept() - scalar and array context, void argument $sv = $q->Accept( '*/*' ); is( $sv, '0.001', 'Accept(), 1' ); # http() - scalar and array context, void argument $sv = $q->http(); @av = $q->http(); ok( $sv > 0, 'http(), 1' ); like( $av[0], qr/HTTP/, 'http(), 2' ); # http() - scalar context, invalid arguments $sv = $q->http( 'http-hell' ); is( $sv, undef, 'http(\'invalid arg\'), 1' ); $sv = $q->http( 'hell' ); is( $sv, undef, 'http(\'invalid arg\'), 2' ); # http() - scalar context, valid arguments $sv = $q->http( 'http-from' ); is( $sv, 'spammer@nowhere.com', 'http(\'valid arg\'), 1' ); $sv = $q->http( 'from' ); is( $sv, 'spammer@nowhere.com', 'http(\'valid arg\'), 2' ); # https() - scalar and array context, void argument $sv = $q->https(); is( $sv, 'ON', 'https(), 1' ); # https() - scalar context, invalid argument $sv = $q->https( 'hell' ); is( $sv, undef, 'https(\'invalid arg\'), 1' ); # https() - scalar context, valid arguments $sv = $q->https( 'https-a' ); is( $sv, 'A', 'https(\'valid arg\'), 1' ); $sv = $q->https( 'a' ); is( $sv, 'A', 'https(\'valid arg\'), 2' ); # protocol() - scalar context, void arguments $sv = $q->protocol(); is( $sv, 'https', 'protocol(), 1' ); $ENV{'HTTPS'} = 'OFF'; $ENV{'SERVER_PORT'} = '443'; $sv = $q->protocol(); is( $sv, 'https', 'protocol(), 2' ); $ENV{'SERVER_PORT'} = '8080'; $sv = $q->protocol(); is( $sv, 'http', 'protocol(), 3' ); # url() - scalar context, void argument $ENV{'HTTP_HOST'} = ''; is( $q->url, 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'url(), 1' ); # url() - scalar context, valid argument is( $q->url( -absolute => 1 ), '/cgi-bin/foo.cgi', 'CGI::url(-absolute=>1)' ); # url() - scalar context, valid argument is( $q->url( -relative => 1 ), 'foo.cgi', 'url(-relative=>1), 1' ); # url() - scalar context, valid argument is( $q->url( -relative => 1, -path => 1 ), 'foo.cgi/somewhere/else', 'url(-relative=>1,-path=>1), 1' ); # url() - scalar context, valid argument is( $q->url( -relative => 1, -path => 1, -query => 1 ), 'foo.cgi/somewhere/else?name=JaPh%2C&color=red&color=green&color=blue', 'url(-relative=>1,-path=>1,-query=>1), 1' ); # self_url() - scalar context, void argument $sv = $q->self_url(); @av = $q->self_url(); is( $sv, 'http://nowhere.com:8080/cgi-bin/foo.cgi/somewhere/else?name=JaPh%2C&color=red&color=green&color=blue', 'self_url(), 1' ); # state() - scalar and array context, void/invalid/valid argument is( $q->state(), $q->self_url(), 'state(), 1' ); ################ Yet More Tests ################ #$CGI::Simple::POST_MAX = 20; #$ENV{'REQUEST_METHOD'} = 'POST'; #$q = new CGI::Simple; #is( $q->cgi_error, '413 Request entity too large: 42 bytes on STDIN exceeds $POST_MAX!' , 'Yet more tests, 1'); $ENV{'REQUEST_METHOD'} = 'HEAD'; $ENV{'QUERY_STRING'} = ''; $ENV{'REDIRECT_QUERY_STRING'} = 'name=JAPH&color=red&color=green&color=blue'; $CGI::Simple::POST_MAX = 50; $q = new CGI::Simple; @av = $q->param; is( join( ' ', @av ), 'name color', 'Yet more tests, 2' ); @av = $q->param( 'color' ); is( join( ' ', @av ), 'red green blue', 'Yet more tests, 3' ); CGI-Simple-1.113/t/060.slow_post.t000555000765000120 140411506110167 15673 0ustar00andyadmin000000000000use Test::More tests => 2; use strict; use Config; use CGI::Simple; # Makes forked test work OK Test::More->builder->no_ending( 1 ); my ( $q, $sv ); $CGI::Simple::POST_MAX = -1; SKIP: { skip "Fork not available on this platform", 2 unless $Config{d_fork}; $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_LENGTH} = 10_005; $ENV{CONTENT_TYPE} = 'application/x-www-form-urlencoded'; if ( open( CHILD, "|-" ) ) { # cparent print CHILD 'SLOW='; for ( 1 .. 10 ) { print CHILD 'X' x 1000; sleep 1; } close CHILD; exit 0; } # at this point, we're in a new (child) process $q = new CGI::Simple; $sv = $q->param( 'SLOW' ); is( length $sv, 10_000, 'length ok' ); is( $sv, 'X' x 10_000, 'value ok' ); } CGI-Simple-1.113/t/070.standard.t000555000765000120 12015611506110167 15511 0ustar00andyadmin000000000000use Test::More tests => 289; use Carp; use strict; use vars qw(%field %in); use CGI::Simple::Standard qw( :all ); my ( $q, $sv, @av ); my $tmpfile = './cgi-tmpfile.tmp'; my $debug = 0; $ENV{'AUTH_TYPE'} = 'PGP MD5 DES rot13'; $ENV{'CONTENT_LENGTH'} = '42'; $ENV{'CONTENT_TYPE'} = 'application/x-www-form-urlencoded'; $ENV{'COOKIE'} = 'foo=a%20phrase; bar=yes%2C%20a%20phrase&I%20say;'; $ENV{'DOCUMENT_ROOT'} = '/vs/www/foo'; $ENV{'GATEWAY_INTERFACE'} = 'bleeding edge'; $ENV{'HTTPS'} = 'ON'; $ENV{'HTTPS_A'} = 'A'; $ENV{'HTTPS_B'} = 'B'; $ENV{'HTTP_ACCEPT'} = 'text/html;q=1, text/plain;q=0.8, image/jpg, image/gif;q=0.42, */*;q=0.001'; $ENV{'HTTP_COOKIE'} = ''; $ENV{'HTTP_FROM'} = 'spammer@nowhere.com'; $ENV{'HTTP_HOST'} = 'the.vatican.org'; $ENV{'HTTP_REFERER'} = 'xxx.sex.com'; $ENV{'HTTP_USER_AGENT'} = 'LWP'; $ENV{'PATH_INFO'} = '/somewhere/else'; $ENV{'PATH_TRANSLATED'} = '/usr/local/somewhere/else'; $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; $ENV{'REDIRECT_QUERY_STRING'} = ''; $ENV{'REMOTE_ADDR'} = '127.0.0.1'; $ENV{'REMOTE_HOST'} = 'localhost'; $ENV{'REMOTE_IDENT'} = 'None of your damn business'; $ENV{'REMOTE_USER'} = 'Just another Perl hacker,'; $ENV{'REQUEST_METHOD'} = 'GET'; $ENV{'SCRIPT_NAME'} = '/cgi-bin/foo.cgi'; $ENV{'SERVER_NAME'} = 'nowhere.com'; $ENV{'SERVER_PORT'} = '8080'; $ENV{'SERVER_PROTOCOL'} = 'HTTP/1.0'; $ENV{'SERVER_SOFTWARE'} = 'Apache - accept no substitutes'; restore_parameters(); sub undef_globals { undef $CGI::Simple::USE_CGI_PM_DEFAULTS; undef $CGI::Simple::DISABLE_UPLOADS; undef $CGI::Simple::POST_MAX; undef $CGI::Simple::NO_UNDEF_PARAMS; undef $CGI::Simple::USE_PARAM_SEMICOLONS; undef $CGI::Simple::HEADERS_ONCE; undef $CGI::Simple::NPH; undef $CGI::Simple::DEBUG; undef $CGI::Simple::NO_NULL; undef $CGI::Simple::FATAL; } undef_globals(); restore_parameters(); # _initialize_globals() _initialize_globals(); is( $CGI::Simple::USE_CGI_PM_DEFAULTS, 0, '_initialize_globals(), 1' ); is( $CGI::Simple::DISABLE_UPLOADS, 1, '_initialize_globals(), 2' ); is( $CGI::Simple::POST_MAX, 102_400, '_initialize_globals(), 3' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 0, '_initialize_globals(), 4' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 0, '_initialize_globals(), 5' ); is( $CGI::Simple::HEADERS_ONCE, 0, '_initialize_globals(), 6' ); is( $CGI::Simple::NPH, 0, '_initialize_globals(), 7' ); is( $CGI::Simple::DEBUG, 0, '_initialize_globals(), 8' ); is( $CGI::Simple::NO_NULL, 1, '_initialize_globals(), 9' ); is( $CGI::Simple::FATAL, -1, '_initialize_globals(), 10' ); undef_globals(); # _use_cgi_pm_global_settings() _use_cgi_pm_global_settings(); restore_parameters(); is( $CGI::Simple::DISABLE_UPLOADS, 0, '_use_cgi_pm_global_settings(), 1' ); is( $CGI::Simple::POST_MAX, -1, '_use_cgi_pm_global_settings(), 2' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 0, '_use_cgi_pm_global_settings(), 3' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 1, '_use_cgi_pm_global_settings(), 4' ); is( $CGI::Simple::HEADERS_ONCE, 0, '_use_cgi_pm_global_settings(), 5' ); is( $CGI::Simple::NPH, 0, '_use_cgi_pm_global_settings(), 6' ); is( $CGI::Simple::DEBUG, 1, '_use_cgi_pm_global_settings(), 7' ); is( $CGI::Simple::NO_NULL, 0, '_use_cgi_pm_global_settings(), 8' ); is( $CGI::Simple::FATAL, -1, '_use_cgi_pm_global_settings(), 9' ); # _store_globals() $q = _cgi_object(); undef %{$q}; ok( !defined $q->{'.globals'}->{'DISABLE_UPLOADS'}, '_store_globals(), 1' ); ok( !defined $q->{'.globals'}->{'POST_MAX'}, '_store_globals(), 2' ); ok( !defined $q->{'.globals'}->{'NO_UNDEF_PARAMS'}, '_store_globals(), 3' ); ok( !defined $q->{'.globals'}->{'USE_PARAM_SEMICOLONS'}, '_store_globals(), 4' ); ok( !defined $q->{'.globals'}->{'HEADERS_ONCE'}, '_store_globals(), 5' ); ok( !defined $q->{'.globals'}->{'NPH'}, '_store_globals(), 6' ); ok( !defined $q->{'.globals'}->{'DEBUG'}, '_store_globals(), 7' ); ok( !defined $q->{'.globals'}->{'NO_NULL'}, '_store_globals(), 8' ); ok( !defined $q->{'.globals'}->{'FATAL'}, '_store_globals(), 9' ); ok( !defined $q->{'.globals'}->{'USE_CGI_PM_DEFAULTS'}, '_store_globals(), 10' ); $q->_store_globals(); ok( defined $q->{'.globals'}->{'DISABLE_UPLOADS'}, '_store_globals(), 11' ); ok( defined $q->{'.globals'}->{'POST_MAX'}, '_store_globals(), 12' ); ok( defined $q->{'.globals'}->{'NO_UNDEF_PARAMS'}, '_store_globals(), 13' ); ok( defined $q->{'.globals'}->{'USE_PARAM_SEMICOLONS'}, '_store_globals(), 14' ); ok( defined $q->{'.globals'}->{'HEADERS_ONCE'}, '_store_globals(), 15' ); ok( defined $q->{'.globals'}->{'NPH'}, '_store_globals(), 16' ); ok( defined $q->{'.globals'}->{'DEBUG'}, '_store_globals(), 17' ); ok( defined $q->{'.globals'}->{'NO_NULL'}, '_store_globals(), 18' ); ok( defined $q->{'.globals'}->{'FATAL'}, '_store_globals(), 19' ); ok( defined $q->{'.globals'}->{'USE_CGI_PM_DEFAULTS'}, '_store_globals(), 20' ); # import() - used to set paragmas my @args = qw( -default -no_upload -unique_header -nph -no_debug -newstyle_url -no_undef_param ); undef_globals(); $q->import( @args ); is( $CGI::Simple::USE_CGI_PM_DEFAULTS, 1, 'import(), 1' ); is( $CGI::Simple::DISABLE_UPLOADS, 1, 'import(), 2' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 1, 'import(), 3' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 1, 'import(), 4' ); is( $CGI::Simple::HEADERS_ONCE, 1, 'import(), 5' ); is( $CGI::Simple::NPH, 1, 'import(), 6' ); is( $CGI::Simple::DEBUG, 0, 'import(), 7' ); undef_globals(); $q->import( qw ( -default -upload -no_undefparams -oldstyle_url -npheader -debug ) ); is( $CGI::Simple::USE_CGI_PM_DEFAULTS, 1, 'import(), 8' ); is( $CGI::Simple::DISABLE_UPLOADS, 0, 'import(), 9' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 1, 'import(), 10' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 0, 'import(), 11' ); is( $CGI::Simple::NPH, 1, 'import(), 12' ); is( $CGI::Simple::DEBUG, 2, 'import(), 13' ); undef_globals(); # _reset_globals() _reset_globals(); is( $CGI::Simple::DISABLE_UPLOADS, 0, '_reset_globals(), 1' ); is( $CGI::Simple::POST_MAX, -1, '_reset_globals(), 2' ); is( $CGI::Simple::NO_UNDEF_PARAMS, 0, '_reset_globals(), 3' ); is( $CGI::Simple::USE_PARAM_SEMICOLONS, 1, '_reset_globals(), 4' ); is( $CGI::Simple::HEADERS_ONCE, 0, '_reset_globals(), 5' ); is( $CGI::Simple::NPH, 0, '_reset_globals(), 6' ); is( $CGI::Simple::DEBUG, 1, '_reset_globals(), 7' ); is( $CGI::Simple::NO_NULL, 0, '_reset_globals(), 8' ); is( $CGI::Simple::FATAL, -1, '_reset_globals(), 9' ); undef_globals(); restore_parameters(); # url_decode() - scalar context, void argument $sv = url_decode(); is( $sv, undef, 'url_decode(), 1' ); # url_decode() - scalar context, valid argument my ( $string, $enc_string ); for ( 32 .. 255 ) { $string .= chr; $enc_string .= uc sprintf "%%%02x", ord chr; } is( url_decode( $enc_string ), $string, 'url_decode(\$enc_string), 1' ); # url_encode() - scalar context, void argument $sv = url_encode(); is( $sv, undef, 'url_encode(), 1' ); # url_encode() - scalar context, valid argument $sv = url_encode( $string ); $sv =~ tr/+/ /; $sv =~ s/%([a-fA-F0-9]{2})/ pack "C", hex $1 /eg; is( $sv, $string, 'url_encode(\$string), 1' ); # url encoding - circular test is( url_decode( $q->url_encode( $string ) ), $string, 'url encoding via circular test, 1' ); # new() plain constructor restore_parameters(); like( _cgi_object(), qr/CGI::Simple/, 'new() plain constructor, 1' ); # new() hash constructor restore_parameters( { 'foo' => '1', 'bar' => [ 2, 3, 4 ] } ); @av = param(); # fix OS bug with testing is( join( ' ', sort @av ), 'bar foo', 'new() hash constructor, 1' ); is( param( 'foo' ), 1, 'new() hash constructor, 2' ); is( param( 'bar' ), 2, 'new() hash constructor, 3' ); @av = param( 'bar' ); is( join( '', @av ), 234, 'new() hash constructor, 4' ); restore_parameters( 'foo=1&bar=2&bar=3&bar=4' ); open FH, ">$tmpfile", or carp "Can't create $tmpfile $!\n"; save_parameters( \*FH ); #close FH; # new() query string constructor restore_parameters( 'foo=5&bar=6&bar=7&bar=8' ); @av = param(); is( join( ' ', @av ), 'foo bar', 'new() query string constructor, 1' ); is( param( 'foo' ), 5, 'new() query string constructor, 2' ); is( param( 'bar' ), 6, 'new() query string constructor, 3' ); @av = param( 'bar' ); is( join( '', @av ), 678, 'new() query string constructor, 4' ); open FH, ">>$tmpfile", or carp "Can't append $tmpfile $!\n"; save_parameters( \*FH ); close FH; # new() \@ARGV constructor $ENV{'REQUEST_METHOD'} = ''; $CGI::Simple::DEBUG = 1; @ARGV = qw( foo=bar\=baz foo=bar\&baz ); restore_parameters(); is( join( ' ', param( 'foo' ) ), 'bar=baz bar&baz', 'new() \@ARGV constructor, 1' ); $ENV{'REQUEST_METHOD'} = 'GET'; ################ The Core Methods ################ restore_parameters(); # param() - scalar and array context, void argument $sv = param(); @av = param(); is( $sv, '2', 'param() void argument, 1' ); is( join( ' ', @av ), 'name color', 'param() void argument, 2' ); # param() - scalar and array context, single argument (valid) $sv = param( 'color' ); @av = param( 'color' ); is( $sv, 'red', 'param(\'color\') single argument (valid), 1' ); is( join( ' ', @av ), 'red green blue', 'param(\'color\') single argument (valid), 2' ); # param() - scalar and array context, single argument (invalid) $sv = param( 'invalid' ); @av = param( 'invalid' ); is( $sv, undef, 'param(\'invalid\') single argument (invalid), 1' ); is( join( ' ', @av ), '', 'param(\'invalid\') single argument (invalid), 2' ); # param() - scalar and array context, -name=>'param' (valid) $sv = param( -name => 'color' ); @av = param( -name => 'color' ); is( $sv, 'red', 'param( -name=>\'color\' ) get values, 1' ); is( join( ' ', @av ), 'red green blue', 'param( -name=>\'color\' ) get values, 2' ); # param() - scalar and array context, -name=>'param' (invalid) $sv = param( -name => 'invalid' ); @av = param( -name => 'invalid' ); is( $sv, undef, 'param( -name=>\'invalid\' ) get values, 1' ); is( join( ' ', @av ), '', 'param( -name=>\'invalid\' ) get values, 2' ); # param() - scalar and array context, set values $sv = param( 'foo', 'some', 'new', 'values' ); @av = param( 'foo', 'some', 'new', 'values' ); is( $sv, 'some', 'param( \'foo\', \'some\', \'new\', \'values\' ) set values, 1' ); is( join( ' ', @av ), 'some new values', 'param( \'foo\', \'some\', \'new\', \'values\' ) set values, 2' ); # param() - scalar and array context $sv = param( -name => 'foo', -value => 'bar' ); @av = param( -name => 'foo', -value => 'bar' ); is( $sv, 'bar', 'param( -name=>\'foo\', -value=>\'bar\' ) set values, 1' ); is( join( ' ', @av ), 'bar', 'param( -name=>\'foo\', -value=>\'bar\' ) set values, 2' ); # param() - scalar and array context $sv = param( -name => 'foo', -value => [ 'bar', 'baz' ] ); @av = param( -name => 'foo', -value => [ 'bar', 'baz' ] ); is( $sv, 'bar', 'param(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 1' ); is( join( ' ', @av ), 'bar baz', 'param(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 2' ); # add_param() - scalar and array context, void argument $sv = add_param(); @av = add_param(); is( $sv, undef, 'add_param(), 1' ); is( join( ' ', @av ), '', 'add_param(), 2' ); # add_param() - scalar and array context, existing param argument add_param( 'foo', 'new' ); @av = param( 'foo' ); is( join( ' ', @av ), 'bar baz new', 'add_param( \'foo\', \'new\' ), 1' ); add_param( 'foo', [ 1, 2, 3, 4, 5 ] ); @av = param( 'foo' ); is( join( ' ', @av ), 'bar baz new 1 2 3 4 5', 'add_param( \'foo\', \'new\' ), 2' ); # add_param() - existing param argument, overwrite add_param( 'foo', 'bar', 'overwrite' ); @av = param( 'foo' ); is( join( ' ', @av ), 'bar', 'add_param(\'foo\', \'bar\', \'overwrite\' ), 1' ); # add_param() - scalar and array context, existing param argument add_param( 'new', 'new%2C' ); @av = param( 'new' ); is( join( ' ', @av ), 'new%2C', 'add_param( \'new\', \'new\' ), 1' ); add_param( 'new', [ 1, 2, 3, 4, 5 ] ); @av = param( 'new' ); is( join( ' ', @av ), 'new%2C 1 2 3 4 5', 'add_param( \'new\', \'new\' ), 2' ); # param_fetch() - scalar context, void argument $sv = param_fetch(); is( $sv, undef, 'param_fetch(), 1' ); # param_fetch() - scalar context, 'color' syntax $sv = param_fetch( 'color' ); is( ref $sv, 'ARRAY', 'param_fetch( \'color\' ), 1' ); is( join( ' ', @$sv ), 'red green blue', 'param_fetch( \'color\' ), 2' ); # param_fetch() - scalar context, -name=>'color' syntax $sv = param_fetch( -name => 'color' ); is( ref $sv, 'ARRAY', 'param_fetch( -name=>\'color\' ), 1' ); is( join( ' ', @$sv ), 'red green blue', 'param_fetch( -name=>\'color\' ), 2' ); # url_param() - scalar and array context, void argument $sv = url_param(); @av = url_param(); is( $sv, '2', 'url_param() void argument, 1' ); is( join( ' ', @av ), 'name color', 'url_param() void argument, 2' ); # url_param() - scalar and array context, single argument (valid) $sv = url_param( 'color' ); @av = url_param( 'color' ); is( $sv, 'red', 'url_param(\'color\') single argument (valid), 1' ); is( join( ' ', @av ), 'red green blue', 'url_param(\'color\') single argument (valid), 2' ); # url_param() - scalar and array context, single argument (invalid) $sv = url_param( 'invalid' ); @av = url_param( 'invalid' ); is( $sv, undef, 'url_param(\'invalid\') single argument (invalid), 1' ); is( join( ' ', @av ), '', 'url_param(\'invalid\') single argument (invalid), 2' ); # keywords() - scalar and array context, void argument $ENV{'QUERY_STRING'} = 'here+are++++some%20keywords'; restore_parameters(); $sv = keywords(); @av = keywords(); is( $sv, '4', 'keywords(), 1' ); is( join( ' ', @av ), 'here are some keywords', 'keywords(), 2' ); $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; # keywords() - scalar and array context, array argument $sv = keywords( 'foo', 'bar', 'baz' ); @av = keywords( 'foo', 'bar', 'baz' ); is( $sv, '3', 'keywords( \'foo\', \'bar\', \'baz\' ), 1' ); is( join( ' ', @av ), 'foo bar baz', 'keywords( \'foo\', \'bar\', \'baz\' ), 2' ); # keywords() - scalar and array context, array ref argument restore_parameters(); $sv = keywords( [ 'foo', 'man', 'chu' ] ); @av = keywords( [ 'foo', 'man', 'chu' ] ); is( $sv, '3', 'keywords( [\'foo\', \'man\', \'chu\'] ), 1' ); is( join( ' ', @av ), 'foo man chu', 'keywords( [\'foo\', \'man\', \'chu\'] ), 2' ); # Vars() - scalar and array context, void argument $sv = Vars(); my %hv = Vars(); is( $sv->{'color'}, "red\0green\0blue", 'Vars(), 1' ); is( $hv{'name'}, 'JaPh,', 'Vars(), 2' ); # Vars() - hash context, "|" argument %hv = Vars( '|' ); is( $hv{'color'}, 'red|green|blue', 'Vars(\'|\'), 1' ); # append() - scalar and array context, void argument $sv = append(); @av = append(); is( $sv, undef, 'append(), 1' ); is( join( '', @av ), '', 'append(), 2' ); # append() - scalar and array context, set values, valid param add_param( 'foo', 'bar', 'overwrite' ); $sv = append( 'foo', 'some' ); @av = append( 'foo', 'some-more' ); is( $sv, 'bar', 'append( \'foo\', \'some\' ) set values, 1' ); is( join( ' ', @av ), 'bar some some-more', 'append( \'foo\', \'some\' ) set values, 2' ); # append() - scalar and array context, set values, non-existant param $sv = append( 'invalid', 'param1' ); @av = append( 'invalid', 'param2' ); is( $sv, 'param1', 'append( \'invalid\', \'param\' ) set values, 1' ); is( join( ' ', @av ), 'param1 param2', 'append( \'invalid\', \'param\' ) set values, 2' ); is( join( ' ', param( 'invalid' ) ), 'param1 param2', 'append( \'invalid\', \'param\' ) set values, 3' ); # append() - scalar and array context, set values $sv = append( 'foo', 'some', 'new', 'values' ); @av = append( 'foo', 'even', 'more', 'stuff' ); is( $sv, 'bar', 'append( \'foo\', \'some\', \'new\', \'values\' ) set values, 1' ); is( join( ' ', @av ), 'bar some some-more some new values even more stuff', 'append( \'foo\', \'some\', \'new\', \'values\' ) set values, 2' ); # append() - scalar and array context $sv = append( -name => 'foo', -value => 'baz' ); @av = append( -name => 'foo', -value => 'xyz' ); is( $sv, 'bar', 'append( -name=>\'foo\', -value=>\'bar\' ) set values, 1' ); is( join( ' ', @av ), 'bar some some-more some new values even more stuff baz xyz', 'append( -name=>\'foo\', -value=>\'bar\' ) set values, 2' ); # append() - scalar and array context $sv = append( -name => 'foo', -value => [ 1, 2 ] ); @av = append( -name => 'foo', -value => [ 3, 4 ] ); is( $sv, 'bar', 'append(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 1' ); is( join( ' ', @av ), 'bar some some-more some new values even more stuff baz xyz 1 2 3 4', 'append(-name=>\'foo\',-value=>[\'bar\',\'baz\']) set values, 2' ); # delete() - void/valid argument Delete(); is( join( ' ', param() ), 'name color foo invalid', 'delete(), 1' ); Delete( 'foo' ); is( join( ' ', param() ), 'name color invalid', 'delete(), 2' ); # Delete() - void/valid argument Delete(); is( join( ' ', param() ), 'name color invalid', 'Delete(), 1' ); Delete( 'invalid' ); is( join( ' ', param() ), 'name color', 'Delete(), 2' ); # delete_all() - scalar and array context, void/invalid/valid argument delete_all(); is( join( '', param() ), '', 'delete_all(), 1' ); is( globals(), '11', 'delete_all(), 2' ); restore_parameters(); # delete_all() - scalar and array context, void/invalid/valid argument is( join( ' ', param() ), 'name color', 'Delete_all(), 1' ); Delete_all(); is( join( '', param() ), '', 'Delete_all(), 2' ); $ENV{'CONTENT_TYPE'} = 'multipart/form-data'; # upload() - scalar and array context, void/invalid/valid argument $sv = upload(); @av = upload(); is( $sv, undef, 'upload() - no files available, 1' ); is( join( ' ', @av ), '', 'upload() - no files available, 2' ); # upload() - scalar and array context, files available, void arg $q = _cgi_object(); $q->{'.filehandles'}->{$_} = $_ for qw( File1 File2 File3 ); $sv = upload(); @av = upload(); is( $sv, 3, 'upload() - files available, 1' ); is( join( ' ', sort @av ), 'File1 File2 File3', 'upload() - files available, 2' ); $q->{'.filehandles'} = {}; # upload() - scalar context, valid argument open FH, $tmpfile or carp "Can't read $tmpfile $!\n"; my $data = join '', ; is( $data && 1, 1, 'upload(\'/some/path/to/myfile\') - real files, 1' ) ; # make sure we have data seek FH, 0, 0; $q->{'.filehandles'}->{'/some/path/to/myfile'} = \*FH; my $handle = upload( '/some/path/to/myfile' ); my $upload = join '', <$handle>; is( $upload, $data, 'upload(\'/some/path/to/myfile\') - real files, 2' ); # upload() - scalar context, invalid argument $sv = upload( 'invalid' ); is( $sv, undef, 'upload(\'invalid\'), 1' ); is( cgi_error, "No filehandle for 'invalid'. Are uploads enabled (\$DISABLE_UPLOADS = 0)? Is \$POST_MAX big enough?", 'upload(\'invalid\'), 2' ); my $ok = upload( '/some/path/to/myfile', "$tmpfile.bak" ); is( $ok, 1, 'upload( \'/some/path/to/myfile\', \, 1' ); open $handle, "$tmpfile.bak" or carp "Can't read $tmpfile.bak $!\n"; $upload = join '', <$handle>; is( $upload, $data, 'upload( \'/some/path/to/myfile\', \, 2' ); $sv = upload( '/some/path/to/myfile', "$tmpfile.bak" ); is( $sv, undef, 'upload( \'/some/path/to/myfile\', \, 3' ); unlink $tmpfile, "$tmpfile.bak"; $ENV{'CONTENT_TYPE'} = 'application/x-www-form-urlencoded'; restore_parameters(); # query_string() - scalar and array context, void/invalid/valid argument $sv = query_string(); is( $sv, 'name=JaPh%2C&color=red&color=green&color=blue', 'query_string(), 1' ); # parse_query_string() delete_all(); is( param(), 0, 'parse_query_string(), 1' ); $ENV{'REQUEST_METHOD'} = 'POST'; parse_query_string(); $sv = query_string(); is( $sv, 'name=JaPh%2C&color=red&color=green&color=blue', 'parse_query_string(), 2' ); $ENV{'REQUEST_METHOD'} = 'GET'; # parse_keywordlist() - scalar and array context $sv = parse_keywordlist( 'Just+another++Perl%20hacker%2C' ); @av = parse_keywordlist( 'Just+another++Perl%20hacker%2C' ); is( $sv, '4', 'parse_keywordlist(), 1' ); is( join( ' ', @av ), 'Just another Perl hacker,', 'parse_keywordlist(), 2' ); ################ Save and Restore params from file ############### # _init_from_file() # save() - scalar and array context, void/invalid/valid argument # save_parameters() - scalar and array context, void/invalid/valid argument # all tested in constructor section ################ Miscelaneous Methods ################ restore_parameters(); # escapeHTML() $sv = escapeHTML(); is( $sv, undef, 'escapeHTML(), 1' ); $sv = escapeHTML( "<>&\"\012\015<>&\"\012\015", 0 ); is( $sv, "<>&"\012\015<>&"\012\015", 'escapeHTML(), 2' ); $sv = escapeHTML( "<>&\"\012\015<>&\"\012\015", 'newlines too' ); is( $sv, "<>&" <>&" ", 'escapeHTML(), 3' ); # unescapeHTML() $sv = unescapeHTML(); is( $sv, undef, 'unescapeHTML(), 1' ); $sv = unescapeHTML( "<>&" <>&" " ); is( $sv, "<>&\"\012\015<>&\"\012\015", 'unescapeHTML(), 2' ); # put() is( put( '' ), 1, 'put(), 1' ); # print() is( print( '' ), 1, 'print(), 1' ); ################# Cookie Methods ################ restore_parameters(); # raw_cookie() - scalar and array context, void argument $sv = raw_cookie(); @av = raw_cookie(); is( $sv, 'foo=a%20phrase; bar=yes%2C%20a%20phrase&I%20say;', 'raw_cookie(), 1' ); is( join( '', @av ), 'foo=a%20phrase; bar=yes%2C%20a%20phrase&I%20say;', 'raw_cookie(), 2' ); # raw_cookie() - scalar and array context, valid argument $sv = raw_cookie( 'foo' ); @av = raw_cookie( 'foo' ); is( $sv, 'a%20phrase', 'raw_cookie(\'foo\'), 1' ); is( join( '', @av ), 'a%20phrase', 'raw_cookie(\'foo\'), 2' ); # raw_cookie() - scalar and array context, invalid argument $sv = raw_cookie( 'invalid' ); @av = raw_cookie( 'invalid' ); is( $sv, undef, 'raw_cookie(\'invalid\'), 1' ); is( join( '', @av ), '', 'raw_cookie(\'invalid\'), 2' ); # cookie() - scalar and array context, void argument $sv = cookie(); @av = cookie(); is( $sv, '2', 'cookie(), 1' ); # fix OS perl version test bug is( join( ' ', sort @av ), 'bar foo', 'cookie(), 2' ); # cookie() - scalar and array context, valid argument, single value $sv = cookie( 'foo' ); @av = cookie( 'foo' ); is( $sv, 'a phrase', 'cookie(\'foo\'), 1' ); is( join( '', @av ), 'a phrase', 'cookie(\'foo\'), 2' ); # cookie() - scalar and array context, valid argument, multiple values $sv = cookie( 'bar' ); @av = cookie( 'bar' ); is( $sv, 'yes, a phrase', 'cookie(\'foo\'), 1' ); is( join( ' ', @av ), 'yes, a phrase I say', 'cookie(\'foo\'), 2' ); # cookie() - scalar and array context, invalid argument $sv = cookie( 'invalid' ); @av = cookie( 'invalid' ); is( $sv, undef, 'cookie(\'invalid\'), 1' ); is( join( '', @av ), '', 'cookie(\'invalid\'), 2' ); my @vals = ( -name => 'Password', -value => [ 'superuser', 'god', 'open sesame', 'mydog woofie' ], -expires => 'Mon, 11-Nov-2018 11:00:00 GMT', -domain => '.nowhere.com', -path => '/cgi-bin/database', -secure => 1, -httponly => 1 ); # cookie() - scalar and array context, full argument set, correct order $sv = cookie( @vals ); @av = cookie( @vals ); is( $sv, 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) correct order, 1' ); is( join( '', @av ), 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) correct order, 2' ); # cookie() - scalar and array context, full argument set, incorrect order $sv = cookie( @vals[ 0, 1, 10, 11, 12, 13, 8, 9, 2, 3, 4, 5, 6, 7 ] ); @av = cookie( @vals[ 0, 1, 10, 11, 12, 13, 8, 9, 2, 3, 4, 5, 6, 7 ] ); is( $sv, 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) incorrect order, 1' ); is( join( '', @av ), 'Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly', 'cookie(\@vals) incorrect order, 2' ); my $cookie = $sv; # save a cookie for header testing # cookie() - scalar and array context, partial argument set $sv = cookie( -name => 'foo', -value => 'bar' ); @av = cookie( -name => 'foo', -value => 'bar' ); is( $sv, 'foo=bar; path=/', 'cookie( -name=>\'foo\', -value=>\'bar\' ), 1' ); is( join( '', @av ), 'foo=bar; path=/', 'cookie( -name=>\'foo\', -value=>\'bar\' ), 2' ); ################# Header Methods ################ $q = new CGI::Simple my $CRLF = crlf(); # header() - scalar and array context, void argument $sv = header(); @av = header(); is( $sv, "Content-Type: text/html; charset=ISO-8859-1$CRLF$CRLF", 'header(), 1' ); is( join( '', @av ), "Content-Type: text/html; charset=ISO-8859-1$CRLF$CRLF", 'header(), 2' ); # header() - scalar context, single argument $sv = header( 'image/gif' ); is( $sv, "Content-Type: image/gif$CRLF$CRLF", 'header(\'image/gif\'), 1' ); @vals = ( -type => 'image/gif', -nph => 1, -status => '402 Payment required', -expires => 'Mon, 11-Nov-2018 11:00:00 GMT', -cookie => $cookie, -charset => 'utf-7', -attachment => 'foo.gif', -Cost => '$2.00' ); # header() - scalar context, complex header $sv = header( @vals ); my $header = <<'HEADER'; HTTP/1.0 402 Payment required Server: Apache - accept no substitutes Status: 402 Payment required Set-Cookie: Password=superuser&god&open%20sesame&mydog%20woofie; domain=.nowhere.com; path=/cgi-bin/database; expires=Mon, 11-Nov-2018 11:00:00 GMT; secure; HttpOnly Expires: Mon, 11-Nov-2018 11:00:00 GMT Date: Tue, 11-Nov-2018 11:00:00 GMT Content-Disposition: attachment; filename="foo.gif" Cost: $2.00 Content-Type: image/gif HEADER $sv =~ s/[\012\015]//g; $header =~ s/[\012\015]//g; $sv =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements $header =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements is( $sv, $header, 'header(\@vals) - complex header, 1' ); # cache() - scalar and array context, void argument $sv = cache(); is( $sv, undef, 'cache(), 1' ); # cache() - scalar and array context, true argument, sets no cache paragma $sv = cache( 1 ); is( $sv, 1, 'cache(1), 1' ); $sv = header(); is( $sv =~ /Pragma: no-cache/, 1, 'cache(1), 2' ); # no_cache() - scalar and array context, void argument $sv = no_cache(); is( $sv, undef, 'cache(), 1' ); # no_cache() - scalar and array context, true argument, sets no cache paragma $sv = no_cache( 1 ); is( $sv, 1, 'cache(1), 1' ); $sv = header(); is( ( $sv =~ /Pragma: no-cache/ and $sv =~ /Expires:(.*?)GMT/ and $sv =~ /Date:$1GMT/ ), 1, 'cache(1), 2' ); # redirect() - scalar and array context, void argument $sv = redirect( 'http://a.galaxy.far.away.gov' ); $header = <<'HEADER'; Status: 302 Moved Expires: Tue, 13 Nov 2001 06:45:15 GMT Date: Tue, 13 Nov 2001 06:45:15 GMT Pragma: no-cache Location: http://a.galaxy.far.away.gov HEADER $sv =~ s/[\012\015]//g; $header =~ s/[\012\015]//g; $sv =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements $header =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements is( $sv, $header, 'redirect(), 1' ); # redirect() - scalar and array context, void argument $sv = redirect( -uri => 'http://a.galaxy.far.away.gov', -nph => 1 ); $header = <<'HEADER'; HTTP/1.0 302 Moved Server: Apache - accept no substitutes Status: 302 Moved Expires: Tue, 13 Nov 2001 06:49:24 GMT Date: Tue, 13 Nov 2001 06:49:24 GMT Pragma: no-cache Location: http://a.galaxy.far.away.gov HEADER $sv =~ s/[\012\015]//g; $header =~ s/[\012\015]//g; $sv =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements $header =~ s/(?:Expires|Date).*?GMT//g; # strip the time elements is( $sv, $header, 'redirect() - nph, 1' ); ################# Server Push Methods ################# restore_parameters(); $sv = multipart_init(); like( $sv, qr|Content-Type: multipart/x-mixed-replace;boundary="------- =_[a-zA-Z0-9]{17}"|, 'multipart_init(), 1' ); like( $sv, qr/--------- =_[a-zA-Z0-9]{17}$CRLF/, 'multipart_init(), 2' ); $sv = multipart_init( 'this_is_the_boundary' ); like( $sv, qr/boundary="this_is_the_boundary"/, 'multipart_init(), 3' ); { my $sv1 = multipart_init(); my $sv2 = multipart_init(); isnt( $sv1, $sv2, "due to random boundaries, multiple calls produce different results" ); } $sv = multipart_init( -boundary => 'this_is_another_boundary' ); like( $sv, qr/boundary="this_is_another_boundary"/, 'multipart_init(), 4' ); # multipart_start() $sv = multipart_start(); is( $sv, "Content-Type: text/html$CRLF$CRLF", 'multipart_start(), 1' ); $sv = multipart_start( 'foo/bar' ); is( $sv, "Content-Type: foo/bar$CRLF$CRLF", 'multipart_start(), 2' ); $sv = multipart_start( -type => 'text/plain' ); is( $sv, "Content-Type: text/plain$CRLF$CRLF", 'multipart_start(), 3' ); # multipart_end() $sv = multipart_end(); is( $sv, "$CRLF--this_is_another_boundary$CRLF", 'multipart_end(), 1' ); # multipart_final() - scalar and array context, void/invalid/valid argument $sv = multipart_final(); like( $sv, qr|--this_is_another_boundary--|, 'multipart_final(), 1' ); ################# Debugging Methods ################ # Dump() - scalar context, void argument $sv = Dump(); is( $sv =~ m/JaPh,/, 1, 'Dump(), 1' ); # as_string() is( as_string(), Dump(), 'as_string(), 1' ); # cgi_error() $ENV{'REQUEST_METHOD'} = 'GET'; $ENV{'QUERY_STRING'} = ''; restore_parameters(); # changed this behaviour # like( cgi_error(), qr/400 No data received via method: GET/ , 'cgi_error(), 1'); is( cgi_error(), undef, 'cgi_error(), 2' ); $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; ############## cgi-lib.pl tests ################ # ReadParse() - scalar and array context, void/invalid/valid argument restore_parameters(); ReadParse(); #ok ( $in{'name'}, 'JaPh,' ); restore_parameters(); ReadParse( *field ); is( $field{'name'}, 'JaPh,', 'ReadParse(), 1' ); # SplitParam() - scalar and array context, void/invalid/valid argument is( join( ' ', SplitParam( $field{'color'} ) ), 'red green blue', 'SplitParam(), 1' ); is( scalar SplitParam( $field{'color'} ), 'red', 'SplitParam(), 2' ); # MethGet() - scalar and array context, void/invalid/valid argument is( MethGet(), 1, 'MethGet(), 1' ); # MethPost() - scalar and array context, void/invalid/valid argument is( !MethPost(), 1, 'MethPost(), 1' ); # MyBaseUrl() - scalar and array context, void/invalid/valid argument is( MyBaseUrl(), 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'MyBaseUrl(), 1' ); $ENV{'SERVER_PORT'} = 80; is( MyBaseUrl(), 'http://nowhere.com/cgi-bin/foo.cgi', 'MyBaseUrl(), 2' ); $ENV{'SERVER_PORT'} = 8080; # MyURL() - scalar and array context, void/invalid/valid argument is( MyURL(), 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'MyURL(), 1' ); # MyFullUrl() - scalar and array context, void/invalid/valid argument is( MyFullUrl(), 'http://nowhere.com:8080/cgi-bin/foo.cgi/somewhere/else?name=JaPh%2C&color=red&color=green&color=blue', 'MyFullUrl(), 1' ); $ENV{'QUERY_STRING'} = ''; $ENV{'PATH_INFO'} = ''; is( MyFullUrl(), 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'MyFullUrl(), 2' ); $ENV{'QUERY_STRING'} = 'name=JaPh%2C&color=red&color=green&color=blue'; $ENV{'PATH_INFO'} = '/somewhere/else'; # PrintHeader() - scalar and array context, void/invalid/valid argument like( PrintHeader(), qr|Content-Type: text/html|, 'PrintHeader(), 1' ); # HtmlTop() - scalar and array context, void/invalid/valid argument is( HtmlTop( '$' ), "\n\n\$\n\n\n

\$

\n", 'HtmlTop(), 1' ); # HtmlBot() - scalar and array context, void/invalid/valid argument is( HtmlBot(), "\n\n", 'HtmlBot(), 1' ); # PrintVariables() - scalar and array context, void/invalid/valid argument like( PrintVariables( \%field ), qr/JaPh,/, 'PrintVariables(), 1' ); # PrintEnv() - scalar and array context, void/invalid/valid argument like( PrintEnv(), qr/PATH_TRANSLATED/, 'PrintEnv(), 1' ); # CgiDie() - scalar and array context, void/invalid/valid argument # CgiError() - scalar and array context, void/invalid/valid argument ################ Accessor Methods ################ restore_parameters(); # version() - scalar context, void argument like( version(), qr/[\d\.]+/, 'version(), 1' ); # nph() - scalar context, void argument is( nph(), globals( 'NPH' ), 'nph(), 1' ); # nph() - scalar context, valid argument is( nph( 42 ), 42, 'nph(42), 1' ); is( globals( 'NPH' ), 42, 'nph(42), 2' ); # all_parameters() - array context, void/invalid/valid argument $sv = all_parameters(); @av = all_parameters(); is( $sv, 2, 'all_parameters(), 1' ); is( join( ' ', @av ), 'name color', 'all_parameters(), 2' ); # charset() - scalar context, void argument $sv = charset(); is( $sv, 'utf-7', 'charset(), 1' ) ; # should remain reset to this from header method # charset() - scalar context, void argument $sv = charset( 'Linear B' ); is( $sv, 'Linear B', 'charset(), 1' ); $sv = charset(); is( $sv, 'Linear B', 'charset(), 2' ); # crlf() - scalar context, void argument $sv = crlf(); like( $sv, qr/[\012\015]{1,2}/, 'crlf(), 1' ); # globals() - scalar and array context, void argument $sv = globals(); is( $sv, 11, 'globals(), 1' ); @av = globals(); is( join( ' ', sort @av ), 'DEBUG DISABLE_UPLOADS FATAL HEADERS_ONCE NO_NULL NO_UNDEF_PARAMS NPH PARAM_UTF8 POST_MAX USE_CGI_PM_DEFAULTS USE_PARAM_SEMICOLONS', 'globals(), 2' ); # globals() - scalar context, invalid argument $sv = globals( 'FOO' ); is( $sv, undef, 'globals(\'FOO\') - invalid arg, 1' ); # globals() - scalar context, valid argument is( globals( 'VERSION', '3.1415' ), '3.1415', 'globals(\'VERSION\') - valid arg, 1' ); is( globals( 'VERSION' ), '3.1415', 'globals(\'VERSION\') - valid arg, 2' ); # auth_type() - scalar context, void argument $sv = auth_type(); is( $sv, 'PGP MD5 DES rot13', 'auth_type(), 1' ); # content_length() - scalar context, void argument $sv = content_length(); is( $sv, '42', 'content_length(), 1' ); # content_type() - scalar context, void argument $sv = content_type(); is( $sv, 'application/x-www-form-urlencoded', 'content_type(), 1' ); # document_root() - scalar context, void argument $sv = document_root(); is( $sv, '/vs/www/foo', 'document_root(), 1' ); # gateway_interface() - scalar context, void argument $sv = gateway_interface(); is( $sv, 'bleeding edge', 'gateway_interface(), 1' ); # path_translated() - scalar context, void argument $sv = path_translated(); is( $sv, '/usr/local/somewhere/else', 'path_translated(), 1' ); # referer() - scalar context, void argument $sv = referer(); is( $sv, 'xxx.sex.com', 'referer(), 1' ); # remote_addr() - scalar and array context, void/invalid/valid argument $sv = remote_addr(); is( $sv, '127.0.0.1', 'remote_addr(), 1' ); # remote_host() - scalar context, void argument $sv = remote_host(); is( $sv, 'localhost', 'remote_host(), 1' ); # remote_ident() - scalar context, void argument $sv = remote_ident(); is( $sv, 'None of your damn business', 'remote_ident(), 1' ); # remote_user() - scalar context, void argument $sv = remote_user(); is( $sv, 'Just another Perl hacker,', 'remote_user(), 1' ); # request_method() - scalar context, void argument $sv = request_method(); is( $sv, 'GET', 'request_method(), 1' ); # script_name() - scalar context, void argument $sv = script_name(); is( $sv, '/cgi-bin/foo.cgi', 'script_name(), 1' ); # server_name() - scalar context, void argument $sv = server_name(); is( $sv, 'nowhere.com', 'server_name(), 1' ); # server_port() - scalar context, void argument $sv = server_port(); is( $sv, '8080', 'server_port(), 1' ); # server_protocol() - scalar context, void argument $sv = server_protocol(); is( $sv, 'HTTP/1.0', 'server_protocol(), 1' ); # server_software() - scalar context, void argument $sv = server_software(); is( $sv, 'Apache - accept no substitutes', 'server_software(), 1' ); # user_name() - scalar context, void argument $sv = user_name(); is( $sv, 'spammer@nowhere.com', 'user_name(), 1' ); # user_agent() - scalar context, void argument $sv = user_agent(); is( $sv, 'LWP', 'user_agent(), 1' ); # user_agent() - scalar context, void argument $sv = user_agent( 'lwp' ); is( $sv, 1, 'user_agent(), 1' ); $sv = user_agent( 'mozilla' ); is( $sv, '', 'user_agent(), 2' ); # virtual_host() - scalar context, void argument $sv = virtual_host(); is( $sv, 'the.vatican.org', 'virtual_host(), 1' ); # path_info() - scalar and array context, void/valid argument $sv = path_info(); is( $sv, '/somewhere/else', 'path_info(), 1' ); $sv = path_info( 'somewhere/else/again' ); is( $sv, '/somewhere/else/again', 'path_info(), 2' ); $sv = path_info(); is( $sv, '/somewhere/else/again', 'path_info(), 3' ); path_info( '/somewhere/else' ); # Accept() - scalar and array context, void argument $sv = Accept(); @av = Accept(); is( $sv, 5, 'Accept(), 1' ); is( join( ' ', sort @av ), '*/* image/gif image/jpg text/html text/plain', 'Accept(), 2' ); # Accept() - scalar context, invalid argument (matches '*/*' $sv = Accept( 'foo/bar' ); is( $sv, '0.001', 'Accept(\'foo/bar\'), 1' ); # Accept() - scalar and array context, void argument $sv = Accept( '*/*' ); is( $sv, '0.001', 'Accept(), 1' ); # http() - scalar and array context, void argument $sv = http(); @av = http(); ok( $sv > 0, 'http(), 1' ); like( $av[0], qr/HTTP/, 'http(), 2' ); # http() - scalar context, invalid arguments $sv = http( 'http-hell' ); is( $sv, undef, 'http(\'invalid arg\'), 1' ); $sv = http( 'hell' ); is( $sv, undef, 'http(\'invalid arg\'), 2' ); # http() - scalar context, valid arguments $sv = http( 'http-from' ); is( $sv, 'spammer@nowhere.com', 'http(\'valid arg\'), 1' ); $sv = http( 'from' ); is( $sv, 'spammer@nowhere.com', 'http(\'valid arg\'), 2' ); # https() - scalar and array context, void argument $sv = https(); is( $sv, 'ON', 'https(), 1' ); # https() - scalar context, invalid argument $sv = https( 'hell' ); is( $sv, undef, 'https(\'invalid arg\'), 1' ); # https() - scalar context, valid arguments $sv = https( 'https-a' ); is( $sv, 'A', 'https(\'valid arg\'), 1' ); $sv = https( 'a' ); is( $sv, 'A', 'https(\'valid arg\'), 2' ); # protocol() - scalar context, void arguments $sv = protocol(); is( $sv, 'https', 'protocol(), 1' ); $ENV{'HTTPS'} = 'OFF'; $ENV{'SERVER_PORT'} = '443'; $sv = protocol(); is( $sv, 'https', 'protocol(), 2' ); $ENV{'SERVER_PORT'} = '8080'; $sv = protocol(); is( $sv, 'http', 'protocol(), 3' ); # url() - scalar context, void argument $ENV{'HTTP_HOST'} = ''; is( url(), 'http://nowhere.com:8080/cgi-bin/foo.cgi', 'url(), 1' ); # url() - scalar context, valid argument is( url( -absolute => 1 ), '/cgi-bin/foo.cgi', 'CGI::url(-absolute=>1)' ); # url() - scalar context, valid argument is( url( -relative => 1 ), 'foo.cgi', 'url(-relative=>1), 1' ); # url() - scalar context, valid argument is( url( -relative => 1, -path => 1 ), 'foo.cgi/somewhere/else', 'url(-relative=>1,-path=>1), 1' ); # url() - scalar context, valid argument is( url( -relative => 1, -path => 1, -query => 1 ), 'foo.cgi/somewhere/else?name=JaPh%2C&color=red&color=green&color=blue', 'url(-relative=>1,-path=>1,-query=>1), 1' ); # self_url() - scalar context, void argument $sv = self_url(); @av = self_url(); is( $sv, 'http://nowhere.com:8080/cgi-bin/foo.cgi/somewhere/else?name=JaPh%2C&color=red&color=green&color=blue', 'self_url(), 1' ); # state() - scalar and array context, void/invalid/valid argument is( state(), self_url(), 'state(), 1' ); ################ Yet More Tests ################ #$CGI::Simple::POST_MAX = 20; #$ENV{'REQUEST_METHOD'} = 'POST'; #restore_parameters(); #ok( cgi_error(), '413 Request entity too large: 42 bytes on STDIN exceeds $POST_MAX!' ); $ENV{'REQUEST_METHOD'} = 'HEAD'; $ENV{'QUERY_STRING'} = ''; $ENV{'REDIRECT_QUERY_STRING'} = 'name=JAPH&color=red&color=green&color=blue'; $CGI::Simple::POST_MAX = 50; restore_parameters(); @av = param(); is( join( ' ', @av ), 'name color', 'Yet more tests, 1' ); @av = param( 'color' ); is( join( ' ', @av ), 'red green blue', 'Yet more tests, 2' ); CGI-Simple-1.113/t/080.util.t000555000765000120 203711506110167 14624 0ustar00andyadmin000000000000use Test::More tests => 58; use strict; use CGI::Simple::Util qw(escape unescape); # ASCII order, ASCII codepoints, ASCII repertoire my %punct = ( ' ' => '20', '!' => '21', '"' => '22', '#' => '23', '$' => '24', '%' => '25', '&' => '26', '\'' => '27', '(' => '28', ')' => '29', '*' => '2A', '+' => '2B', ',' => '2C', # '-' => '2D', '.' => '2E' '/' => '2F', ':' => '3A', ';' => '3B', '<' => '3C', '=' => '3D', '>' => '3E', '?' => '3F', '[' => '5B', '\\' => '5C', ']' => '5D', '^' => '5E', # '_' => '5F', '`' => '60', '{' => '7B', '|' => '7C', '}' => '7D', '~' => '7E', ); # The sort order may not be ASCII on EBCDIC machines: foreach ( sort( keys( %punct ) ) ) { my $escape = "AbC\%$punct{$_}dEF"; my $cgi_escape = escape( "AbC$_" . "dEF" ); is( $escape, $cgi_escape, "$escape ne $cgi_escape" ); my $unescape = "AbC$_" . "dEF"; my $cgi_unescape = unescape( "AbC\%$punct{$_}dEF" ); is( $unescape, $cgi_unescape, "$unescape ne $cgi_unescape" ); } CGI-Simple-1.113/t/090.14838.t000444000765000120 152111506110167 14331 0ustar00andyadmin000000000000use strict; use Test::More; Test::More->builder->no_ending( 1 ); use Config; use CGI::Simple; $| = 1; BEGIN { if ( !$Config{d_fork} ) { plan skip_all => "fork not available on this platform"; } eval "use HTTP::Request::Common"; plan skip_all => "HTTP::Request::Common not available" if $@; plan tests => 1; } my $req = HTTP::Request::Common::POST( '/dummy_location', Content_Type => 'form-data', Content => [ test_file => ["t/090.14838.t"], ] ); # Useful in simulating an upload. $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_TYPE} = $req->header( 'Content-type' ); $ENV{CONTENT_LENGTH} = $req->content_length; if ( open( CHILD, "|-" ) ) { print CHILD $req->content; close CHILD; exit 0; } $CGI::Simple::DISABLE_UPLOADS = 0; my $q = new CGI::Simple; is $q->cgi_error, undef, "CGI::Simple can handle this"; CGI-Simple-1.113/t/100.set-cookie.t000444000765000120 35611506110167 15661 0ustar00andyadmin000000000000use strict; use Test::More tests => 1; use CGI::Simple; my $cgi = CGI::Simple->new; like( $cgi->header( '-content-type', 'foo/fum', '-set-cookie', [ 'a=b', 'b=c' ] ), qr/Set-cookie: a=b\s+Set-cookie: b=c/si, 'Set-Cookie' ); CGI-Simple-1.113/t/110.bad-upload.t000444000765000120 153411506110167 15647 0ustar00andyadmin000000000000#!perl use strict; use Test::More; Test::More->builder->no_ending( 1 ); use Config; use File::Spec; use CGI::Simple; $| = 1; plan skip_all => "fork not available on this platform" unless $Config{d_fork}; eval { require HTTP::Request::Common; }; plan skip_all => 'HTTP::Request::Common not available' if $@; plan tests => 1; my $req = HTTP::Request::Common::POST( '/dummy_location', Content_Type => 'form-data', Content => [ test_file => [ File::Spec->catfile( split /\//, "t/test_file.txt" ) ], ] ); # Useful in simulating an upload. $ENV{REQUEST_METHOD} = 'POST'; $ENV{CONTENT_TYPE} = 'multipart/form-data'; $ENV{CONTENT_LENGTH} = $req->content_length; if ( open( CHILD, "|-" ) ) { print CHILD $req->content; close CHILD; exit 0; } my $q = new CGI::Simple; is( $q->cgi_error, undef, "CGI::Simple can handle this" ); CGI-Simple-1.113/t/headers.t000444000765000120 360711506110167 14755 0ustar00andyadmin000000000000 # Test that header generation is spec compliant. # References: # http://www.w3.org/Protocols/rfc2616/rfc2616.html # http://www.w3.org/Protocols/rfc822/3_Lexical.html use strict; use warnings; use Test::More 'no_plan'; use CGI::Simple; my $cgi = CGI::Simple->new; like $cgi->header( -type => "text/html" ), qr#Type: text/html#, 'known header, basic case: type => "text/html"'; eval { like $cgi->header( -type => "text/html" . $cgi->crlf . "evil: stuff" ), qr#Type: text/html evil: stuff#, 'known header'; }; like( $@, qr/contains a newline/, 'invalid header blows up' ); like $cgi->header( -type => "text/html" . $cgi->crlf . " evil: stuff " ), qr#Content-Type: text/html evil: stuff#, 'known header, with leading and trailing whitespace on the continuation line'; eval { like $cgi->header( -foobar => "text/html" . $cgi->crlf . "evil: stuff" ), qr#Foobar: text/htmlevil: stuff#, 'unknown header'; }; like( $@, qr/contains a newline/, 'unknown header with CRLF embedded blows up' ); like $cgi->header( -foobar => "Content-type: evil/header" ), qr#^Foobar: Content-type: evil/header#m, 'unknown header with leading newlines'; eval { like $cgi->redirect( -type => "text/html" . $cgi->crlf . "evil: stuff" ), qr#Type: text/htmlevil: stuff#, 'redirect w/ known header'; }; like( $@, qr/contains a newline/, 'redirect with known header with CRLF embedded blows up' ); eval { like $cgi->redirect( -foobar => "text/html" . $cgi->crlf . "evil: stuff" ), qr#Foobar: text/htmlevil: stuff#, 'redirect w/ unknown header'; }; like( $@, qr/contains a newline/, 'redirect with unknown header with CRLF embedded blows up' ); eval { like $cgi->redirect( $cgi->crlf . $cgi->crlf . "Content-Type: text/html" ), qr#Location: Content-Type#, 'redirect w/ leading newline '; }; like( $@, qr/contains a newline/, 'redirect with leading newlines blows up' ); CGI-Simple-1.113/t/manifest.t000444000765000120 60311506110167 15121 0ustar00andyadmin000000000000#!perl use strict; use warnings; use Test::More; eval { require ExtUtils::Manifest }; plan skip_all => 'No ExtUtils::Manifest' if $@; plan skip_all => 'No MANIFEST.SKIP' unless -f 'MANIFEST.SKIP'; plan tests => 2; my ( $missing, $extra ) = ExtUtils::Manifest::fullcheck(); is_deeply $missing, [], 'missing files'; is_deeply $extra, [], 'extra files'; # vim:ts=2:sw=2:et:ft=perl CGI-Simple-1.113/t/pod-coverage.t000444000765000120 145611506110167 15715 0ustar00andyadmin000000000000#!perl -T use Test::More; eval "use Test::Pod::Coverage 1.04"; plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@; all_pod_coverage_ok( { private => [ qr{^BUILD|DEMOLISH|AUTOMETHOD|START$}, qr{^_}, qr{^\(\"\"|as_string|CgiDie|CgiError|charset|CLEAR|\(cmp|compare|Delete|DELETE$}, qr{^Delete_all|DESTROY|ebcdic|escape|escapeHTML|EXISTS|expires|fetch|FETCH$}, qr{^FIRSTKEY|HtmlBot|HtmlTop|import|init|loader|make_attributes|MethGet$}, qr{^MethPost|MyBaseUrl|MyFullUrl|MyURL|new|NEXTKEY|os|parse|PrintHeader$}, qr{^PrintVariables|query_string|raw_fetch|read_from_cmdline|ReadParse$}, qr{^rearrange|save_parameters|SplitParam|STORE|TIEHASH|unescape|unescapeHTML$}, qr{^upload_fieldnames|uploadInfo|utf8_chr$} ] } ); CGI-Simple-1.113/t/pod.t000444000765000120 21411506110167 14073 0ustar00andyadmin000000000000#!perl -T use Test::More; eval "use Test::Pod 1.14"; plan skip_all => "Test::Pod 1.14 required for testing POD" if $@; all_pod_files_ok(); CGI-Simple-1.113/t/test_file.txt000444000765000120 2511506110167 15623 0ustar00andyadmin000000000000Just a little test. CGI-Simple-1.113/t/upload_info.t000444000765000120 353411506110167 15640 0ustar00andyadmin000000000000use Test::More tests => 3; use strict; use warnings; use IO::Scalar; use CGI::Simple; # Set up a CGI environment $ENV{REQUEST_METHOD} = 'POST'; $ENV{QUERY_STRING} = ''; $ENV{PATH_INFO} = '/somewhere/else'; $ENV{PATH_TRANSLATED} = '/usr/local/somewhere/else'; $ENV{SCRIPT_NAME} = '/cgi-bin/foo.cgi'; $ENV{SERVER_PROTOCOL} = 'HTTP/1.0'; $ENV{SERVER_PORT} = 8080; $ENV{SERVER_NAME} = 'upload.info.com'; $ENV{CONTENT_TYPE} = q{multipart/form-data; boundary=---------------------------10263292819275730631136676268}; $ENV{REQUEST_URI} = "$ENV{SCRIPT_NAME}$ENV{PATH_INFO}?$ENV{QUERY_STRING}"; $ENV{HTTP_LOVE} = 'true'; my $body = <fake\r -----------------------------10263292819275730631136676268\r Content-Disposition: form-data; name="file2"; filename="spreadsheet.xls"\r Content-Type: application/vnd.ms-excel\r \r fake\r -----------------------------10263292819275730631136676268--\r EOF $ENV{CONTENT_LENGTH} = length $body; my $h = IO::Scalar->new( \$body ); my $q = new CGI::Simple( $h ); ok( $q->upload_info( $q->param( 'file0' ), 'mime' ) eq 'image/png', 'Guess mime for image/png' ); ok( $q->upload_info( $q->param( 'file1' ), 'mime' ) eq 'image/svg+xml', 'Guess mime for image/svg+xml' ); ok( $q->upload_info( $q->param( 'file2' ), 'mime' ) eq 'application/vnd.ms-excel', 'Guess mime for application/vnd.ms-excel' ); #2010-03-19 by Krasimir Berov, based on 041.multipart.t