Add built local::lib
[catagits/Gitalist.git] / local-lib5 / lib / perl5 / CGI / Simple.pm
1 package CGI::Simple;
2
3 require 5.004;
4
5 # this module is both strict (and warnings) compliant, but they are only used
6 # in testing as they add an unnecessary compile time overhead in production.
7 use strict;
8 use Carp;
9
10 use vars qw(
11  $VERSION $USE_CGI_PM_DEFAULTS $DISABLE_UPLOADS $POST_MAX
12  $NO_UNDEF_PARAMS $USE_PARAM_SEMICOLONS $PARAM_UTF8 $HEADERS_ONCE
13  $NPH $DEBUG $NO_NULL $FATAL *in
14 );
15
16 $VERSION = "1.112";
17
18 # you can hard code the global variable settings here if you want.
19 # warning - do not delete the unless defined $VAR part unless you
20 # want to permanently remove the ability to change the variable.
21 sub _initialize_globals {
22
23   # set this to 1 to use CGI.pm default global settings
24   $USE_CGI_PM_DEFAULTS = 0
25    unless defined $USE_CGI_PM_DEFAULTS;
26
27   # see if user wants old CGI.pm defaults
28   if ( $USE_CGI_PM_DEFAULTS ) {
29     _use_cgi_pm_global_settings();
30     return;
31   }
32
33   # no file uploads by default, set to 0 to enable uploads
34   $DISABLE_UPLOADS = 1
35    unless defined $DISABLE_UPLOADS;
36
37   # use a post max of 100K, set to -1 for no limits
38   $POST_MAX = 102_400
39    unless defined $POST_MAX;
40
41   # set to 1 to not include undefined params parsed from query string
42   $NO_UNDEF_PARAMS = 0
43    unless defined $NO_UNDEF_PARAMS;
44
45   # separate the name=value pairs with ; rather than &
46   $USE_PARAM_SEMICOLONS = 0
47    unless defined $USE_PARAM_SEMICOLONS;
48
49   # return everything as utf-8
50   $PARAM_UTF8 ||= 0;
51   $PARAM_UTF8 and require Encode;
52
53   # only print headers once
54   $HEADERS_ONCE = 0
55    unless defined $HEADERS_ONCE;
56
57   # Set this to 1 to enable NPH scripts
58   $NPH = 0
59    unless defined $NPH;
60
61   # 0 => no debug, 1 => from @ARGV,  2 => from STDIN
62   $DEBUG = 0
63    unless defined $DEBUG;
64
65   # filter out null bytes in param - value pairs
66   $NO_NULL = 1
67    unless defined $NO_NULL;
68
69 # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak
70   $FATAL = -1
71    unless defined $FATAL;
72 }
73
74 # I happen to disagree with many of the default global settings in CGI.pm
75 # This sub is called if you set $CGI::Simple::USE_CGI_PM_GLOBALS = 1; or
76 # invoke the '-default' pragma via a use CGI::Simple qw(-default);
77 sub _use_cgi_pm_global_settings {
78   $USE_CGI_PM_DEFAULTS  = 1;
79   $DISABLE_UPLOADS      = 0 unless defined $DISABLE_UPLOADS;
80   $POST_MAX             = -1 unless defined $POST_MAX;
81   $NO_UNDEF_PARAMS      = 0 unless defined $NO_UNDEF_PARAMS;
82   $USE_PARAM_SEMICOLONS = 1 unless defined $USE_PARAM_SEMICOLONS;
83   $HEADERS_ONCE         = 0 unless defined $HEADERS_ONCE;
84   $NPH                  = 0 unless defined $NPH;
85   $DEBUG                = 1 unless defined $DEBUG;
86   $NO_NULL              = 0 unless defined $NO_NULL;
87   $FATAL                = -1 unless defined $FATAL;
88   $PARAM_UTF8           = 0 unless defined $PARAM_UTF8;
89 }
90
91 # this is called by new, we will never directly reference the globals again
92 sub _store_globals {
93   my $self = shift;
94
95   $self->{'.globals'}->{'DISABLE_UPLOADS'}      = $DISABLE_UPLOADS;
96   $self->{'.globals'}->{'POST_MAX'}             = $POST_MAX;
97   $self->{'.globals'}->{'NO_UNDEF_PARAMS'}      = $NO_UNDEF_PARAMS;
98   $self->{'.globals'}->{'USE_PARAM_SEMICOLONS'} = $USE_PARAM_SEMICOLONS;
99   $self->{'.globals'}->{'HEADERS_ONCE'}         = $HEADERS_ONCE;
100   $self->{'.globals'}->{'NPH'}                  = $NPH;
101   $self->{'.globals'}->{'DEBUG'}                = $DEBUG;
102   $self->{'.globals'}->{'NO_NULL'}              = $NO_NULL;
103   $self->{'.globals'}->{'FATAL'}                = $FATAL;
104   $self->{'.globals'}->{'USE_CGI_PM_DEFAULTS'}  = $USE_CGI_PM_DEFAULTS;
105   $self->{'.globals'}->{'PARAM_UTF8'}           = $PARAM_UTF8;
106 }
107
108 # use the automatic calling of the import sub to set our pragmas. CGI.pm compat
109 sub import {
110   my ( $self, @args ) = @_;
111
112 # arguments supplied in the 'use CGI::Simple [ARGS];' will now be in @args
113   foreach ( @args ) {
114     $USE_CGI_PM_DEFAULTS = 1, next if m/^-default/i;
115     $DISABLE_UPLOADS     = 1, next if m/^-no.?upload/i;
116     $DISABLE_UPLOADS     = 0, next if m/^-upload/i;
117     $HEADERS_ONCE        = 1, next if m/^-unique.?header/i;
118     $NPH                 = 1, next if m/^-nph/i;
119     $DEBUG               = 0, next if m/^-no.?debug/i;
120     $DEBUG = defined $1 ? $1 : 2, next if m/^-debug(\d)?/i;
121     $USE_PARAM_SEMICOLONS = 1, next if m/^-newstyle.?url/i;
122     $USE_PARAM_SEMICOLONS = 0, next if m/^-oldstyle.?url/i;
123     $NO_UNDEF_PARAMS      = 1, next if m/^-no.?undef.?param/i;
124     $FATAL                = 0, next if m/^-carp/i;
125     $FATAL                = 1, next if m/^-croak/i;
126     croak "Pragma '$_' is not defined in CGI::Simple\n";
127   }
128 }
129
130 # used in CGI.pm .t files
131 sub _reset_globals {
132   _use_cgi_pm_global_settings();
133 }
134
135 binmode STDIN;
136 binmode STDOUT;
137
138 # use correct encoding conversion to handle non ASCII char sets.
139 # we import and install the complex routines only if we have to.
140 BEGIN {
141
142   sub url_decode {
143     my ( $self, $decode ) = @_;
144     return () unless defined $decode;
145     $decode =~ tr/+/ /;
146     $decode =~ s/%([a-fA-F0-9]{2})/ pack "C", hex $1 /eg;
147     return $decode;
148   }
149
150   sub url_encode {
151     my ( $self, $encode ) = @_;
152     return () unless defined $encode;
153     $encode
154      =~ s/([^A-Za-z0-9\-_.!~*'() ])/ uc sprintf "%%%02x",ord $1 /eg;
155     $encode =~ tr/ /+/;
156     return $encode;
157   }
158
159   if ( "\t" ne "\011" ) {
160     eval { require CGI::Simple::Util };
161     if ( $@ ) {
162       croak
163        "Your server is using not using ASCII, you must install CGI::Simple::Util, error: $@";
164     }
165
166     # hack the symbol table and replace simple encode/decode subs
167     *CGI::Simple::url_encode
168      = sub { CGI::Simple::Util::escape( $_[1] ) };
169     *CGI::Simple::url_decode
170      = sub { CGI::Simple::Util::unescape( $_[1] ) };
171   }
172 }
173
174 ################ The Guts ################
175
176 sub new {
177   my ( $class, $init ) = @_;
178   $class = ref( $class ) || $class;
179   my $self = {};
180   bless $self, $class;
181   if ( $self->_mod_perl ) {
182     if ( $init ) {
183       $self->{'.mod_perl_request'} = $init;
184       undef $init;    # otherwise _initialize takes the wrong path
185     }
186     $self->_initialize_mod_perl();
187   }
188   $self->_initialize_globals;
189   $self->_store_globals;
190   $self->_initialize( $init );
191   return $self;
192 }
193
194 sub _mod_perl {
195   return (
196     exists $ENV{MOD_PERL}
197      or ( $ENV{GATEWAY_INTERFACE}
198       and $ENV{GATEWAY_INTERFACE} =~ m{^CGI-Perl/} )
199   );
200 }
201
202 # Return the global request object under mod_perl. If you use mod_perl 2
203 # and you don't set PerlOptions +GlobalRequest then the request must be
204 # passed in to the new() method.
205 sub _mod_perl_request {
206   my $self = shift;
207
208   my $mp = $self->{'.mod_perl'};
209
210   return unless $mp;
211
212   my $req = $self->{'.mod_perl_request'};
213   return $req if $req;
214
215   $self->{'.mod_perl_request'} = do {
216     if ( $mp == 2 ) {
217       Apache2::RequestUtil->request;
218     }
219     else {
220       Apache->request;
221     }
222   };
223 }
224
225 sub _initialize_mod_perl {
226   my ( $self ) = @_;
227
228   eval "require mod_perl";
229
230   if ( defined $mod_perl::VERSION ) {
231
232     if ( $mod_perl::VERSION >= 2.00 ) {
233       $self->{'.mod_perl'} = 2;
234
235       require Apache2::RequestRec;
236       require Apache2::RequestIO;
237       require Apache2::RequestUtil;
238       require Apache2::Response;
239       require APR::Pool;
240
241       my $r = $self->_mod_perl_request();
242
243       if ( defined $r ) {
244         $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
245         $r->pool->cleanup_register(
246           \&CGI::Simple::_initialize_globals );
247       }
248     }
249     else {
250       $self->{'.mod_perl'} = 1;
251
252       require Apache;
253
254       my $r = $self->_mod_perl_request();
255
256       if ( defined $r ) {
257         $r->register_cleanup( \&CGI::Simple::_initialize_globals );
258       }
259     }
260   }
261 }
262
263 sub _initialize {
264   my ( $self, $init ) = @_;
265
266   if ( !defined $init ) {
267
268     # initialize from QUERY_STRING, STDIN or @ARGV
269     $self->_read_parse();
270   }
271   elsif ( ( ref $init ) =~ m/HASH/i ) {
272
273     # initialize from param hash
274     for my $param ( keys %{$init} ) {
275       $self->_add_param( $param, $init->{$param} );
276     }
277   }
278
279   # chromatic's blessed GLOB patch
280   # elsif ( (ref $init) =~ m/GLOB/i ) { # initialize from a file
281   elsif ( UNIVERSAL::isa( $init, 'GLOB' ) ) {   # initialize from a file
282     $self->_read_parse( $init );
283   }
284   elsif ( ( ref $init ) eq 'CGI::Simple' ) {
285
286     # initialize from a CGI::Simple object
287     require Data::Dumper;
288
289     # avoid problems with strict when Data::Dumper returns $VAR1
290     my $VAR1;
291     my $clone = eval( Data::Dumper::Dumper( $init ) );
292     if ( $@ ) {
293       $self->cgi_error( "Can't clone CGI::Simple object: $@" );
294     }
295     else {
296       $_[0] = $clone;
297     }
298   }
299   else {
300     $self->_parse_params( $init );    # initialize from a query string
301   }
302 }
303
304 sub _internal_read($*\$;$) {
305   my ( $self, $glob, $buffer, $len ) = @_;
306   $len = 4096 if !defined $len;
307   if ( $self->{'.mod_perl'} ) {
308     my $r = $self->_mod_perl_request();
309     $r->read( $$buffer, $len );
310   }
311   else {
312     read( $glob, $$buffer, $len );
313   }
314 }
315
316 sub _read_parse {
317   my $self = shift;
318   my $handle = shift || \*STDIN;
319
320   my $data   = '';
321   my $type   = $ENV{'CONTENT_TYPE'} || 'No CONTENT_TYPE received';
322   my $length = $ENV{'CONTENT_LENGTH'} || 0;
323   my $method = $ENV{'REQUEST_METHOD'} || 'No REQUEST_METHOD received';
324
325   # first check POST_MAX Steve Purkis pointed out the previous bug
326   if (  ( $method eq 'POST' or $method eq "PUT" )
327     and $self->{'.globals'}->{'POST_MAX'} != -1
328     and $length > $self->{'.globals'}->{'POST_MAX'} ) {
329     $self->cgi_error(
330       "413 Request entity too large: $length bytes on STDIN exceeds \$POST_MAX!"
331     );
332
333     # silently discard data ??? better to just close the socket ???
334     while ( $length > 0 ) {
335       last unless _internal_read( $self, $handle, my $buffer );
336       $length -= length( $buffer );
337     }
338
339     return;
340   }
341
342   if ( $length and $type =~ m|^multipart/form-data|i ) {
343     my $got_length = $self->_parse_multipart( $handle );
344     if ( $length != $got_length ) {
345       $self->cgi_error(
346         "500 Bad read on multipart/form-data! wanted $length, got $got_length"
347       );
348     }
349
350     return;
351   }
352   elsif ( $method eq 'POST' or $method eq 'PUT' ) {
353     if ( $length ) {
354
355       # we may not get all the data we want with a single read on large
356       # POSTs as it may not be here yet! Credit Jason Luther for patch
357       # CGI.pm < 2.99 suffers from same bug
358       _internal_read( $self, $handle, $data, $length );
359       while ( length( $data ) < $length ) {
360         last unless _internal_read( $self, $handle, my $buffer );
361         $data .= $buffer;
362       }
363
364       unless ( $length == length $data ) {
365         $self->cgi_error( "500 Bad read on POST! wanted $length, got "
366            . length( $data ) );
367         return;
368       }
369
370       if ( $type !~ m|^application/x-www-form-urlencoded| ) {
371         $self->_add_param( $method . "DATA", $data );
372       }
373       else {
374         $self->_parse_params( $data );
375       }
376     }
377   }
378   elsif ( $method eq 'GET' or $method eq 'HEAD' ) {
379     $data
380      = $self->{'.mod_perl'}
381      ? $self->_mod_perl_request()->args()
382      : $ENV{'QUERY_STRING'}
383      || $ENV{'REDIRECT_QUERY_STRING'}
384      || '';
385     $self->_parse_params( $data );
386   }
387   else {
388     unless ( $self->{'.globals'}->{'DEBUG'}
389       and $data = $self->read_from_cmdline() ) {
390       $self->cgi_error( "400 Unknown method $method" );
391       return;
392     }
393
394     unless ( $data ) {
395
396 # I liked this reporting but CGI.pm does not behave like this so
397 # out it goes......
398 # $self->cgi_error("400 No data received via method: $method, type: $type");
399       return;
400     }
401
402     $self->_parse_params( $data );
403   }
404 }
405
406 sub _parse_params {
407   my ( $self, $data ) = @_;
408   return () unless defined $data;
409   unless ( $data =~ /[&=;]/ ) {
410     $self->{'keywords'} = [ $self->_parse_keywordlist( $data ) ];
411     return;
412   }
413   my @pairs = split /[&;]/, $data;
414   for my $pair ( @pairs ) {
415     my ( $param, $value ) = split /=/, $pair, 2;
416     next unless defined $param;
417     $value = '' unless defined $value;
418     $self->_add_param( $self->url_decode( $param ),
419       $self->url_decode( $value ) );
420   }
421 }
422
423 sub _add_param {
424   my ( $self, $param, $value, $overwrite ) = @_;
425   return () unless defined $param and defined $value;
426   $param =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'};
427   @{ $self->{$param} } = () if $overwrite;
428   @{ $self->{$param} } = () unless exists $self->{$param};
429   my @values = ref $value ? @{$value} : ( $value );
430   for my $value ( @values ) {
431     next
432      if $value eq ''
433        and $self->{'.globals'}->{'NO_UNDEF_PARAMS'};
434     $value =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'};
435     $value = Encode::decode( utf8 => $value )
436      if $self->{'.globals'}->{PARAM_UTF8};
437     push @{ $self->{$param} }, $value;
438     unless ( $self->{'.fieldnames'}->{$param} ) {
439       push @{ $self->{'.parameters'} }, $param;
440       $self->{'.fieldnames'}->{$param}++;
441     }
442   }
443   return scalar @values;    # for compatibility with CGI.pm request.t
444 }
445
446 sub _parse_keywordlist {
447   my ( $self, $data ) = @_;
448   return () unless defined $data;
449   $data = $self->url_decode( $data );
450   $data =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'};
451   my @keywords = split /\s+/, $data;
452   return @keywords;
453 }
454
455 sub _massage_boundary {
456   my ( $self, $boundary ) = @_;
457
458   # BUG: IE 3.01 on the Macintosh uses just the boundary,
459   # forgetting the --
460   $boundary = '--' . $boundary
461    unless exists $ENV{'HTTP_USER_AGENT'}
462      && $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+3\.0[12];\s*Mac/i;
463
464   return quotemeta $boundary;
465 }
466
467 sub _parse_multipart {
468   my $self = shift;
469   my $handle = shift or die "NEED A HANDLE!?";
470
471   my ( $boundary )
472    = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
473
474   $boundary = $self->_massage_boundary( $boundary ) if $boundary;
475
476   my $got_data = 0;
477   my $data     = '';
478   my $length   = $ENV{'CONTENT_LENGTH'} || 0;
479   my $CRLF     = $self->crlf;
480
481   READ:
482
483   while ( $got_data < $length ) {
484     last READ unless _internal_read( $self, $handle, my $buffer );
485     $data .= $buffer;
486     $got_data += length $buffer;
487
488     unless ( $boundary ) {
489       # If we're going to guess the boundary we need a complete line.
490       next READ unless $data =~ /^(.*)$CRLF/o;
491       $boundary = $1;
492
493       # Still no boundary? Give up...
494       unless ( $boundary ) {
495         $self->cgi_error(
496           '400 No boundary supplied for multipart/form-data' );
497         return 0;
498       }
499       $boundary = $self->_massage_boundary( $boundary );
500     }
501
502     BOUNDARY:
503
504     while ( $data =~ m/^$boundary$CRLF/ ) {
505       ## TAB and high ascii chars are definitivelly allowed in headers.
506       ## Not accepting them in the following regex prevents the upload of
507       ## files with filenames like "España.txt".
508       # next READ unless $data =~ m/^([\040-\176$CRLF]+?$CRLF$CRLF)/o;
509       next READ
510        unless $data =~ m/^([\x20-\x7E\x80-\xFF\x09$CRLF]+?$CRLF$CRLF)/o;
511       my $header = $1;
512       ( my $unfold = $1 ) =~ s/$CRLF\s+/ /og;
513       my ( $param ) = $unfold =~ m/form-data;\s+name="?([^\";]*)"?/;
514       my ( $filename )
515        = $unfold =~ m/name="?\Q$param\E"?;\s+filename="?([^\"]*)"?/;
516
517       if ( defined $filename ) {
518         my ( $mime ) = $unfold =~ m/Content-Type:\s+([-\w\/]+)/io;
519         $data =~ s/^\Q$header\E//;
520         ( $got_data, $data, my $fh, my $size )
521          = $self->_save_tmpfile( $handle, $boundary, $filename,
522           $got_data, $data );
523         $self->_add_param( $param, $filename );
524         $self->{'.upload_fields'}->{$param} = $filename;
525         $self->{'.filehandles'}->{$filename} = $fh if $fh;
526         $self->{'.tmpfiles'}->{$filename}
527          = { 'size' => $size, 'mime' => $mime }
528          if $size;
529         next BOUNDARY;
530       }
531       next READ
532        unless $data =~ s/^\Q$header\E(.*?)$CRLF(?=$boundary)//s;
533       $self->_add_param( $param, $1 );
534     }
535     unless ( $data =~ m/^$boundary/ ) {
536       ## In a perfect world, $data should always begin with $boundary.
537       ## But sometimes, IE5 prepends garbage boundaries into POST(ed) data.
538       ## Then, $data does not start with $boundary and the previous block
539       ## never gets executed. The following fix attempts to remove those
540       ## extra boundaries from readed $data and restart boundary parsing.
541       ## Note about performance: with well formed data, previous check is
542       ## executed (generally) only once, when $data value is "$boundary--"
543       ## at end of parsing.
544       goto BOUNDARY if ( $data =~ s/.*?$CRLF(?=$boundary$CRLF)//s );
545     }
546   }
547   return $got_data;
548 }
549
550 sub _save_tmpfile {
551   my ( $self, $handle, $boundary, $filename, $got_data, $data ) = @_;
552   my $fh;
553   my $CRLF      = $self->crlf;
554   my $length    = $ENV{'CONTENT_LENGTH'} || 0;
555   my $file_size = 0;
556   if ( $self->{'.globals'}->{'DISABLE_UPLOADS'} ) {
557     $self->cgi_error( "405 Not Allowed - File uploads are disabled" );
558   }
559   elsif ( $filename ) {
560     eval { require IO::File };
561     $self->cgi_error( "500 IO::File is not available $@" ) if $@;
562     $fh = new_tmpfile IO::File;
563     $self->cgi_error( "500 IO::File can't create new temp_file" )
564      unless $fh;
565   }
566
567 # read in data until closing boundary found. buffer to catch split boundary
568 # we do this regardless of whether we save the file or not to read the file
569 # data from STDIN. if either uploads are disabled or no file has been sent
570 # $fh will be undef so only do file stuff if $fh is true using $fh && syntax
571   $fh && binmode $fh;
572   while ( $got_data < $length ) {
573
574     my $buffer = $data;
575     last unless _internal_read( $self, \*STDIN, $data );
576
577     # fixed hanging bug if browser terminates upload part way through
578     # thanks to Brandon Black
579     unless ( $data ) {
580       $self->cgi_error(
581         '400 Malformed multipart, no terminating boundary' );
582       undef $fh;
583       return $got_data;
584     }
585
586     $got_data += length $data;
587     if ( "$buffer$data" =~ m/$boundary/ ) {
588       $data = $buffer . $data;
589       last;
590     }
591
592     # we do not have partial boundary so print to file if valid $fh
593     $fh && print $fh $buffer;
594     $file_size += length $buffer;
595   }
596   $data =~ s/^(.*?)$CRLF(?=$boundary)//s;
597   $fh && print $fh $1;    # print remainder of file if valid $fh
598   $file_size += length $1;
599   return $got_data, $data, $fh, $file_size;
600 }
601
602 # Define the CRLF sequence.  You can't use a simple "\r\n" because of system
603 # specific 'features'. On EBCDIC systems "\t" ne "\011" as the don't use ASCII
604 sub crlf {
605   my ( $self, $CRLF ) = @_;
606   $self->{'.crlf'} = $CRLF if $CRLF;    # allow value to be set manually
607   unless ( $self->{'.crlf'} ) {
608     my $OS = $^O
609      || do { require Config; $Config::Config{'osname'} };
610     $self->{'.crlf'}
611      = ( $OS =~ m/VMS/i ) ? "\n"
612      : ( "\t" ne "\011" ) ? "\r\n"
613      :                      "\015\012";
614   }
615   return $self->{'.crlf'};
616 }
617
618 ################ The Core Methods ################
619
620 sub param {
621   my ( $self, $param, @p ) = @_;
622   unless ( defined $param ) {    # return list of all params
623     my @params
624      = $self->{'.parameters'} ? @{ $self->{'.parameters'} } : ();
625     return @params;
626   }
627   unless ( @p ) {                # return values for $param
628     return () unless exists $self->{$param};
629     return wantarray ? @{ $self->{$param} } : $self->{$param}->[0];
630   }
631   if ( $param =~ m/^-name$/i and @p == 1 ) {
632     return () unless exists $self->{ $p[0] };
633     return wantarray ? @{ $self->{ $p[0] } } : $self->{ $p[0] }->[0];
634   }
635
636   # set values using -name=>'foo',-value=>'bar' syntax.
637   # also allows for $q->param( 'foo', 'some', 'new', 'values' ) syntax
638   ( $param, undef, @p ) = @p
639    if $param =~ m/^-name$/i;     # undef represents -value token
640   $self->_add_param( $param, ( ref $p[0] eq 'ARRAY' ? $p[0] : [@p] ),
641     'overwrite' );
642   return wantarray ? @{ $self->{$param} } : $self->{$param}->[0];
643 }
644
645 # a new method that provides access to a new internal routine. Useage:
646 # $q->add_param( $param, $value, $overwrite )
647 # $param must be a plain scalar
648 # $value may be either a scalar or an array ref
649 # if $overwrite is a true value $param will be overwritten with new values.
650 sub add_param {
651   _add_param( @_ );
652 }
653
654 sub param_fetch {
655   my ( $self, $param, @p ) = @_;
656   $param
657    = ( defined $param and $param =~ m/^-name$/i ) ? $p[0] : $param;
658   return undef unless defined $param;
659   $self->_add_param( $param, [] ) unless exists $self->{$param};
660   return $self->{$param};
661 }
662
663 # Return a parameter in the QUERY_STRING, regardless of whether a POST or GET
664 sub url_param {
665   my ( $self, $param ) = @_;
666   return () unless $ENV{'QUERY_STRING'};
667   $self->{'.url_param'} = {};
668   bless $self->{'.url_param'}, 'CGI::Simple';
669   $self->{'.url_param'}->_parse_params( $ENV{'QUERY_STRING'} );
670   return $self->{'.url_param'}->param( $param );
671 }
672
673 sub keywords {
674   my ( $self, @values ) = @_;
675   $self->{'keywords'}
676    = ref $values[0] eq 'ARRAY' ? $values[0] : [@values]
677    if @values;
678   my @result
679    = defined( $self->{'keywords'} ) ? @{ $self->{'keywords'} } : ();
680   return @result;
681 }
682
683 sub Vars {
684   my $self = shift;
685   $self->{'.sep'} = shift || $self->{'.sep'} || "\0";
686   my ( %hash, %tied );
687   for my $param ( $self->param ) {
688     $hash{$param} = join $self->{'.sep'}, $self->param( $param );
689   }
690   tie %tied, "CGI::Simple", $self;
691   return wantarray ? %hash : \%tied;
692 }
693
694 sub TIEHASH { $_[1] ? $_[1] : new $_[0] }
695
696 sub STORE {
697   my ( $q, $p, $v ) = @_;
698   $q->param( $p, split $q->{'.sep'}, $v );
699 }
700
701 sub FETCH {
702   my ( $q, $p ) = @_;
703   ref $q->{$p} eq "ARRAY" ? join $q->{'.sep'}, @{ $q->{$p} } : $q->{$p};
704 }
705 sub FIRSTKEY { my $a = scalar keys %{ $_[0] }; each %{ $_[0] } }
706 sub NEXTKEY { each %{ $_[0] } }
707 sub EXISTS  { exists $_[0]->{ $_[1] } }
708 sub DELETE  { $_[0]->delete( $_[1] ) }
709 sub CLEAR   { %{ $_[0] } = () }
710
711 sub append {
712   my ( $self, $param, @p ) = @_;
713   return () unless defined $param;
714
715   # set values using $q->append(-name=>'foo',-value=>'bar') syntax
716   # also allows for $q->append( 'foo', 'some', 'new', 'values' ) syntax
717   ( $param, undef, @p ) = @p
718    if $param =~ m/^-name$/i;    # undef represents -value token
719   $self->_add_param( $param,
720     ( ( defined $p[0] and ref $p[0] ) ? $p[0] : [@p] ) );
721   return $self->param( $param );
722 }
723
724 sub delete {
725   my ( $self, $param ) = @_;
726   return () unless defined $param;
727   $param
728    = $param =~ m/^-name$/i
729    ? shift
730    : $param;                    # allow delete(-name=>'foo') syntax
731   return undef unless defined $self->{$param};
732   delete $self->{$param};
733   delete $self->{'.fieldnames'}->{$param};
734   $self->{'.parameters'}
735    = [ grep { $_ ne $param } @{ $self->{'.parameters'} } ];
736 }
737
738 sub Delete { CGI::Simple::delete( @_ ) }    # for method style interface
739
740 sub delete_all {
741   my $self = shift;
742   undef %{$self};
743   $self->_store_globals;
744 }
745
746 sub Delete_all { $_[0]->delete_all }        # as used by CGI.pm
747
748 sub upload {
749   my ( $self, $filename, $writefile ) = @_;
750   unless ( $filename ) {
751     $self->cgi_error( "No filename submitted for upload to $writefile" )
752      if $writefile;
753     return $self->{'.filehandles'}
754      ? keys %{ $self->{'.filehandles'} }
755      : ();
756   }
757   unless ( $ENV{'CONTENT_TYPE'} =~ m|^multipart/form-data|i ) {
758     $self->cgi_error(
759       'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your <FORM> tag'
760     );
761     return undef;
762   }
763   my $fh = $self->{'.filehandles'}->{$filename};
764
765   # allow use of upload fieldname to get filehandle
766   # this has limitation that in the event of duplicate
767   # upload field names there can only be one filehandle
768   # which will point to the last upload file
769   # access by filename does not suffer from this issue.
770   $fh
771    = $self->{'.filehandles'}->{ $self->{'.upload_fields'}->{$filename} }
772    if !$fh and defined $self->{'.upload_fields'}->{$filename};
773
774   if ( $fh ) {
775     seek $fh, 0, 0;    # get ready for reading
776     return $fh unless $writefile;
777     my $buffer;
778     unless ( open OUT, ">$writefile" ) {
779       $self->cgi_error( "500 Can't write to $writefile: $!\n" );
780       return undef;
781     }
782     binmode OUT;
783     binmode $fh;
784     print OUT $buffer while read( $fh, $buffer, 4096 );
785     close OUT;
786     $self->{'.filehandles'}->{$filename} = undef;
787     undef $fh;
788     return 1;
789   }
790   else {
791     $self->cgi_error(
792       "No filehandle for '$filename'. Are uploads enabled (\$DISABLE_UPLOADS = 0)? Is \$POST_MAX big enough?"
793     );
794     return undef;
795   }
796 }
797
798 sub upload_fieldnames {
799   my ( $self ) = @_;
800   return wantarray
801    ? ( keys %{ $self->{'.upload_fields'} } )
802    : [ keys %{ $self->{'.upload_fields'} } ];
803 }
804
805 # return the file size of an uploaded file
806 sub upload_info {
807   my ( $self, $filename, $info ) = @_;
808   unless ( $ENV{'CONTENT_TYPE'} =~ m|^multipart/form-data|i ) {
809     $self->cgi_error(
810       'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your <FORM> tag'
811     );
812     return undef;
813   }
814   return keys %{ $self->{'.tmpfiles'} } unless $filename;
815   return $self->{'.tmpfiles'}->{$filename}->{'mime'}
816    if $info =~ /mime/i;
817   return $self->{'.tmpfiles'}->{$filename}->{'size'};
818 }
819
820 sub uploadInfo { &upload_info }    # alias for CGI.pm compatibility
821
822 # return all params/values in object as a query string suitable for 'GET'
823 sub query_string {
824   my $self = shift;
825   my @pairs;
826   for my $param ( $self->param ) {
827     for my $value ( $self->param( $param ) ) {
828       next unless defined $value;
829       push @pairs,
830        $self->url_encode( $param ) . '=' . $self->url_encode( $value );
831     }
832   }
833   return join $self->{'.globals'}->{'USE_PARAM_SEMICOLONS'} ? ';' : '&',
834    @pairs;
835 }
836
837 # new method that will add QUERY_STRING data to our CGI::Simple object
838 # if the REQUEST_METHOD was 'POST'
839 sub parse_query_string {
840   my $self = shift;
841   $self->_parse_params( $ENV{'QUERY_STRING'} )
842    if defined $ENV{'QUERY_STRING'}
843      and $ENV{'REQUEST_METHOD'} eq 'POST';
844 }
845
846 ################   Save and Restore params from file    ###############
847
848 sub _init_from_file {
849   use Carp qw(confess);
850   confess "INIT_FROM_FILE called, stupid fucker!";
851   my ( $self, $fh ) = @_;
852   local $/ = "\n";
853   while ( my $pair = <$fh> ) {
854     chomp $pair;
855     return if $pair eq '=';
856     $self->_parse_params( $pair );
857   }
858 }
859
860 sub save {
861   my ( $self, $fh ) = @_;
862   local ( $,, $\ ) = ( '', '' );
863   unless ( $fh and fileno $fh ) {
864     $self->cgi_error( 'Invalid filehandle' );
865     return undef;
866   }
867   for my $param ( $self->param ) {
868     for my $value ( $self->param( $param ) ) {
869       ;
870       print $fh $self->url_encode( $param ), '=',
871        $self->url_encode( $value ), "\n";
872     }
873   }
874   print $fh "=\n";
875 }
876
877 sub save_parameters { save( @_ ) }    # CGI.pm alias for save
878
879 ################ Miscellaneous Methods ################
880
881 sub parse_keywordlist {
882   _parse_keywordlist( @_ );
883 }                                     # CGI.pm compatibility
884
885 sub escapeHTML {
886   my ( $self, $escape, $newlinestoo ) = @_;
887   require CGI::Simple::Util;
888   $escape = CGI::Simple::Util::escapeHTML( $escape );
889   $escape =~ s/([\012\015])/'&#'.(ord $1).';'/eg if $newlinestoo;
890   return $escape;
891 }
892
893 sub unescapeHTML {
894   require CGI::Simple::Util;
895   return CGI::Simple::Util::unescapeHTML( $_[1] );
896 }
897
898 sub put {
899   my $self = shift;
900   $self->print( @_ );
901 }    # send output to browser
902
903 sub print {
904   shift;
905   CORE::print( @_ );
906 }    # print to standard output (for overriding in mod_perl)
907
908 ################# Cookie Methods ################
909
910 sub cookie {
911   my ( $self, @params ) = @_;
912   require CGI::Simple::Cookie;
913   require CGI::Simple::Util;
914   my ( $name, $value, $path, $domain, $secure, $expires, $httponly )
915    = CGI::Simple::Util::rearrange(
916     [
917       'NAME', [ 'VALUE', 'VALUES' ],
918       'PATH',   'DOMAIN',
919       'SECURE', 'EXPIRES',
920       'HTTPONLY'
921     ],
922     @params
923    );
924
925   # retrieve the value of the cookie, if no value is supplied
926   unless ( defined( $value ) ) {
927     $self->{'.cookies'} = CGI::Simple::Cookie->fetch
928      unless $self->{'.cookies'};
929     return () unless $self->{'.cookies'};
930
931    # if no name is supplied, then retrieve the names of all our cookies.
932     return keys %{ $self->{'.cookies'} } unless $name;
933
934     # return the value of the cookie
935     return
936      exists $self->{'.cookies'}->{$name}
937      ? $self->{'.cookies'}->{$name}->value
938      : ();
939   }
940
941   # If we get here, we're creating a new cookie
942   return undef unless $name;    # this is an error
943   @params = ();
944   push @params, '-name'     => $name;
945   push @params, '-value'    => $value;
946   push @params, '-domain'   => $domain if $domain;
947   push @params, '-path'     => $path if $path;
948   push @params, '-expires'  => $expires if $expires;
949   push @params, '-secure'   => $secure if $secure;
950   push @params, '-httponly' => $httponly if $httponly;
951   return CGI::Simple::Cookie->new( @params );
952 }
953
954 sub raw_cookie {
955   my ( $self, $key ) = @_;
956   if ( defined $key ) {
957     unless ( $self->{'.raw_cookies'} ) {
958       require CGI::Simple::Cookie;
959       $self->{'.raw_cookies'} = CGI::Simple::Cookie->raw_fetch;
960     }
961     return $self->{'.raw_cookies'}->{$key} || ();
962   }
963   return $ENV{'HTTP_COOKIE'} || $ENV{'COOKIE'} || '';
964 }
965
966 ################# Header Methods ################
967
968 sub header {
969   my ( $self, @params ) = @_;
970   require CGI::Simple::Util;
971   my @header;
972   return undef
973    if $self->{'.header_printed'}++
974      and $self->{'.globals'}->{'HEADERS_ONCE'};
975   my (
976     $type, $status,  $cookie,     $target, $expires,
977     $nph,  $charset, $attachment, $p3p,    @other
978    )
979    = CGI::Simple::Util::rearrange(
980     [
981       [ 'TYPE',   'CONTENT_TYPE', 'CONTENT-TYPE' ], 'STATUS',
982       [ 'COOKIE', 'COOKIES',      'SET-COOKIE' ],   'TARGET',
983       'EXPIRES', 'NPH',
984       'CHARSET', 'ATTACHMENT',
985       'P3P'
986     ],
987     @params
988    );
989   $nph ||= $self->{'.globals'}->{'NPH'};
990   $charset = $self->charset( $charset )
991    ;    # get charset (and set new charset if supplied)
992    # rearrange() was designed for the HTML portion, so we need to fix it up a little.
993
994   for ( @other ) {
995
996     # Don't use \s because of perl bug 21951
997     next
998      unless my ( $header, $value ) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
999     ( $_ = $header )
1000      =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
1001   }
1002   $type ||= 'text/html' unless defined $type;
1003   $type .= "; charset=$charset"
1004    if $type
1005      and $type =~ m!^text/!
1006      and $type !~ /\bcharset\b/;
1007   my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1008   push @header, $protocol . ' ' . ( $status || '200 OK' ) if $nph;
1009   push @header, "Server: " . server_software() if $nph;
1010   push @header, "Status: $status"              if $status;
1011   push @header, "Window-Target: $target"       if $target;
1012
1013   if ( $p3p ) {
1014     $p3p = join ' ', @$p3p if ref( $p3p ) eq 'ARRAY';
1015     push( @header, qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p") );
1016   }
1017
1018   # push all the cookies -- there may be several
1019   if ( $cookie ) {
1020     my @cookie = ref $cookie eq 'ARRAY' ? @{$cookie} : $cookie;
1021     for my $cookie ( @cookie ) {
1022       my $cs
1023        = ref $cookie eq 'CGI::Simple::Cookie'
1024        ? $cookie->as_string
1025        : $cookie;
1026       push @header, "Set-Cookie: $cs" if $cs;
1027     }
1028   }
1029
1030 # if the user indicates an expiration time, then we need both an Expires
1031 # and a Date header (so that the browser is using OUR clock)
1032   $expires = 'now'
1033    if $self->no_cache;    # encourage no caching via expires now
1034   push @header,
1035    "Expires: " . CGI::Simple::Util::expires( $expires, 'http' )
1036    if $expires;
1037   push @header, "Date: " . CGI::Simple::Util::expires( 0, 'http' )
1038    if defined $expires || $cookie || $nph;
1039   push @header, "Pragma: no-cache" if $self->cache or $self->no_cache;
1040   push @header,
1041    "Content-Disposition: attachment; filename=\"$attachment\""
1042    if $attachment;
1043   push @header, @other;
1044   push @header, "Content-Type: $type" if $type;
1045   my $CRLF = $self->crlf;
1046   my $header = join $CRLF, @header;
1047   $header .= $CRLF . $CRLF;    # add the statutory two CRLFs
1048
1049   if ( $self->{'.mod_perl'} and not $nph ) {
1050     my $r = $self->_mod_perl_request();
1051     $r->send_cgi_header( $header );
1052     return '';
1053   }
1054   return $header;
1055 }
1056
1057 # Control whether header() will produce the no-cache Pragma directive.
1058 sub cache {
1059   my ( $self, $value ) = @_;
1060   $self->{'.cache'} = $value if defined $value;
1061   return $self->{'.cache'};
1062 }
1063
1064 # Control whether header() will produce expires now + the no-cache Pragma.
1065 sub no_cache {
1066   my ( $self, $value ) = @_;
1067   $self->{'.no_cache'} = $value if defined $value;
1068   return $self->{'.no_cache'};
1069 }
1070
1071 sub redirect {
1072   my ( $self, @params ) = @_;
1073   require CGI::Simple::Util;
1074   my ( $url, $target, $cookie, $nph, @other )
1075    = CGI::Simple::Util::rearrange(
1076     [
1077       [ 'LOCATION', 'URI',       'URL' ], 'TARGET',
1078       [ 'COOKIE',   'COOKIES' ], 'NPH'
1079     ],
1080     @params
1081    );
1082   $url ||= $self->self_url;
1083   my @o;
1084   for ( @other ) { tr/\"//d; push @o, split "=", $_, 2; }
1085   unshift @o,
1086    '-Status'   => '302 Moved',
1087    '-Location' => $url,
1088    '-nph'      => $nph;
1089   unshift @o, '-Target' => $target if $target;
1090   unshift @o, '-Cookie' => $cookie if $cookie;
1091   unshift @o, '-Type'   => '';
1092   my @unescaped;
1093   unshift( @unescaped, '-Cookie' => $cookie ) if $cookie;
1094   return $self->header( ( map { $self->unescapeHTML( $_ ) } @o ),
1095     @unescaped );
1096 }
1097
1098 ################# Server Push Methods #################
1099 # Return a Content-Type: style header for server-push
1100 # This has to be NPH, and it is advisable to set $| = 1
1101 # Credit to Ed Jordan <ed@fidalgo.net> and
1102 # Andrew Benham <adsb@bigfoot.com> for this section
1103
1104 sub multipart_init {
1105   my ( $self, @p ) = @_;
1106   use CGI::Simple::Util qw(rearrange);
1107   my ( $boundary, @other ) = rearrange( ['BOUNDARY'], @p );
1108   $boundary = $boundary || '------- =_aaaaaaaaaa0';
1109   my $CRLF = $self->crlf;    # get CRLF sequence
1110   my $warning
1111    = "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY.";
1112   $self->{'.separator'}       = "$CRLF--$boundary$CRLF";
1113   $self->{'.final_separator'} = "$CRLF--$boundary--$CRLF$warning$CRLF";
1114   my $type = 'multipart/x-mixed-replace;boundary="' . $boundary . '"';
1115   return $self->header(
1116     -nph  => 1,
1117     -type => $type,
1118     map { split "=", $_, 2 } @other
1119    )
1120    . $warning
1121    . $self->multipart_end;
1122 }
1123
1124 sub multipart_start {
1125   my ( $self, @p ) = @_;
1126   use CGI::Simple::Util qw(rearrange);
1127   my ( $type, @other ) = rearrange( ['TYPE'], @p );
1128   foreach ( @other ) {    # fix return from rearange
1129     next unless my ( $header, $value ) = /([^\s=]+)=\"?(.+?)\"?$/;
1130     $_ = ucfirst( lc $header ) . ': ' . unescapeHTML( 1, $value );
1131   }
1132   $type = $type || 'text/html';
1133   my @header = ( "Content-Type: $type" );
1134   push @header, @other;
1135   my $CRLF = $self->crlf;    # get CRLF sequence
1136   return ( join $CRLF, @header ) . $CRLF . $CRLF;
1137 }
1138
1139 sub multipart_end { return $_[0]->{'.separator'} }
1140
1141 sub multipart_final { return $_[0]->{'.final_separator'} }
1142
1143 ################# Debugging Methods ################
1144
1145 sub read_from_cmdline {
1146   my @words;
1147   if ( $_[0]->{'.globals'}->{'DEBUG'} == 1 and @ARGV ) {
1148     @words = @ARGV;
1149   }
1150   elsif ( $_[0]->{'.globals'}->{'DEBUG'} == 2 ) {
1151     require "shellwords.pl";
1152     print "(offline mode: enter name=value pairs on standard input)\n";
1153     chomp( my @lines = <STDIN> );
1154     @words = &shellwords( join " ", @lines );
1155   }
1156   else {
1157     return '';
1158   }
1159   @words = map { s/\\=/%3D/g; s/\\&/%26/g; $_ } @words;
1160   return "@words" =~ m/=/ ? join '&', @words : join '+', @words;
1161 }
1162
1163 sub Dump {
1164   require Data::Dumper;    # short and sweet way of doing it
1165   ( my $dump = Data::Dumper::Dumper( @_ ) )
1166    =~ tr/\000/0/;          # remove null bytes cgi-lib.pl
1167   return '<pre>' . escapeHTML( 1, $dump ) . '</pre>';
1168 }
1169
1170 sub as_string { Dump( @_ ) }    # CGI.pm alias for Dump()
1171
1172 sub cgi_error {
1173   my ( $self, $err ) = @_;
1174   if ( $err ) {
1175     $self->{'.cgi_error'} = $err;
1176        $self->{'.globals'}->{'FATAL'} == 1 ? croak $err
1177      : $self->{'.globals'}->{'FATAL'} == 0 ? carp $err
1178      :                                       return $err;
1179   }
1180   return $self->{'.cgi_error'};
1181 }
1182
1183 ################# cgi-lib.pl Compatibility Methods #################
1184 # Lightly GOLFED but the original functionality remains. You can call
1185 # them using either: # $q->MethodName or CGI::Simple::MethodName
1186
1187 sub _shift_if_ref { shift if ref $_[0] eq 'CGI::Simple' }
1188
1189 sub ReadParse {
1190   my $q = &_shift_if_ref || new CGI::Simple;
1191   my $pkg = caller();
1192   no strict 'refs';
1193   *in
1194    = @_
1195    ? $_[0]
1196    : *{"${pkg}::in"};    # set *in to passed glob or export *in
1197   %in = $q->Vars;
1198   $in{'CGI'} = $q;
1199   return scalar %in;
1200 }
1201
1202 sub SplitParam {
1203   &_shift_if_ref;
1204   defined $_[0]
1205    && ( wantarray ? split "\0", $_[0] : ( split "\0", $_[0] )[0] );
1206 }
1207
1208 sub MethGet { request_method() eq 'GET' }
1209
1210 sub MethPost { request_method() eq 'POST' }
1211
1212 sub MyBaseUrl {
1213   local $^W = 0;
1214   'http://'
1215    . server_name()
1216    . ( server_port() != 80 ? ':' . server_port() : '' )
1217    . script_name();
1218 }
1219
1220 sub MyURL { MyBaseUrl() }
1221
1222 sub MyFullUrl {
1223   local $^W = 0;
1224   MyBaseUrl()
1225    . $ENV{'PATH_INFO'}
1226    . ( $ENV{'QUERY_STRING'} ? "?$ENV{'QUERY_STRING'}" : '' );
1227 }
1228
1229 sub PrintHeader {
1230   ref $_[0] ? $_[0]->header() : "Content-Type: text/html\n\n";
1231 }
1232
1233 sub HtmlTop {
1234   &_shift_if_ref;
1235   "<html>\n<head>\n<title>$_[0]</title>\n</head>\n<body>\n<h1>$_[0]</h1>\n";
1236 }
1237
1238 sub HtmlBot { "</body>\n</html>\n" }
1239
1240 sub PrintVariables { &_shift_if_ref; &Dump }
1241
1242 sub PrintEnv { &Dump( \%ENV ) }
1243
1244 sub CgiDie { CgiError( @_ ); die @_ }
1245
1246 sub CgiError {
1247   &_shift_if_ref;
1248   @_
1249    = @_
1250    ? @_
1251    : ( "Error: script " . MyFullUrl() . " encountered fatal error\n" );
1252   print PrintHeader(), HtmlTop( shift ), ( map { "<p>$_</p>\n" } @_ ),
1253    HtmlBot();
1254 }
1255
1256 ################ Accessor Methods ################
1257
1258 sub version { $VERSION }
1259
1260 sub nph {
1261   $_[0]->{'.globals'}->{'NPH'} = $_[1] if defined $_[1];
1262   return $_[0]->{'.globals'}->{'NPH'};
1263 }
1264
1265 sub all_parameters { $_[0]->param }
1266
1267 sub charset {
1268   require CGI::Simple::Util;
1269   $CGI::Simple::Util::UTIL->charset( $_[1] );
1270 }
1271
1272 sub globals {
1273   my ( $self, $global, $value ) = @_;
1274   return keys %{ $self->{'.globals'} } unless $global;
1275   $self->{'.globals'}->{$global} = $value if defined $value;
1276   return $self->{'.globals'}->{$global};
1277 }
1278
1279 sub auth_type         { $ENV{'AUTH_TYPE'} }
1280 sub content_length    { $ENV{'CONTENT_LENGTH'} }
1281 sub content_type      { $ENV{'CONTENT_TYPE'} }
1282 sub document_root     { $ENV{'DOCUMENT_ROOT'} }
1283 sub gateway_interface { $ENV{'GATEWAY_INTERFACE'} }
1284 sub path_translated   { $ENV{'PATH_TRANSLATED'} }
1285 sub referer           { $ENV{'HTTP_REFERER'} }
1286 sub remote_addr       { $ENV{'REMOTE_ADDR'} || '127.0.0.1' }
1287
1288 sub remote_host {
1289   $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'} || 'localhost';
1290 }
1291
1292 sub remote_ident   { $ENV{'REMOTE_IDENT'} }
1293 sub remote_user    { $ENV{'REMOTE_USER'} }
1294 sub request_method { $ENV{'REQUEST_METHOD'} }
1295 sub script_name    { $ENV{'SCRIPT_NAME'} || $0 || '' }
1296 sub server_name     { $ENV{'SERVER_NAME'}     || 'localhost' }
1297 sub server_port     { $ENV{'SERVER_PORT'}     || 80 }
1298 sub server_protocol { $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0' }
1299 sub server_software { $ENV{'SERVER_SOFTWARE'} || 'cmdline' }
1300
1301 sub user_name {
1302   $ENV{'HTTP_FROM'} || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
1303 }
1304
1305 sub user_agent {
1306   my ( $self, $match ) = @_;
1307   return $match
1308    ? $ENV{'HTTP_USER_AGENT'} =~ /\Q$match\E/i
1309    : $ENV{'HTTP_USER_AGENT'};
1310 }
1311
1312 sub virtual_host {
1313   my $vh = $ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'};
1314   $vh =~ s/:\d+$//;    # get rid of port number
1315   return $vh;
1316 }
1317
1318 sub path_info {
1319   my ( $self, $info ) = @_;
1320   if ( defined $info ) {
1321     $info = "/$info" if $info !~ m|^/|;
1322     $self->{'.path_info'} = $info;
1323   }
1324   elsif ( !defined( $self->{'.path_info'} ) ) {
1325     $self->{'.path_info'}
1326      = defined( $ENV{'PATH_INFO'} ) ? $ENV{'PATH_INFO'} : '';
1327
1328     # hack to fix broken path info in IIS source CGI.pm
1329     $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E//
1330      if defined( $ENV{'SERVER_SOFTWARE'} )
1331        && $ENV{'SERVER_SOFTWARE'} =~ /IIS/;
1332   }
1333   return $self->{'.path_info'};
1334 }
1335
1336 sub accept {
1337   my ( $self, $search ) = @_;
1338   my %prefs;
1339   for my $accept ( split ',', $ENV{'HTTP_ACCEPT'} ) {
1340     ( my $pref ) = $accept =~ m|q=([\d\.]+)|;
1341     ( my $type ) = $accept =~ m|(\S+/[^;]+)|;
1342     next unless $type;
1343     $prefs{$type} = $pref || 1;
1344   }
1345   return keys %prefs unless $search;
1346   return $prefs{$search} if $prefs{$search};
1347
1348   # Didn't get it, so try pattern matching.
1349   for my $pref ( keys %prefs ) {
1350     next unless $pref =~ m/\*/;    # not a pattern match
1351     ( my $pat = $pref ) =~ s/([^\w*])/\\$1/g;   # escape meta characters
1352     $pat =~ s/\*/.*/g;                          # turn it into a pattern
1353     return $prefs{$pref} if $search =~ /$pat/;
1354   }
1355 }
1356
1357 sub Accept { my $self = shift; $self->accept( @_ ) }
1358
1359 sub http {
1360   my ( $self, $parameter ) = @_;
1361   if ( defined $parameter ) {
1362     ( $parameter = uc $parameter ) =~ tr/-/_/;
1363     return $ENV{$parameter} if $parameter =~ m/^HTTP/;
1364     return $ENV{"HTTP_$parameter"} if $parameter;
1365   }
1366   return grep { /^HTTP/ } keys %ENV;
1367 }
1368
1369 sub https {
1370   my ( $self, $parameter ) = @_;
1371   return $ENV{'HTTPS'} unless $parameter;
1372   ( $parameter = uc $parameter ) =~ tr/-/_/;
1373   return $ENV{$parameter} if $parameter =~ /^HTTPS/;
1374   return $ENV{"HTTPS_$parameter"};
1375 }
1376
1377 sub protocol {
1378   local ( $^W ) = 0;
1379   my $self = shift;
1380   return 'https' if uc $ENV{'HTTPS'} eq 'ON';
1381   return 'https' if $self->server_port == 443;
1382   my ( $protocol, $version ) = split '/', $self->server_protocol;
1383   return lc $protocol;
1384 }
1385
1386 sub url {
1387   my ( $self, @p ) = @_;
1388   use CGI::Simple::Util 'rearrange';
1389   my ( $relative, $absolute, $full, $path_info, $query, $base )
1390    = rearrange(
1391     [
1392       'RELATIVE', 'ABSOLUTE', 'FULL',
1393       [ 'PATH',  'PATH_INFO' ],
1394       [ 'QUERY', 'QUERY_STRING' ], 'BASE'
1395     ],
1396     @p
1397    );
1398   my $url;
1399   $full++ if $base || !( $relative || $absolute );
1400   my $path        = $self->path_info;
1401   my $script_name = $self->script_name;
1402   if ( $full ) {
1403     my $protocol = $self->protocol();
1404     $url = "$protocol://";
1405     my $vh = $self->http( 'host' );
1406     if ( $vh ) {
1407       $url .= $vh;
1408     }
1409     else {
1410       $url .= server_name();
1411       my $port = $self->server_port;
1412       $url .= ":" . $port
1413        unless ( lc( $protocol ) eq 'http' && $port == 80 )
1414        or ( lc( $protocol ) eq 'https' && $port == 443 );
1415     }
1416     return $url if $base;
1417     $url .= $script_name;
1418   }
1419   elsif ( $relative ) {
1420     ( $url ) = $script_name =~ m#([^/]+)$#;
1421   }
1422   elsif ( $absolute ) {
1423     $url = $script_name;
1424   }
1425   $url .= $path if $path_info and defined $path;
1426   $url .= "?" . $self->query_string if $query and $self->query_string;
1427   $url = '' unless defined $url;
1428   $url
1429    =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/uc sprintf("%%%02x",ord($1))/eg;
1430   return $url;
1431 }
1432
1433 sub self_url {
1434   my ( $self, @params ) = @_;
1435   return $self->url(
1436     '-path_info' => 1,
1437     '-query'     => 1,
1438     '-full'      => 1,
1439     @params
1440   );
1441 }
1442
1443 sub state { self_url( @_ ) }    # CGI.pm synonym routine
1444
1445 1;
1446
1447 =head1 NAME
1448
1449 CGI::Simple - A Simple totally OO CGI interface that is CGI.pm compliant
1450
1451 =head1 VERSION
1452
1453 This document describes CGI::Simple version 1.112.
1454
1455 =head1 SYNOPSIS
1456
1457     use CGI::Simple;
1458     $CGI::Simple::POST_MAX = 1024;       # max upload via post default 100kB
1459     $CGI::Simple::DISABLE_UPLOADS = 0;   # enable uploads
1460
1461     $q = new CGI::Simple;
1462     $q = new CGI::Simple( { 'foo'=>'1', 'bar'=>[2,3,4] } );
1463     $q = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' );
1464     $q = new CGI::Simple( \*FILEHANDLE );
1465
1466     $q->save( \*FILEHANDLE );   # save current object to a file as used by new
1467
1468     @params = $q->param;        # return all param names as a list
1469     $value = $q->param('foo');  # return the first value supplied for 'foo'
1470     @values = $q->param('foo'); # return all values supplied for foo
1471
1472     %fields   = $q->Vars;      # returns untied key value pair hash
1473     $hash_ref = $q->Vars;      # or as a hash ref
1474     %fields   = $q->Vars("|"); # packs multiple values with "|" rather than "\0";
1475
1476     @keywords = $q->keywords;  # return all keywords as a list
1477
1478     $q->param( 'foo', 'some', 'new', 'values' );      # set new 'foo' values
1479     $q->param( -name=>'foo', -value=>'bar' );
1480     $q->param( -name=>'foo', -value=>['bar','baz'] );
1481
1482     $q->param( 'foo', 'some', 'new', 'values' );      # append values to 'foo'
1483     $q->append( -name=>'foo', -value=>'bar' );
1484     $q->append( -name=>'foo', -value=>['some', 'new', 'values'] );
1485
1486     $q->delete('foo'); # delete param 'foo' and all its values
1487     $q->delete_all;    # delete everything
1488
1489     <INPUT TYPE="file" NAME="upload_file" SIZE="42">
1490
1491     $files    = $q->upload()                # number of files uploaded
1492     @files    = $q->upload();               # names of all uploaded files
1493     $filename = $q->param('upload_file')    # filename of uploaded file
1494     $mime     = $q->upload_info($filename,'mime'); # MIME type of uploaded file
1495     $size     = $q->upload_info($filename,'size'); # size of uploaded file
1496
1497     my $fh = $q->upload($filename);         # get filehandle to read from
1498     while ( read( $fh, $buffer, 1024 ) ) { ... }
1499
1500     # short and sweet upload
1501     $ok = $q->upload( $q->param('upload_file'), '/path/to/write/file.name' );
1502     print "Uploaded ".$q->param('upload_file')." and wrote it OK!" if $ok;
1503
1504     $decoded    = $q->url_decode($encoded);
1505     $encoded    = $q->url_encode($unencoded);
1506     $escaped    = $q->escapeHTML('<>"&');
1507     $unescaped  = $q->unescapeHTML('&lt;&gt;&quot;&amp;');
1508
1509     $qs = $q->query_string; # get all data in $q as a query string OK for GET
1510
1511     $q->no_cache(1);        # set Pragma: no-cache + expires
1512     print $q->header();     # print a simple header
1513     # get a complex header
1514     $header = $q->header(   -type       => 'image/gif'
1515                             -nph        => 1,
1516                             -status     => '402 Payment required',
1517                             -expires    =>'+24h',
1518                             -cookie     => $cookie,
1519                             -charset    => 'utf-7',
1520                             -attachment => 'foo.gif',
1521                             -Cost       => '$2.00'
1522                         );
1523     # a p3p header (OK for redirect use as well)
1524     $header = $q->header( -p3p => 'policyref="http://somesite.com/P3P/PolicyReferences.xml' );
1525
1526     @cookies = $q->cookie();        # get names of all available cookies
1527     $value   = $q->cookie('foo')    # get first value of cookie 'foo'
1528     @value   = $q->cookie('foo')    # get all values of cookie 'foo'
1529     # get a cookie formatted for header() method
1530     $cookie  = $q->cookie(  -name    => 'Password',
1531                             -values  => ['superuser','god','my dog woofie'],
1532                             -expires => '+3d',
1533                             -domain  => '.nowhere.com',
1534                             -path    => '/cgi-bin/database',
1535                             -secure  => 1
1536                          );
1537     print $q->header( -cookie=>$cookie );       # set cookie
1538
1539     print $q->redirect('http://go.away.now');   # print a redirect header
1540
1541     dienice( $q->cgi_error ) if $q->cgi_error;
1542
1543 =head1 DESCRIPTION
1544
1545 CGI::Simple provides a relatively lightweight drop in replacement for CGI.pm.
1546 It shares an identical OO interface to CGI.pm for parameter parsing, file
1547 upload, cookie handling and header generation. This module is entirely object
1548 oriented, however a complete functional interface is available by using the
1549 CGI::Simple::Standard module.
1550
1551 Essentially everything in CGI.pm that relates to the CGI (not HTML) side of
1552 things is available. There are even a few new methods and additions to old
1553 ones! If you are interested in what has gone on under the hood see the
1554 Compatibility with CGI.pm section at the end.
1555
1556 In practical testing this module loads and runs about twice as fast as CGI.pm
1557 depending on the precise task.
1558
1559 =head1 CALLING CGI::Simple ROUTINES USING THE OBJECT INTERFACE
1560
1561 Here is a very brief rundown on how you use the interface. Full details
1562 follow.
1563
1564 =head2 First you need to initialize an object
1565
1566 Before you can call a CGI::Simple method you must create a CGI::Simple object.
1567 You do that by using the module and then calling the new() constructor:
1568
1569     use CGI::Simple;
1570     my $q = new CGI::Simple;
1571
1572 It is traditional to call your object $q for query or perhaps $cgi.
1573
1574 =head2 Next you call methods on that object
1575
1576 Once you have your object you can call methods on it using the -> arrow
1577 syntax For example to get the names of all the parameters passed to your
1578 script you would just write:
1579
1580     @names = $q->param();
1581
1582 Many methods are sensitive to the context in which you call them. In the
1583 example above the B<param()> method returns a list of all the parameter names
1584 when called without any arguments.
1585
1586 When you call B<param('arg')> with a single argument it assumes you want
1587 to get the value(s) associated with that argument (parameter). If you ask
1588 for an array it gives you an array of all the values associated with it's
1589 argument:
1590
1591     @values = $q->param('foo');  # get all the values for 'foo'
1592
1593 whereas if you ask for a scalar like this:
1594
1595     $value = $q->param('foo');   # get only the first value for 'foo'
1596
1597 then it returns only the first value (if more than one value for
1598 'foo' exists).
1599
1600 Most CGI::Simple routines accept several arguments, sometimes as many as
1601 10 optional ones!  To simplify this interface, all routines use a named
1602 argument calling style that looks like this:
1603
1604     print $q->header( -type=>'image/gif', -expires=>'+3d' );
1605
1606 Each argument name is preceded by a dash.  Neither case nor order
1607 matters in the argument list.  -type, -Type, and -TYPE are all
1608 acceptable.
1609
1610 Several routines are commonly called with just one argument.  In the
1611 case of these routines you can provide the single argument without an
1612 argument name.  B<header()> happens to be one of these routines.  In this
1613 case, the single argument is the document type.
1614
1615    print $q->header('text/html');
1616
1617 Sometimes methods expect a scalar, sometimes a reference to an
1618 array, and sometimes a reference to a hash.  Often, you can pass any
1619 type of argument and the routine will do whatever is most appropriate.
1620 For example, the B<param()> method can be used to set a CGI parameter to a
1621 single or a multi-valued value.  The two cases are shown below:
1622
1623    $q->param(-name=>'veggie',-value=>'tomato');
1624    $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
1625
1626 =head1 CALLING CGI::Simple ROUTINES USING THE FUNCTION INTERFACE
1627
1628 For convenience a functional interface is provided by the
1629 CGI::Simple::Standard module. This hides the OO details from you and allows
1630 you to simply call methods. You may either use AUTOLOADING of methods or
1631 import specific method sets into you namespace. Here are the first few
1632 examples again using the function interface.
1633
1634     use CGI::Simple::Standard qw(-autoload);
1635     @names  = param();
1636     @values = param('foo');
1637     $value  = param('foo');
1638     print header(-type=>'image/gif',-expires=>'+3d');
1639     print header('text/html');
1640
1641 Yes that's it. Not a $q-> in sight. You just use the module and select
1642 how/which methods to load. You then just call the methods you want exactly
1643 as before but without the $q-> notation.
1644
1645 When (if) you read the following docs and are using the functional interface
1646 just pretend the $q-> is not there.
1647
1648 =head2 Selecting which methods to load
1649
1650 When you use the functional interface Perl needs to be able to find the
1651 functions you call. The simplest way of doing this is to use autoloading as
1652 shown above. When you use CGI::Simple::Standard with the '-autoload' pragma
1653 it exports a single AUTOLOAD sub into you namespace. Every time you call a
1654 non existent function AUTOLOAD is called and will load the required
1655 function and install it in your namespace. Thus only the AUTOLOAD sub and
1656 those functions you specifically call will be imported.
1657
1658 Alternatively CGI::Simple::Standard provides a range of function sets you can
1659 import or you can just select exactly what you want. You do this using the
1660 familiar
1661
1662     use CGI::Simple::Standard qw( :func_set  some_func);
1663
1664 notation. This will import the ':func_set' function set and the specific
1665 function 'some_func'.
1666
1667 =head2 To Autoload or not to Autoload, that is the question.
1668
1669 If you do not have a AUTOLOAD sub in you script it is generally best to use
1670 the '-autoload' option. Under autoload you can use any method you want but
1671 only import and compile those functions you actually use.
1672
1673 If you do not use autoload you must specify what functions to import. You can
1674 only use functions that you have imported. For comvenience functions are
1675 grouped into related sets. If you choose to import one or more ':func_set'
1676 you may have potential namespace collisions so check out the docs to see
1677 what gets imported. Using the ':all' tag is pretty slack but it is there
1678 if you want. Full details of the function sets are provided in the
1679 CGI::Simple::Standard docs
1680
1681 If you just want say the param and header methods just load these two.
1682
1683     use CGI::Simple::Standard qw(param header);
1684
1685 =head2 Setting globals using the functional interface
1686
1687 Where you see global variables being set using the syntax:
1688
1689     $CGI::Simple::DEBUG = 1;
1690
1691 You use exactly the same syntax when using CGI::Simple::Standard.
1692
1693 =cut
1694
1695 ################ The Core Methods ################
1696
1697 =head1 THE CORE METHODS
1698
1699 =head2 new() Creating a new query object
1700
1701 The first step in using CGI::Simple is to create a new query object using
1702 the B<new()> constructor:
1703
1704      $q = new CGI::Simple;
1705
1706 This will parse the input (from both POST and GET methods) and store
1707 it into an object called $q.
1708
1709 If you provide a file handle to the B<new()> method, it will read
1710 parameters from the file (or STDIN, or whatever).
1711
1712      open FH, "test.in" or die $!;
1713      $q = new CGI::Simple(\*FH);
1714
1715      open $fh, "test.in" or die $!;
1716      $q = new CGI::Simple($fh);
1717
1718 The file should be a series of newline delimited TAG=VALUE pairs.
1719 Conveniently, this type of file is created by the B<save()> method
1720 (see below). Multiple records can be saved and restored.
1721 IO::File objects work fine.
1722
1723 If you are using the function-oriented interface provided by
1724 CGI::Simple::Standard and want to initialize from a file handle,
1725 the way to do this is with B<restore_parameters()>.  This will (re)initialize
1726 the default CGI::Simple object from the indicated file handle.
1727
1728     restore_parameters(\*FH);
1729
1730 In fact for all intents and purposes B<restore_parameters()> is identical
1731 to B<new()> Note that B<restore_parameters()> does not exist in
1732 CGI::Simple itself so you can't use it.
1733
1734 You can also initialize the query object from an associative array
1735 reference:
1736
1737     $q = new CGI::Simple( { 'dinosaur' => 'barney',
1738                             'song'     => 'I love you',
1739                             'friends'  => [qw/Jessica George Nancy/] }
1740                         );
1741
1742 or from a properly formatted, URL-escaped query string:
1743
1744     $q = new CGI::Simple( 'dinosaur=barney&color=purple' );
1745
1746 or from a previously existing CGI::Simple object (this generates an identical clone
1747 including all global variable settings, etc that are stored in the object):
1748
1749     $old_query = new CGI::Simple;
1750     $new_query = new CGI::Simple($old_query);
1751
1752 To create an empty query, initialize it from an empty string or hash:
1753
1754     $empty_query = new CGI::Simple("");
1755
1756        -or-
1757
1758     $empty_query = new CGI::Simple({});
1759
1760 =head2 keywords() Fetching a list of keywords from a query
1761
1762     @keywords = $q->keywords;
1763
1764 If the script was invoked as the result of an <ISINDEX> search, the
1765 parsed keywords can be obtained as an array using the B<keywords()> method.
1766
1767 =head2 param() Fetching the names of all parameters passed to your script
1768
1769     @names = $q->param;
1770
1771 If the script was invoked with a parameter list
1772 (e.g. "name1=value1&name2=value2&name3=value3"), the B<param()> method
1773 will return the parameter names as a list.  If the script was invoked
1774 as an <ISINDEX> script and contains a string without ampersands
1775 (e.g. "value1+value2+value3") , there will be a single parameter named
1776 "keywords" containing the "+"-delimited keywords.
1777
1778 NOTE: The array of parameter names returned will
1779 be in the same order as they were submitted by the browser.
1780 Usually this order is the same as the order in which the
1781 parameters are defined in the form (however, this isn't part
1782 of the spec, and so isn't guaranteed).
1783
1784 =head2 param() Fetching the value or values of a simple named parameter
1785
1786     @values = $q->param('foo');
1787
1788           -or-
1789
1790     $value = $q->param('foo');
1791
1792 Pass the B<param()> method a single argument to fetch the value of the
1793 named parameter. If the parameter is multi-valued (e.g. from multiple
1794 selections in a scrolling list), you can ask to receive an array.  Otherwise
1795 the method will return a single value.
1796
1797 If a value is not given in the query string, as in the queries
1798 "name1=&name2=" or "name1&name2", it will be returned by default
1799 as an empty string. If you set the global variable:
1800
1801     $CGI::Simple::NO_UNDEF_PARAMS = 1;
1802
1803 Then value-less parameters will be ignored, and will not exist in the
1804 query object. If you try to access them via param you will get an undef
1805 return value.
1806
1807 =head2 param() Setting the values of a named parameter
1808
1809     $q->param('foo','an','array','of','values');
1810
1811 This sets the value for the named parameter 'foo' to an array of
1812 values.  This is one way to change the value of a field.
1813
1814 B<param()> also recognizes a named parameter style of calling described
1815 in more detail later:
1816
1817     $q->param(-name=>'foo',-values=>['an','array','of','values']);
1818
1819                   -or-
1820
1821     $q->param(-name=>'foo',-value=>'the value');
1822
1823 =head2 param() Retrieving non-application/x-www-form-urlencoded data
1824
1825 If POSTed or PUTed data is not of type application/x-www-form-urlencoded or multipart/form-data, 
1826 then the data will not be processed, but instead be returned as-is in a parameter named POSTDATA
1827 or PUTDATA.  To retrieve it, use code like this:
1828
1829     my $data = $q->param( 'POSTDATA' );
1830
1831                   -or-
1832
1833     my $data = $q->param( 'PUTDATA' );
1834
1835 (If you don't know what the preceding means, don't worry about it.  It only affects people trying
1836 to use CGI::Simple for REST webservices)
1837
1838 =head2 add_param() Setting the values of a named parameter
1839
1840 You nay also use the new method B<add_param> to add parameters. This is an
1841 alias to the _add_param() internal method that actually does all the work.
1842 You can call it like this:
1843
1844     $q->add_param('foo', 'new');
1845     $q->add_param('foo', [1,2,3,4,5]);
1846     $q->add_param( 'foo', 'bar', 'overwrite' );
1847
1848 The first argument is the parameter, the second the value or an array ref
1849 of values and the optional third argument sets overwrite mode. If the third
1850 argument is absent of false the values will be appended. If true the values
1851 will overwrite any existing ones
1852
1853 =head2 append() Appending values to a named parameter
1854
1855    $q->append(-name=>'foo',-values=>['yet','more','values']);
1856
1857 This adds a value or list of values to the named parameter.  The
1858 values are appended to the end of the parameter if it already exists.
1859 Otherwise the parameter is created.  Note that this method only
1860 recognizes the named argument calling syntax.
1861
1862 =head2 import_names() Importing all parameters into a namespace.
1863
1864 This method was silly, non OO and has been deleted. You can get all the params
1865 as a hash using B<Vars> or via all the other accessors.
1866
1867 =head2 delete() Deleting a parameter completely
1868
1869     $q->delete('foo');
1870
1871 This completely clears a parameter. If you are using the function call
1872 interface, use B<Delete()> instead to avoid conflicts with Perl's
1873 built-in delete operator.
1874
1875 If you are using the function call interface, use B<Delete()> instead to
1876 avoid conflicts with Perl's built-in delete operator.
1877
1878 =head2 delete_all() Deleting all parameters
1879
1880     $q->delete_all();
1881
1882 This clears the CGI::Simple object completely. For CGI.pm compatibility
1883 B<Delete_all()> is provided however there is no reason to use this in the
1884 function call interface other than symmetry.
1885
1886 For CGI.pm compatibility B<Delete_all()> is provided as an alias for
1887 B<delete_all> however there is no reason to use this, even in the
1888 function call interface.
1889
1890 =head2 param_fetch() Direct access to the parameter list
1891
1892 This method is provided for CGI.pm compatibility only. It returns an
1893 array ref to the values associated with a named param. It is deprecated.
1894
1895 =head2 Vars() Fetching the entire parameter list as a hash
1896
1897     $params = $q->Vars;  # as a tied hash ref
1898     print $params->{'address'};
1899     @foo = split "\0", $params->{'foo'};
1900
1901     %params = $q->Vars;  # as a plain hash
1902     print $params{'address'};
1903     @foo = split "\0", $params{'foo'};
1904
1905     %params = $q->Vars(','); # specifying a different separator than "\0"
1906     @foo = split ',', $params{'foo'};
1907
1908 Many people want to fetch the entire parameter list as a hash in which
1909 the keys are the names of the CGI parameters, and the values are the
1910 parameters' values.  The B<Vars()> method does this.
1911
1912 Called in a scalar context, it returns the parameter list as a tied
1913 hash reference. Because this hash ref is tied changing a key/value
1914 changes the underlying CGI::Simple object.
1915
1916 Called in a list context, it returns the parameter list as an ordinary hash.
1917 Changing this hash will not change the underlying CGI::Simple object
1918
1919 When using B<Vars()>, the thing you must watch out for are multi-valued CGI
1920 parameters.  Because a hash cannot distinguish between scalar and
1921 list context, multi-valued parameters will be returned as a packed
1922 string, separated by the "\0" (null) character.  You must split this
1923 packed string in order to get at the individual values.  This is the
1924 convention introduced long ago by Steve Brenner in his cgi-lib.pl
1925 module for Perl version 4.
1926
1927 You can change the character used to do the multiple value packing by passing
1928 it to B<Vars()> as an argument as shown.
1929
1930 =head2 url_param() Access the QUERY_STRING regardless of 'GET' or 'POST'
1931
1932 The B<url_param()> method makes the QUERY_STRING data available regardless
1933 of whether the REQUEST_METHOD was 'GET' or 'POST'. You can do anything
1934 with B<url_param> that you can do with B<param()>, however the data set
1935 is completely independent.
1936
1937 Technically what happens if you use this method is that the QUERY_STRING data
1938 is parsed into a new CGI::Simple object which is stored within the current
1939 object. B<url_param> then just calls B<param()> on this new object.
1940
1941 =head2 parse_query_string() Add QUERY_STRING data to 'POST' requests
1942
1943 When the REQUEST_METHOD is 'POST' the default behavior is to ignore
1944 name/value pairs or keywords in the $ENV{'QUERY_STRING'}. You can override
1945 this by calling B<parse_query_string()> which will add the QUERY_STRING data to
1946 the data already in our CGI::Simple object if the REQUEST_METHOD was 'POST'
1947
1948     $q = new CGI::Simple;
1949     $q->parse_query_string;  # add $ENV{'QUERY_STRING'} data to our $q object
1950
1951 If the REQUEST_METHOD was 'GET' then the QUERY_STRING will already be
1952 stored in our object so B<parse_query_string> will be ignored.
1953
1954 This is a new method in CGI::Simple that is not available in CGI.pm
1955
1956 =head2 save() Saving the state of an object to file
1957
1958     $q->save(\*FILEHANDLE)
1959
1960 This will write the current state of the form to the provided
1961 filehandle.  You can read it back in by providing a filehandle
1962 to the B<new()> method.
1963
1964 The format of the saved file is:
1965
1966     NAME1=VALUE1
1967     NAME1=VALUE1'
1968     NAME2=VALUE2
1969     NAME3=VALUE3
1970     =
1971
1972 Both name and value are URL escaped.  Multi-valued CGI parameters are
1973 represented as repeated names.  A session record is delimited by a
1974 single = symbol.  You can write out multiple records and read them
1975 back in with several calls to B<new()>.
1976
1977     open FH, "test.in" or die $!;
1978     $q1 = new CGI::Simple(\*FH);  # get the first record
1979     $q2 = new CGI::Simple(\*FH);  # get the next record
1980
1981 Note: If you wish to use this method from the function-oriented (non-OO)
1982 interface, the exported name for this method is B<save_parameters()>.
1983 Also if you want to initialize from a file handle, the way to do this is
1984 with B<restore_parameters()>.  This will (re)initialize
1985 the default CGI::Simple object from the indicated file handle.
1986
1987     restore_parameters(\*FH);
1988
1989 =cut
1990
1991 ################ Uploading Files ###################
1992
1993 =head1 FILE UPLOADS
1994
1995 File uploads are easy with CGI::Simple. You use the B<upload()> method.
1996 Assuming you have the following in your HTML:
1997
1998     <FORM
1999      METHOD="POST"
2000      ACTION="http://somewhere.com/cgi-bin/script.cgi"
2001      ENCTYPE="multipart/form-data">
2002         <INPUT TYPE="file" NAME="upload_file1" SIZE="42">
2003         <INPUT TYPE="file" NAME="upload_file2" SIZE="42">
2004     </FORM>
2005
2006 Note that the ENCTYPE is "multipart/form-data". You must specify this or the
2007 browser will default to "application/x-www-form-urlencoded" which will result
2008 in no files being uploaded although on the surface things will appear OK.
2009
2010 When the user submits this form any supplied files will be spooled onto disk
2011 and saved in temporary files. These files will be deleted when your script.cgi
2012 exits so if you want to keep them you will need to proceed as follows.
2013
2014 =head2 upload() The key file upload method
2015
2016 The B<upload()> method is quite versatile. If you call B<upload()> without
2017 any arguments it will return a list of uploaded files in list context and
2018 the number of uploaded files in scalar context.
2019
2020     $number_of_files = $q->upload;
2021     @list_of_files   = $q->upload;
2022
2023 Having established that you have uploaded files available you can get the
2024 browser supplied filename using B<param()> like this:
2025
2026     $filename1 = $q->param('upload_file1');
2027
2028 You can then get a filehandle to read from by calling B<upload()> and
2029 supplying this filename as an argument. Warning: do not modify the
2030 value you get from B<param()> in any way - you don't need to untaint it.
2031
2032     $fh = $q->upload( $filename1 );
2033
2034 Now to save the file you would just do something like:
2035
2036     $save_path = '/path/to/write/file.name';
2037     open FH, ">$save_path" or die "Oops $!\n";
2038     binmode FH;
2039     print FH $buffer while read( $fh, $buffer, 4096 );
2040     close FH;
2041
2042 By utilizing a new feature of the upload method this process can be
2043 simplified to:
2044
2045     $ok = $q->upload( $q->param('upload_file1'), '/path/to/write/file.name' );
2046     if ($ok) {
2047         print "Uploaded and wrote file OK!";
2048     } else {
2049         print $q->cgi_error();
2050     }
2051
2052 As you can see upload will accept an optional second argument and will write
2053 the file to this file path. It will return 1 for success and undef if it
2054 fails. If it fails you can get the error from B<cgi_error>
2055
2056 You can also use just the fieldname as an argument to upload ie:
2057
2058     $fh = $q->upload( 'upload_field_name' );
2059
2060     or
2061
2062     $ok = $q->upload( 'upload_field_name', '/path/to/write/file.name' );
2063
2064 BUT there is a catch. If you have multiple upload fields, all called
2065 'upload_field_name' then you will only get the last uploaded file from
2066 these fields.
2067
2068 =head2 upload_info() Get the details about uploaded files
2069
2070 The B<upload_info()> method is a new method. Called without arguments it
2071 returns the number of uploaded files in scalar context and the names of
2072 those files in list context.
2073
2074     $number_of_upload_files   = $q->upload_info();
2075     @filenames_of_all_uploads = $q->upload_info();
2076
2077 You can get the MIME type of an uploaded file like this:
2078
2079     $mime = $q->upload_info( $filename1, 'mime' );
2080
2081 If you want to know how big a file is before you copy it you can get that
2082 information from B<uploadInfo> which will return the file size in bytes.
2083
2084     $file_size = $q->upload_info( $filename1, 'size' );
2085
2086 The size attribute is optional as this is the default value returned.
2087
2088 Note: The old CGI.pm B<uploadInfo()> method has been deleted.
2089
2090 =head2 $POST_MAX and $DISABLE_UPLOADS
2091
2092 CGI.pm has a default setting that allows infinite size file uploads by
2093 default. In contrast file uploads are disabled by default in CGI::Simple
2094 to discourage Denial of Service attacks. You must enable them before you
2095 expect file uploads to work.
2096
2097 When file uploads are disabled the file name and file size details will
2098 still be available from B<param()> and B<upload_info> respectively but
2099 the upload filehandle returned by B<upload()> will be undefined - not
2100 surprising as the underlying temp file will not exist either.
2101
2102 You can enable uploads using the '-upload' pragma. You do this by specifying
2103 this in you use statement:
2104
2105     use CGI::Simple qw(-upload);
2106
2107 Alternatively you can enable uploads via the $DISABLE_UPLOADS global like this:
2108
2109     use CGI::Simple;
2110     $CGI::Simple::DISABLE_UPLOADS = 0;
2111     $q = new CGI::Simple;
2112
2113 If you wish to set $DISABLE_UPLOADS you must do this *after* the
2114 use statement and *before* the new constructor call as shown above.
2115
2116 The maximum acceptable data via post is capped at 102_400kB rather than
2117 infinity which is the CGI.pm default. This should be ample for most tasks
2118 but you can set this to whatever you want using the $POST_MAX global.
2119
2120     use CGI::Simple;
2121     $CGI::Simple::DISABLE_UPLOADS = 0;      # enable uploads
2122     $CGI::Simple::POST_MAX = 1_048_576;     # allow 1MB uploads
2123     $q = new CGI::Simple;
2124
2125 If you set to -1 infinite size uploads will be permitted, which is the CGI.pm
2126 default.
2127
2128     $CGI::Simple::POST_MAX = -1;            # infinite size upload
2129
2130 Alternatively you can specify all the CGI.pm default values which allow file
2131 uploads of infinite size in one easy step by specifying the '-default' pragma
2132 in your use statement.
2133
2134     use CGI::Simple qw( -default ..... );
2135
2136 =head2 binmode() and Win32
2137
2138 If you are using CGI::Simple be sure to call B<binmode()> on any handle that
2139 you create to write the uploaded file to disk. Calling B<binmode()> will do
2140 no harm on other systems anyway.
2141
2142 =cut
2143
2144 ################ Miscellaneous Methods ################
2145
2146 =head1 MISCELANEOUS METHODS
2147
2148 =head2 escapeHTML() Escaping HTML special characters
2149
2150 In HTML the < > " and & chars have special meaning and need to be
2151 escaped to &lt; &gt; &quot; and &amp; respectively.
2152
2153     $escaped = $q->escapeHTML( $string );
2154
2155     $escaped = $q->escapeHTML( $string, 'new_lines_too' );
2156
2157 If the optional second argument is supplied then newlines will be escaped to.
2158
2159 =head2 unescapeHTML() Unescape HTML special characters
2160
2161 This performs the reverse of B<escapeHTML()>.
2162
2163     $unescaped = $q->unescapeHTML( $HTML_escaped_string );
2164
2165 =head2 url_decode() Decode a URL encoded string
2166
2167 This method will correctly decode a url encoded string.
2168
2169     $decoded = $q->url_decode( $encoded );
2170
2171 =head2 url_encode() URL encode a string
2172
2173 This method will correctly URL encode a string.
2174
2175     $encoded = $q->url_encode( $string );
2176
2177 =head2 parse_keywordlist() Parse a supplied keyword list
2178
2179     @keywords = $q->parse_keywordlist( $keyword_list );
2180
2181 This method returns a list of keywords, correctly URL escaped and split out
2182 of the supplied string
2183
2184 =head2 put() Send output to browser
2185
2186 CGI.pm alias for print. $q->put('Hello World!') will print the usual
2187
2188 =head2 print() Send output to browser
2189
2190 CGI.pm alias for print. $q->print('Hello World!') will print the usual
2191
2192 =cut
2193
2194 ################# Cookie Methods ################
2195
2196 =head1 HTTP COOKIES
2197
2198 CGI.pm has several methods that support cookies.
2199
2200 A cookie is a name=value pair much like the named parameters in a CGI
2201 query string.  CGI scripts create one or more cookies and send
2202 them to the browser in the HTTP header.  The browser maintains a list
2203 of cookies that belong to a particular Web server, and returns them
2204 to the CGI script during subsequent interactions.
2205
2206 In addition to the required name=value pair, each cookie has several
2207 optional attributes:
2208
2209 =over 4
2210
2211 =item 1. an expiration time
2212
2213 This is a time/date string (in a special GMT format) that indicates
2214 when a cookie expires.  The cookie will be saved and returned to your
2215 script until this expiration date is reached if the user exits
2216 the browser and restarts it.  If an expiration date isn't specified, the cookie
2217 will remain active until the user quits the browser.
2218
2219 =item 2. a domain
2220
2221 This is a partial or complete domain name for which the cookie is
2222 valid.  The browser will return the cookie to any host that matches
2223 the partial domain name.  For example, if you specify a domain name
2224 of ".capricorn.com", then the browser will return the cookie to
2225 Web servers running on any of the machines "www.capricorn.com",
2226 "www2.capricorn.com", "feckless.capricorn.com", etc.  Domain names
2227 must contain at least two periods to prevent attempts to match
2228 on top level domains like ".edu".  If no domain is specified, then
2229 the browser will only return the cookie to servers on the host the
2230 cookie originated from.
2231
2232 =item 3. a path
2233
2234 If you provide a cookie path attribute, the browser will check it
2235 against your script's URL before returning the cookie.  For example,
2236 if you specify the path "/cgi-bin", then the cookie will be returned
2237 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
2238 and "/cgi-bin/customer_service/complain.pl", but not to the script
2239 "/cgi-private/site_admin.pl".  By default, path is set to "/", which
2240 causes the cookie to be sent to any CGI script on your site.
2241
2242 =item 4. a "secure" flag
2243
2244 If the "secure" attribute is set, the cookie will only be sent to your
2245 script if the CGI request is occurring on a secure channel, such as SSL.
2246
2247 =back
2248
2249 =head2 cookie() A simple access method to cookies
2250
2251 The interface to HTTP cookies is the B<cookie()> method:
2252
2253     $cookie = $q->cookie( -name      => 'sessionID',
2254                           -value     => 'xyzzy',
2255                           -expires   => '+1h',
2256                           -path      => '/cgi-bin/database',
2257                           -domain    => '.capricorn.org',
2258                           -secure    => 1
2259                          );
2260     print $q->header(-cookie=>$cookie);
2261
2262 B<cookie()> creates a new cookie.  Its parameters include:
2263
2264 =over 4
2265
2266 =item B<-name>
2267
2268 The name of the cookie (required).  This can be any string at all.
2269 Although browsers limit their cookie names to non-whitespace
2270 alphanumeric characters, CGI.pm removes this restriction by escaping
2271 and unescaping cookies behind the scenes.
2272
2273 =item B<-value>
2274
2275 The value of the cookie.  This can be any scalar value,
2276 array reference, or even associative array reference.  For example,
2277 you can store an entire associative array into a cookie this way:
2278
2279     $cookie=$q->cookie( -name   => 'family information',
2280                         -value  => \%childrens_ages );
2281
2282 =item B<-path>
2283
2284 The optional partial path for which this cookie will be valid, as described
2285 above.
2286
2287 =item B<-domain>
2288
2289 The optional partial domain for which this cookie will be valid, as described
2290 above.
2291
2292 =item B<-expires>
2293
2294 The optional expiration date for this cookie.  The format is as described
2295 in the section on the B<header()> method:
2296
2297     "+1h"  one hour from now
2298
2299 =item B<-secure>
2300
2301 If set to true, this cookie will only be used within a secure
2302 SSL session.
2303
2304 =back
2305
2306 The cookie created by B<cookie()> must be incorporated into the HTTP
2307 header within the string returned by the B<header()> method:
2308
2309     print $q->header(-cookie=>$my_cookie);
2310
2311 To create multiple cookies, give B<header()> an array reference:
2312
2313     $cookie1 = $q->cookie( -name  => 'riddle_name',
2314                            -value => "The Sphynx's Question"
2315                          );
2316     $cookie2 = $q->cookie( -name  => 'answers',
2317                            -value => \%answers
2318                          );
2319     print $q->header( -cookie => [ $cookie1, $cookie2 ] );
2320
2321 To retrieve a cookie, request it by name by calling B<cookie()> method
2322 without the B<-value> parameter:
2323
2324     use CGI::Simple;
2325     $q = new CGI::Simple;
2326     $riddle  = $q->cookie('riddle_name');
2327     %answers = $q->cookie('answers');
2328
2329 Cookies created with a single scalar value, such as the "riddle_name"
2330 cookie, will be returned in that form.  Cookies with array and hash
2331 values can also be retrieved.
2332
2333 The cookie and CGI::Simple  namespaces are separate.  If you have a parameter
2334 named 'answers' and a cookie named 'answers', the values retrieved by
2335 B<param()> and B<cookie()> are independent of each other.  However, it's
2336 simple to turn a CGI parameter into a cookie, and vice-versa:
2337
2338     # turn a CGI parameter into a cookie
2339     $c = $q->cookie( -name=>'answers', -value=>[$q->param('answers')] );
2340     # vice-versa
2341     $q->param( -name=>'answers', -value=>[$q->cookie('answers')] );
2342
2343 =head2 raw_cookie()
2344
2345 Returns the HTTP_COOKIE variable. Cookies have a special format, and
2346 this method call just returns the raw form (?cookie dough). See
2347 B<cookie()> for ways of setting and retrieving cooked cookies.
2348
2349 Called with no parameters, B<raw_cookie()> returns the packed cookie
2350 structure.  You can separate it into individual cookies by splitting
2351 on the character sequence "; ".  Called with the name of a cookie,
2352 retrieves the B<unescaped> form of the cookie.  You can use the
2353 regular B<cookie()> method to get the names, or use the raw_fetch()
2354 method from the CGI::Simmple::Cookie module.
2355
2356 =cut
2357
2358 ################# Header Methods ################
2359
2360 =head1 CREATING HTTP HEADERS
2361
2362 Normally the first thing you will do in any CGI script is print out an
2363 HTTP header.  This tells the browser what type of document to expect,
2364 and gives other optional information, such as the language, expiration
2365 date, and whether to cache the document.  The header can also be
2366 manipulated for special purposes, such as server push and pay per view
2367 pages.
2368
2369 =head2 header() Create simple or complex HTTP headers
2370
2371     print $q->header;
2372
2373          -or-
2374
2375     print $q->header('image/gif');
2376
2377          -or-
2378
2379     print $q->header('text/html','204 No response');
2380
2381          -or-
2382
2383     print $q->header( -type       => 'image/gif',
2384                       -nph        => 1,
2385                       -status     => '402 Payment required',
2386                       -expires    => '+3d',
2387                       -cookie     => $cookie,
2388                       -charset    => 'utf-7',
2389                       -attachment => 'foo.gif',
2390                       -Cost       => '$2.00'
2391                     );
2392
2393 B<header()> returns the Content-type: header.  You can provide your own
2394 MIME type if you choose, otherwise it defaults to text/html.  An
2395 optional second parameter specifies the status code and a human-readable
2396 message.  For example, you can specify 204, "No response" to create a
2397 script that tells the browser to do nothing at all.
2398
2399 The last example shows the named argument style for passing arguments
2400 to the CGI methods using named parameters.  Recognized parameters are
2401 B<-type>, B<-status>, B<-cookie>, B<-target>, B<-expires>, B<-nph>,
2402 B<-charset> and B<-attachment>.  Any other named parameters will be
2403 stripped of their initial hyphens and turned into header fields, allowing
2404 you to specify any HTTP header you desire.
2405
2406 For example, you can produce non-standard HTTP header fields by providing
2407 them as named arguments:
2408
2409   print $q->header( -type            => 'text/html',
2410                     -nph             => 1,
2411                     -cost            => 'Three smackers',
2412                     -annoyance_level => 'high',
2413                     -complaints_to   => 'bit bucket'
2414                   );
2415
2416 This will produce the following non-standard HTTP header:
2417
2418     HTTP/1.0 200 OK
2419     Cost: Three smackers
2420     Annoyance-level: high
2421     Complaints-to: bit bucket
2422     Content-type: text/html
2423
2424 Note that underscores are translated automatically into hyphens. This feature
2425 allows you to keep up with the rapidly changing HTTP "standards".
2426
2427 The B<-type> is a key element that tell the browser how to display your
2428 document. The default is 'text/html'. Common types are:
2429
2430     text/html
2431     text/plain
2432     image/gif
2433     image/jpg
2434     image/png
2435     application/octet-stream
2436
2437 The B<-status> code is the HTTP response code. The default is 200 OK. Common
2438 status codes are:
2439
2440     200 OK
2441     204 No Response
2442     301 Moved Permanently
2443     302 Found
2444     303 See Other
2445     307 Temporary Redirect
2446     400 Bad Request
2447     401 Unauthorized
2448     403 Forbidden
2449     404 Not Found
2450     405 Not Allowed
2451     408 Request Timed Out
2452     500 Internal Server Error
2453     503 Service Unavailable
2454     504 Gateway Timed Out
2455
2456 The B<-expires> parameter lets you indicate to a browser and proxy server
2457 how long to cache pages for. When you specify an absolute or relative
2458 expiration interval with this parameter, some browsers and proxy servers
2459 will cache the script's output until the indicated expiration date.
2460 The following forms are all valid for the -expires field:
2461
2462     +30s                                30 seconds from now
2463     +10m                                ten minutes from now
2464     +1h                                 one hour from now
2465     -1d                                 yesterday (i.e. "ASAP!")
2466     now                                 immediately
2467     +3M                                 in three months
2468     +10y                                in ten years time
2469     Thursday, 25-Apr-1999 00:40:33 GMT  at the indicated time & date
2470
2471 The B<-cookie> parameter generates a header that tells the browser to provide
2472 a "magic cookie" during all subsequent transactions with your script.
2473 Netscape cookies have a special format that includes interesting attributes
2474 such as expiration time.  Use the B<cookie()> method to create and retrieve
2475 session cookies.
2476
2477 The B<-target> is for frames use
2478
2479 The B<-nph> parameter, if set to a true value, will issue the correct
2480 headers to work with a NPH (no-parse-header) script.  This is important
2481 to use with certain servers that expect all their scripts to be NPH.
2482
2483 The B<-charset> parameter can be used to control the character set
2484 sent to the browser.  If not provided, defaults to ISO-8859-1.  As a
2485 side effect, this sets the charset() method as well.
2486
2487 The B<-attachment> parameter can be used to turn the page into an
2488 attachment.  Instead of displaying the page, some browsers will prompt
2489 the user to save it to disk.  The value of the argument is the
2490 suggested name for the saved file.  In order for this to work, you may
2491 have to set the B<-type> to 'application/octet-stream'.
2492
2493 =head2 no_cache() Preventing browser caching of scripts
2494
2495 Most browsers will not cache the output from CGI scripts. Every time
2496 the browser reloads the page, the script is invoked anew. However some
2497 browsers do cache pages. You can discourage this behavior using the
2498 B<no_cache()> function.
2499
2500     $q->no_cache(1); # turn caching off by sending appropriate headers
2501     $q->no_cache(1); # do not send cache related headers.
2502
2503     $q->no_cache(1);
2504     print header (-type=>'image/gif', -nph=>1);
2505
2506     This will produce a header like the following:
2507
2508     HTTP/1.0 200 OK
2509     Server: Apache - accept no substitutes
2510     Expires: Thu, 15 Nov 2001 03:37:50 GMT
2511     Date: Thu, 15 Nov 2001 03:37:50 GMT
2512     Pragma: no-cache
2513     Content-Type: image/gif
2514
2515 Both the Pragma: no-cache header field and an Expires header that corresponds
2516 to the current time (ie now) will be sent.
2517
2518 =head2 cache() Preventing browser caching of scripts
2519
2520 The somewhat ill named B<cache()> method is a legacy from CGI.pm. It operates
2521 the same as the new B<no_cache()> method. The difference is/was that when set
2522 it results only in the Pragma: no-cache line being printed.
2523 Expires time data is not sent.
2524
2525 =head2 redirect() Generating a redirection header
2526
2527     print $q->redirect('http://somewhere.else/in/movie/land');
2528
2529 Sometimes you don't want to produce a document yourself, but simply
2530 redirect the browser elsewhere, perhaps choosing a URL based on the
2531 time of day or the identity of the user.
2532
2533 The B<redirect()> function redirects the browser to a different URL.  If
2534 you use redirection like this, you should B<not> print out a header as
2535 well.
2536
2537 One hint I can offer is that relative links may not work correctly
2538 when you generate a redirection to another document on your site.
2539 This is due to a well-intentioned optimization that some servers use.
2540 The solution to this is to use the full URL (including the http: part)
2541 of the document you are redirecting to.
2542
2543 You can also use named arguments:
2544
2545     print $q->redirect( -uri=>'http://somewhere.else/in/movie/land',
2546                         -nph=>1
2547                       );
2548
2549 The B<-nph> parameter, if set to a true value, will issue the correct
2550 headers to work with a NPH (no-parse-header) script.  This is important
2551 to use with certain servers, such as Microsoft ones, which
2552 expect all their scripts to be NPH.
2553
2554 =cut
2555
2556 =head1 PRAGMAS
2557
2558 There are a number of pragmas that you can specify in your use CGI::Simple
2559 statement. Pragmas, which are always preceded by a hyphen, change the way
2560 that CGI::Simple functions in various ways. You can generally achieve
2561 exactly the same results by setting the underlying $GLOBAL_VARIABLES.
2562
2563 For example the '-upload' pargma will enable file uploads:
2564
2565     use CGI::Simple qw(-upload);
2566
2567 In CGI::Simple::Standard Pragmas, function sets , and individual functions
2568 can all be imported in the same use() line.  For example, the following
2569 use statement imports the standard set of functions and enables debugging
2570 mode (pragma -debug):
2571
2572     use CGI::Simple::Standard qw(:standard -debug);
2573
2574 The current list of pragmas is as follows:
2575
2576 =over 4
2577
2578 =item -no_undef_params
2579
2580 If a value is not given in the query string, as in the queries
2581 "name1=&name2=" or "name1&name2", by default it will be returned
2582 as an empty string.
2583
2584 If you specify the '-no_undef_params' pragma then CGI::Simple ignores
2585 parameters with no values and they will not appear in the query object.
2586
2587 =item -nph
2588
2589 This makes CGI.pm produce a header appropriate for an NPH (no
2590 parsed header) script.  You may need to do other things as well
2591 to tell the server that the script is NPH.  See the discussion
2592 of NPH scripts below.
2593
2594 =item -newstyle_urls
2595
2596 Separate the name=value pairs in CGI parameter query strings with
2597 semicolons rather than ampersands.  For example:
2598
2599     ?name=fred;age=24;favorite_color=3
2600
2601 Semicolon-delimited query strings are always accepted, but will not be
2602 emitted by self_url() and query_string() unless the -newstyle_urls
2603 pragma is specified.
2604
2605 =item -oldstyle_urls
2606
2607 Separate the name=value pairs in CGI parameter query strings with
2608 ampersands rather than semicolons.  This is the default.
2609
2610     ?name=fred&age=24&favorite_color=3
2611
2612 =item -autoload
2613
2614 This is only available for CGI::Simple::Standard and uses AUTOLOAD to
2615 load functions on demand. See the CGI::Simple::Standard docs for details.
2616
2617 =item -no_debug
2618
2619 This turns off the command-line processing features. This is the default.
2620
2621 =item -debug1 and debug2
2622
2623 This turns on debugging.  At debug level 1 CGI::Simple will read arguments
2624 from the command-line. At debug level 2 CGI.pm will produce the prompt
2625 "(offline mode: enter name=value pairs on standard input)" and wait for
2626 input on STDIN. If no number is specified then a debug level of 2 is used.
2627
2628 See the section on debugging for more details.
2629
2630 =item -default
2631
2632 This sets the default global values for CGI.pm which will enable infinite
2633 size file uploads, and specify the '-newstyle_urls' and '-debug1' pragmas
2634
2635 =item -no_upload
2636
2637 Disable uploads - the default setting
2638
2639 =item - upload
2640
2641 Enable uploads - the CGI.pm default
2642
2643 =item -unique_header
2644
2645 Only allows headers to be generated once per script invocation
2646
2647 =item -carp
2648
2649 Carp when B<cgi_error()> called, default is to do nothing
2650
2651 =item -croak
2652
2653 Croak when B<cgi_error()> called, default is to do nothing
2654
2655 =back
2656
2657 =cut
2658
2659 ############### NPH Scripts ################
2660
2661 =head1 USING NPH SCRIPTS
2662
2663 NPH, or "no-parsed-header", scripts bypass the server completely by
2664 sending the complete HTTP header directly to the browser.  This has
2665 slight performance benefits, but is of most use for taking advantage
2666 of HTTP extensions that are not directly supported by your server,
2667 such as server push and PICS headers.
2668
2669 Servers use a variety of conventions for designating CGI scripts as
2670 NPH.  Many Unix servers look at the beginning of the script's name for
2671 the prefix "nph-".  The Macintosh WebSTAR server and Microsoft's
2672 Internet Information Server, in contrast, try to decide whether a
2673 program is an NPH script by examining the first line of script output.
2674
2675 CGI.pm supports NPH scripts with a special NPH mode.  When in this
2676 mode, CGI.pm will output the necessary extra header information when
2677 the B<header()> and B<redirect()> methods are called. You can set NPH mode
2678 in any of the following ways:
2679
2680 =over 4
2681
2682 =item In the B<use> statement
2683
2684 Simply add the "-nph" pragma to the use:
2685
2686     use CGI::Simple qw(-nph)
2687
2688 =item By calling the B<nph()> method:
2689
2690 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
2691
2692     $q->nph(1)
2693
2694 =item By using B<-nph> parameters
2695
2696 in the B<header()> and B<redirect()>  statements:
2697
2698     print $q->header(-nph=>1);
2699
2700 =back
2701
2702 The Microsoft Internet Information Server requires NPH mode.
2703 CGI::Simple will automatically detect when the script is
2704 running under IIS and put itself into this mode.  You do not need to
2705 do this manually, although it won't hurt anything if you do.  However,
2706 note that if you have applied Service Pack 6, much of the
2707 functionality of NPH scripts, including the ability to redirect while
2708 setting a cookie, b<do not work at all> on IIS without a special patch
2709 from Microsoft.  See
2710 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
2711 Non-Parsed Headers Stripped From CGI Applications That Have nph-
2712 Prefix in Name.
2713
2714 =cut
2715
2716 ################# Server Push Methods #################
2717
2718 =head1 SERVER PUSH
2719
2720 CGI.pm provides four simple functions for producing multipart
2721 documents of the type needed to implement server push.  These
2722 functions were graciously provided by Ed Jordan <ed@fidalgo.net> with
2723 additions from Andrew Benham <adsb@bigfoot.com>
2724
2725 You are also advised to put the script into NPH mode and to set $| to
2726 1 to avoid buffering problems.
2727
2728 Browser support for server push is variable.
2729
2730 Here is a simple script that demonstrates server push:
2731
2732     #!/usr/local/bin/perl
2733     use CGI::Simple::Standard qw/:push -nph/;
2734     $| = 1;
2735     print multipart_init(-boundary=>'----here we go!');
2736     foreach (0 .. 4) {
2737         print multipart_start(-type=>'text/plain'),
2738         "The current time is ",scalar(localtime),"\n";
2739         if ($_ < 4) {
2740             print multipart_end;
2741         }
2742         else {
2743             print multipart_final;
2744         }
2745         sleep 1;
2746     }
2747
2748 This script initializes server push by calling B<multipart_init()>.
2749 It then enters a loop in which it begins a new multipart section by
2750 calling B<multipart_start()>, prints the current local time,
2751 and ends a multipart section with B<multipart_end()>.  It then sleeps
2752 a second, and begins again. On the final iteration, it ends the
2753 multipart section with B<multipart_final()> rather than with
2754 B<multipart_end()>.
2755
2756 =head2 multipart_init() Initialize the multipart system
2757
2758     multipart_init(-boundary=>$boundary);
2759
2760 Initialize the multipart system.  The -boundary argument specifies
2761 what MIME boundary string to use to separate parts of the document.
2762 If not provided, CGI.pm chooses a reasonable boundary for you.
2763
2764 =head2 multipart_start() Start a new part of the multipart document
2765
2766     multipart_start(-type=>$type)
2767
2768 Start a new part of the multipart document using the specified MIME
2769 type.  If not specified, text/html is assumed.
2770
2771 =head2 multipart_end() End a multipart part
2772
2773     multipart_end()
2774
2775 End a part.  You must remember to call B<multipart_end()> once for each
2776 B<multipart_start()>, except at the end of the last part of the multipart
2777 document when B<multipart_final()> should be called instead of
2778 B<multipart_end()>.
2779
2780 =head2 multipart_final()
2781
2782     multipart_final()
2783
2784 End all parts.  You should call B<multipart_final()> rather than
2785 B<multipart_end()> at the end of the last part of the multipart document.
2786
2787 =head2 CGI::Push
2788
2789 Users interested in server push applications should also have a look
2790 at the B<CGI::Push> module.
2791
2792 =cut
2793
2794 ################# Debugging Methods ################
2795
2796 =head1 DEBUGGING
2797
2798 If you are running the script from the command line or in the perl
2799 debugger, you can pass the script a list of keywords or
2800 parameter=value pairs on the command line or from standard input (you
2801 don't have to worry about tricking your script into reading from
2802 environment variables).  Before you do this you will need to change the
2803 debug level from the default level of 0 (no debug) to either 1 if you
2804 want to debug from @ARGV (the command line) of 2 if you want to debug from
2805 STDIN. You can do this using the debug pragma like this:
2806
2807     use CGI::Simple qw(-debug2);  # set debug to level 2 => from STDIN
2808
2809         or this:
2810
2811     $CGI::Simple::DEBUG = 1;      # set debug to level 1 => from @ARGV
2812
2813 At debug level 1 you can pass keywords and name=value pairs like this:
2814
2815     your_script.pl keyword1 keyword2 keyword3
2816
2817         or this:
2818
2819     your_script.pl keyword1+keyword2+keyword3
2820
2821         or this:
2822
2823     your_script.pl name1=value1 name2=value2
2824
2825         or this:
2826
2827     your_script.pl name1=value1&name2=value2
2828
2829 At debug level 2 you can feed newline-delimited name=value
2830 pairs to the script on standard input. You will be presented
2831 with the following prompt:
2832
2833     (offline mode: enter name=value pairs on standard input)
2834
2835 You end the input with your system dependent end of file character.
2836 You should try ^Z ^X ^D and ^C if all else fails. The ^ means hold down
2837 the [Ctrl] button while you press the other key.
2838
2839 When debugging, you can use quotes and backslashes to escape
2840 characters in the familiar shell manner, letting you place
2841 spaces and other funny characters in your parameter=value
2842 pairs:
2843
2844     your_script.pl "name1='I am a long value'" "name2=two\ words"
2845
2846 =head2 Dump() Dumping the current object details
2847
2848 The B<Dump()> method produces a string consisting of all the
2849 query's object attributes formatted nicely as a nested list.  This dump
2850 includes the name/value pairs and a number of other details. This is useful
2851 for debugging purposes:
2852
2853     print $q->Dump
2854
2855 The actual result of this is HTML escaped formatted text wrapped in <pre> tags
2856 so if you send it straight to the browser it produces something that looks
2857 like:
2858
2859     $VAR1 = bless( {
2860          '.parameters' => [
2861                             'name',
2862                             'color'
2863                           ],
2864          '.globals' => {
2865                          'FATAL' => -1,
2866                          'DEBUG' => 0,
2867                          'NO_NULL' => 1,
2868                          'POST_MAX' => 102400,
2869                          'USE_CGI_PM_DEFAULTS' => 0,
2870                          'HEADERS_ONCE' => 0,
2871                          'NPH' => 0,
2872                          'DISABLE_UPLOADS' => 1,
2873                          'NO_UNDEF_PARAMS' => 0,
2874                          'USE_PARAM_SEMICOLONS' => 0
2875                        },
2876          '.fieldnames' => {
2877                             'color' => '1',
2878                             'name' => '1'
2879                           },
2880          '.mod_perl' => '',
2881          'color' => [
2882                       'red',
2883                       'green',
2884                       'blue'
2885                     ],
2886          'name' => [
2887                      'JaPh,'
2888                    ]
2889         }, 'CGI::Simple' );
2890
2891 You may recognize this as valid Perl syntax (which it is) and/or the output
2892 from Data::Dumper (also true). This is the actual guts of how the information
2893 is stored in the query object. All the internal params start with a . char
2894
2895 Alternatively you can dump your object and the current environment using:
2896
2897     print $q->Dump(\%ENV);
2898
2899 =head2 PrintEnv() Dumping the environment
2900
2901 You can get a similar browser friendly dump of the current %ENV hash using:
2902
2903     print $q->PrintEnv;
2904
2905 This will produce something like (in the browser):
2906
2907     $VAR1 = {
2908           'QUERY_STRING' => 'name=JaPh%2C&color=red&color=green&color=blue',
2909           'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
2910           'REGRESSION_TEST' => 'simple.t.pl',
2911           'VIM' => 'C:\\WINDOWS\\Desktop\\vim',
2912           'HTTP_REFERER' => 'xxx.sex.com',
2913           'HTTP_USER_AGENT' => 'LWP',
2914           'HTTP_ACCEPT' => 'text/html;q=1, image/gif;q=0.42, */*;q=0.001',
2915           'REMOTE_HOST' => 'localhost',
2916           'HTTP_HOST' => 'the.restaurant.at.the.end.of.the.universe',
2917           'GATEWAY_INTERFACE' => 'bleeding edge',
2918           'REMOTE_IDENT' => 'None of your damn business',
2919           'SCRIPT_NAME' => '/cgi-bin/foo.cgi',
2920           'SERVER_NAME' => 'nowhere.com',
2921           'HTTP_COOKIE' => '',
2922           'CONTENT_LENGTH' => '42',
2923           'HTTPS_A' => 'A',
2924           'HTTP_FROM' => 'spammer@nowhere.com',
2925           'HTTPS_B' => 'B',
2926           'SERVER_PROTOCOL' => 'HTTP/1.0',
2927           'PATH_TRANSLATED' => '/usr/local/somewhere/else',
2928           'SERVER_SOFTWARE' => 'Apache - accept no substitutes',
2929           'PATH_INFO' => '/somewhere/else',
2930           'REMOTE_USER' => 'Just another Perl hacker,',
2931           'REMOTE_ADDR' => '127.0.0.1',
2932           'HTTPS' => 'ON',
2933           'DOCUMENT_ROOT' => '/vs/www/foo',
2934           'REQUEST_METHOD' => 'GET',
2935           'REDIRECT_QUERY_STRING' => '',
2936           'AUTH_TYPE' => 'PGP MD5 DES rot13',
2937           'COOKIE' => 'foo=a%20phrase; bar=yes%2C%20a%20phrase&;I%20say;',
2938           'SERVER_PORT' => '8080'
2939         };
2940
2941
2942 =head2 cgi_error() Retrieving CGI::Simple error messages
2943
2944 Errors can occur while processing user input, particularly when
2945 processing uploaded files.  When these errors occur, CGI::Simple will stop
2946 processing and return an empty parameter list.  You can test for
2947 the existence and nature of errors using the B<cgi_error()> function.
2948 The error messages are formatted as HTTP status codes. You can either
2949 incorporate the error text into an HTML page, or use it as the value
2950 of the HTTP status:
2951
2952     my $error = $q->cgi_error;
2953     if ($error) {
2954         print $q->header(-status=>$error);
2955         print "<H2>$error</H2>;
2956       exit;
2957     }
2958
2959 =cut
2960
2961 ############### Accessor Methods ################
2962
2963 =head1 ACCESSOR METHODS
2964
2965 =head2 version() Get the CGI::Simple version info
2966
2967     $version = $q->version();
2968
2969 The B<version()> method returns the value of $VERSION
2970
2971 =head2 nph() Enable/disable NPH (Non Parsed Header) mode
2972
2973     $q->nph(1);  # enable NPH mode
2974     $q->nph(0);  # disable NPH mode
2975
2976 The B<nph()> method enables and disables NPH headers. See the NPH section.
2977
2978 =head2 all_parameters() Get the names/values of all parameters
2979
2980     @all_parameters = $q->all_parameters();
2981
2982 The B<all_parameters()> method is an alias for B<param()>
2983
2984 =head2 charset() Get/set the current character set.
2985
2986     $charset = $q->charset(); # get current charset
2987     $q->charset('utf-42');    # set the charset
2988
2989 The B<charset()> method gets the current charset value if no argument is
2990 supplied or sets it if an argument is supplied.
2991
2992 =head2 crlf() Get the system specific line ending sequence
2993
2994     $crlf = $q->crlf();
2995
2996 The B<crlf()> method returns the system specific line ending sequence.
2997
2998 =head2 globals() Get/set the value of the remaining global variables
2999
3000     $globals = $q->globals('FATAL');     # get the current value of $FATAL
3001     $globals = $q->globals('FATAL', 1 ); # set croak mode on cgi_error()
3002
3003 The B<globals()> method gets/sets the values of the global variables after the
3004 script has been invoked. For globals like $POST_MAX and $DISABLE_UPLOADS this
3005 makes no difference as they must be set prior to calling the new constructor
3006 but there might be reason the change the value of others.
3007
3008 =head2 auth_type() Get the current authorization/verification method
3009
3010     $auth_type = $q->auth_type();
3011
3012 The B<auth_type()> method returns the value of $ENV{'AUTH_TYPE'} which should
3013 contain the authorization/verification method in use for this script, if any.
3014
3015 =head2 content_length() Get the content length submitted in a POST
3016
3017     $content_length = $q->content_length();
3018
3019 The B<content_length()> method returns the value of $ENV{'AUTH_TYPE'}
3020
3021 =head2 content_type() Get the content_type of data submitted in a POST
3022
3023     $content_type = $q->content_type();
3024
3025 The B<content_type()> method returns the content_type of data submitted in
3026 a POST, generally 'multipart/form-data' or
3027 'application/x-www-form-urlencoded' as supplied in $ENV{'CONTENT_TYPE'}
3028
3029 =head2 document_root() Get the document root
3030
3031     $document_root = $q->document_root();
3032
3033 The B<document_root()> method returns the value of $ENV{'DOCUMENT_ROOT'}
3034
3035 =head2 gateway_interface() Get the gateway interface
3036
3037     $gateway_interface = $q->gateway_interface();
3038
3039 The B<gateway_interface()> method returns the value of
3040 $ENV{'GATEWAY_INTERFACE'}
3041
3042 =head2 path_translated() Get the value of path translated
3043
3044     $path_translated = $q->path_translated();
3045
3046 The B<path_translated()> method returns the value of $ENV{'PATH_TRANSLATED'}
3047
3048 =head2 referer() Spy on your users
3049
3050     $referer = $q->referer();
3051
3052 The B<referer()> method returns the value of $ENV{'REFERER'} This will return
3053 the URL of the page the browser was viewing prior to fetching your script.
3054 Not available for all browsers.
3055
3056 =head2 remote_addr() Get the remote address
3057
3058     $remote_addr = $q->remote_addr();
3059
3060 The B<remote_addr()> method returns the value of $ENV{'REMOTE_ADDR'} or
3061 127.0.0.1 (localhost) if this is not defined.
3062
3063 =head2 remote_host() Get a value for remote host
3064
3065     $remote_host = $q->remote_host();
3066
3067 The B<remote_host()> method returns the value of $ENV{'REMOTE_HOST'} if it is
3068 defined. If this is not defined it returns $ENV{'REMOTE_ADDR'} If this is not
3069 defined it returns 'localhost'
3070
3071 =head2 remote_ident() Get the remote identity
3072
3073     $remote_ident = $q->remote_ident();
3074
3075 The B<remote_ident()> method returns the value of $ENV{'REMOTE_IDENT'}
3076
3077 =head2 remote_user() Get the remote user
3078
3079     $remote_user = $q->remote_user();
3080
3081 The B<remote_user()> method returns the authorization/verification name used
3082 for user verification, if this script is protected. The value comes from
3083 $ENV{'REMOTE_USER'}
3084
3085 =head2 request_method() Get the request method
3086
3087     $request_method = $q->request_method();
3088
3089 The B<request_method()> method returns the method used to access your
3090 script, usually one of 'POST', 'GET' or 'HEAD' as supplied by
3091 $ENV{'REQUEST_METHOD'}
3092
3093 =head2 script_name() Get the script name
3094
3095     $script_name = $q->script_name();
3096
3097 The B<script_name()> method returns the value of $ENV{'SCRIPT_NAME'} if it is
3098 defined. Otherwise it returns Perl's script name from $0. Failing this it
3099 returns a null string ''
3100
3101 =head2 server_name() Get the server name
3102
3103     $server_name = $q->server_name();
3104
3105 The B<server_name()> method returns the value of $ENV{'SERVER_NAME'} if defined
3106 or 'localhost' otherwise
3107
3108 =head2 server_port() Get the port the server is listening on
3109
3110     $server_port = $q->server_port();
3111
3112 The B<server_port()> method returns the value $ENV{'SERVER_PORT'} if defined or
3113 80 if not.
3114
3115 =head2 server_protocol() Get the current server protocol
3116
3117     $server_protocol = $q->server_protocol();
3118
3119 The B<server_protocol()> method returns the value of $ENV{'SERVER_PROTOCOL'} if
3120 defined or 'HTTP/1.0' otherwise
3121
3122 =head2 server_software() Get the server software
3123
3124     $server_software = $q->server_software();
3125
3126 The B<server_software()> method returns the value $ENV{'SERVER_SOFTWARE'} or
3127 'cmdline' If the server software is IIS it formats your hard drive, installs
3128 Linux, FTPs to www.apache.org, installs Apache, and then restores your system
3129 from tape. Well maybe not, but it's a nice thought.
3130
3131 =head2 user_name() Get a value for the user name.
3132
3133     $user_name = $q->user_name();
3134
3135 Attempt to obtain the remote user's name, using a variety of different
3136 techniques.  This only works with older browsers such as Mosaic.
3137 Newer browsers do not report the user name for privacy reasons!
3138
3139 Technically the B<user_name()> method returns the value of $ENV{'HTTP_FROM'}
3140 or failing that $ENV{'REMOTE_IDENT'} or as a last choice $ENV{'REMOTE_USER'}
3141
3142 =head2 user_agent() Get the users browser type
3143
3144     $ua = $q->user_agent();          # return the user agent
3145     $ok = $q->user_agent('mozilla'); # return true if user agent 'mozilla'
3146
3147 The B<user_agent()> method returns the value of $ENV{'HTTP_USER_AGENT'}  when
3148 called without an argument or true or false if the $ENV{'HTTP_USER_AGENT'}
3149 matches the passed argument. The matching is case insensitive and partial.
3150
3151 =head2 virtual_host() Get the virtual host
3152
3153     $virtual_host = $q->virtual_host();
3154
3155 The B<virtual_host()> method returns the value of  $ENV{'HTTP_HOST'} if defined
3156 or $ENV{'SERVER_NAME'} as a default. Port numbers are removed.
3157
3158 =head2 path_info() Get any extra path info set to the script
3159
3160     $path_info = $q->path_info();
3161
3162 The B<path_info()> method returns additional path information from the script
3163 URL. E.G. fetching /cgi-bin/your_script/additional/stuff will result in
3164 $q->path_info() returning "/additional/stuff".
3165
3166 NOTE: The Microsoft Internet Information Server
3167 is broken with respect to additional path information.  If
3168 you use the Perl DLL library, the IIS server will attempt to
3169 execute the additional path information as a Perl script.
3170 If you use the ordinary file associations mapping, the
3171 path information will be present in the environment,
3172 but incorrect.  The best thing to do is to avoid using additional
3173 path information in CGI scripts destined for use with IIS.
3174
3175 =head2 Accept() Get the browser MIME types
3176
3177     $Accept = $q->Accept();
3178
3179 The B<Accept()> method returns a list of MIME types that the remote browser
3180 accepts. If you give this method a single argument corresponding to a
3181 MIME type, as in $q->Accept('text/html'), it will return a floating point
3182 value corresponding to the browser's preference for this type from 0.0
3183 (don't want) to 1.0.  Glob types (e.g. text/*) in the browser's accept
3184 list are handled correctly.
3185
3186 =head2 accept() Alias for Accept()
3187
3188     $accept = $q->accept();
3189
3190 The B<accept()> Method is an alias for Accept()
3191
3192 =head2 http() Get a range of HTTP related information
3193
3194     $http = $q->http();
3195
3196 Called with no arguments the B<http()> method returns the list of HTTP or HTTPS
3197 environment variables, including such things as HTTP_USER_AGENT,
3198 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
3199 like-named HTTP header fields in the request. Called with the name of
3200 an HTTP header field, returns its value.  Capitalization and the use
3201 of hyphens versus underscores are not significant.
3202
3203 For example, all three of these examples are equivalent:
3204
3205    $requested_language = $q->http('Accept-language');
3206    $requested_language = $q->http('Accept_language');
3207    $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
3208
3209 =head2 https() Get a range of HTTPS related information
3210
3211     $https = $q->https();
3212
3213 The B<https()> method is similar to the http() method except that when called
3214 without an argument it returns the value of $ENV{'HTTPS'} which will be
3215 true if a HTTPS connection is in use and false otherwise.
3216
3217 =head2 protocol() Get the current protocol
3218
3219     $protocol = $q->protocol();
3220
3221 The B<protocol()> method returns 'https' if a HTTPS connection is in use or the
3222 B<server_protocol()> minus version numbers ('http') otherwise.
3223
3224 =head2 url() Return the script's URL in several formats
3225
3226     $full_url      = $q->url();
3227     $full_url      = $q->url(-full=>1);
3228     $relative_url  = $q->url(-relative=>1);
3229     $absolute_url  = $q->url(-absolute=>1);
3230     $url_with_path = $q->url(-path_info=>1);
3231     $url_with_path_and_query = $q->url(-path_info=>1,-query=>1);
3232     $netloc        = $q->url(-base => 1);
3233
3234 B<url()> returns the script's URL in a variety of formats.  Called
3235 without any arguments, it returns the full form of the URL, including
3236 host name and port number
3237
3238     http://your.host.com/path/to/script.cgi
3239
3240 You can modify this format with the following named arguments:
3241
3242 =over 4
3243
3244 =item B<-absolute>
3245
3246 If true, produce an absolute URL, e.g.
3247
3248     /path/to/script.cgi
3249
3250 =item B<-relative>
3251
3252 Produce a relative URL.  This is useful if you want to reinvoke your
3253 script with different parameters. For example:
3254
3255     script.cgi
3256
3257 =item B<-full>
3258
3259 Produce the full URL, exactly as if called without any arguments.
3260 This overrides the -relative and -absolute arguments.
3261
3262 =item B<-path> (B<-path_info>)
3263
3264 Append the additional path information to the URL.  This can be
3265 combined with B<-full>, B<-absolute> or B<-relative>.  B<-path_info>
3266 is provided as a synonym.
3267
3268 =item B<-query> (B<-query_string>)
3269
3270 Append the query string to the URL.  This can be combined with
3271 B<-full>, B<-absolute> or B<-relative>.  B<-query_string> is provided
3272 as a synonym.
3273
3274 =item B<-base>
3275
3276 Generate just the protocol and net location, as in http://www.foo.com:8000
3277
3278 =back
3279
3280 =head2 self_url() Get the scripts complete URL
3281
3282     $self_url = $q->self_url();
3283
3284 The B<self_url()> method returns the value of:
3285
3286    $self->url( '-path_info'=>1, '-query'=>1, '-full'=>1 );
3287
3288 =head2 state() Alias for self_url()
3289
3290     $state = $q->state();
3291
3292 The B<state()> method is an alias for self_url()
3293
3294 =cut
3295
3296 ################# cgi-lib.pl Compatibility Methods #################
3297
3298 =head1 COMPATIBILITY WITH cgi-lib.pl 2.18
3299
3300 To make it easier to port existing programs that use cgi-lib.pl all
3301 the subs within cgi-lib.pl are available in CGI::Simple.  Using the
3302 functional interface of CGI::Simple::Standard porting is
3303 as easy as:
3304
3305     OLD VERSION
3306         require "cgi-lib.pl";
3307         &ReadParse;
3308         print "The value of the antique is $in{'antique'}.\n";
3309
3310     NEW VERSION
3311         use CGI::Simple::Standard qw(:cgi-lib);
3312         &ReadParse;
3313         print "The value of the antique is $in{'antique'}.\n";
3314
3315 CGI:Simple's B<ReadParse()> routine creates a variable named %in,
3316 which can be accessed to obtain the query variables.  Like
3317 ReadParse, you can also provide your own variable via a glob. Infrequently
3318 used features of B<ReadParse()>, such as the creation of @in and $in
3319 variables, are not supported.
3320
3321 You can also use the OO interface of CGI::Simple and call B<ReadParse()> and
3322 other cgi-lib.pl functions like this:
3323
3324     &CGI::Simple::ReadParse;       # get hash values in %in
3325
3326     my $q = new CGI::Simple;
3327     $q->ReadParse();                # same thing
3328
3329     CGI::Simple::ReadParse(*field); # get hash values in %field function style
3330
3331     my $q = new CGI::Simple;
3332     $q->ReadParse(*field);          # same thing
3333
3334 Once you use B<ReadParse()> under the functional interface , you can retrieve
3335 the query object itself this way if needed:
3336
3337     $q = $in{'CGI'};
3338
3339 Either way it allows you to start using the more interesting features
3340 of CGI.pm without rewriting your old scripts from scratch.
3341
3342 Unlike CGI.pm all the cgi-lib.pl functions from Version 2.18 are supported:
3343
3344     ReadParse()
3345     SplitParam()
3346     MethGet()
3347     MethPost()
3348     MyBaseUrl()
3349     MyURL()
3350     MyFullUrl()
3351     PrintHeader()
3352     HtmlTop()
3353     HtmlBot()
3354     PrintVariables()
3355     PrintEnv()
3356     CgiDie()
3357     CgiError()
3358
3359 =head1 COMPATIBILITY WITH CGI.pm
3360
3361 I has long been suggested that the CGI and HTML parts of CGI.pm should be
3362 split into separate modules (even the author suggests this!), CGI::Simple
3363 represents the realization of this and contains the complete CGI side of
3364 CGI.pm. Code-wise it weighs in at a little under 30% of the size of CGI.pm at
3365 a little under 1000 lines.
3366
3367 A great deal of care has been taken to ensure that the interface remains
3368 unchanged although a few tweaks have been made. The test suite is extensive
3369 and includes all the CGI.pm test scripts as well as a series of new test
3370 scripts. You may like to have a look at /t/concur.t which makes 160 tests
3371 of CGI::Simple and CGI in parallel and compares the results to ensure they
3372 are identical. This is the case as of CGI.pm 2.78.
3373
3374 You can't make an omelet without breaking eggs. A large number of methods
3375 and global variables have been deleted as detailed below. Some pragmas are
3376 also gone. In the tarball there is a script B</misc/check.pl> that will check if
3377 a script seems to be using any of these now non existent methods, globals or
3378 pragmas. You call it like this:
3379
3380     perl check.pl <files>
3381
3382 If it finds any likely candidates it will print a line with the line number,
3383 problem method/global and the complete line. For example here is some output
3384 from running the script on CGI.pm:
3385
3386     ...
3387     3162: Problem:'$CGI::OS'   local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3388     3165: Problem:'fillBuffer' $self->fillBuffer($FILLUNIT);
3389     ....
3390
3391 =head1 DIFFERENCES FROM CGI.pm
3392
3393 CGI::Simple is strict and warnings compliant.
3394
3395 There are 4 modules in this distribution:
3396
3397     CGI/Simple.pm           supplies all the core code.
3398     CGI/Simple/Cookie.pm    supplies the cookie handling functions.
3399     CGI/Simple/Util.pm      supplies a variety of utility functions
3400     CGI/Simple/Standard.pm  supplies a functional interface for Simple.pm
3401
3402 Simple.pm is the core module that provide all the essential functionality.
3403 Cookie.pm is a shortened rehash of the CGI.pm module of the same name
3404 which supplies the required cookie functionality. Util.pm has been recoded to
3405 use an internal object for data storage and supplies rarely needed non core
3406 functions and/or functions needed for the HTML side of things. Standard.pm is
3407 a wrapper module that supplies a complete functional interface to the OO
3408 back end supplied by CGI::Simple.
3409
3410 Although a serious attempt has been made to keep the interface identical,
3411 some minor changes and tweaks have been made. They will likely be
3412 insignificant to most users but here are the gory details.
3413
3414 =head2 Globals Variables
3415
3416 The list of global variables has been pruned by 75%. Here is the complete
3417 list of the global variables used:
3418
3419     $VERSION = "0.01";
3420     # set this to 1 to use CGI.pm default global settings
3421     $USE_CGI_PM_DEFAULTS = 0 unless defined $USE_CGI_PM_DEFAULTS;
3422     # see if user wants old  CGI.pm defaults
3423     do{ _use_cgi_pm_global_settings(); return } if $USE_CGI_PM_DEFAULTS;
3424     # no file uploads by default, set to 0 to enable uploads
3425     $DISABLE_UPLOADS = 1 unless defined $DISABLE_UPLOADS;
3426     # use a post max of 100K, set to -1 for no limits
3427     $POST_MAX = 102_400 unless defined $POST_MAX;
3428     # do not include undefined params parsed from query string
3429     $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS;
3430     # separate the name=value pairs with ; rather than &
3431     $USE_PARAM_SEMICOLONS = 0 unless defined $USE_PARAM_SEMICOLONS;
3432     # only print headers once
3433     $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE;
3434     # Set this to 1 to enable NPH scripts
3435     $NPH = 0 unless defined $NPH;
3436     # 0 => no debug, 1 => from @ARGV,  2 => from STDIN
3437     $DEBUG = 0 unless defined $DEBUG;
3438     # filter out null bytes in param - value pairs
3439     $NO_NULL  = 1 unless defined $NO_NULL;
3440     # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak
3441     $FATAL = -1 unless defined $FATAL;
3442
3443 Four of the default values of the old CGI.pm variables have been changed.
3444 Unlike CGI.pm which by default allows unlimited POST data and file uploads
3445 by default CGI::Simple limits POST data size to 100kB and denies file uploads
3446 by default. $USE_PARAM_SEMICOLONS is set to 0 by default so we use (old style)
3447 & rather than ; as the pair separator for query strings. Debugging is
3448 disabled by default.
3449
3450 There are three new global variables. If $NO_NULL is true (the default) then
3451 CGI::Simple will strip null bytes out of names, values and keywords. Null
3452 bytes can do interesting things to C based code like Perl. Uploaded files
3453 are not touched. $FATAL controls the behavior when B<cgi_error()> is called.
3454 The default value of -1 makes errors silent. $USE_CGI_PM_DEFAULTS reverts the
3455 defaults to the CGI.pm standard values ie unlimited file uploads via POST
3456 for DNS attacks. You can also get the defaults back by using the '-default'
3457 pragma in the use:
3458
3459     use CGI::Simple qw(-default);
3460     use CGI::Simple::Standard qw(-default);
3461
3462 The values of the global variables are stored in the CGI::Simple object and
3463 can be referenced and changed using the B<globals()> method like this:
3464
3465     my $value = $q->globals( 'VARNAME' );      # get
3466     $q->globals( 'VARNAME', 'some value' );    # set
3467
3468 As with many CGI.pm methods if you pass the optional value that will
3469 be set.
3470
3471 The $CGI::Simple::VARNAME = 'N' syntax is only useful prior to calling the
3472 B<new()> constructor. After that all reference is to the values stored in the
3473 CGI::Simple object so you must change these using the B<globals()> method.
3474
3475 $DISABLE_UPLOADS and $POST_MAX *must* be set prior to calling the constructor
3476 if you want the changes to have any effect as they control behavior during
3477 initialization. This is the same a CGI.pm although some people seem to miss
3478 this rather important point and set these after calling the constructor which
3479 does nothing.
3480
3481 The following globals are no longer relevant and have all been deleted:
3482
3483     $AUTOLOADED_ROUTINES
3484     $AUTOLOAD_DEBUG
3485     $BEEN_THERE
3486     $CRLF
3487     $DEFAULT_DTD
3488     $EBCDIC
3489     $FH
3490     $FILLUNIT
3491     $IIS
3492     $IN
3493     $INITIAL_FILLUNIT
3494     $JSCRIPT
3495     $MAC
3496     $MAXTRIES
3497     $MOD_PERL
3498     $NOSTICKY
3499     $OS
3500     $PERLEX
3501     $PRIVATE_TEMPFILES
3502     $Q
3503     $QUERY_CHARSET
3504     $QUERY_PARAM
3505     $SCRATCH
3506     $SL
3507     $SPIN_LOOP_MAX
3508     $TIMEOUT
3509     $TMPDIRECTORY
3510     $XHTML
3511     %EXPORT
3512     %EXPORT_OK
3513     %EXPORT_TAGS
3514     %OVERLOAD
3515     %QUERY_FIELDNAMES
3516     %SUBS
3517     @QUERY_PARAM
3518     @TEMP
3519
3520 Notes: CGI::Simple uses IO::File->new_tmpfile to get tempfile filehandles.
3521 These are private by default so $PRIVATE_TEMPFILES is no longer required nor
3522 is $TMPDIRECTORY. The value that were stored in $OS, $CRLF, $QUERY_CHARSET
3523 and $EBCDIC are now stored in the CGI::Simple::Util object where they find
3524 most of their use. The $MOD_PERL and $PERLEX values are now stored in our
3525 CGI::Simple object. $IIS was only used once in path_info().  $SL the system
3526 specific / \ : path delimiter is not required as we let IO::File handle our
3527 tempfile requirements. The rest of the globals are HTML related, export
3528 related, hand rolled autoload related or serve obscure purposes in CGI.pm
3529
3530 =head2 Changes to pragmas
3531
3532 There are some new pragmas available. See the pragmas section for details.
3533 The following CGI.pm pragmas are not available:
3534
3535     -any
3536     -compile
3537     -nosticky
3538     -no_xhtml
3539     -private_tempfiles
3540
3541 =head2 Filehandles
3542
3543 Unlike CGI.pm which tries to accept all filehandle like objects only \*FH
3544 and $fh are accepted by CGI::Simple as file accessors for B<new()> and B<save()>.
3545 IO::File objects work fine.
3546
3547 =head2 Hash interface
3548
3549     %hash = $q->Vars();     # pack values with "\0";
3550     %hash = $q->Vars(",");  # comma separate values
3551
3552 You may optionally pass B<Vars()> a string that will be used to separate multiple
3553 values when they are packed into the single hash value. If no value is
3554 supplied the default "\0" (null byte) will be used. Null bytes are dangerous
3555 things for C based code (ie Perl).
3556
3557 =head2 cgi-lib.pl
3558
3559 All the cgi-lib.pl 2.18 routines are supported. Unlike CGI.pm all the
3560 subroutines from cgi-lib.pl are included. They have been GOLFED down to
3561 25 lines but they all work pretty much the same as the originals.
3562
3563 =head1 CGI::Simple COMPLETE METHOD LIST
3564
3565 Here is a complete list of all the CGI::Simple methods.
3566
3567 =head2 Guts (hands off, except of course for new)
3568
3569     _initialize_globals
3570     _use_cgi_pm_global_settings
3571     _store_globals
3572     import
3573     _reset_globals
3574     new
3575     _initialize
3576     _read_parse
3577     _parse_params
3578     _add_param
3579     _parse_keywordlist
3580     _parse_multipart
3581     _save_tmpfile
3582     _read_data
3583
3584 =head2 Core Methods
3585
3586     param
3587     add_param
3588     param_fetch
3589     url_param
3590     keywords
3591     Vars
3592     append
3593     delete
3594     Delete
3595     delete_all
3596     Delete_all
3597     upload
3598     upload_info
3599     query_string
3600     parse_query_string
3601     parse_keywordlist
3602
3603 =head2 Save and Restore from File Methods
3604
3605     _init_from_file
3606     save
3607     save_parameters
3608
3609 =head2 Miscellaneous Methods
3610
3611     url_decode
3612     url_encode
3613     escapeHTML
3614     unescapeHTML
3615     put
3616     print
3617
3618 =head2 Cookie Methods
3619
3620     cookie
3621     raw_cookie
3622
3623 =head2 Header Methods
3624
3625     header
3626     cache
3627     no_cache
3628     redirect
3629
3630 =head2 Server Push Methods
3631
3632     multipart_init
3633     multipart_start
3634     multipart_end
3635     multipart_final
3636
3637 =head2 Debugging Methods
3638
3639     read_from_cmdline
3640     Dump
3641     as_string
3642     cgi_error
3643
3644 =head2 cgi-lib.pl Compatibility Routines - all 2.18 functions available
3645
3646     _shift_if_ref
3647     ReadParse
3648     SplitParam
3649     MethGet
3650     MethPost
3651     MyBaseUrl
3652     MyURL
3653     MyFullUrl
3654     PrintHeader
3655     HtmlTop
3656     HtmlBot
3657     PrintVariables
3658     PrintEnv
3659     CgiDie
3660     CgiError
3661
3662 =head2 Accessor Methods
3663
3664     version
3665     nph
3666     all_parameters
3667     charset
3668     crlf                # new, returns OS specific CRLF sequence
3669     globals             # get/set global variables
3670     auth_type
3671     content_length
3672     content_type
3673     document_root
3674     gateway_interface
3675     path_translated
3676     referer
3677     remote_addr
3678     remote_host
3679     remote_ident
3680     remote_user
3681     request_method
3682     script_name
3683     server_name
3684     server_port
3685     server_protocol
3686     server_software
3687     user_name
3688     user_agent
3689     virtual_host
3690     path_info
3691     Accept
3692     accept
3693     http
3694     https
3695     protocol
3696     url
3697     self_url
3698     state
3699
3700 =head1 NEW METHODS IN CGI::Simple
3701
3702 There are a few new methods in CGI::Simple as listed below. The highlights are
3703 the B<parse_query_string()> method to add the QUERY_STRING data to your object if
3704 the method was POST. The B<no_cache()> method adds an expires now directive and
3705 the Pragma: no-cache directive to the header to encourage some browsers to
3706 do the right thing. B<PrintEnv()> from the cgi-lib.pl routines will dump an
3707 HTML friendly list of the %ENV and makes a handy addition to B<Dump()> for use
3708 in debugging. The upload method now accepts a filepath as an optional second
3709 argument as shown in the synopsis. If this is supplied the uploaded file will
3710 be written to there automagically.
3711
3712 =head2 Internal Routines
3713
3714     _initialize_globals()
3715     _use_cgi_pm_global_settings()
3716     _store_globals()
3717     _initialize()
3718     _init_from_file()
3719     _read_parse()
3720     _parse_params()
3721     _add_param()
3722     _parse_keywordlist()
3723     _parse_multipart()
3724     _save_tmpfile()
3725     _read_data()
3726
3727 =head2 New Public Methods
3728
3729     add_param()             # adds a param/value(s) pair +/- overwrite
3730     upload_info()           # uploaded files MIME type and size
3731     url_decode()            # decode s url encoded string
3732     url_encode()            # url encode a string
3733     parse_query_string()    # add QUERY_STRING data to $q object if 'POST'
3734     no_cache()              # add both the Pragma: no-cache
3735                             # and Expires/Date => 'now' to header
3736
3737 =head2  cgi-lib.pl methods added for completeness
3738
3739     _shift_if_ref()         # internal hack reminiscent of self_or_default :-)
3740     MyBaseUrl()
3741     MyURL()
3742     MyFullUrl()
3743     PrintVariables()
3744     PrintEnv()
3745     CgiDie()
3746     CgiError()
3747
3748 =head2 New Accessors
3749
3750     crlf()                  # returns CRLF sequence
3751     globals()               # global vars now stored in $q object - get/set
3752     content_length()        # returns $ENV{'CONTENT_LENGTH'}
3753     document_root()         # returns $ENV{'DOCUMENT_ROOT'}
3754     gateway_interface()     # returns $ENV{'GATEWAY_INTERFACE'}
3755
3756 =head1 METHODS IN CGI.pm NOT IN CGI::Simple
3757
3758 Here is a complete list of what is not included in CGI::Simple. Basically all
3759 the HTML related stuff plus large redundant chunks of the guts. The check.pl
3760 script in the /misc dir will check to see if a script is using any of these.
3761
3762 =head2 Guts - rearranged, recoded, renamed and hacked out of existence
3763
3764     initialize_globals()
3765     compile()
3766     expand_tags()
3767     self_or_default()
3768     self_or_CGI()
3769     init()
3770     to_filehandle()
3771     save_request()
3772     parse_params()
3773     add_parameter()
3774     binmode()
3775     _make_tag_func()
3776     AUTOLOAD()
3777     _compile()
3778     _setup_symbols()
3779     new_MultipartBuffer()
3780     read_from_client()
3781     import_names()     # I dislike this and left it out, so shoot me.
3782
3783 =head2 HTML Related
3784
3785     autoEscape()
3786     URL_ENCODED()
3787     MULTIPART()
3788     SERVER_PUSH()
3789     start_html()
3790     _style()
3791     _script()
3792     end_html()
3793     isindex()
3794     startform()
3795     start_form()
3796     end_multipart_form()
3797     start_multipart_form()
3798     endform()
3799     end_form()
3800     _textfield()
3801     textfield()
3802     filefield()
3803     password_field()
3804     textarea()
3805     button()
3806     submit()
3807     reset()
3808     defaults()
3809     comment()
3810     checkbox()
3811     checkbox_group()
3812     _tableize()
3813     radio_group()
3814     popup_menu()
3815     scrolling_list()
3816     hidden()
3817     image_button()
3818     nosticky()
3819     default_dtd()
3820
3821 =head2 Upload Related
3822
3823 CGI::Simple uses anonymous tempfiles supplied by IO::File to spool uploaded
3824 files to.
3825
3826     private_tempfiles() # automatic in CGI::Simple
3827     tmpFileName()       # all upload files are anonymous
3828     uploadInfo()        # relied on FH access, replaced with upload_info()
3829
3830
3831 =head2 Really Private Subs (marked as so)
3832
3833     previous_or_default()
3834     register_parameter()
3835     get_fields()
3836     _set_values_and_labels()
3837     _compile_all()
3838     asString()
3839     compare()
3840
3841 =head2 Internal Multipart Parsing Routines
3842
3843     read_multipart()
3844     readHeader()
3845     readBody()
3846     read()
3847     fillBuffer()
3848     eof()
3849
3850 =head1 EXPORT
3851
3852 Nothing.
3853
3854 =head1 AUTHOR INFORMATION
3855
3856 Originally copyright 2001 Dr James Freeman E<lt>jfreeman@tassie.net.auE<gt>
3857 This release by Andy Armstrong <andy@hexten.net>
3858
3859 This package is free software and is provided "as is" without express or
3860 implied warranty. It may be used, redistributed and/or modified under the terms
3861 of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html)
3862
3863 Address bug reports and comments to: andy@hexten.net.  When sending
3864 bug reports, please provide the version of CGI::Simple, the version of
3865 Perl, the name and version of your Web server, and the name and
3866 version of the operating system you are using.  If the problem is even
3867 remotely browser dependent, please provide information about the
3868 affected browsers as well.
3869
3870 Address bug reports and comments to: andy@hexten.net
3871
3872 =head1 CREDITS
3873
3874 Lincoln D. Stein (lstein@cshl.org) and everyone else who worked on the
3875 original CGI.pm upon which this module is heavily based
3876
3877 Brandon Black for some heavy duty testing and bug fixes
3878
3879 John D Robinson and Jeroen Latour for helping solve some interesting test
3880 failures as well as Perlmonks:
3881 tommyw, grinder, Jaap, vek, erasei, jlongino and strider_corinth
3882
3883 Thanks for patches to:
3884
3885 Ewan Edwards, Joshua N Pritikin, Mike Barry
3886
3887 =head1 LICENCE AND COPYRIGHT
3888
3889 Copyright (c) 2007, Andy Armstrong C<< <andy@hexten.net> >>. All rights reserved.
3890
3891 This module is free software; you can redistribute it and/or
3892 modify it under the same terms as Perl itself. See L<perlartistic>.
3893
3894 =head1 SEE ALSO
3895
3896 B<CGI>, L<CGI::Simple::Standard>, L<CGI::Simple::Cookie>,
3897 L<CGI::Simple::Util>, L<CGI::Minimal>
3898
3899 =cut
3900