This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Enhance the failure reporting for the pod2html tests
[perl5.git] / lib / CGI.pm
1 package CGI;
2 require 5.004;
3 use Carp 'croak';
4
5 # See the bottom of this file for the POD documentation.  Search for the
6 # string '=head'.
7
8 # You can run this file through either pod2man or pod2html to produce pretty
9 # documentation in manual or html file format (these utilities are part of the
10 # Perl 5 distribution).
11
12 # Copyright 1995-1998 Lincoln D. Stein.  All rights reserved.
13 # It may be used and modified freely, but I do request that this copyright
14 # notice remain attached to the file.  You may modify this module as you 
15 # wish, but if you redistribute a modified version, please attach a note
16 # listing the modifications you have made.
17
18 # The most recent version and complete docs are available at:
19 #   http://stein.cshl.org/WWW/software/CGI/
20
21 $CGI::revision = '$Id: CGI.pm,v 1.75 2002/10/16 17:48:37 lstein Exp $';
22 $CGI::VERSION='2.89';
23
24 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
26 # $CGITempFile::TMPDIRECTORY = '/usr/tmp';
27 use CGI::Util qw(rearrange make_attributes unescape escape expires);
28
29 #use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 #                           'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
31
32 use constant XHTML_DTD => ['-//W3C//DTD XHTML 1.0 Transitional//EN',
33                            'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'];
34
35 $TAINTED = substr("$0$^X",0,0);
36
37 my @SAVED_SYMBOLS;
38
39 # >>>>> Here are some globals that you might want to adjust <<<<<<
40 sub initialize_globals {
41     # Set this to 1 to enable copious autoloader debugging messages
42     $AUTOLOAD_DEBUG = 0;
43
44     # Set this to 1 to generate XTML-compatible output
45     $XHTML = 1;
46
47     # Change this to the preferred DTD to print in start_html()
48     # or use default_dtd('text of DTD to use');
49     $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
50                      'http://www.w3.org/TR/html4/loose.dtd' ] ;
51
52     # Set this to 1 to enable NOSTICKY scripts
53     # or: 
54     #    1) use CGI qw(-nosticky)
55     #    2) $CGI::nosticky(1)
56     $NOSTICKY = 0;
57
58     # Set this to 1 to enable NPH scripts
59     # or: 
60     #    1) use CGI qw(-nph)
61     #    2) CGI::nph(1)
62     #    3) print header(-nph=>1)
63     $NPH = 0;
64
65     # Set this to 1 to enable debugging from @ARGV
66     # Set to 2 to enable debugging from STDIN
67     $DEBUG = 1;
68
69     # Set this to 1 to make the temporary files created
70     # during file uploads safe from prying eyes
71     # or do...
72     #    1) use CGI qw(:private_tempfiles)
73     #    2) CGI::private_tempfiles(1);
74     $PRIVATE_TEMPFILES = 0;
75
76     # Set this to a positive value to limit the size of a POSTing
77     # to a certain number of bytes:
78     $POST_MAX = -1;
79
80     # Change this to 1 to disable uploads entirely:
81     $DISABLE_UPLOADS = 0;
82
83     # Automatically determined -- don't change
84     $EBCDIC = 0;
85
86     # Change this to 1 to suppress redundant HTTP headers
87     $HEADERS_ONCE = 0;
88
89     # separate the name=value pairs by semicolons rather than ampersands
90     $USE_PARAM_SEMICOLONS = 1;
91
92     # Do not include undefined params parsed from query string
93     # use CGI qw(-no_undef_params);
94     $NO_UNDEF_PARAMS = 0;
95
96     # Other globals that you shouldn't worry about.
97     undef $Q;
98     $BEEN_THERE = 0;
99     undef @QUERY_PARAM;
100     undef %EXPORT;
101     undef $QUERY_CHARSET;
102     undef %QUERY_FIELDNAMES;
103
104     # prevent complaints by mod_perl
105     1;
106 }
107
108 # ------------------ START OF THE LIBRARY ------------
109
110 # make mod_perlhappy
111 initialize_globals();
112
113 # FIGURE OUT THE OS WE'RE RUNNING UNDER
114 # Some systems support the $^O variable.  If not
115 # available then require() the Config library
116 unless ($OS) {
117     unless ($OS = $^O) {
118         require Config;
119         $OS = $Config::Config{'osname'};
120     }
121 }
122 if ($OS =~ /^MSWin/i) {
123   $OS = 'WINDOWS';
124 } elsif ($OS =~ /^VMS/i) {
125   $OS = 'VMS';
126 } elsif ($OS =~ /^dos/i) {
127   $OS = 'DOS';
128 } elsif ($OS =~ /^MacOS/i) {
129     $OS = 'MACINTOSH';
130 } elsif ($OS =~ /^os2/i) {
131     $OS = 'OS2';
132 } elsif ($OS =~ /^epoc/i) {
133     $OS = 'EPOC';
134 } elsif ($OS =~ /^cygwin/i) {
135     $OS = 'CYGWIN';
136 } else {
137     $OS = 'UNIX';
138 }
139
140 # Some OS logic.  Binary mode enabled on DOS, NT and VMS
141 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin|CYGWIN)/;
142
143 # This is the default class for the CGI object to use when all else fails.
144 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
145
146 # This is where to look for autoloaded routines.
147 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
148
149 # The path separator is a slash, backslash or semicolon, depending
150 # on the paltform.
151 $SL = {
152     UNIX    => '/',  OS2 => '\\', EPOC      => '/', CYGWIN => '/',
153     WINDOWS => '\\', DOS => '\\', MACINTOSH => ':', VMS    => '/'
154     }->{$OS};
155
156 # This no longer seems to be necessary
157 # Turn on NPH scripts by default when running under IIS server!
158 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
159 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
160
161 # Turn on special checking for Doug MacEachern's modperl
162 if (exists $ENV{'GATEWAY_INTERFACE'}
163     &&
164     ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
165   {
166     $| = 1;
167     require mod_perl;
168     if ($mod_perl::VERSION >= 1.99) {
169       require Apache::compat;
170     } else {
171       require Apache;
172     }
173   }
174
175 # Turn on special checking for ActiveState's PerlEx
176 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
177
178 # Define the CRLF sequence.  I can't use a simple "\r\n" because the meaning
179 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
180 # and sometimes CR).  The most popular VMS web server
181 # doesn't accept CRLF -- instead it wants a LR.  EBCDIC machines don't
182 # use ASCII, so \015\012 means something different.  I find this all 
183 # really annoying.
184 $EBCDIC = "\t" ne "\011";
185 if ($OS eq 'VMS') {
186   $CRLF = "\n";
187 } elsif ($EBCDIC) {
188   $CRLF= "\r\n";
189 } else {
190   $CRLF = "\015\012";
191 }
192
193 if ($needs_binmode) {
194     $CGI::DefaultClass->binmode(main::STDOUT);
195     $CGI::DefaultClass->binmode(main::STDIN);
196     $CGI::DefaultClass->binmode(main::STDERR);
197 }
198
199 %EXPORT_TAGS = (
200                 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
201                            tt u i b blockquote pre img a address cite samp dfn html head
202                            base body Link nextid title meta kbd start_html end_html
203                            input Select option comment charset escapeHTML/],
204                 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param 
205                            embed basefont style span layer ilayer font frameset frame script small big/],
206                 ':html4'=>[qw/abbr acronym bdo col colgroup del fieldset iframe
207                             ins label legend noframes noscript object optgroup Q 
208                             thead tbody tfoot/], 
209                 ':netscape'=>[qw/blink fontsize center/],
210                 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group 
211                           submit reset defaults radio_group popup_menu button autoEscape
212                           scrolling_list image_button start_form end_form startform endform
213                           start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
214                 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
215                          raw_cookie request_method query_string Accept user_agent remote_host content_type
216                          remote_addr referer server_name server_software server_port server_protocol
217                          virtual_host remote_ident auth_type http
218                          save_parameters restore_parameters param_fetch
219                          remote_user user_name header redirect import_names put 
220                          Delete Delete_all url_param cgi_error/],
221                 ':ssl' => [qw/https/],
222                 ':imagemap' => [qw/Area Map/],
223                 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
224                 ':html' => [qw/:html2 :html3 :html4 :netscape/],
225                 ':standard' => [qw/:html2 :html3 :html4 :form :cgi/],
226                 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
227                 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal :html4/]
228                 );
229
230 # to import symbols into caller
231 sub import {
232     my $self = shift;
233
234     # This causes modules to clash.
235     undef %EXPORT_OK;
236     undef %EXPORT;
237
238     $self->_setup_symbols(@_);
239     my ($callpack, $callfile, $callline) = caller;
240
241     # To allow overriding, search through the packages
242     # Till we find one in which the correct subroutine is defined.
243     my @packages = ($self,@{"$self\:\:ISA"});
244     foreach $sym (keys %EXPORT) {
245         my $pck;
246         my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
247         foreach $pck (@packages) {
248             if (defined(&{"$pck\:\:$sym"})) {
249                 $def = $pck;
250                 last;
251             }
252         }
253         *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
254     }
255 }
256
257 sub compile {
258     my $pack = shift;
259     $pack->_setup_symbols('-compile',@_);
260 }
261
262 sub expand_tags {
263     my($tag) = @_;
264     return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
265     my(@r);
266     return ($tag) unless $EXPORT_TAGS{$tag};
267     foreach (@{$EXPORT_TAGS{$tag}}) {
268         push(@r,&expand_tags($_));
269     }
270     return @r;
271 }
272
273 #### Method: new
274 # The new routine.  This will check the current environment
275 # for an existing query string, and initialize itself, if so.
276 ####
277 sub new {
278     my($class,$initializer) = @_;
279     my $self = {};
280     bless $self,ref $class || $class || $DefaultClass;
281     if ($MOD_PERL && defined Apache->request) {
282       Apache->request->register_cleanup(\&CGI::_reset_globals);
283       undef $NPH;
284     }
285     $self->_reset_globals if $PERLEX;
286     $self->init($initializer);
287     return $self;
288 }
289
290 # We provide a DESTROY method so that the autoloader
291 # doesn't bother trying to find it.
292 sub DESTROY { }
293
294 #### Method: param
295 # Returns the value(s)of a named parameter.
296 # If invoked in a list context, returns the
297 # entire list.  Otherwise returns the first
298 # member of the list.
299 # If name is not provided, return a list of all
300 # the known parameters names available.
301 # If more than one argument is provided, the
302 # second and subsequent arguments are used to
303 # set the value of the parameter.
304 ####
305 sub param {
306     my($self,@p) = self_or_default(@_);
307     return $self->all_parameters unless @p;
308     my($name,$value,@other);
309
310     # For compatibility between old calling style and use_named_parameters() style, 
311     # we have to special case for a single parameter present.
312     if (@p > 1) {
313         ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
314         my(@values);
315
316         if (substr($p[0],0,1) eq '-') {
317             @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
318         } else {
319             foreach ($value,@other) {
320                 push(@values,$_) if defined($_);
321             }
322         }
323         # If values is provided, then we set it.
324         if (@values) {
325             $self->add_parameter($name);
326             $self->{$name}=[@values];
327         }
328     } else {
329         $name = $p[0];
330     }
331
332     return unless defined($name) && $self->{$name};
333     return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
334 }
335
336 sub self_or_default {
337     return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
338     unless (defined($_[0]) && 
339             (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
340             ) {
341         $Q = $CGI::DefaultClass->new unless defined($Q);
342         unshift(@_,$Q);
343     }
344     return wantarray ? @_ : $Q;
345 }
346
347 sub self_or_CGI {
348     local $^W=0;                # prevent a warning
349     if (defined($_[0]) &&
350         (substr(ref($_[0]),0,3) eq 'CGI' 
351          || UNIVERSAL::isa($_[0],'CGI'))) {
352         return @_;
353     } else {
354         return ($DefaultClass,@_);
355     }
356 }
357
358 ########################################
359 # THESE METHODS ARE MORE OR LESS PRIVATE
360 # GO TO THE __DATA__ SECTION TO SEE MORE
361 # PUBLIC METHODS
362 ########################################
363
364 # Initialize the query object from the environment.
365 # If a parameter list is found, this object will be set
366 # to an associative array in which parameter names are keys
367 # and the values are stored as lists
368 # If a keyword list is found, this method creates a bogus
369 # parameter list with the single parameter 'keywords'.
370
371 sub init {
372     my($self,$initializer) = @_;
373     my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
374     local($/) = "\n";
375
376     # if we get called more than once, we want to initialize
377     # ourselves from the original query (which may be gone
378     # if it was read from STDIN originally.)
379     if (defined(@QUERY_PARAM) && !defined($initializer)) {
380         foreach (@QUERY_PARAM) {
381             $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
382         }
383         $self->charset($QUERY_CHARSET);
384         $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
385         return;
386     }
387
388     $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
389     $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
390
391     $fh = to_filehandle($initializer) if $initializer;
392
393     # set charset to the safe ISO-8859-1
394     $self->charset('ISO-8859-1');
395
396     # set autoescaping to on
397     $self->{'escape'} = 1;
398
399   METHOD: {
400
401       # avoid unreasonably large postings
402       if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
403           $self->cgi_error("413 Request entity too large");
404           last METHOD;
405       }
406
407       # Process multipart postings, but only if the initializer is
408       # not defined.
409       if ($meth eq 'POST'
410           && defined($ENV{'CONTENT_TYPE'})
411           && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
412           && !defined($initializer)
413           ) {
414           my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
415           $self->read_multipart($boundary,$content_length);
416           last METHOD;
417       } 
418
419       # If initializer is defined, then read parameters
420       # from it.
421       if (defined($initializer)) {
422           if (UNIVERSAL::isa($initializer,'CGI')) {
423               $query_string = $initializer->query_string;
424               last METHOD;
425           }
426           if (ref($initializer) && ref($initializer) eq 'HASH') {
427               foreach (keys %$initializer) {
428                   $self->param('-name'=>$_,'-value'=>$initializer->{$_});
429               }
430               last METHOD;
431           }
432           
433           if (defined($fh) && ($fh ne '')) {
434               while (<$fh>) {
435                   chomp;
436                   last if /^=/;
437                   push(@lines,$_);
438               }
439               # massage back into standard format
440               if ("@lines" =~ /=/) {
441                   $query_string=join("&",@lines);
442               } else {
443                   $query_string=join("+",@lines);
444               }
445               last METHOD;
446           }
447
448           # last chance -- treat it as a string
449           $initializer = $$initializer if ref($initializer) eq 'SCALAR';
450           $query_string = $initializer;
451
452           last METHOD;
453       }
454
455       # If method is GET or HEAD, fetch the query from
456       # the environment.
457       if ($meth=~/^(GET|HEAD)$/) {
458           if ($MOD_PERL) {
459               $query_string = Apache->request->args;
460           } else {
461               $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
462               $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
463           }
464           last METHOD;
465       }
466
467       if ($meth eq 'POST') {
468           $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
469               if $content_length > 0;
470           # Some people want to have their cake and eat it too!
471           # Uncomment this line to have the contents of the query string
472           # APPENDED to the POST data.
473           # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
474           last METHOD;
475       }
476
477       # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
478       # Check the command line and then the standard input for data.
479       # We use the shellwords package in order to behave the way that
480       # UN*X programmers expect.
481       $query_string = read_from_cmdline() if $DEBUG;
482   }
483
484     # We now have the query string in hand.  We do slightly
485     # different things for keyword lists and parameter lists.
486     if (defined $query_string && length $query_string) {
487         if ($query_string =~ /[&=;]/) {
488             $self->parse_params($query_string);
489         } else {
490             $self->add_parameter('keywords');
491             $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
492         }
493     }
494
495     # Special case.  Erase everything if there is a field named
496     # .defaults.
497     if ($self->param('.defaults')) {
498         undef %{$self};
499     }
500
501     # Associative array containing our defined fieldnames
502     $self->{'.fieldnames'} = {};
503     foreach ($self->param('.cgifields')) {
504         $self->{'.fieldnames'}->{$_}++;
505     }
506     
507     # Clear out our default submission button flag if present
508     $self->delete('.submit');
509     $self->delete('.cgifields');
510
511     $self->save_request unless $initializer;
512 }
513
514 # FUNCTIONS TO OVERRIDE:
515 # Turn a string into a filehandle
516 sub to_filehandle {
517     my $thingy = shift;
518     return undef unless $thingy;
519     return $thingy if UNIVERSAL::isa($thingy,'GLOB');
520     return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
521     if (!ref($thingy)) {
522         my $caller = 1;
523         while (my $package = caller($caller++)) {
524             my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy"; 
525             return $tmp if defined(fileno($tmp));
526         }
527     }
528     return undef;
529 }
530
531 # send output to the browser
532 sub put {
533     my($self,@p) = self_or_default(@_);
534     $self->print(@p);
535 }
536
537 # print to standard output (for overriding in mod_perl)
538 sub print {
539     shift;
540     CORE::print(@_);
541 }
542
543 # get/set last cgi_error
544 sub cgi_error {
545     my ($self,$err) = self_or_default(@_);
546     $self->{'.cgi_error'} = $err if defined $err;
547     return $self->{'.cgi_error'};
548 }
549
550 sub save_request {
551     my($self) = @_;
552     # We're going to play with the package globals now so that if we get called
553     # again, we initialize ourselves in exactly the same way.  This allows
554     # us to have several of these objects.
555     @QUERY_PARAM = $self->param; # save list of parameters
556     foreach (@QUERY_PARAM) {
557       next unless defined $_;
558       $QUERY_PARAM{$_}=$self->{$_};
559     }
560     $QUERY_CHARSET = $self->charset;
561     %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
562 }
563
564 sub parse_params {
565     my($self,$tosplit) = @_;
566     my(@pairs) = split(/[&;]/,$tosplit);
567     my($param,$value);
568     foreach (@pairs) {
569         ($param,$value) = split('=',$_,2);
570         next unless defined $param;
571         next if $NO_UNDEF_PARAMS and not defined $value;
572         $value = '' unless defined $value;
573         $param = unescape($param);
574         $value = unescape($value);
575         $self->add_parameter($param);
576         push (@{$self->{$param}},$value);
577     }
578 }
579
580 sub add_parameter {
581     my($self,$param)=@_;
582     return unless defined $param;
583     push (@{$self->{'.parameters'}},$param) 
584         unless defined($self->{$param});
585 }
586
587 sub all_parameters {
588     my $self = shift;
589     return () unless defined($self) && $self->{'.parameters'};
590     return () unless @{$self->{'.parameters'}};
591     return @{$self->{'.parameters'}};
592 }
593
594 # put a filehandle into binary mode (DOS)
595 sub binmode {
596     CORE::binmode($_[1]);
597 }
598
599 sub _make_tag_func {
600     my ($self,$tagname) = @_;
601     my $func = qq(
602         sub $tagname {
603             shift if \$_[0] && 
604                     (ref(\$_[0]) &&
605                      (substr(ref(\$_[0]),0,3) eq 'CGI' ||
606                     UNIVERSAL::isa(\$_[0],'CGI')));
607             my(\$attr) = '';
608             if (ref(\$_[0]) && ref(\$_[0]) eq 'HASH') {
609                 my(\@attr) = make_attributes(shift()||undef,1);
610                 \$attr = " \@attr" if \@attr;
611             }
612         );
613     if ($tagname=~/start_(\w+)/i) {
614         $func .= qq! return "<\L$1\E\$attr>";} !;
615     } elsif ($tagname=~/end_(\w+)/i) {
616         $func .= qq! return "<\L/$1\E>"; } !;
617     } else {
618         $func .= qq#
619             return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@_;
620             my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
621             my \@result = map { "\$tag\$_\$untag" } 
622                               (ref(\$_[0]) eq 'ARRAY') ? \@{\$_[0]} : "\@_";
623             return "\@result";
624             }#;
625     }
626 return $func;
627 }
628
629 sub AUTOLOAD {
630     print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
631     my $func = &_compile;
632     goto &$func;
633 }
634
635 sub _compile {
636     my($func) = $AUTOLOAD;
637     my($pack,$func_name);
638     {
639         local($1,$2); # this fixes an obscure variable suicide problem.
640         $func=~/(.+)::([^:]+)$/;
641         ($pack,$func_name) = ($1,$2);
642         $pack=~s/::SUPER$//;    # fix another obscure problem
643         $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
644             unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
645
646         my($sub) = \%{"$pack\:\:SUBS"};
647         unless (%$sub) {
648            my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
649            eval "package $pack; $$auto";
650            croak("$AUTOLOAD: $@") if $@;
651            $$auto = '';  # Free the unneeded storage (but don't undef it!!!)
652        }
653        my($code) = $sub->{$func_name};
654
655        $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
656        if (!$code) {
657            (my $base = $func_name) =~ s/^(start_|end_)//i;
658            if ($EXPORT{':any'} || 
659                $EXPORT{'-any'} ||
660                $EXPORT{$base} || 
661                (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
662                    && $EXPORT_OK{$base}) {
663                $code = $CGI::DefaultClass->_make_tag_func($func_name);
664            }
665        }
666        croak("Undefined subroutine $AUTOLOAD\n") unless $code;
667        eval "package $pack; $code";
668        if ($@) {
669            $@ =~ s/ at .*\n//;
670            croak("$AUTOLOAD: $@");
671        }
672     }       
673     CORE::delete($sub->{$func_name});  #free storage
674     return "$pack\:\:$func_name";
675 }
676
677 sub _selected {
678   my $self = shift;
679   my $value = shift;
680   return '' unless $value;
681   return $XHTML ? qq( selected="selected") : qq( selected);
682 }
683
684 sub _checked {
685   my $self = shift;
686   my $value = shift;
687   return '' unless $value;
688   return $XHTML ? qq( checked="checked") : qq( checked);
689 }
690
691 sub _reset_globals { initialize_globals(); }
692
693 sub _setup_symbols {
694     my $self = shift;
695     my $compile = 0;
696
697     # to avoid reexporting unwanted variables
698     undef %EXPORT;
699
700     foreach (@_) {
701         $HEADERS_ONCE++,         next if /^[:-]unique_headers$/;
702         $NPH++,                  next if /^[:-]nph$/;
703         $NOSTICKY++,             next if /^[:-]nosticky$/;
704         $DEBUG=0,                next if /^[:-]no_?[Dd]ebug$/;
705         $DEBUG=2,                next if /^[:-][Dd]ebug$/;
706         $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
707         $XHTML++,                next if /^[:-]xhtml$/;
708         $XHTML=0,                next if /^[:-]no_?xhtml$/;
709         $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
710         $PRIVATE_TEMPFILES++,    next if /^[:-]private_tempfiles$/;
711         $EXPORT{$_}++,           next if /^[:-]any$/;
712         $compile++,              next if /^[:-]compile$/;
713         $NO_UNDEF_PARAMS++,      next if /^[:-]no_undef_params$/;
714         
715         # This is probably extremely evil code -- to be deleted some day.
716         if (/^[-]autoload$/) {
717             my($pkg) = caller(1);
718             *{"${pkg}::AUTOLOAD"} = sub { 
719                 my($routine) = $AUTOLOAD;
720                 $routine =~ s/^.*::/CGI::/;
721                 &$routine;
722             };
723             next;
724         }
725
726         foreach (&expand_tags($_)) {
727             tr/a-zA-Z0-9_//cd;  # don't allow weird function names
728             $EXPORT{$_}++;
729         }
730     }
731     _compile_all(keys %EXPORT) if $compile;
732     @SAVED_SYMBOLS = @_;
733 }
734
735 sub charset {
736   my ($self,$charset) = self_or_default(@_);
737   $self->{'.charset'} = $charset if defined $charset;
738   $self->{'.charset'};
739 }
740
741 ###############################################################################
742 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
743 ###############################################################################
744 $AUTOLOADED_ROUTINES = '';      # get rid of -w warning
745 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
746
747 %SUBS = (
748
749 'URL_ENCODED'=> <<'END_OF_FUNC',
750 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
751 END_OF_FUNC
752
753 'MULTIPART' => <<'END_OF_FUNC',
754 sub MULTIPART {  'multipart/form-data'; }
755 END_OF_FUNC
756
757 'SERVER_PUSH' => <<'END_OF_FUNC',
758 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
759 END_OF_FUNC
760
761 'new_MultipartBuffer' => <<'END_OF_FUNC',
762 # Create a new multipart buffer
763 sub new_MultipartBuffer {
764     my($self,$boundary,$length,$filehandle) = @_;
765     return MultipartBuffer->new($self,$boundary,$length,$filehandle);
766 }
767 END_OF_FUNC
768
769 'read_from_client' => <<'END_OF_FUNC',
770 # Read data from a file handle
771 sub read_from_client {
772     my($self, $fh, $buff, $len, $offset) = @_;
773     local $^W=0;                # prevent a warning
774     return undef unless defined($fh);
775     return read($fh, $$buff, $len, $offset);
776 }
777 END_OF_FUNC
778
779 'delete' => <<'END_OF_FUNC',
780 #### Method: delete
781 # Deletes the named parameter entirely.
782 ####
783 sub delete {
784     my($self,@p) = self_or_default(@_);
785     my(@names) = rearrange([NAME],@p);
786     for my $name (@names) {
787       CORE::delete $self->{$name};
788       CORE::delete $self->{'.fieldnames'}->{$name};
789       @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
790     }
791 }
792 END_OF_FUNC
793
794 #### Method: import_names
795 # Import all parameters into the given namespace.
796 # Assumes namespace 'Q' if not specified
797 ####
798 'import_names' => <<'END_OF_FUNC',
799 sub import_names {
800     my($self,$namespace,$delete) = self_or_default(@_);
801     $namespace = 'Q' unless defined($namespace);
802     die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
803     if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
804         # can anyone find an easier way to do this?
805         foreach (keys %{"${namespace}::"}) {
806             local *symbol = "${namespace}::${_}";
807             undef $symbol;
808             undef @symbol;
809             undef %symbol;
810         }
811     }
812     my($param,@value,$var);
813     foreach $param ($self->param) {
814         # protect against silly names
815         ($var = $param)=~tr/a-zA-Z0-9_/_/c;
816         $var =~ s/^(?=\d)/_/;
817         local *symbol = "${namespace}::$var";
818         @value = $self->param($param);
819         @symbol = @value;
820         $symbol = $value[0];
821     }
822 }
823 END_OF_FUNC
824
825 #### Method: keywords
826 # Keywords acts a bit differently.  Calling it in a list context
827 # returns the list of keywords.  
828 # Calling it in a scalar context gives you the size of the list.
829 ####
830 'keywords' => <<'END_OF_FUNC',
831 sub keywords {
832     my($self,@values) = self_or_default(@_);
833     # If values is provided, then we set it.
834     $self->{'keywords'}=[@values] if @values;
835     my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
836     @result;
837 }
838 END_OF_FUNC
839
840 # These are some tie() interfaces for compatibility
841 # with Steve Brenner's cgi-lib.pl routines
842 'Vars' => <<'END_OF_FUNC',
843 sub Vars {
844     my $q = shift;
845     my %in;
846     tie(%in,CGI,$q);
847     return %in if wantarray;
848     return \%in;
849 }
850 END_OF_FUNC
851
852 # These are some tie() interfaces for compatibility
853 # with Steve Brenner's cgi-lib.pl routines
854 'ReadParse' => <<'END_OF_FUNC',
855 sub ReadParse {
856     local(*in);
857     if (@_) {
858         *in = $_[0];
859     } else {
860         my $pkg = caller();
861         *in=*{"${pkg}::in"};
862     }
863     tie(%in,CGI);
864     return scalar(keys %in);
865 }
866 END_OF_FUNC
867
868 'PrintHeader' => <<'END_OF_FUNC',
869 sub PrintHeader {
870     my($self) = self_or_default(@_);
871     return $self->header();
872 }
873 END_OF_FUNC
874
875 'HtmlTop' => <<'END_OF_FUNC',
876 sub HtmlTop {
877     my($self,@p) = self_or_default(@_);
878     return $self->start_html(@p);
879 }
880 END_OF_FUNC
881
882 'HtmlBot' => <<'END_OF_FUNC',
883 sub HtmlBot {
884     my($self,@p) = self_or_default(@_);
885     return $self->end_html(@p);
886 }
887 END_OF_FUNC
888
889 'SplitParam' => <<'END_OF_FUNC',
890 sub SplitParam {
891     my ($param) = @_;
892     my (@params) = split ("\0", $param);
893     return (wantarray ? @params : $params[0]);
894 }
895 END_OF_FUNC
896
897 'MethGet' => <<'END_OF_FUNC',
898 sub MethGet {
899     return request_method() eq 'GET';
900 }
901 END_OF_FUNC
902
903 'MethPost' => <<'END_OF_FUNC',
904 sub MethPost {
905     return request_method() eq 'POST';
906 }
907 END_OF_FUNC
908
909 'TIEHASH' => <<'END_OF_FUNC',
910 sub TIEHASH { 
911     return $_[1] if defined $_[1];
912     return $Q ||= new shift;
913 }
914 END_OF_FUNC
915
916 'STORE' => <<'END_OF_FUNC',
917 sub STORE {
918     my $self = shift;
919     my $tag  = shift;
920     my $vals = shift;
921     my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
922     $self->param(-name=>$tag,-value=>\@vals);
923 }
924 END_OF_FUNC
925
926 'FETCH' => <<'END_OF_FUNC',
927 sub FETCH {
928     return $_[0] if $_[1] eq 'CGI';
929     return undef unless defined $_[0]->param($_[1]);
930     return join("\0",$_[0]->param($_[1]));
931 }
932 END_OF_FUNC
933
934 'FIRSTKEY' => <<'END_OF_FUNC',
935 sub FIRSTKEY {
936     $_[0]->{'.iterator'}=0;
937     $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
938 }
939 END_OF_FUNC
940
941 'NEXTKEY' => <<'END_OF_FUNC',
942 sub NEXTKEY {
943     $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
944 }
945 END_OF_FUNC
946
947 'EXISTS' => <<'END_OF_FUNC',
948 sub EXISTS {
949     exists $_[0]->{$_[1]};
950 }
951 END_OF_FUNC
952
953 'DELETE' => <<'END_OF_FUNC',
954 sub DELETE {
955     $_[0]->delete($_[1]);
956 }
957 END_OF_FUNC
958
959 'CLEAR' => <<'END_OF_FUNC',
960 sub CLEAR {
961     %{$_[0]}=();
962 }
963 ####
964 END_OF_FUNC
965
966 ####
967 # Append a new value to an existing query
968 ####
969 'append' => <<'EOF',
970 sub append {
971     my($self,@p) = @_;
972     my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
973     my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
974     if (@values) {
975         $self->add_parameter($name);
976         push(@{$self->{$name}},@values);
977     }
978     return $self->param($name);
979 }
980 EOF
981
982 #### Method: delete_all
983 # Delete all parameters
984 ####
985 'delete_all' => <<'EOF',
986 sub delete_all {
987     my($self) = self_or_default(@_);
988     undef %{$self};
989 }
990 EOF
991
992 'Delete' => <<'EOF',
993 sub Delete {
994     my($self,@p) = self_or_default(@_);
995     $self->delete(@p);
996 }
997 EOF
998
999 'Delete_all' => <<'EOF',
1000 sub Delete_all {
1001     my($self,@p) = self_or_default(@_);
1002     $self->delete_all(@p);
1003 }
1004 EOF
1005
1006 #### Method: autoescape
1007 # If you want to turn off the autoescaping features,
1008 # call this method with undef as the argument
1009 'autoEscape' => <<'END_OF_FUNC',
1010 sub autoEscape {
1011     my($self,$escape) = self_or_default(@_);
1012     my $d = $self->{'escape'};
1013     $self->{'escape'} = $escape;
1014     $d;
1015 }
1016 END_OF_FUNC
1017
1018
1019 #### Method: version
1020 # Return the current version
1021 ####
1022 'version' => <<'END_OF_FUNC',
1023 sub version {
1024     return $VERSION;
1025 }
1026 END_OF_FUNC
1027
1028 #### Method: url_param
1029 # Return a parameter in the QUERY_STRING, regardless of
1030 # whether this was a POST or a GET
1031 ####
1032 'url_param' => <<'END_OF_FUNC',
1033 sub url_param {
1034     my ($self,@p) = self_or_default(@_);
1035     my $name = shift(@p);
1036     return undef unless exists($ENV{QUERY_STRING});
1037     unless (exists($self->{'.url_param'})) {
1038         $self->{'.url_param'}={}; # empty hash
1039         if ($ENV{QUERY_STRING} =~ /=/) {
1040             my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
1041             my($param,$value);
1042             foreach (@pairs) {
1043                 ($param,$value) = split('=',$_,2);
1044                 $param = unescape($param);
1045                 $value = unescape($value);
1046                 push(@{$self->{'.url_param'}->{$param}},$value);
1047             }
1048         } else {
1049             $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1050         }
1051     }
1052     return keys %{$self->{'.url_param'}} unless defined($name);
1053     return () unless $self->{'.url_param'}->{$name};
1054     return wantarray ? @{$self->{'.url_param'}->{$name}}
1055                      : $self->{'.url_param'}->{$name}->[0];
1056 }
1057 END_OF_FUNC
1058
1059 #### Method: Dump
1060 # Returns a string in which all the known parameter/value 
1061 # pairs are represented as nested lists, mainly for the purposes 
1062 # of debugging.
1063 ####
1064 'Dump' => <<'END_OF_FUNC',
1065 sub Dump {
1066     my($self) = self_or_default(@_);
1067     my($param,$value,@result);
1068     return '<ul></ul>' unless $self->param;
1069     push(@result,"<ul>");
1070     foreach $param ($self->param) {
1071         my($name)=$self->escapeHTML($param);
1072         push(@result,"<li><strong>$param</strong>");
1073         push(@result,"<ul>");
1074         foreach $value ($self->param($param)) {
1075             $value = $self->escapeHTML($value);
1076             $value =~ s/\n/<br>\n/g;
1077             push(@result,"<li>$value");
1078         }
1079         push(@result,"</ul>");
1080     }
1081     push(@result,"</ul>");
1082     return join("\n",@result);
1083 }
1084 END_OF_FUNC
1085
1086 #### Method as_string
1087 #
1088 # synonym for "dump"
1089 ####
1090 'as_string' => <<'END_OF_FUNC',
1091 sub as_string {
1092     &Dump(@_);
1093 }
1094 END_OF_FUNC
1095
1096 #### Method: save
1097 # Write values out to a filehandle in such a way that they can
1098 # be reinitialized by the filehandle form of the new() method
1099 ####
1100 'save' => <<'END_OF_FUNC',
1101 sub save {
1102     my($self,$filehandle) = self_or_default(@_);
1103     $filehandle = to_filehandle($filehandle);
1104     my($param);
1105     local($,) = '';  # set print field separator back to a sane value
1106     local($\) = '';  # set output line separator to a sane value
1107     foreach $param ($self->param) {
1108         my($escaped_param) = escape($param);
1109         my($value);
1110         foreach $value ($self->param($param)) {
1111             print $filehandle "$escaped_param=",escape("$value"),"\n";
1112         }
1113     }
1114     foreach (keys %{$self->{'.fieldnames'}}) {
1115           print $filehandle ".cgifields=",escape("$_"),"\n";
1116     }
1117     print $filehandle "=\n";    # end of record
1118 }
1119 END_OF_FUNC
1120
1121
1122 #### Method: save_parameters
1123 # An alias for save() that is a better name for exportation.
1124 # Only intended to be used with the function (non-OO) interface.
1125 ####
1126 'save_parameters' => <<'END_OF_FUNC',
1127 sub save_parameters {
1128     my $fh = shift;
1129     return save(to_filehandle($fh));
1130 }
1131 END_OF_FUNC
1132
1133 #### Method: restore_parameters
1134 # A way to restore CGI parameters from an initializer.
1135 # Only intended to be used with the function (non-OO) interface.
1136 ####
1137 'restore_parameters' => <<'END_OF_FUNC',
1138 sub restore_parameters {
1139     $Q = $CGI::DefaultClass->new(@_);
1140 }
1141 END_OF_FUNC
1142
1143 #### Method: multipart_init
1144 # Return a Content-Type: style header for server-push
1145 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1146 #
1147 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1148 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1149 ####
1150 'multipart_init' => <<'END_OF_FUNC',
1151 sub multipart_init {
1152     my($self,@p) = self_or_default(@_);
1153     my($boundary,@other) = rearrange([BOUNDARY],@p);
1154     $boundary = $boundary || '------- =_aaaaaaaaaa0';
1155     $self->{'separator'} = "$CRLF--$boundary$CRLF";
1156     $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1157     $type = SERVER_PUSH($boundary);
1158     return $self->header(
1159         -nph => 1,
1160         -type => $type,
1161         (map { split "=", $_, 2 } @other),
1162     ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1163 }
1164 END_OF_FUNC
1165
1166
1167 #### Method: multipart_start
1168 # Return a Content-Type: style header for server-push, start of section
1169 #
1170 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1171 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1172 ####
1173 'multipart_start' => <<'END_OF_FUNC',
1174 sub multipart_start {
1175     my(@header);
1176     my($self,@p) = self_or_default(@_);
1177     my($type,@other) = rearrange([TYPE],@p);
1178     $type = $type || 'text/html';
1179     push(@header,"Content-Type: $type");
1180
1181     # rearrange() was designed for the HTML portion, so we
1182     # need to fix it up a little.
1183     foreach (@other) {
1184         next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1185         ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1186     }
1187     push(@header,@other);
1188     my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1189     return $header;
1190 }
1191 END_OF_FUNC
1192
1193
1194 #### Method: multipart_end
1195 # Return a MIME boundary separator for server-push, end of section
1196 #
1197 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1198 # contribution
1199 ####
1200 'multipart_end' => <<'END_OF_FUNC',
1201 sub multipart_end {
1202     my($self,@p) = self_or_default(@_);
1203     return $self->{'separator'};
1204 }
1205 END_OF_FUNC
1206
1207
1208 #### Method: multipart_final
1209 # Return a MIME boundary separator for server-push, end of all sections
1210 #
1211 # Contributed by Andrew Benham (adsb@bigfoot.com)
1212 ####
1213 'multipart_final' => <<'END_OF_FUNC',
1214 sub multipart_final {
1215     my($self,@p) = self_or_default(@_);
1216     return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1217 }
1218 END_OF_FUNC
1219
1220
1221 #### Method: header
1222 # Return a Content-Type: style header
1223 #
1224 ####
1225 'header' => <<'END_OF_FUNC',
1226 sub header {
1227     my($self,@p) = self_or_default(@_);
1228     my(@header);
1229
1230     return undef if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1231
1232     my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,@other) = 
1233         rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1234                             'STATUS',['COOKIE','COOKIES'],'TARGET',
1235                             'EXPIRES','NPH','CHARSET',
1236                             'ATTACHMENT'],@p);
1237
1238     $nph     ||= $NPH;
1239     if (defined $charset) {
1240       $self->charset($charset);
1241     } else {
1242       $charset = $self->charset;
1243     }
1244
1245     # rearrange() was designed for the HTML portion, so we
1246     # need to fix it up a little.
1247     foreach (@other) {
1248         next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1249         ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1250         $header = ucfirst($header);
1251     }
1252
1253     $type ||= 'text/html' unless defined($type);
1254     $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/;
1255
1256     # Maybe future compatibility.  Maybe not.
1257     my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1258     push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1259     push(@header,"Server: " . &server_software()) if $nph;
1260
1261     push(@header,"Status: $status") if $status;
1262     push(@header,"Window-Target: $target") if $target;
1263     # push all the cookies -- there may be several
1264     if ($cookie) {
1265         my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1266         foreach (@cookie) {
1267             my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1268             push(@header,"Set-Cookie: $cs") if $cs ne '';
1269         }
1270     }
1271     # if the user indicates an expiration time, then we need
1272     # both an Expires and a Date header (so that the browser is
1273     # uses OUR clock)
1274     push(@header,"Expires: " . expires($expires,'http'))
1275         if $expires;
1276     push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1277     push(@header,"Pragma: no-cache") if $self->cache();
1278     push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1279     push(@header,map {ucfirst $_} @other);
1280     push(@header,"Content-Type: $type") if $type ne '';
1281
1282     my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1283     if ($MOD_PERL and not $nph) {
1284         my $r = Apache->request;
1285         $r->send_cgi_header($header);
1286         return '';
1287     }
1288     return $header;
1289 }
1290 END_OF_FUNC
1291
1292
1293 #### Method: cache
1294 # Control whether header() will produce the no-cache
1295 # Pragma directive.
1296 ####
1297 'cache' => <<'END_OF_FUNC',
1298 sub cache {
1299     my($self,$new_value) = self_or_default(@_);
1300     $new_value = '' unless $new_value;
1301     if ($new_value ne '') {
1302         $self->{'cache'} = $new_value;
1303     }
1304     return $self->{'cache'};
1305 }
1306 END_OF_FUNC
1307
1308
1309 #### Method: redirect
1310 # Return a Location: style header
1311 #
1312 ####
1313 'redirect' => <<'END_OF_FUNC',
1314 sub redirect {
1315     my($self,@p) = self_or_default(@_);
1316     my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,COOKIE,NPH],@p);
1317     $url ||= $self->self_url;
1318     my(@o);
1319     foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1320     unshift(@o,
1321          '-Status'=>'302 Moved',
1322          '-Location'=>$url,
1323          '-nph'=>$nph);
1324     unshift(@o,'-Target'=>$target) if $target;
1325     unshift(@o,'-Cookie'=>$cookie) if $cookie;
1326     unshift(@o,'-Type'=>'');
1327     return $self->header(@o);
1328 }
1329 END_OF_FUNC
1330
1331
1332 #### Method: start_html
1333 # Canned HTML header
1334 #
1335 # Parameters:
1336 # $title -> (optional) The title for this HTML document (-title)
1337 # $author -> (optional) e-mail address of the author (-author)
1338 # $base -> (optional) if set to true, will enter the BASE address of this document
1339 #          for resolving relative references (-base) 
1340 # $xbase -> (optional) alternative base at some remote location (-xbase)
1341 # $target -> (optional) target window to load all links into (-target)
1342 # $script -> (option) Javascript code (-script)
1343 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1344 # $meta -> (optional) Meta information tags
1345 # $head -> (optional) any other elements you'd like to incorporate into the <head> tag
1346 #           (a scalar or array ref)
1347 # $style -> (optional) reference to an external style sheet
1348 # @other -> (optional) any other named parameters you'd like to incorporate into
1349 #           the <body> tag.
1350 ####
1351 'start_html' => <<'END_OF_FUNC',
1352 sub start_html {
1353     my($self,@p) = &self_or_default(@_);
1354     my($title,$author,$base,$xbase,$script,$noscript,
1355         $target,$meta,$head,$style,$dtd,$lang,$encoding,@other) = 
1356         rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG,ENCODING],@p);
1357
1358     $encoding = 'iso-8859-1' unless defined $encoding;
1359
1360     # strangely enough, the title needs to be escaped as HTML
1361     # while the author needs to be escaped as a URL
1362     $title = $self->escapeHTML($title || 'Untitled Document');
1363     $author = $self->escape($author);
1364     $lang ||= 'en-US';
1365     my(@result,$xml_dtd);
1366     if ($dtd) {
1367         if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1368             $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1369         } else {
1370             $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1371         }
1372     } else {
1373         $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1374     }
1375
1376     $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1377     $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1378     push @result,qq(<?xml version="1.0" encoding="$encoding"?>) if $xml_dtd; 
1379
1380     if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1381         push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t "$dtd->[1]">));
1382     } else {
1383         push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1384     }
1385     push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang" xml:lang="$lang"><head><title>$title</title>)
1386                         : qq(<html lang="$lang"><head><title>$title</title>));
1387         if (defined $author) {
1388     push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1389                                                                 : "<link rev=\"made\" href=\"mailto:$author\">");
1390         }
1391
1392     if ($base || $xbase || $target) {
1393         my $href = $xbase || $self->url('-path'=>1);
1394         my $t = $target ? qq/ target="$target"/ : '';
1395         push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1396     }
1397
1398     if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1399         foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />) 
1400                         : qq(<meta name="$_" content="$meta->{$_}">)); }
1401     }
1402
1403     push(@result,ref($head) ? @$head : $head) if $head;
1404
1405     # handle the infrequently-used -style and -script parameters
1406     push(@result,$self->_style($style)) if defined $style;
1407     push(@result,$self->_script($script)) if defined $script;
1408
1409     # handle -noscript parameter
1410     push(@result,<<END) if $noscript;
1411 <noscript>
1412 $noscript
1413 </noscript>
1414 END
1415     ;
1416     my($other) = @other ? " @other" : '';
1417     push(@result,"</head><body$other>");
1418     return join("\n",@result);
1419 }
1420 END_OF_FUNC
1421
1422 ### Method: _style
1423 # internal method for generating a CSS style section
1424 ####
1425 '_style' => <<'END_OF_FUNC',
1426 sub _style {
1427     my ($self,$style) = @_;
1428     my (@result);
1429     my $type = 'text/css';
1430
1431     my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1432     my $cdata_end   = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1433
1434     if (ref($style)) {
1435      my($src,$code,$stype,@other) =
1436          rearrange([SRC,CODE,TYPE],
1437                     '-foo'=>'bar', # a trick to allow the '-' to be omitted
1438                     ref($style) eq 'ARRAY' ? @$style : %$style);
1439      $type = $stype if $stype;
1440      if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1441      { # If it is, push a LINK tag for each one.
1442        foreach $src (@$src)
1443        {
1444          push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1445                              : qq(<link rel="stylesheet" type="$type" href="$src">)) if $src;
1446        }
1447      }
1448      else
1449      { # Otherwise, push the single -src, if it exists.
1450        push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1451                            : qq(<link rel="stylesheet" type="$type" href="$src">)
1452             ) if $src;
1453       }
1454      push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
1455     } else {
1456      push(@result,style({'type'=>$type},"$cdata_start\n$style\n$cdata_end"));
1457     }
1458     @result;
1459 }
1460 END_OF_FUNC
1461
1462 '_script' => <<'END_OF_FUNC',
1463 sub _script {
1464     my ($self,$script) = @_;
1465     my (@result);
1466
1467     my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1468     foreach $script (@scripts) {
1469         my($src,$code,$language);
1470         if (ref($script)) { # script is a hash
1471             ($src,$code,$language, $type) =
1472                 rearrange([SRC,CODE,LANGUAGE,TYPE],
1473                                  '-foo'=>'bar', # a trick to allow the '-' to be omitted
1474                                  ref($script) eq 'ARRAY' ? @$script : %$script);
1475             # User may not have specified language
1476             $language ||= 'JavaScript';
1477             unless (defined $type) {
1478                 $type = lc $language;
1479                 # strip '1.2' from 'javascript1.2'
1480                 $type =~ s/^(\D+).*$/text\/$1/;
1481             }
1482         } else {
1483             ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1484         }
1485
1486     my $comment = '//';  # javascript by default
1487     $comment = '#' if $type=~/perl|tcl/i;
1488     $comment = "'" if $type=~/vbscript/i;
1489
1490     my $cdata_start  =  "\n<!-- Hide script\n";
1491     $cdata_start    .= "$comment<![CDATA[\n"  if $XHTML; 
1492     my $cdata_end    = $XHTML ? "\n$comment]]>" : $comment;
1493     $cdata_end      .= " End script hiding -->\n";
1494
1495         my(@satts);
1496         push(@satts,'src'=>$src) if $src;
1497         push(@satts,'language'=>$language);
1498         push(@satts,'type'=>$type);
1499         $code = "$cdata_start$code$cdata_end" if defined $code;
1500         push(@result,script({@satts},$code || ''));
1501     }
1502     @result;
1503 }
1504 END_OF_FUNC
1505
1506 #### Method: end_html
1507 # End an HTML document.
1508 # Trivial method for completeness.  Just returns "</body>"
1509 ####
1510 'end_html' => <<'END_OF_FUNC',
1511 sub end_html {
1512     return "</body></html>";
1513 }
1514 END_OF_FUNC
1515
1516
1517 ################################
1518 # METHODS USED IN BUILDING FORMS
1519 ################################
1520
1521 #### Method: isindex
1522 # Just prints out the isindex tag.
1523 # Parameters:
1524 #  $action -> optional URL of script to run
1525 # Returns:
1526 #   A string containing a <isindex> tag
1527 'isindex' => <<'END_OF_FUNC',
1528 sub isindex {
1529     my($self,@p) = self_or_default(@_);
1530     my($action,@other) = rearrange([ACTION],@p);
1531     $action = qq/ action="$action"/ if $action;
1532     my($other) = @other ? " @other" : '';
1533     return $XHTML ? "<isindex$action$other />" : "<isindex$action$other>";
1534 }
1535 END_OF_FUNC
1536
1537
1538 #### Method: startform
1539 # Start a form
1540 # Parameters:
1541 #   $method -> optional submission method to use (GET or POST)
1542 #   $action -> optional URL of script to run
1543 #   $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1544 'startform' => <<'END_OF_FUNC',
1545 sub startform {
1546     my($self,@p) = self_or_default(@_);
1547
1548     my($method,$action,$enctype,@other) = 
1549         rearrange([METHOD,ACTION,ENCTYPE],@p);
1550
1551     $method = lc($method) || 'post';
1552     $enctype = $enctype || &URL_ENCODED;
1553     unless (defined $action) {
1554        $action = $self->url(-absolute=>1,-path=>1);
1555        if (length($ENV{QUERY_STRING})>0) {
1556            $action .= "?$ENV{QUERY_STRING}";
1557        }
1558     }
1559     $action = qq(action="$action");
1560     my($other) = @other ? " @other" : '';
1561     $self->{'.parametersToAdd'}={};
1562     return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1563 }
1564 END_OF_FUNC
1565
1566
1567 #### Method: start_form
1568 # synonym for startform
1569 'start_form' => <<'END_OF_FUNC',
1570 sub start_form {
1571     &startform;
1572 }
1573 END_OF_FUNC
1574
1575 'end_multipart_form' => <<'END_OF_FUNC',
1576 sub end_multipart_form {
1577     &endform;
1578 }
1579 END_OF_FUNC
1580
1581 #### Method: start_multipart_form
1582 # synonym for startform
1583 'start_multipart_form' => <<'END_OF_FUNC',
1584 sub start_multipart_form {
1585     my($self,@p) = self_or_default(@_);
1586     if (defined($param[0]) && substr($param[0],0,1) eq '-') {
1587         my(%p) = @p;
1588         $p{'-enctype'}=&MULTIPART;
1589         return $self->startform(%p);
1590     } else {
1591         my($method,$action,@other) = 
1592             rearrange([METHOD,ACTION],@p);
1593         return $self->startform($method,$action,&MULTIPART,@other);
1594     }
1595 }
1596 END_OF_FUNC
1597
1598
1599 #### Method: endform
1600 # End a form
1601 'endform' => <<'END_OF_FUNC',
1602 sub endform {
1603     my($self,@p) = self_or_default(@_);    
1604     if ( $NOSTICKY ) {
1605     return wantarray ? ("</form>") : "\n</form>";
1606     } else {
1607     return wantarray ? ($self->get_fields,"</form>") : 
1608                         $self->get_fields ."\n</form>";
1609     }
1610 }
1611 END_OF_FUNC
1612
1613
1614 #### Method: end_form
1615 # synonym for endform
1616 'end_form' => <<'END_OF_FUNC',
1617 sub end_form {
1618     &endform;
1619 }
1620 END_OF_FUNC
1621
1622
1623 '_textfield' => <<'END_OF_FUNC',
1624 sub _textfield {
1625     my($self,$tag,@p) = self_or_default(@_);
1626     my($name,$default,$size,$maxlength,$override,@other) = 
1627         rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1628
1629     my $current = $override ? $default : 
1630         (defined($self->param($name)) ? $self->param($name) : $default);
1631
1632     $current = defined($current) ? $self->escapeHTML($current,1) : '';
1633     $name = defined($name) ? $self->escapeHTML($name) : '';
1634     my($s) = defined($size) ? qq/ size="$size"/ : '';
1635     my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1636     my($other) = @other ? " @other" : '';
1637     # this entered at cristy's request to fix problems with file upload fields
1638     # and WebTV -- not sure it won't break stuff
1639     my($value) = $current ne '' ? qq(value="$current") : '';
1640     return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />) 
1641                   : qq(<input type="$tag" name="$name" $value$s$m$other>);
1642 }
1643 END_OF_FUNC
1644
1645 #### Method: textfield
1646 # Parameters:
1647 #   $name -> Name of the text field
1648 #   $default -> Optional default value of the field if not
1649 #                already defined.
1650 #   $size ->  Optional width of field in characaters.
1651 #   $maxlength -> Optional maximum number of characters.
1652 # Returns:
1653 #   A string containing a <input type="text"> field
1654 #
1655 'textfield' => <<'END_OF_FUNC',
1656 sub textfield {
1657     my($self,@p) = self_or_default(@_);
1658     $self->_textfield('text',@p);
1659 }
1660 END_OF_FUNC
1661
1662
1663 #### Method: filefield
1664 # Parameters:
1665 #   $name -> Name of the file upload field
1666 #   $size ->  Optional width of field in characaters.
1667 #   $maxlength -> Optional maximum number of characters.
1668 # Returns:
1669 #   A string containing a <input type="file"> field
1670 #
1671 'filefield' => <<'END_OF_FUNC',
1672 sub filefield {
1673     my($self,@p) = self_or_default(@_);
1674     $self->_textfield('file',@p);
1675 }
1676 END_OF_FUNC
1677
1678
1679 #### Method: password
1680 # Create a "secret password" entry field
1681 # Parameters:
1682 #   $name -> Name of the field
1683 #   $default -> Optional default value of the field if not
1684 #                already defined.
1685 #   $size ->  Optional width of field in characters.
1686 #   $maxlength -> Optional maximum characters that can be entered.
1687 # Returns:
1688 #   A string containing a <input type="password"> field
1689 #
1690 'password_field' => <<'END_OF_FUNC',
1691 sub password_field {
1692     my ($self,@p) = self_or_default(@_);
1693     $self->_textfield('password',@p);
1694 }
1695 END_OF_FUNC
1696
1697 #### Method: textarea
1698 # Parameters:
1699 #   $name -> Name of the text field
1700 #   $default -> Optional default value of the field if not
1701 #                already defined.
1702 #   $rows ->  Optional number of rows in text area
1703 #   $columns -> Optional number of columns in text area
1704 # Returns:
1705 #   A string containing a <textarea></textarea> tag
1706 #
1707 'textarea' => <<'END_OF_FUNC',
1708 sub textarea {
1709     my($self,@p) = self_or_default(@_);
1710     
1711     my($name,$default,$rows,$cols,$override,@other) =
1712         rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1713
1714     my($current)= $override ? $default :
1715         (defined($self->param($name)) ? $self->param($name) : $default);
1716
1717     $name = defined($name) ? $self->escapeHTML($name) : '';
1718     $current = defined($current) ? $self->escapeHTML($current) : '';
1719     my($r) = $rows ? qq/ rows="$rows"/ : '';
1720     my($c) = $cols ? qq/ cols="$cols"/ : '';
1721     my($other) = @other ? " @other" : '';
1722     return qq{<textarea name="$name"$r$c$other>$current</textarea>};
1723 }
1724 END_OF_FUNC
1725
1726
1727 #### Method: button
1728 # Create a javascript button.
1729 # Parameters:
1730 #   $name ->  (optional) Name for the button. (-name)
1731 #   $value -> (optional) Value of the button when selected (and visible name) (-value)
1732 #   $onclick -> (optional) Text of the JavaScript to run when the button is
1733 #                clicked.
1734 # Returns:
1735 #   A string containing a <input type="button"> tag
1736 ####
1737 'button' => <<'END_OF_FUNC',
1738 sub button {
1739     my($self,@p) = self_or_default(@_);
1740
1741     my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
1742                                                          [ONCLICK,SCRIPT]],@p);
1743
1744     $label=$self->escapeHTML($label);
1745     $value=$self->escapeHTML($value,1);
1746     $script=$self->escapeHTML($script);
1747
1748     my($name) = '';
1749     $name = qq/ name="$label"/ if $label;
1750     $value = $value || $label;
1751     my($val) = '';
1752     $val = qq/ value="$value"/ if $value;
1753     $script = qq/ onclick="$script"/ if $script;
1754     my($other) = @other ? " @other" : '';
1755     return $XHTML ? qq(<input type="button"$name$val$script$other />)
1756                   : qq(<input type="button"$name$val$script$other>);
1757 }
1758 END_OF_FUNC
1759
1760
1761 #### Method: submit
1762 # Create a "submit query" button.
1763 # Parameters:
1764 #   $name ->  (optional) Name for the button.
1765 #   $value -> (optional) Value of the button when selected (also doubles as label).
1766 #   $label -> (optional) Label printed on the button(also doubles as the value).
1767 # Returns:
1768 #   A string containing a <input type="submit"> tag
1769 ####
1770 'submit' => <<'END_OF_FUNC',
1771 sub submit {
1772     my($self,@p) = self_or_default(@_);
1773
1774     my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
1775
1776     $label=$self->escapeHTML($label);
1777     $value=$self->escapeHTML($value,1);
1778
1779     my($name) = ' name=".submit"' unless $NOSTICKY;
1780     $name = qq/ name="$label"/ if defined($label);
1781     $value = defined($value) ? $value : $label;
1782     my($val) = '';
1783     $val = qq/ value="$value"/ if defined($value);
1784     my($other) = @other ? " @other" : '';
1785     return $XHTML ? qq(<input type="submit"$name$val$other />)
1786                   : qq(<input type="submit"$name$val$other>);
1787 }
1788 END_OF_FUNC
1789
1790
1791 #### Method: reset
1792 # Create a "reset" button.
1793 # Parameters:
1794 #   $name -> (optional) Name for the button.
1795 # Returns:
1796 #   A string containing a <input type="reset"> tag
1797 ####
1798 'reset' => <<'END_OF_FUNC',
1799 sub reset {
1800     my($self,@p) = self_or_default(@_);
1801     my($label,@other) = rearrange([NAME],@p);
1802     $label=$self->escapeHTML($label);
1803     my($value) = defined($label) ? qq/ value="$label"/ : '';
1804     my($other) = @other ? " @other" : '';
1805     return $XHTML ? qq(<input type="reset"$value$other />)
1806                   : qq(<input type="reset"$value$other>);
1807 }
1808 END_OF_FUNC
1809
1810
1811 #### Method: defaults
1812 # Create a "defaults" button.
1813 # Parameters:
1814 #   $name -> (optional) Name for the button.
1815 # Returns:
1816 #   A string containing a <input type="submit" name=".defaults"> tag
1817 #
1818 # Note: this button has a special meaning to the initialization script,
1819 # and tells it to ERASE the current query string so that your defaults
1820 # are used again!
1821 ####
1822 'defaults' => <<'END_OF_FUNC',
1823 sub defaults {
1824     my($self,@p) = self_or_default(@_);
1825
1826     my($label,@other) = rearrange([[NAME,VALUE]],@p);
1827
1828     $label=$self->escapeHTML($label,1);
1829     $label = $label || "Defaults";
1830     my($value) = qq/ value="$label"/;
1831     my($other) = @other ? " @other" : '';
1832     return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
1833                   : qq/<input type="submit" NAME=".defaults"$value$other>/;
1834 }
1835 END_OF_FUNC
1836
1837
1838 #### Method: comment
1839 # Create an HTML <!-- comment -->
1840 # Parameters: a string
1841 'comment' => <<'END_OF_FUNC',
1842 sub comment {
1843     my($self,@p) = self_or_CGI(@_);
1844     return "<!-- @p -->";
1845 }
1846 END_OF_FUNC
1847
1848 #### Method: checkbox
1849 # Create a checkbox that is not logically linked to any others.
1850 # The field value is "on" when the button is checked.
1851 # Parameters:
1852 #   $name -> Name of the checkbox
1853 #   $checked -> (optional) turned on by default if true
1854 #   $value -> (optional) value of the checkbox, 'on' by default
1855 #   $label -> (optional) a user-readable label printed next to the box.
1856 #             Otherwise the checkbox name is used.
1857 # Returns:
1858 #   A string containing a <input type="checkbox"> field
1859 ####
1860 'checkbox' => <<'END_OF_FUNC',
1861 sub checkbox {
1862     my($self,@p) = self_or_default(@_);
1863
1864     my($name,$checked,$value,$label,$override,@other) = 
1865         rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1866     
1867     $value = defined $value ? $value : 'on';
1868
1869     if (!$override && ($self->{'.fieldnames'}->{$name} || 
1870                        defined $self->param($name))) {
1871         $checked = grep($_ eq $value,$self->param($name)) ? $self->_checked(1) : '';
1872     } else {
1873         $checked = $self->_checked($checked);
1874     }
1875     my($the_label) = defined $label ? $label : $name;
1876     $name = $self->escapeHTML($name);
1877     $value = $self->escapeHTML($value,1);
1878     $the_label = $self->escapeHTML($the_label);
1879     my($other) = @other ? " @other" : '';
1880     $self->register_parameter($name);
1881     return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
1882                   : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
1883 }
1884 END_OF_FUNC
1885
1886
1887 #### Method: checkbox_group
1888 # Create a list of logically-linked checkboxes.
1889 # Parameters:
1890 #   $name -> Common name for all the check boxes
1891 #   $values -> A pointer to a regular array containing the
1892 #             values for each checkbox in the group.
1893 #   $defaults -> (optional)
1894 #             1. If a pointer to a regular array of checkbox values,
1895 #             then this will be used to decide which
1896 #             checkboxes to turn on by default.
1897 #             2. If a scalar, will be assumed to hold the
1898 #             value of a single checkbox in the group to turn on. 
1899 #   $linebreak -> (optional) Set to true to place linebreaks
1900 #             between the buttons.
1901 #   $labels -> (optional)
1902 #             A pointer to an associative array of labels to print next to each checkbox
1903 #             in the form $label{'value'}="Long explanatory label".
1904 #             Otherwise the provided values are used as the labels.
1905 # Returns:
1906 #   An ARRAY containing a series of <input type="checkbox"> fields
1907 ####
1908 'checkbox_group' => <<'END_OF_FUNC',
1909 sub checkbox_group {
1910     my($self,@p) = self_or_default(@_);
1911
1912     my($name,$values,$defaults,$linebreak,$labels,$attributes,$rows,$columns,
1913        $rowheaders,$colheaders,$override,$nolabels,@other) =
1914         rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1915             LINEBREAK,LABELS,ATTRIBUTES,ROWS,[COLUMNS,COLS],
1916                           ROWHEADERS,COLHEADERS,
1917                           [OVERRIDE,FORCE],NOLABELS],@p);
1918
1919     my($checked,$break,$result,$label);
1920
1921     my(%checked) = $self->previous_or_default($name,$defaults,$override);
1922
1923         if ($linebreak) {
1924     $break = $XHTML ? "<br />" : "<br>";
1925         }
1926         else {
1927         $break = '';
1928         }
1929     $name=$self->escapeHTML($name);
1930
1931     # Create the elements
1932     my(@elements,@values);
1933
1934     @values = $self->_set_values_and_labels($values,\$labels,$name);
1935
1936     my($other) = @other ? " @other" : '';
1937     foreach (@values) {
1938         $checked = $self->_checked($checked{$_});
1939         $label = '';
1940         unless (defined($nolabels) && $nolabels) {
1941             $label = $_;
1942             $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1943             $label = $self->escapeHTML($label);
1944         }
1945         my $attribs = $self->_set_attributes($_, $attributes);
1946         $_ = $self->escapeHTML($_,1);
1947         push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other$attribs />${label}${break})
1948                               : qq/<input type="checkbox" name="$name" value="$_"$checked$other$attribs>${label}${break}/);
1949     }
1950     $self->register_parameter($name);
1951     return wantarray ? @elements : join(' ',@elements)            
1952         unless defined($columns) || defined($rows);
1953     return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1954 }
1955 END_OF_FUNC
1956
1957 # Escape HTML -- used internally
1958 'escapeHTML' => <<'END_OF_FUNC',
1959 sub escapeHTML {
1960          # hack to work around  earlier hacks
1961          push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
1962          my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
1963          return undef unless defined($toencode);
1964          return $toencode if ref($self) && !$self->{'escape'};
1965          $toencode =~ s{&}{&amp;}gso;
1966          $toencode =~ s{<}{&lt;}gso;
1967          $toencode =~ s{>}{&gt;}gso;
1968          $toencode =~ s{"}{&quot;}gso;
1969          my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
1970                      uc $self->{'.charset'} eq 'WINDOWS-1252';
1971          if ($latin) {  # bug in some browsers
1972                 $toencode =~ s{'}{&#39;}gso;
1973                 $toencode =~ s{\x8b}{&#8249;}gso;
1974                 $toencode =~ s{\x9b}{&#8250;}gso;
1975                 if (defined $newlinestoo && $newlinestoo) {
1976                      $toencode =~ s{\012}{&#10;}gso;
1977                      $toencode =~ s{\015}{&#13;}gso;
1978                 }
1979          }
1980          return $toencode;
1981 }
1982 END_OF_FUNC
1983
1984 # unescape HTML -- used internally
1985 'unescapeHTML' => <<'END_OF_FUNC',
1986 sub unescapeHTML {
1987     my ($self,$string) = CGI::self_or_default(@_);
1988     return undef unless defined($string);
1989     my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
1990                                             : 1;
1991     # thanks to Randal Schwartz for the correct solution to this one
1992     $string=~ s[&(.*?);]{
1993         local $_ = $1;
1994         /^amp$/i        ? "&" :
1995         /^quot$/i       ? '"' :
1996         /^gt$/i         ? ">" :
1997         /^lt$/i         ? "<" :
1998         /^#(\d+)$/ && $latin         ? chr($1) :
1999         /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
2000         $_
2001         }gex;
2002     return $string;
2003 }
2004 END_OF_FUNC
2005
2006 # Internal procedure - don't use
2007 '_tableize' => <<'END_OF_FUNC',
2008 sub _tableize {
2009     my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
2010     $rowheaders = [] unless defined $rowheaders;
2011     $colheaders = [] unless defined $colheaders;
2012     my($result);
2013
2014     if (defined($columns)) {
2015         $rows = int(0.99 + @elements/$columns) unless defined($rows);
2016     }
2017     if (defined($rows)) {
2018         $columns = int(0.99 + @elements/$rows) unless defined($columns);
2019     }
2020     
2021     # rearrange into a pretty table
2022     $result = "<table>";
2023     my($row,$column);
2024     unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
2025     $result .= "<tr>" if @{$colheaders};
2026     foreach (@{$colheaders}) {
2027         $result .= "<th>$_</th>";
2028     }
2029     for ($row=0;$row<$rows;$row++) {
2030         $result .= "<tr>";
2031         $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
2032         for ($column=0;$column<$columns;$column++) {
2033             $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
2034                 if defined($elements[$column*$rows + $row]);
2035         }
2036         $result .= "</tr>";
2037     }
2038     $result .= "</table>";
2039     return $result;
2040 }
2041 END_OF_FUNC
2042
2043
2044 #### Method: radio_group
2045 # Create a list of logically-linked radio buttons.
2046 # Parameters:
2047 #   $name -> Common name for all the buttons.
2048 #   $values -> A pointer to a regular array containing the
2049 #             values for each button in the group.
2050 #   $default -> (optional) Value of the button to turn on by default.  Pass '-'
2051 #               to turn _nothing_ on.
2052 #   $linebreak -> (optional) Set to true to place linebreaks
2053 #             between the buttons.
2054 #   $labels -> (optional)
2055 #             A pointer to an associative array of labels to print next to each checkbox
2056 #             in the form $label{'value'}="Long explanatory label".
2057 #             Otherwise the provided values are used as the labels.
2058 # Returns:
2059 #   An ARRAY containing a series of <input type="radio"> fields
2060 ####
2061 'radio_group' => <<'END_OF_FUNC',
2062 sub radio_group {
2063     my($self,@p) = self_or_default(@_);
2064
2065     my($name,$values,$default,$linebreak,$labels,$attributes,
2066        $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
2067   rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,ATTRIBUTES,
2068                           ROWS,[COLUMNS,COLS],
2069                           ROWHEADERS,COLHEADERS,
2070                           [OVERRIDE,FORCE],NOLABELS],@p);
2071     my($result,$checked);
2072
2073     if (!$override && defined($self->param($name))) {
2074         $checked = $self->param($name);
2075     } else {
2076         $checked = $default;
2077     }
2078     my(@elements,@values);
2079     @values = $self->_set_values_and_labels($values,\$labels,$name);
2080
2081     # If no check array is specified, check the first by default
2082     $checked = $values[0] unless defined($checked) && $checked ne '';
2083     $name=$self->escapeHTML($name);
2084
2085     my($other) = @other ? " @other" : '';
2086     foreach (@values) {
2087         my($checkit) = $checked eq $_ ? qq/ checked="checked"/ : '';
2088         my($break);
2089         if ($linebreak) {
2090           $break = $XHTML ? "<br />" : "<br>";
2091         }
2092         else {
2093           $break = '';
2094         }
2095         my($label)='';
2096         unless (defined($nolabels) && $nolabels) {
2097             $label = $_;
2098             $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2099             $label = $self->escapeHTML($label,1);
2100         }
2101   my $attribs = $self->_set_attributes($_, $attributes);
2102         $_=$self->escapeHTML($_);
2103   push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other$attribs />${label}${break})
2104                               : qq/<input type="radio" name="$name" value="$_"$checkit$other$attribs>${label}${break}/);
2105     }
2106     $self->register_parameter($name);
2107     return wantarray ? @elements : join(' ',@elements) 
2108            unless defined($columns) || defined($rows);
2109     return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2110 }
2111 END_OF_FUNC
2112
2113
2114 #### Method: popup_menu
2115 # Create a popup menu.
2116 # Parameters:
2117 #   $name -> Name for all the menu
2118 #   $values -> A pointer to a regular array containing the
2119 #             text of each menu item.
2120 #   $default -> (optional) Default item to display
2121 #   $labels -> (optional)
2122 #             A pointer to an associative array of labels to print next to each checkbox
2123 #             in the form $label{'value'}="Long explanatory label".
2124 #             Otherwise the provided values are used as the labels.
2125 # Returns:
2126 #   A string containing the definition of a popup menu.
2127 ####
2128 'popup_menu' => <<'END_OF_FUNC',
2129 sub popup_menu {
2130     my($self,@p) = self_or_default(@_);
2131
2132     my($name,$values,$default,$labels,$attributes,$override,@other) =
2133        rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,
2134        ATTRIBUTES,[OVERRIDE,FORCE]],@p);
2135     my($result,$selected);
2136
2137     if (!$override && defined($self->param($name))) {
2138         $selected = $self->param($name);
2139     } else {
2140         $selected = $default;
2141     }
2142     $name=$self->escapeHTML($name);
2143     my($other) = @other ? " @other" : '';
2144
2145     my(@values);
2146     @values = $self->_set_values_and_labels($values,\$labels,$name);
2147
2148     $result = qq/<select name="$name"$other>\n/;
2149     foreach (@values) {
2150         if (/<optgroup/) {
2151             foreach (split(/\n/)) {
2152                 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2153                 s/(value="$selected")/$selectit $1/ if defined $selected;
2154                 $result .= "$_\n";
2155             }
2156         }
2157         else {
2158             my $attribs = $self->_set_attributes($_, $attributes);
2159         my($selectit) = defined($selected) ? $self->_selected($selected eq $_) : '';
2160         my($label) = $_;
2161         $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2162         my($value) = $self->escapeHTML($_);
2163         $label=$self->escapeHTML($label,1);
2164             $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2165         }
2166     }
2167
2168     $result .= "</select>";
2169     return $result;
2170 }
2171 END_OF_FUNC
2172
2173
2174 #### Method: optgroup
2175 # Create a optgroup.
2176 # Parameters:
2177 #   $name -> Label for the group
2178 #   $values -> A pointer to a regular array containing the
2179 #              values for each option line in the group.
2180 #   $labels -> (optional)
2181 #              A pointer to an associative array of labels to print next to each item
2182 #              in the form $label{'value'}="Long explanatory label".
2183 #              Otherwise the provided values are used as the labels.
2184 #   $labeled -> (optional)
2185 #               A true value indicates the value should be used as the label attribute
2186 #               in the option elements.
2187 #               The label attribute specifies the option label presented to the user.
2188 #               This defaults to the content of the <option> element, but the label
2189 #               attribute allows authors to more easily use optgroup without sacrificing
2190 #               compatibility with browsers that do not support option groups.
2191 #   $novals -> (optional)
2192 #              A true value indicates to suppress the val attribute in the option elements
2193 # Returns:
2194 #   A string containing the definition of an option group.
2195 ####
2196 'optgroup' => <<'END_OF_FUNC',
2197 sub optgroup {
2198     my($self,@p) = self_or_default(@_);
2199     my($name,$values,$attributes,$labeled,$noval,$labels,@other)
2200         = rearrange([NAME,[VALUES,VALUE],ATTRIBUTES,LABELED,NOVALS,LABELS],@p);
2201
2202     my($result,@values);
2203     @values = $self->_set_values_and_labels($values,\$labels,$name,$labeled,$novals);
2204     my($other) = @other ? " @other" : '';
2205
2206     $name=$self->escapeHTML($name);
2207     $result = qq/<optgroup label="$name"$other>\n/;
2208     foreach (@values) {
2209         if (/<optgroup/) {
2210             foreach (split(/\n/)) {
2211                 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2212                 s/(value="$selected")/$selectit $1/ if defined $selected;
2213                 $result .= "$_\n";
2214             }
2215         }
2216         else {
2217             my $attribs = $self->_set_attributes($_, $attributes);
2218             my($label) = $_;
2219             $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2220             $label=$self->escapeHTML($label);
2221             my($value)=$self->escapeHTML($_,1);
2222             $result .= $labeled ? $novals ? "<option$attribs label=\"$value\">$label</option>\n"
2223                                           : "<option$attribs label=\"$value\" value=\"$value\">$label</option>\n"
2224                                 : $novals ? "<option$attribs>$label</option>\n"
2225                                           : "<option$attribs value=\"$value\">$label</option>\n";
2226         }
2227     }
2228     $result .= "</optgroup>";
2229     return $result;
2230 }
2231 END_OF_FUNC
2232
2233
2234 #### Method: scrolling_list
2235 # Create a scrolling list.
2236 # Parameters:
2237 #   $name -> name for the list
2238 #   $values -> A pointer to a regular array containing the
2239 #             values for each option line in the list.
2240 #   $defaults -> (optional)
2241 #             1. If a pointer to a regular array of options,
2242 #             then this will be used to decide which
2243 #             lines to turn on by default.
2244 #             2. Otherwise holds the value of the single line to turn on.
2245 #   $size -> (optional) Size of the list.
2246 #   $multiple -> (optional) If set, allow multiple selections.
2247 #   $labels -> (optional)
2248 #             A pointer to an associative array of labels to print next to each checkbox
2249 #             in the form $label{'value'}="Long explanatory label".
2250 #             Otherwise the provided values are used as the labels.
2251 # Returns:
2252 #   A string containing the definition of a scrolling list.
2253 ####
2254 'scrolling_list' => <<'END_OF_FUNC',
2255 sub scrolling_list {
2256     my($self,@p) = self_or_default(@_);
2257     my($name,$values,$defaults,$size,$multiple,$labels,$attributes,$override,@other)
2258         = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2259           SIZE,MULTIPLE,LABELS,ATTRIBUTES,[OVERRIDE,FORCE]],@p);
2260
2261     my($result,@values);
2262     @values = $self->_set_values_and_labels($values,\$labels,$name);
2263
2264     $size = $size || scalar(@values);
2265
2266     my(%selected) = $self->previous_or_default($name,$defaults,$override);
2267     my($is_multiple) = $multiple ? qq/ multiple="multiple"/ : '';
2268     my($has_size) = $size ? qq/ size="$size"/: '';
2269     my($other) = @other ? " @other" : '';
2270
2271     $name=$self->escapeHTML($name);
2272     $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
2273     foreach (@values) {
2274         my($selectit) = $self->_selected($selected{$_});
2275         my($label) = $_;
2276         $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2277         $label=$self->escapeHTML($label);
2278         my($value)=$self->escapeHTML($_,1);
2279         my $attribs = $self->_set_attributes($_, $attributes);
2280         $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2281     }
2282     $result .= "</select>";
2283     $self->register_parameter($name);
2284     return $result;
2285 }
2286 END_OF_FUNC
2287
2288
2289 #### Method: hidden
2290 # Parameters:
2291 #   $name -> Name of the hidden field
2292 #   @default -> (optional) Initial values of field (may be an array)
2293 #      or
2294 #   $default->[initial values of field]
2295 # Returns:
2296 #   A string containing a <input type="hidden" name="name" value="value">
2297 ####
2298 'hidden' => <<'END_OF_FUNC',
2299 sub hidden {
2300     my($self,@p) = self_or_default(@_);
2301
2302     # this is the one place where we departed from our standard
2303     # calling scheme, so we have to special-case (darn)
2304     my(@result,@value);
2305     my($name,$default,$override,@other) = 
2306         rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2307
2308     my $do_override = 0;
2309     if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2310         @value = ref($default) ? @{$default} : $default;
2311         $do_override = $override;
2312     } else {
2313         foreach ($default,$override,@other) {
2314             push(@value,$_) if defined($_);
2315         }
2316     }
2317
2318     # use previous values if override is not set
2319     my @prev = $self->param($name);
2320     @value = @prev if !$do_override && @prev;
2321
2322     $name=$self->escapeHTML($name);
2323     foreach (@value) {
2324         $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2325         push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
2326                             : qq(<input type="hidden" name="$name" value="$_">);
2327     }
2328     return wantarray ? @result : join('',@result);
2329 }
2330 END_OF_FUNC
2331
2332
2333 #### Method: image_button
2334 # Parameters:
2335 #   $name -> Name of the button
2336 #   $src ->  URL of the image source
2337 #   $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2338 # Returns:
2339 #   A string containing a <input type="image" name="name" src="url" align="alignment">
2340 ####
2341 'image_button' => <<'END_OF_FUNC',
2342 sub image_button {
2343     my($self,@p) = self_or_default(@_);
2344
2345     my($name,$src,$alignment,@other) =
2346         rearrange([NAME,SRC,ALIGN],@p);
2347
2348     my($align) = $alignment ? " align=\U\"$alignment\"" : '';
2349     my($other) = @other ? " @other" : '';
2350     $name=$self->escapeHTML($name);
2351     return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2352                   : qq/<input type="image" name="$name" src="$src"$align$other>/;
2353 }
2354 END_OF_FUNC
2355
2356
2357 #### Method: self_url
2358 # Returns a URL containing the current script and all its
2359 # param/value pairs arranged as a query.  You can use this
2360 # to create a link that, when selected, will reinvoke the
2361 # script with all its state information preserved.
2362 ####
2363 'self_url' => <<'END_OF_FUNC',
2364 sub self_url {
2365     my($self,@p) = self_or_default(@_);
2366     return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2367 }
2368 END_OF_FUNC
2369
2370
2371 # This is provided as a synonym to self_url() for people unfortunate
2372 # enough to have incorporated it into their programs already!
2373 'state' => <<'END_OF_FUNC',
2374 sub state {
2375     &self_url;
2376 }
2377 END_OF_FUNC
2378
2379
2380 #### Method: url
2381 # Like self_url, but doesn't return the query string part of
2382 # the URL.
2383 ####
2384 'url' => <<'END_OF_FUNC',
2385 sub url {
2386     my($self,@p) = self_or_default(@_);
2387     my ($relative,$absolute,$full,$path_info,$query,$base) = 
2388         rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
2389     my $url;
2390     $full++      if $base || !($relative || $absolute);
2391
2392     my $path = $self->path_info;
2393     my $script_name = $self->script_name;
2394
2395     # for compatibility with Apache's MultiViews
2396     if (exists($ENV{REQUEST_URI})) {
2397         my $index;
2398         $script_name = $ENV{REQUEST_URI};
2399         $script_name =~ s/\?.+$//;   # strip query string
2400         # and path
2401         if (exists($ENV{PATH_INFO})) {
2402            (my $encoded_path = $ENV{PATH_INFO}) =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
2403            $script_name      =~ s/$encoded_path$//i;
2404          }
2405     }
2406
2407     if ($full) {
2408         my $protocol = $self->protocol();
2409         $url = "$protocol://";
2410         my $vh = http('host');
2411         if ($vh) {
2412             $url .= $vh;
2413         } else {
2414             $url .= server_name();
2415             my $port = $self->server_port;
2416             $url .= ":" . $port
2417                 unless (lc($protocol) eq 'http' && $port == 80)
2418                     || (lc($protocol) eq 'https' && $port == 443);
2419         }
2420         return $url if $base;
2421         $url .= $script_name;
2422     } elsif ($relative) {
2423         ($url) = $script_name =~ m!([^/]+)$!;
2424     } elsif ($absolute) {
2425         $url = $script_name;
2426     }
2427
2428     $url .= $path if $path_info and defined $path;
2429     $url .= "?" . $self->query_string if $query and $self->query_string;
2430     $url = '' unless defined $url;
2431     $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
2432     return $url;
2433 }
2434
2435 END_OF_FUNC
2436
2437 #### Method: cookie
2438 # Set or read a cookie from the specified name.
2439 # Cookie can then be passed to header().
2440 # Usual rules apply to the stickiness of -value.
2441 #  Parameters:
2442 #   -name -> name for this cookie (optional)
2443 #   -value -> value of this cookie (scalar, array or hash) 
2444 #   -path -> paths for which this cookie is valid (optional)
2445 #   -domain -> internet domain in which this cookie is valid (optional)
2446 #   -secure -> if true, cookie only passed through secure channel (optional)
2447 #   -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2448 ####
2449 'cookie' => <<'END_OF_FUNC',
2450 sub cookie {
2451     my($self,@p) = self_or_default(@_);
2452     my($name,$value,$path,$domain,$secure,$expires) =
2453         rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2454
2455     require CGI::Cookie;
2456
2457     # if no value is supplied, then we retrieve the
2458     # value of the cookie, if any.  For efficiency, we cache the parsed
2459     # cookies in our state variables.
2460     unless ( defined($value) ) {
2461         $self->{'.cookies'} = CGI::Cookie->fetch
2462             unless $self->{'.cookies'};
2463
2464         # If no name is supplied, then retrieve the names of all our cookies.
2465         return () unless $self->{'.cookies'};
2466         return keys %{$self->{'.cookies'}} unless $name;
2467         return () unless $self->{'.cookies'}->{$name};
2468         return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2469     }
2470
2471     # If we get here, we're creating a new cookie
2472     return undef unless defined($name) && $name ne '';  # this is an error
2473
2474     my @param;
2475     push(@param,'-name'=>$name);
2476     push(@param,'-value'=>$value);
2477     push(@param,'-domain'=>$domain) if $domain;
2478     push(@param,'-path'=>$path) if $path;
2479     push(@param,'-expires'=>$expires) if $expires;
2480     push(@param,'-secure'=>$secure) if $secure;
2481
2482     return new CGI::Cookie(@param);
2483 }
2484 END_OF_FUNC
2485
2486 'parse_keywordlist' => <<'END_OF_FUNC',
2487 sub parse_keywordlist {
2488     my($self,$tosplit) = @_;
2489     $tosplit = unescape($tosplit); # unescape the keywords
2490     $tosplit=~tr/+/ /;          # pluses to spaces
2491     my(@keywords) = split(/\s+/,$tosplit);
2492     return @keywords;
2493 }
2494 END_OF_FUNC
2495
2496 'param_fetch' => <<'END_OF_FUNC',
2497 sub param_fetch {
2498     my($self,@p) = self_or_default(@_);
2499     my($name) = rearrange([NAME],@p);
2500     unless (exists($self->{$name})) {
2501         $self->add_parameter($name);
2502         $self->{$name} = [];
2503     }
2504     
2505     return $self->{$name};
2506 }
2507 END_OF_FUNC
2508
2509 ###############################################
2510 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2511 ###############################################
2512
2513 #### Method: path_info
2514 # Return the extra virtual path information provided
2515 # after the URL (if any)
2516 ####
2517 'path_info' => <<'END_OF_FUNC',
2518 sub path_info {
2519     my ($self,$info) = self_or_default(@_);
2520     if (defined($info)) {
2521         $info = "/$info" if $info ne '' &&  substr($info,0,1) ne '/';
2522         $self->{'.path_info'} = $info;
2523     } elsif (! defined($self->{'.path_info'}) ) {
2524         $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ? 
2525             $ENV{'PATH_INFO'} : '';
2526
2527         # hack to fix broken path info in IIS
2528         $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2529
2530     }
2531     return $self->{'.path_info'};
2532 }
2533 END_OF_FUNC
2534
2535
2536 #### Method: request_method
2537 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2538 ####
2539 'request_method' => <<'END_OF_FUNC',
2540 sub request_method {
2541     return $ENV{'REQUEST_METHOD'};
2542 }
2543 END_OF_FUNC
2544
2545 #### Method: content_type
2546 # Returns the content_type string
2547 ####
2548 'content_type' => <<'END_OF_FUNC',
2549 sub content_type {
2550     return $ENV{'CONTENT_TYPE'};
2551 }
2552 END_OF_FUNC
2553
2554 #### Method: path_translated
2555 # Return the physical path information provided
2556 # by the URL (if any)
2557 ####
2558 'path_translated' => <<'END_OF_FUNC',
2559 sub path_translated {
2560     return $ENV{'PATH_TRANSLATED'};
2561 }
2562 END_OF_FUNC
2563
2564
2565 #### Method: query_string
2566 # Synthesize a query string from our current
2567 # parameters
2568 ####
2569 'query_string' => <<'END_OF_FUNC',
2570 sub query_string {
2571     my($self) = self_or_default(@_);
2572     my($param,$value,@pairs);
2573     foreach $param ($self->param) {
2574         my($eparam) = escape($param);
2575         foreach $value ($self->param($param)) {
2576             $value = escape($value);
2577             next unless defined $value;
2578             push(@pairs,"$eparam=$value");
2579         }
2580     }
2581     foreach (keys %{$self->{'.fieldnames'}}) {
2582       push(@pairs,".cgifields=".escape("$_"));
2583     }
2584     return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2585 }
2586 END_OF_FUNC
2587
2588
2589 #### Method: accept
2590 # Without parameters, returns an array of the
2591 # MIME types the browser accepts.
2592 # With a single parameter equal to a MIME
2593 # type, will return undef if the browser won't
2594 # accept it, 1 if the browser accepts it but
2595 # doesn't give a preference, or a floating point
2596 # value between 0.0 and 1.0 if the browser
2597 # declares a quantitative score for it.
2598 # This handles MIME type globs correctly.
2599 ####
2600 'Accept' => <<'END_OF_FUNC',
2601 sub Accept {
2602     my($self,$search) = self_or_CGI(@_);
2603     my(%prefs,$type,$pref,$pat);
2604     
2605     my(@accept) = split(',',$self->http('accept'));
2606
2607     foreach (@accept) {
2608         ($pref) = /q=(\d\.\d+|\d+)/;
2609         ($type) = m#(\S+/[^;]+)#;
2610         next unless $type;
2611         $prefs{$type}=$pref || 1;
2612     }
2613
2614     return keys %prefs unless $search;
2615     
2616     # if a search type is provided, we may need to
2617     # perform a pattern matching operation.
2618     # The MIME types use a glob mechanism, which
2619     # is easily translated into a perl pattern match
2620
2621     # First return the preference for directly supported
2622     # types:
2623     return $prefs{$search} if $prefs{$search};
2624
2625     # Didn't get it, so try pattern matching.
2626     foreach (keys %prefs) {
2627         next unless /\*/;       # not a pattern match
2628         ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2629         $pat =~ s/\*/.*/g; # turn it into a pattern
2630         return $prefs{$_} if $search=~/$pat/;
2631     }
2632 }
2633 END_OF_FUNC
2634
2635
2636 #### Method: user_agent
2637 # If called with no parameters, returns the user agent.
2638 # If called with one parameter, does a pattern match (case
2639 # insensitive) on the user agent.
2640 ####
2641 'user_agent' => <<'END_OF_FUNC',
2642 sub user_agent {
2643     my($self,$match)=self_or_CGI(@_);
2644     return $self->http('user_agent') unless $match;
2645     return $self->http('user_agent') =~ /$match/i;
2646 }
2647 END_OF_FUNC
2648
2649
2650 #### Method: raw_cookie
2651 # Returns the magic cookies for the session.
2652 # The cookies are not parsed or altered in any way, i.e.
2653 # cookies are returned exactly as given in the HTTP
2654 # headers.  If a cookie name is given, only that cookie's
2655 # value is returned, otherwise the entire raw cookie
2656 # is returned.
2657 ####
2658 'raw_cookie' => <<'END_OF_FUNC',
2659 sub raw_cookie {
2660     my($self,$key) = self_or_CGI(@_);
2661
2662     require CGI::Cookie;
2663
2664     if (defined($key)) {
2665         $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2666             unless $self->{'.raw_cookies'};
2667
2668         return () unless $self->{'.raw_cookies'};
2669         return () unless $self->{'.raw_cookies'}->{$key};
2670         return $self->{'.raw_cookies'}->{$key};
2671     }
2672     return $self->http('cookie') || $ENV{'COOKIE'} || '';
2673 }
2674 END_OF_FUNC
2675
2676 #### Method: virtual_host
2677 # Return the name of the virtual_host, which
2678 # is not always the same as the server
2679 ######
2680 'virtual_host' => <<'END_OF_FUNC',
2681 sub virtual_host {
2682     my $vh = http('host') || server_name();
2683     $vh =~ s/:\d+$//;           # get rid of port number
2684     return $vh;
2685 }
2686 END_OF_FUNC
2687
2688 #### Method: remote_host
2689 # Return the name of the remote host, or its IP
2690 # address if unavailable.  If this variable isn't
2691 # defined, it returns "localhost" for debugging
2692 # purposes.
2693 ####
2694 'remote_host' => <<'END_OF_FUNC',
2695 sub remote_host {
2696     return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'} 
2697     || 'localhost';
2698 }
2699 END_OF_FUNC
2700
2701
2702 #### Method: remote_addr
2703 # Return the IP addr of the remote host.
2704 ####
2705 'remote_addr' => <<'END_OF_FUNC',
2706 sub remote_addr {
2707     return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2708 }
2709 END_OF_FUNC
2710
2711
2712 #### Method: script_name
2713 # Return the partial URL to this script for
2714 # self-referencing scripts.  Also see
2715 # self_url(), which returns a URL with all state information
2716 # preserved.
2717 ####
2718 'script_name' => <<'END_OF_FUNC',
2719 sub script_name {
2720     return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2721     # These are for debugging
2722     return "/$0" unless $0=~/^\//;
2723     return $0;
2724 }
2725 END_OF_FUNC
2726
2727
2728 #### Method: referer
2729 # Return the HTTP_REFERER: useful for generating
2730 # a GO BACK button.
2731 ####
2732 'referer' => <<'END_OF_FUNC',
2733 sub referer {
2734     my($self) = self_or_CGI(@_);
2735     return $self->http('referer');
2736 }
2737 END_OF_FUNC
2738
2739
2740 #### Method: server_name
2741 # Return the name of the server
2742 ####
2743 'server_name' => <<'END_OF_FUNC',
2744 sub server_name {
2745     return $ENV{'SERVER_NAME'} || 'localhost';
2746 }
2747 END_OF_FUNC
2748
2749 #### Method: server_software
2750 # Return the name of the server software
2751 ####
2752 'server_software' => <<'END_OF_FUNC',
2753 sub server_software {
2754     return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2755 }
2756 END_OF_FUNC
2757
2758 #### Method: server_port
2759 # Return the tcp/ip port the server is running on
2760 ####
2761 'server_port' => <<'END_OF_FUNC',
2762 sub server_port {
2763     return $ENV{'SERVER_PORT'} || 80; # for debugging
2764 }
2765 END_OF_FUNC
2766
2767 #### Method: server_protocol
2768 # Return the protocol (usually HTTP/1.0)
2769 ####
2770 'server_protocol' => <<'END_OF_FUNC',
2771 sub server_protocol {
2772     return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2773 }
2774 END_OF_FUNC
2775
2776 #### Method: http
2777 # Return the value of an HTTP variable, or
2778 # the list of variables if none provided
2779 ####
2780 'http' => <<'END_OF_FUNC',
2781 sub http {
2782     my ($self,$parameter) = self_or_CGI(@_);
2783     return $ENV{$parameter} if $parameter=~/^HTTP/;
2784     $parameter =~ tr/-/_/;
2785     return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2786     my(@p);
2787     foreach (keys %ENV) {
2788         push(@p,$_) if /^HTTP/;
2789     }
2790     return @p;
2791 }
2792 END_OF_FUNC
2793
2794 #### Method: https
2795 # Return the value of HTTPS
2796 ####
2797 'https' => <<'END_OF_FUNC',
2798 sub https {
2799     local($^W)=0;
2800     my ($self,$parameter) = self_or_CGI(@_);
2801     return $ENV{HTTPS} unless $parameter;
2802     return $ENV{$parameter} if $parameter=~/^HTTPS/;
2803     $parameter =~ tr/-/_/;
2804     return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2805     my(@p);
2806     foreach (keys %ENV) {
2807         push(@p,$_) if /^HTTPS/;
2808     }
2809     return @p;
2810 }
2811 END_OF_FUNC
2812
2813 #### Method: protocol
2814 # Return the protocol (http or https currently)
2815 ####
2816 'protocol' => <<'END_OF_FUNC',
2817 sub protocol {
2818     local($^W)=0;
2819     my $self = shift;
2820     return 'https' if uc($self->https()) eq 'ON'; 
2821     return 'https' if $self->server_port == 443;
2822     my $prot = $self->server_protocol;
2823     my($protocol,$version) = split('/',$prot);
2824     return "\L$protocol\E";
2825 }
2826 END_OF_FUNC
2827
2828 #### Method: remote_ident
2829 # Return the identity of the remote user
2830 # (but only if his host is running identd)
2831 ####
2832 'remote_ident' => <<'END_OF_FUNC',
2833 sub remote_ident {
2834     return $ENV{'REMOTE_IDENT'};
2835 }
2836 END_OF_FUNC
2837
2838
2839 #### Method: auth_type
2840 # Return the type of use verification/authorization in use, if any.
2841 ####
2842 'auth_type' => <<'END_OF_FUNC',
2843 sub auth_type {
2844     return $ENV{'AUTH_TYPE'};
2845 }
2846 END_OF_FUNC
2847
2848
2849 #### Method: remote_user
2850 # Return the authorization name used for user
2851 # verification.
2852 ####
2853 'remote_user' => <<'END_OF_FUNC',
2854 sub remote_user {
2855     return $ENV{'REMOTE_USER'};
2856 }
2857 END_OF_FUNC
2858
2859
2860 #### Method: user_name
2861 # Try to return the remote user's name by hook or by
2862 # crook
2863 ####
2864 'user_name' => <<'END_OF_FUNC',
2865 sub user_name {
2866     my ($self) = self_or_CGI(@_);
2867     return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2868 }
2869 END_OF_FUNC
2870
2871 #### Method: nosticky
2872 # Set or return the NOSTICKY global flag
2873 ####
2874 'nosticky' => <<'END_OF_FUNC',
2875 sub nosticky {
2876     my ($self,$param) = self_or_CGI(@_);
2877     $CGI::NOSTICKY = $param if defined($param);
2878     return $CGI::NOSTICKY;
2879 }
2880 END_OF_FUNC
2881
2882 #### Method: nph
2883 # Set or return the NPH global flag
2884 ####
2885 'nph' => <<'END_OF_FUNC',
2886 sub nph {
2887     my ($self,$param) = self_or_CGI(@_);
2888     $CGI::NPH = $param if defined($param);
2889     return $CGI::NPH;
2890 }
2891 END_OF_FUNC
2892
2893 #### Method: private_tempfiles
2894 # Set or return the private_tempfiles global flag
2895 ####
2896 'private_tempfiles' => <<'END_OF_FUNC',
2897 sub private_tempfiles {
2898     my ($self,$param) = self_or_CGI(@_);
2899     $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2900     return $CGI::PRIVATE_TEMPFILES;
2901 }
2902 END_OF_FUNC
2903
2904 #### Method: default_dtd
2905 # Set or return the default_dtd global
2906 ####
2907 'default_dtd' => <<'END_OF_FUNC',
2908 sub default_dtd {
2909     my ($self,$param,$param2) = self_or_CGI(@_);
2910     if (defined $param2 && defined $param) {
2911         $CGI::DEFAULT_DTD = [ $param, $param2 ];
2912     } elsif (defined $param) {
2913         $CGI::DEFAULT_DTD = $param;
2914     }
2915     return $CGI::DEFAULT_DTD;
2916 }
2917 END_OF_FUNC
2918
2919 # -------------- really private subroutines -----------------
2920 'previous_or_default' => <<'END_OF_FUNC',
2921 sub previous_or_default {
2922     my($self,$name,$defaults,$override) = @_;
2923     my(%selected);
2924
2925     if (!$override && ($self->{'.fieldnames'}->{$name} || 
2926                        defined($self->param($name)) ) ) {
2927         grep($selected{$_}++,$self->param($name));
2928     } elsif (defined($defaults) && ref($defaults) && 
2929              (ref($defaults) eq 'ARRAY')) {
2930         grep($selected{$_}++,@{$defaults});
2931     } else {
2932         $selected{$defaults}++ if defined($defaults);
2933     }
2934
2935     return %selected;
2936 }
2937 END_OF_FUNC
2938
2939 'register_parameter' => <<'END_OF_FUNC',
2940 sub register_parameter {
2941     my($self,$param) = @_;
2942     $self->{'.parametersToAdd'}->{$param}++;
2943 }
2944 END_OF_FUNC
2945
2946 'get_fields' => <<'END_OF_FUNC',
2947 sub get_fields {
2948     my($self) = @_;
2949     return $self->CGI::hidden('-name'=>'.cgifields',
2950                               '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2951                               '-override'=>1);
2952 }
2953 END_OF_FUNC
2954
2955 'read_from_cmdline' => <<'END_OF_FUNC',
2956 sub read_from_cmdline {
2957     my($input,@words);
2958     my($query_string);
2959     if ($DEBUG && @ARGV) {
2960         @words = @ARGV;
2961     } elsif ($DEBUG > 1) {
2962         require "shellwords.pl";
2963         print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2964         chomp(@lines = <STDIN>); # remove newlines
2965         $input = join(" ",@lines);
2966         @words = &shellwords($input);    
2967     }
2968     foreach (@words) {
2969         s/\\=/%3D/g;
2970         s/\\&/%26/g;        
2971     }
2972
2973     if ("@words"=~/=/) {
2974         $query_string = join('&',@words);
2975     } else {
2976         $query_string = join('+',@words);
2977     }
2978     return $query_string;
2979 }
2980 END_OF_FUNC
2981
2982 #####
2983 # subroutine: read_multipart
2984 #
2985 # Read multipart data and store it into our parameters.
2986 # An interesting feature is that if any of the parts is a file, we
2987 # create a temporary file and open up a filehandle on it so that the
2988 # caller can read from it if necessary.
2989 #####
2990 'read_multipart' => <<'END_OF_FUNC',
2991 sub read_multipart {
2992     my($self,$boundary,$length,$filehandle) = @_;
2993     my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
2994     return unless $buffer;
2995     my(%header,$body);
2996     my $filenumber = 0;
2997     while (!$buffer->eof) {
2998         %header = $buffer->readHeader;
2999
3000         unless (%header) {
3001             $self->cgi_error("400 Bad request (malformed multipart POST)");
3002             return;
3003         }
3004
3005         my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
3006         $param .= $TAINTED;
3007
3008         # Bug:  Netscape doesn't escape quotation marks in file names!!!
3009         my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
3010
3011         # add this parameter to our list
3012         $self->add_parameter($param);
3013
3014         # If no filename specified, then just read the data and assign it
3015         # to our parameter list.
3016         if ( !defined($filename) || $filename eq '' ) {
3017             my($value) = $buffer->readBody;
3018             $value .= $TAINTED;
3019             push(@{$self->{$param}},$value);
3020             next;
3021         }
3022
3023         my ($tmpfile,$tmp,$filehandle);
3024       UPLOADS: {
3025           # If we get here, then we are dealing with a potentially large
3026           # uploaded form.  Save the data to a temporary file, then open
3027           # the file for reading.
3028
3029           # skip the file if uploads disabled
3030           if ($DISABLE_UPLOADS) {
3031               while (defined($data = $buffer->read)) { }
3032               last UPLOADS;
3033           }
3034
3035           # choose a relatively unpredictable tmpfile sequence number
3036           my $seqno = unpack("%16C*",join('',localtime,values %ENV));
3037           for (my $cnt=10;$cnt>0;$cnt--) {
3038             next unless $tmpfile = new CGITempFile($seqno);
3039             $tmp = $tmpfile->as_string;
3040             last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
3041             $seqno += int rand(100);
3042           }
3043           die "CGI open of tmpfile: $!\n" unless defined $filehandle;
3044           $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3045
3046           my ($data);
3047           local($\) = '';
3048           while (defined($data = $buffer->read)) {
3049               print $filehandle $data;
3050           }
3051
3052           # back up to beginning of file
3053           seek($filehandle,0,0);
3054           $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3055
3056           # Save some information about the uploaded file where we can get
3057           # at it later.
3058           $self->{'.tmpfiles'}->{fileno($filehandle)}= {
3059               name => $tmpfile,
3060               info => {%header},
3061           };
3062           push(@{$self->{$param}},$filehandle);
3063       }
3064     }
3065 }
3066 END_OF_FUNC
3067
3068 'upload' =><<'END_OF_FUNC',
3069 sub upload {
3070     my($self,$param_name) = self_or_default(@_);
3071     my @param = grep(ref && fileno($_), $self->param($param_name));
3072     return unless @param;
3073     return wantarray ? @param : $param[0];
3074 }
3075 END_OF_FUNC
3076
3077 'tmpFileName' => <<'END_OF_FUNC',
3078 sub tmpFileName {
3079     my($self,$filename) = self_or_default(@_);
3080     return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
3081         $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
3082             : '';
3083 }
3084 END_OF_FUNC
3085
3086 'uploadInfo' => <<'END_OF_FUNC',
3087 sub uploadInfo {
3088     my($self,$filename) = self_or_default(@_);
3089     return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
3090 }
3091 END_OF_FUNC
3092
3093 # internal routine, don't use
3094 '_set_values_and_labels' => <<'END_OF_FUNC',
3095 sub _set_values_and_labels {
3096     my $self = shift;
3097     my ($v,$l,$n) = @_;
3098     $$l = $v if ref($v) eq 'HASH' && !ref($$l);
3099     return $self->param($n) if !defined($v);
3100     return $v if !ref($v);
3101     return ref($v) eq 'HASH' ? keys %$v : @$v;
3102 }
3103 END_OF_FUNC
3104
3105 # internal routine, don't use
3106 '_set_attributes' => <<'END_OF_FUNC',
3107 sub _set_attributes {
3108     my $self = shift;
3109     my($element, $attributes) = @_;
3110     return '' unless defined($attributes->{$element});
3111     $attribs = ' ';
3112     foreach my $attrib (keys %{$attributes->{$element}}) {
3113         $attrib =~ s/^-//;
3114         $attribs .= "@{[lc($attrib)]}=\"$attributes->{$element}{$attrib}\" ";
3115     }
3116     $attribs =~ s/ $//;
3117     return $attribs;
3118 }
3119 END_OF_FUNC
3120
3121 '_compile_all' => <<'END_OF_FUNC',
3122 sub _compile_all {
3123     foreach (@_) {
3124         next if defined(&$_);
3125         $AUTOLOAD = "CGI::$_";
3126         _compile();
3127     }
3128 }
3129 END_OF_FUNC
3130
3131 );
3132 END_OF_AUTOLOAD
3133 ;
3134
3135 #########################################################
3136 # Globals and stubs for other packages that we use.
3137 #########################################################
3138
3139 ################### Fh -- lightweight filehandle ###############
3140 package Fh;
3141 use overload 
3142     '""'  => \&asString,
3143     'cmp' => \&compare,
3144     'fallback'=>1;
3145
3146 $FH='fh00000';
3147
3148 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3149
3150 $AUTOLOADED_ROUTINES = '';      # prevent -w error
3151 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3152 %SUBS =  (
3153 'asString' => <<'END_OF_FUNC',
3154 sub asString {
3155     my $self = shift;
3156     # get rid of package name
3157     (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//; 
3158     $i =~ s/%(..)/ chr(hex($1)) /eg;
3159     return $i.$CGI::TAINTED;
3160 # BEGIN DEAD CODE
3161 # This was an extremely clever patch that allowed "use strict refs".
3162 # Unfortunately it relied on another bug that caused leaky file descriptors.
3163 # The underlying bug has been fixed, so this no longer works.  However
3164 # "strict refs" still works for some reason.
3165 #    my $self = shift;
3166 #    return ${*{$self}{SCALAR}};
3167 # END DEAD CODE
3168 }
3169 END_OF_FUNC
3170
3171 'compare' => <<'END_OF_FUNC',
3172 sub compare {
3173     my $self = shift;
3174     my $value = shift;
3175     return "$self" cmp $value;
3176 }
3177 END_OF_FUNC
3178
3179 'new'  => <<'END_OF_FUNC',
3180 sub new {
3181     my($pack,$name,$file,$delete) = @_;
3182     _setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
3183     require Fcntl unless defined &Fcntl::O_RDWR;
3184     (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3185     my $fv = ++$FH . $safename;
3186     my $ref = \*{"Fh::$fv"};
3187     $file =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3188     my $safe = $1;
3189     sysopen($ref,$safe,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3190     unlink($safe) if $delete;
3191     CORE::delete $Fh::{$fv};
3192     return bless $ref,$pack;
3193 }
3194 END_OF_FUNC
3195
3196 'DESTROY'  => <<'END_OF_FUNC',
3197 sub DESTROY {
3198     my $self = shift;
3199     close $self;
3200 }
3201 END_OF_FUNC
3202
3203 );
3204 END_OF_AUTOLOAD
3205
3206 ######################## MultipartBuffer ####################
3207 package MultipartBuffer;
3208
3209 # how many bytes to read at a time.  We use
3210 # a 4K buffer by default.
3211 $INITIAL_FILLUNIT = 1024 * 4;
3212 $TIMEOUT = 240*60;       # 4 hour timeout for big files
3213 $SPIN_LOOP_MAX = 2000;  # bug fix for some Netscape servers
3214 $CRLF=$CGI::CRLF;
3215
3216 #reuse the autoload function
3217 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3218
3219 # avoid autoloader warnings
3220 sub DESTROY {}
3221
3222 ###############################################################################
3223 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3224 ###############################################################################
3225 $AUTOLOADED_ROUTINES = '';      # prevent -w error
3226 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3227 %SUBS =  (
3228
3229 'new' => <<'END_OF_FUNC',
3230 sub new {
3231     my($package,$interface,$boundary,$length,$filehandle) = @_;
3232     $FILLUNIT = $INITIAL_FILLUNIT;
3233     my $IN;
3234     if ($filehandle) {
3235         my($package) = caller;
3236         # force into caller's package if necessary
3237         $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle"; 
3238     }
3239     $IN = "main::STDIN" unless $IN;
3240
3241     $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
3242     
3243     # If the user types garbage into the file upload field,
3244     # then Netscape passes NOTHING to the server (not good).
3245     # We may hang on this read in that case. So we implement
3246     # a read timeout.  If nothing is ready to read
3247     # by then, we return.
3248
3249     # Netscape seems to be a little bit unreliable
3250     # about providing boundary strings.
3251     my $boundary_read = 0;
3252     if ($boundary) {
3253
3254         # Under the MIME spec, the boundary consists of the 
3255         # characters "--" PLUS the Boundary string
3256
3257         # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3258         # the two extra hyphens.  We do a special case here on the user-agent!!!!
3259         $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
3260
3261     } else { # otherwise we find it ourselves
3262         my($old);
3263         ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3264         $boundary = <$IN>;      # BUG: This won't work correctly under mod_perl
3265         $length -= length($boundary);
3266         chomp($boundary);               # remove the CRLF
3267         $/ = $old;                      # restore old line separator
3268         $boundary_read++;
3269     }
3270
3271     my $self = {LENGTH=>$length,
3272                 BOUNDARY=>$boundary,
3273                 IN=>$IN,
3274                 INTERFACE=>$interface,
3275                 BUFFER=>'',
3276             };
3277
3278     $FILLUNIT = length($boundary)
3279         if length($boundary) > $FILLUNIT;
3280
3281     my $retval = bless $self,ref $package || $package;
3282
3283     # Read the preamble and the topmost (boundary) line plus the CRLF.
3284     unless ($boundary_read) {
3285       while ($self->read(0)) { }
3286     }
3287     die "Malformed multipart POST\n" if $self->eof;
3288
3289     return $retval;
3290 }
3291 END_OF_FUNC
3292
3293 'readHeader' => <<'END_OF_FUNC',
3294 sub readHeader {
3295     my($self) = @_;
3296     my($end);
3297     my($ok) = 0;
3298     my($bad) = 0;
3299
3300     local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3301
3302     do {
3303         $self->fillBuffer($FILLUNIT);
3304         $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3305         $ok++ if $self->{BUFFER} eq '';
3306         $bad++ if !$ok && $self->{LENGTH} <= 0;
3307         # this was a bad idea
3308         # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT; 
3309     } until $ok || $bad;
3310     return () if $bad;
3311
3312     my($header) = substr($self->{BUFFER},0,$end+2);
3313     substr($self->{BUFFER},0,$end+4) = '';
3314     my %return;
3315
3316     # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3317     #   (Folding Long Header Fields), 3.4.3 (Comments)
3318     #   and 3.4.5 (Quoted-Strings).
3319
3320     my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3321     $header=~s/$CRLF\s+/ /og;           # merge continuation lines
3322
3323     while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3324         my ($field_name,$field_value) = ($1,$2);
3325         $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3326         $return{$field_name}=$field_value;
3327     }
3328     return %return;
3329 }
3330 END_OF_FUNC
3331
3332 # This reads and returns the body as a single scalar value.
3333 'readBody' => <<'END_OF_FUNC',
3334 sub readBody {
3335     my($self) = @_;
3336     my($data);
3337     my($returnval)='';
3338     while (defined($data = $self->read)) {
3339         $returnval .= $data;
3340     }
3341     return $returnval;
3342 }
3343 END_OF_FUNC
3344
3345 # This will read $bytes or until the boundary is hit, whichever happens
3346 # first.  After the boundary is hit, we return undef.  The next read will
3347 # skip over the boundary and begin reading again;
3348 'read' => <<'END_OF_FUNC',
3349 sub read {
3350     my($self,$bytes) = @_;
3351
3352     # default number of bytes to read
3353     $bytes = $bytes || $FILLUNIT;       
3354
3355     # Fill up our internal buffer in such a way that the boundary
3356     # is never split between reads.
3357     $self->fillBuffer($bytes);
3358
3359     # Find the boundary in the buffer (it may not be there).
3360     my $start = index($self->{BUFFER},$self->{BOUNDARY});
3361     # protect against malformed multipart POST operations
3362     die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3363
3364     # If the boundary begins the data, then skip past it
3365     # and return undef.
3366     if ($start == 0) {
3367
3368         # clear us out completely if we've hit the last boundary.
3369         if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3370             $self->{BUFFER}='';
3371             $self->{LENGTH}=0;
3372             return undef;
3373         }
3374
3375         # just remove the boundary.
3376         substr($self->{BUFFER},0,length($self->{BOUNDARY}))='';
3377         $self->{BUFFER} =~ s/^\012\015?//;
3378         return undef;
3379     }
3380
3381     my $bytesToReturn;    
3382     if ($start > 0) {           # read up to the boundary
3383         $bytesToReturn = $start > $bytes ? $bytes : $start;
3384     } else {    # read the requested number of bytes
3385         # leave enough bytes in the buffer to allow us to read
3386         # the boundary.  Thanks to Kevin Hendrick for finding
3387         # this one.
3388         $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3389     }
3390
3391     my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3392     substr($self->{BUFFER},0,$bytesToReturn)='';
3393     
3394     # If we hit the boundary, remove the CRLF from the end.
3395     return (($start > 0) && ($start <= $bytes)) 
3396            ? substr($returnval,0,-2) : $returnval;
3397 }
3398 END_OF_FUNC
3399
3400
3401 # This fills up our internal buffer in such a way that the
3402 # boundary is never split between reads
3403 'fillBuffer' => <<'END_OF_FUNC',
3404 sub fillBuffer {
3405     my($self,$bytes) = @_;
3406     return unless $self->{LENGTH};
3407
3408     my($boundaryLength) = length($self->{BOUNDARY});
3409     my($bufferLength) = length($self->{BUFFER});
3410     my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3411     $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3412
3413     # Try to read some data.  We may hang here if the browser is screwed up.  
3414     my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3415                                                          \$self->{BUFFER},
3416                                                          $bytesToRead,
3417                                                          $bufferLength);
3418     $self->{BUFFER} = '' unless defined $self->{BUFFER};
3419
3420     # An apparent bug in the Apache server causes the read()
3421     # to return zero bytes repeatedly without blocking if the
3422     # remote user aborts during a file transfer.  I don't know how
3423     # they manage this, but the workaround is to abort if we get
3424     # more than SPIN_LOOP_MAX consecutive zero reads.
3425     if ($bytesRead == 0) {
3426         die  "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3427             if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3428     } else {
3429         $self->{ZERO_LOOP_COUNTER}=0;
3430     }
3431
3432     $self->{LENGTH} -= $bytesRead;
3433 }
3434 END_OF_FUNC
3435
3436
3437 # Return true when we've finished reading
3438 'eof' => <<'END_OF_FUNC'
3439 sub eof {
3440     my($self) = @_;
3441     return 1 if (length($self->{BUFFER}) == 0)
3442                  && ($self->{LENGTH} <= 0);
3443     undef;
3444 }
3445 END_OF_FUNC
3446
3447 );
3448 END_OF_AUTOLOAD
3449
3450 ####################################################################################
3451 ################################## TEMPORARY FILES #################################
3452 ####################################################################################
3453 package CGITempFile;
3454
3455 $SL = $CGI::SL;
3456 $MAC = $CGI::OS eq 'MACINTOSH';
3457 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3458 unless ($TMPDIRECTORY) {
3459     @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3460            "C:${SL}temp","${SL}tmp","${SL}temp",
3461            "${vol}${SL}Temporary Items",
3462            "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3463            "C:${SL}system${SL}temp");
3464     unshift(@TEMP,$ENV{'TMPDIR'}) if defined $ENV{'TMPDIR'};
3465
3466     # this feature was supposed to provide per-user tmpfiles, but
3467     # it is problematic.
3468     #    unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3469     # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3470     #    : can generate a 'getpwuid() not implemented' exception, even though
3471     #    : it's never called.  Found under DOS/Win with the DJGPP perl port.
3472     #    : Refer to getpwuid() only at run-time if we're fortunate and have  UNIX.
3473     # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3474
3475     foreach (@TEMP) {
3476         do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3477     }
3478 }
3479
3480 $TMPDIRECTORY  = $MAC ? "" : "." unless $TMPDIRECTORY;
3481 $MAXTRIES = 5000;
3482
3483 # cute feature, but overload implementation broke it
3484 # %OVERLOAD = ('""'=>'as_string');
3485 *CGITempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3486
3487 sub DESTROY {
3488     my($self) = @_;
3489     $$self =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3490     my $safe = $1;             # untaint operation
3491     unlink $safe;              # get rid of the file
3492 }
3493
3494 ###############################################################################
3495 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3496 ###############################################################################
3497 $AUTOLOADED_ROUTINES = '';      # prevent -w error
3498 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3499 %SUBS = (
3500
3501 'new' => <<'END_OF_FUNC',
3502 sub new {
3503     my($package,$sequence) = @_;
3504     my $filename;
3505     for (my $i = 0; $i < $MAXTRIES; $i++) {
3506         last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3507     }
3508     # check that it is a more-or-less valid filename
3509     return unless $filename =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$!;
3510     # this used to untaint, now it doesn't
3511     # $filename = $1;
3512     return bless \$filename;
3513 }
3514 END_OF_FUNC
3515
3516 'as_string' => <<'END_OF_FUNC'
3517 sub as_string {
3518     my($self) = @_;
3519     return $$self;
3520 }
3521 END_OF_FUNC
3522
3523 );
3524 END_OF_AUTOLOAD
3525
3526 package CGI;
3527
3528 # We get a whole bunch of warnings about "possibly uninitialized variables"
3529 # when running with the -w switch.  Touch them all once to get rid of the
3530 # warnings.  This is ugly and I hate it.
3531 if ($^W) {
3532     $CGI::CGI = '';
3533     $CGI::CGI=<<EOF;
3534     $CGI::VERSION;
3535     $MultipartBuffer::SPIN_LOOP_MAX;
3536     $MultipartBuffer::CRLF;
3537     $MultipartBuffer::TIMEOUT;
3538     $MultipartBuffer::INITIAL_FILLUNIT;
3539 EOF
3540     ;
3541 }
3542
3543 1;
3544
3545 __END__
3546
3547 =head1 NAME
3548
3549 CGI - Simple Common Gateway Interface Class
3550
3551 =head1 SYNOPSIS
3552
3553   # CGI script that creates a fill-out form
3554   # and echoes back its values.
3555
3556   use CGI qw/:standard/;
3557   print header,
3558         start_html('A Simple Example'),
3559         h1('A Simple Example'),
3560         start_form,
3561         "What's your name? ",textfield('name'),p,
3562         "What's the combination?", p,
3563         checkbox_group(-name=>'words',
3564                        -values=>['eenie','meenie','minie','moe'],
3565                        -defaults=>['eenie','minie']), p,
3566         "What's your favorite color? ",
3567         popup_menu(-name=>'color',
3568                    -values=>['red','green','blue','chartreuse']),p,
3569         submit,
3570         end_form,
3571         hr;
3572
3573    if (param()) {
3574        print "Your name is",em(param('name')),p,
3575              "The keywords are: ",em(join(", ",param('words'))),p,
3576              "Your favorite color is ",em(param('color')),
3577              hr;
3578    }
3579
3580 =head1 ABSTRACT
3581
3582 This perl library uses perl5 objects to make it easy to create Web
3583 fill-out forms and parse their contents.  This package defines CGI
3584 objects, entities that contain the values of the current query string
3585 and other state variables.  Using a CGI object's methods, you can
3586 examine keywords and parameters passed to your script, and create
3587 forms whose initial values are taken from the current query (thereby
3588 preserving state information).  The module provides shortcut functions
3589 that produce boilerplate HTML, reducing typing and coding errors. It
3590 also provides functionality for some of the more advanced features of
3591 CGI scripting, including support for file uploads, cookies, cascading
3592 style sheets, server push, and frames.
3593
3594 CGI.pm also provides a simple function-oriented programming style for
3595 those who don't need its object-oriented features.
3596
3597 The current version of CGI.pm is available at
3598
3599   http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3600   ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3601
3602 =head1 DESCRIPTION
3603
3604 =head2 PROGRAMMING STYLE
3605
3606 There are two styles of programming with CGI.pm, an object-oriented
3607 style and a function-oriented style.  In the object-oriented style you
3608 create one or more CGI objects and then use object methods to create
3609 the various elements of the page.  Each CGI object starts out with the
3610 list of named parameters that were passed to your CGI script by the
3611 server.  You can modify the objects, save them to a file or database
3612 and recreate them.  Because each object corresponds to the "state" of
3613 the CGI script, and because each object's parameter list is
3614 independent of the others, this allows you to save the state of the
3615 script and restore it later.
3616
3617 For example, using the object oriented style, here is how you create
3618 a simple "Hello World" HTML page:
3619
3620    #!/usr/local/bin/perl -w
3621    use CGI;                             # load CGI routines
3622    $q = new CGI;                        # create new CGI object
3623    print $q->header,                    # create the HTTP header
3624          $q->start_html('hello world'), # start the HTML
3625          $q->h1('hello world'),         # level 1 header
3626          $q->end_html;                  # end the HTML
3627
3628 In the function-oriented style, there is one default CGI object that
3629 you rarely deal with directly.  Instead you just call functions to
3630 retrieve CGI parameters, create HTML tags, manage cookies, and so
3631 on.  This provides you with a cleaner programming interface, but
3632 limits you to using one CGI object at a time.  The following example
3633 prints the same page, but uses the function-oriented interface.
3634 The main differences are that we now need to import a set of functions
3635 into our name space (usually the "standard" functions), and we don't
3636 need to create the CGI object.
3637
3638    #!/usr/local/bin/perl
3639    use CGI qw/:standard/;           # load standard CGI routines
3640    print header,                    # create the HTTP header
3641          start_html('hello world'), # start the HTML
3642          h1('hello world'),         # level 1 header
3643          end_html;                  # end the HTML
3644
3645 The examples in this document mainly use the object-oriented style.
3646 See HOW TO IMPORT FUNCTIONS for important information on
3647 function-oriented programming in CGI.pm
3648
3649 =head2 CALLING CGI.PM ROUTINES
3650
3651 Most CGI.pm routines accept several arguments, sometimes as many as 20
3652 optional ones!  To simplify this interface, all routines use a named
3653 argument calling style that looks like this:
3654
3655    print $q->header(-type=>'image/gif',-expires=>'+3d');
3656
3657 Each argument name is preceded by a dash.  Neither case nor order
3658 matters in the argument list.  -type, -Type, and -TYPE are all
3659 acceptable.  In fact, only the first argument needs to begin with a
3660 dash.  If a dash is present in the first argument, CGI.pm assumes
3661 dashes for the subsequent ones.
3662
3663 Several routines are commonly called with just one argument.  In the
3664 case of these routines you can provide the single argument without an
3665 argument name.  header() happens to be one of these routines.  In this
3666 case, the single argument is the document type.
3667
3668    print $q->header('text/html');
3669
3670 Other such routines are documented below.
3671
3672 Sometimes named arguments expect a scalar, sometimes a reference to an
3673 array, and sometimes a reference to a hash.  Often, you can pass any
3674 type of argument and the routine will do whatever is most appropriate.
3675 For example, the param() routine is used to set a CGI parameter to a
3676 single or a multi-valued value.  The two cases are shown below:
3677
3678    $q->param(-name=>'veggie',-value=>'tomato');
3679    $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3680
3681 A large number of routines in CGI.pm actually aren't specifically
3682 defined in the module, but are generated automatically as needed.
3683 These are the "HTML shortcuts," routines that generate HTML tags for
3684 use in dynamically-generated pages.  HTML tags have both attributes
3685 (the attribute="value" pairs within the tag itself) and contents (the
3686 part between the opening and closing pairs.)  To distinguish between
3687 attributes and contents, CGI.pm uses the convention of passing HTML
3688 attributes as a hash reference as the first argument, and the
3689 contents, if any, as any subsequent arguments.  It works out like
3690 this:
3691
3692    Code                           Generated HTML
3693    ----                           --------------
3694    h1()                           <h1>
3695    h1('some','contents');         <h1>some contents</h1>
3696    h1({-align=>left});            <h1 align="LEFT">
3697    h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
3698
3699 HTML tags are described in more detail later.
3700
3701 Many newcomers to CGI.pm are puzzled by the difference between the
3702 calling conventions for the HTML shortcuts, which require curly braces
3703 around the HTML tag attributes, and the calling conventions for other
3704 routines, which manage to generate attributes without the curly
3705 brackets.  Don't be confused.  As a convenience the curly braces are
3706 optional in all but the HTML shortcuts.  If you like, you can use
3707 curly braces when calling any routine that takes named arguments.  For
3708 example:
3709
3710    print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3711
3712 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3713 names conflict with built-in Perl functions.  The most frequent of
3714 these is the -values argument, used to create multi-valued menus,
3715 radio button clusters and the like.  To get around this warning, you
3716 have several choices:
3717
3718 =over 4
3719
3720 =item 1.
3721
3722 Use another name for the argument, if one is available. 
3723 For example, -value is an alias for -values.
3724
3725 =item 2.
3726
3727 Change the capitalization, e.g. -Values
3728
3729 =item 3.
3730
3731 Put quotes around the argument name, e.g. '-values'
3732
3733 =back
3734
3735 Many routines will do something useful with a named argument that it
3736 doesn't recognize.  For example, you can produce non-standard HTTP
3737 header fields by providing them as named arguments:
3738
3739   print $q->header(-type  =>  'text/html',
3740                    -cost  =>  'Three smackers',
3741                    -annoyance_level => 'high',
3742                    -complaints_to   => 'bit bucket');
3743
3744 This will produce the following nonstandard HTTP header:
3745
3746    HTTP/1.0 200 OK
3747    Cost: Three smackers
3748    Annoyance-level: high
3749    Complaints-to: bit bucket
3750    Content-type: text/html
3751
3752 Notice the way that underscores are translated automatically into
3753 hyphens.  HTML-generating routines perform a different type of
3754 translation. 
3755
3756 This feature allows you to keep up with the rapidly changing HTTP and
3757 HTML "standards".
3758
3759 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3760
3761      $query = new CGI;
3762
3763 This will parse the input (from both POST and GET methods) and store
3764 it into a perl5 object called $query.  
3765
3766 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3767
3768      $query = new CGI(INPUTFILE);
3769
3770 If you provide a file handle to the new() method, it will read
3771 parameters from the file (or STDIN, or whatever).  The file can be in
3772 any of the forms describing below under debugging (i.e. a series of
3773 newline delimited TAG=VALUE pairs will work).  Conveniently, this type
3774 of file is created by the save() method (see below).  Multiple records
3775 can be saved and restored.
3776
3777 Perl purists will be pleased to know that this syntax accepts
3778 references to file handles, or even references to filehandle globs,
3779 which is the "official" way to pass a filehandle:
3780
3781     $query = new CGI(\*STDIN);
3782
3783 You can also initialize the CGI object with a FileHandle or IO::File
3784 object.
3785
3786 If you are using the function-oriented interface and want to
3787 initialize CGI state from a file handle, the way to do this is with
3788 B<restore_parameters()>.  This will (re)initialize the
3789 default CGI object from the indicated file handle.
3790
3791     open (IN,"test.in") || die;
3792     restore_parameters(IN);
3793     close IN;
3794
3795 You can also initialize the query object from an associative array
3796 reference:
3797
3798     $query = new CGI( {'dinosaur'=>'barney',
3799                        'song'=>'I love you',
3800                        'friends'=>[qw/Jessica George Nancy/]}
3801                     );
3802
3803 or from a properly formatted, URL-escaped query string:
3804
3805     $query = new CGI('dinosaur=barney&color=purple');
3806
3807 or from a previously existing CGI object (currently this clones the
3808 parameter list, but none of the other object-specific fields, such as
3809 autoescaping):
3810
3811     $old_query = new CGI;
3812     $new_query = new CGI($old_query);
3813
3814 To create an empty query, initialize it from an empty string or hash:
3815
3816    $empty_query = new CGI("");
3817
3818        -or-
3819
3820    $empty_query = new CGI({});
3821
3822 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3823
3824      @keywords = $query->keywords
3825
3826 If the script was invoked as the result of an <ISINDEX> search, the
3827 parsed keywords can be obtained as an array using the keywords() method.
3828
3829 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3830
3831      @names = $query->param
3832
3833 If the script was invoked with a parameter list
3834 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
3835 will return the parameter names as a list.  If the script was invoked
3836 as an <ISINDEX> script and contains a string without ampersands
3837 (e.g. "value1+value2+value3") , there will be a single parameter named
3838 "keywords" containing the "+"-delimited keywords.
3839
3840 NOTE: As of version 1.5, the array of parameter names returned will
3841 be in the same order as they were submitted by the browser.
3842 Usually this order is the same as the order in which the 
3843 parameters are defined in the form (however, this isn't part
3844 of the spec, and so isn't guaranteed).
3845
3846 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3847
3848     @values = $query->param('foo');
3849
3850               -or-
3851
3852     $value = $query->param('foo');
3853
3854 Pass the param() method a single argument to fetch the value of the
3855 named parameter. If the parameter is multivalued (e.g. from multiple
3856 selections in a scrolling list), you can ask to receive an array.  Otherwise
3857 the method will return a single value.
3858
3859 If a value is not given in the query string, as in the queries
3860 "name1=&name2=" or "name1&name2", it will be returned as an empty
3861 string.  This feature is new in 2.63.
3862
3863 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3864
3865     $query->param('foo','an','array','of','values');
3866
3867 This sets the value for the named parameter 'foo' to an array of
3868 values.  This is one way to change the value of a field AFTER
3869 the script has been invoked once before.  (Another way is with
3870 the -override parameter accepted by all methods that generate
3871 form elements.)
3872
3873 param() also recognizes a named parameter style of calling described
3874 in more detail later:
3875
3876     $query->param(-name=>'foo',-values=>['an','array','of','values']);
3877
3878                               -or-
3879
3880     $query->param(-name=>'foo',-value=>'the value');
3881
3882 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
3883
3884    $query->append(-name=>'foo',-values=>['yet','more','values']);
3885
3886 This adds a value or list of values to the named parameter.  The
3887 values are appended to the end of the parameter if it already exists.
3888 Otherwise the parameter is created.  Note that this method only
3889 recognizes the named argument calling syntax.
3890
3891 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
3892
3893    $query->import_names('R');
3894
3895 This creates a series of variables in the 'R' namespace.  For example,
3896 $R::foo, @R:foo.  For keyword lists, a variable @R::keywords will appear.
3897 If no namespace is given, this method will assume 'Q'.
3898 WARNING:  don't import anything into 'main'; this is a major security
3899 risk!!!!
3900
3901 In older versions, this method was called B<import()>.  As of version 2.20, 
3902 this name has been removed completely to avoid conflict with the built-in
3903 Perl module B<import> operator.
3904
3905 =head2 DELETING A PARAMETER COMPLETELY:
3906
3907     $query->delete('foo','bar','baz');
3908
3909 This completely clears a list of parameters.  It sometimes useful for
3910 resetting parameters that you don't want passed down between script
3911 invocations.
3912
3913 If you are using the function call interface, use "Delete()" instead
3914 to avoid conflicts with Perl's built-in delete operator.
3915
3916 =head2 DELETING ALL PARAMETERS:
3917
3918    $query->delete_all();
3919
3920 This clears the CGI object completely.  It might be useful to ensure
3921 that all the defaults are taken when you create a fill-out form.
3922
3923 Use Delete_all() instead if you are using the function call interface.
3924
3925 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
3926
3927    $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
3928    unshift @{$q->param_fetch(-name=>'address')},'George Munster';
3929
3930 If you need access to the parameter list in a way that isn't covered
3931 by the methods above, you can obtain a direct reference to it by
3932 calling the B<param_fetch()> method with the name of the .  This
3933 will return an array reference to the named parameters, which you then
3934 can manipulate in any way you like.
3935
3936 You can also use a named argument style using the B<-name> argument.
3937
3938 =head2 FETCHING THE PARAMETER LIST AS A HASH:
3939
3940     $params = $q->Vars;
3941     print $params->{'address'};
3942     @foo = split("\0",$params->{'foo'});
3943     %params = $q->Vars;
3944
3945     use CGI ':cgi-lib';
3946     $params = Vars;
3947
3948 Many people want to fetch the entire parameter list as a hash in which
3949 the keys are the names of the CGI parameters, and the values are the
3950 parameters' values.  The Vars() method does this.  Called in a scalar
3951 context, it returns the parameter list as a tied hash reference.
3952 Changing a key changes the value of the parameter in the underlying
3953 CGI parameter list.  Called in a list context, it returns the
3954 parameter list as an ordinary hash.  This allows you to read the
3955 contents of the parameter list, but not to change it.
3956
3957 When using this, the thing you must watch out for are multivalued CGI
3958 parameters.  Because a hash cannot distinguish between scalar and
3959 list context, multivalued parameters will be returned as a packed
3960 string, separated by the "\0" (null) character.  You must split this
3961 packed string in order to get at the individual values.  This is the
3962 convention introduced long ago by Steve Brenner in his cgi-lib.pl
3963 module for Perl version 4.
3964
3965 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
3966 function calls (also see the section on CGI-LIB compatibility).
3967
3968 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
3969
3970     $query->save(FILEHANDLE)
3971
3972 This will write the current state of the form to the provided
3973 filehandle.  You can read it back in by providing a filehandle
3974 to the new() method.  Note that the filehandle can be a file, a pipe,
3975 or whatever!
3976
3977 The format of the saved file is:
3978
3979         NAME1=VALUE1
3980         NAME1=VALUE1'
3981         NAME2=VALUE2
3982         NAME3=VALUE3
3983         =
3984
3985 Both name and value are URL escaped.  Multi-valued CGI parameters are
3986 represented as repeated names.  A session record is delimited by a
3987 single = symbol.  You can write out multiple records and read them
3988 back in with several calls to B<new>.  You can do this across several
3989 sessions by opening the file in append mode, allowing you to create
3990 primitive guest books, or to keep a history of users' queries.  Here's
3991 a short example of creating multiple session records:
3992
3993    use CGI;
3994
3995    open (OUT,">>test.out") || die;
3996    $records = 5;
3997    foreach (0..$records) {
3998        my $q = new CGI;
3999        $q->param(-name=>'counter',-value=>$_);
4000        $q->save(OUT);
4001    }
4002    close OUT;
4003
4004    # reopen for reading
4005    open (IN,"test.out") || die;
4006    while (!eof(IN)) {
4007        my $q = new CGI(IN);
4008        print $q->param('counter'),"\n";
4009    }
4010
4011 The file format used for save/restore is identical to that used by the
4012 Whitehead Genome Center's data exchange format "Boulderio", and can be
4013 manipulated and even databased using Boulderio utilities.  See
4014
4015   http://stein.cshl.org/boulder/
4016
4017 for further details.
4018
4019 If you wish to use this method from the function-oriented (non-OO)
4020 interface, the exported name for this method is B<save_parameters()>.
4021
4022 =head2 RETRIEVING CGI ERRORS
4023
4024 Errors can occur while processing user input, particularly when
4025 processing uploaded files.  When these errors occur, CGI will stop
4026 processing and return an empty parameter list.  You can test for
4027 the existence and nature of errors using the I<cgi_error()> function.
4028 The error messages are formatted as HTTP status codes. You can either
4029 incorporate the error text into an HTML page, or use it as the value
4030 of the HTTP status:
4031
4032     my $error = $q->cgi_error;
4033     if ($error) {
4034         print $q->header(-status=>$error),
4035               $q->start_html('Problems'),
4036               $q->h2('Request not processed'),
4037               $q->strong($error);
4038         exit 0;
4039     }
4040
4041 When using the function-oriented interface (see the next section),
4042 errors may only occur the first time you call I<param()>. Be ready
4043 for this!
4044
4045 =head2 USING THE FUNCTION-ORIENTED INTERFACE
4046
4047 To use the function-oriented interface, you must specify which CGI.pm
4048 routines or sets of routines to import into your script's namespace.
4049 There is a small overhead associated with this importation, but it
4050 isn't much.
4051
4052    use CGI <list of methods>;
4053
4054 The listed methods will be imported into the current package; you can
4055 call them directly without creating a CGI object first.  This example
4056 shows how to import the B<param()> and B<header()>
4057 methods, and then use them directly:
4058
4059    use CGI 'param','header';
4060    print header('text/plain');
4061    $zipcode = param('zipcode');
4062
4063 More frequently, you'll import common sets of functions by referring
4064 to the groups by name.  All function sets are preceded with a ":"
4065 character as in ":html3" (for tags defined in the HTML 3 standard).
4066
4067 Here is a list of the function sets you can import:
4068
4069 =over 4
4070
4071 =item B<:cgi>
4072
4073 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4074 and the like.
4075
4076 =item B<:form>
4077
4078 Import all fill-out form generating methods, such as B<textfield()>.
4079
4080 =item B<:html2>
4081
4082 Import all methods that generate HTML 2.0 standard elements.
4083
4084 =item B<:html3>
4085
4086 Import all methods that generate HTML 3.0 elements (such as
4087 <table>, <super> and <sub>).
4088
4089 =item B<:html4>
4090
4091 Import all methods that generate HTML 4 elements (such as
4092 <abbrev>, <acronym> and <thead>).
4093
4094 =item B<:netscape>
4095
4096 Import all methods that generate Netscape-specific HTML extensions.
4097
4098 =item B<:html>
4099
4100 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4101 'netscape')...
4102
4103 =item B<:standard>
4104
4105 Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
4106
4107 =item B<:all>
4108
4109 Import all the available methods.  For the full list, see the CGI.pm
4110 code, where the variable %EXPORT_TAGS is defined.
4111
4112 =back
4113
4114 If you import a function name that is not part of CGI.pm, the module
4115 will treat it as a new HTML tag and generate the appropriate
4116 subroutine.  You can then use it like any other HTML tag.  This is to
4117 provide for the rapidly-evolving HTML "standard."  For example, say
4118 Microsoft comes out with a new tag called <gradient> (which causes the
4119 user's desktop to be flooded with a rotating gradient fill until his
4120 machine reboots).  You don't need to wait for a new version of CGI.pm
4121 to start using it immediately:
4122
4123    use CGI qw/:standard :html3 gradient/;
4124    print gradient({-start=>'red',-end=>'blue'});
4125
4126 Note that in the interests of execution speed CGI.pm does B<not> use
4127 the standard L<Exporter> syntax for specifying load symbols.  This may
4128 change in the future.
4129
4130 If you import any of the state-maintaining CGI or form-generating
4131 methods, a default CGI object will be created and initialized
4132 automatically the first time you use any of the methods that require
4133 one to be present.  This includes B<param()>, B<textfield()>,
4134 B<submit()> and the like.  (If you need direct access to the CGI
4135 object, you can find it in the global variable B<$CGI::Q>).  By
4136 importing CGI.pm methods, you can create visually elegant scripts:
4137
4138    use CGI qw/:standard/;
4139    print 
4140        header,
4141        start_html('Simple Script'),
4142        h1('Simple Script'),
4143        start_form,
4144        "What's your name? ",textfield('name'),p,
4145        "What's the combination?",
4146        checkbox_group(-name=>'words',
4147                       -values=>['eenie','meenie','minie','moe'],
4148                       -defaults=>['eenie','moe']),p,
4149        "What's your favorite color?",
4150        popup_menu(-name=>'color',
4151                   -values=>['red','green','blue','chartreuse']),p,
4152        submit,
4153        end_form,
4154        hr,"\n";
4155
4156     if (param) {
4157        print 
4158            "Your name is ",em(param('name')),p,
4159            "The keywords are: ",em(join(", ",param('words'))),p,
4160            "Your favorite color is ",em(param('color')),".\n";
4161     }
4162     print end_html;
4163
4164 =head2 PRAGMAS
4165
4166 In addition to the function sets, there are a number of pragmas that
4167 you can import.  Pragmas, which are always preceded by a hyphen,
4168 change the way that CGI.pm functions in various ways.  Pragmas,
4169 function sets, and individual functions can all be imported in the
4170 same use() line.  For example, the following use statement imports the
4171 standard set of functions and enables debugging mode (pragma
4172 -debug):
4173
4174    use CGI qw/:standard -debug/;
4175
4176 The current list of pragmas is as follows:
4177
4178 =over 4
4179
4180 =item -any
4181
4182 When you I<use CGI -any>, then any method that the query object
4183 doesn't recognize will be interpreted as a new HTML tag.  This allows
4184 you to support the next I<ad hoc> Netscape or Microsoft HTML
4185 extension.  This lets you go wild with new and unsupported tags:
4186
4187    use CGI qw(-any);
4188    $q=new CGI;
4189    print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4190
4191 Since using <cite>any</cite> causes any mistyped method name
4192 to be interpreted as an HTML tag, use it with care or not at
4193 all.
4194
4195 =item -compile
4196
4197 This causes the indicated autoloaded methods to be compiled up front,
4198 rather than deferred to later.  This is useful for scripts that run
4199 for an extended period of time under FastCGI or mod_perl, and for
4200 those destined to be crunched by Malcom Beattie's Perl compiler.  Use
4201 it in conjunction with the methods or method families you plan to use.
4202
4203    use CGI qw(-compile :standard :html3);
4204
4205 or even
4206
4207    use CGI qw(-compile :all);
4208
4209 Note that using the -compile pragma in this way will always have
4210 the effect of importing the compiled functions into the current
4211 namespace.  If you want to compile without importing use the
4212 compile() method instead:
4213
4214    use CGI();
4215    CGI->compile();
4216
4217 This is particularly useful in a mod_perl environment, in which you
4218 might want to precompile all CGI routines in a startup script, and
4219 then import the functions individually in each mod_perl script.
4220
4221 =item -nosticky
4222
4223 This makes CGI.pm not generating the hidden fields .submit
4224 and .cgifields. It is very useful if you don't want to
4225 have the hidden fields appear in the querystring in a GET method.
4226 For example, a search script generated this way will have
4227 a very nice url with search parameters for bookmarking.
4228
4229 =item -no_undef_params
4230
4231 This keeps CGI.pm from including undef params in the parameter list.
4232
4233 =item -no_xhtml
4234
4235 By default, CGI.pm versions 2.69 and higher emit XHTML
4236 (http://www.w3.org/TR/xhtml1/).  The -no_xhtml pragma disables this
4237 feature.  Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4238 feature.
4239
4240 =item -nph
4241
4242 This makes CGI.pm produce a header appropriate for an NPH (no
4243 parsed header) script.  You may need to do other things as well
4244 to tell the server that the script is NPH.  See the discussion
4245 of NPH scripts below.
4246
4247 =item -newstyle_urls
4248
4249 Separate the name=value pairs in CGI parameter query strings with
4250 semicolons rather than ampersands.  For example:
4251
4252    ?name=fred;age=24;favorite_color=3
4253
4254 Semicolon-delimited query strings are always accepted, but will not be
4255 emitted by self_url() and query_string() unless the -newstyle_urls
4256 pragma is specified.
4257
4258 This became the default in version 2.64.
4259
4260 =item -oldstyle_urls
4261
4262 Separate the name=value pairs in CGI parameter query strings with
4263 ampersands rather than semicolons.  This is no longer the default.
4264
4265 =item -autoload
4266
4267 This overrides the autoloader so that any function in your program
4268 that is not recognized is referred to CGI.pm for possible evaluation.
4269 This allows you to use all the CGI.pm functions without adding them to
4270 your symbol table, which is of concern for mod_perl users who are
4271 worried about memory consumption.  I<Warning:> when
4272 I<-autoload> is in effect, you cannot use "poetry mode"
4273 (functions without the parenthesis).  Use I<hr()> rather
4274 than I<hr>, or add something like I<use subs qw/hr p header/> 
4275 to the top of your script.
4276
4277 =item -no_debug
4278
4279 This turns off the command-line processing features.  If you want to
4280 run a CGI.pm script from the command line to produce HTML, and you
4281 don't want it to read CGI parameters from the command line or STDIN,
4282 then use this pragma:
4283
4284    use CGI qw(-no_debug :standard);
4285
4286 =item -debug
4287
4288 This turns on full debugging.  In addition to reading CGI arguments
4289 from the command-line processing, CGI.pm will pause and try to read
4290 arguments from STDIN, producing the message "(offline mode: enter
4291 name=value pairs on standard input)" features.
4292
4293 See the section on debugging for more details.
4294
4295 =item -private_tempfiles
4296
4297 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4298 file to a temporary directory, then deletes the file when done.
4299 However, this opens the risk of eavesdropping as described in the file
4300 upload section.  Another CGI script author could peek at this data
4301 during the upload, even if it is confidential information. On Unix
4302 systems, the -private_tempfiles pragma will cause the temporary file
4303 to be unlinked as soon as it is opened and before any data is written
4304 into it, reducing, but not eliminating the risk of eavesdropping
4305 (there is still a potential race condition).  To make life harder for
4306 the attacker, the program chooses tempfile names by calculating a 32
4307 bit checksum of the incoming HTTP headers.
4308
4309 To ensure that the temporary file cannot be read by other CGI scripts,
4310 use suEXEC or a CGI wrapper program to run your script.  The temporary
4311 file is created with mode 0600 (neither world nor group readable).
4312
4313 The temporary directory is selected using the following algorithm:
4314
4315     1. if the current user (e.g. "nobody") has a directory named
4316     "tmp" in its home directory, use that (Unix systems only).
4317
4318     2. if the environment variable TMPDIR exists, use the location
4319     indicated.
4320
4321     3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4322     /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4323
4324 Each of these locations is checked that it is a directory and is
4325 writable.  If not, the algorithm tries the next choice.
4326
4327 =back
4328
4329 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4330
4331 Many of the methods generate HTML tags.  As described below, tag
4332 functions automatically generate both the opening and closing tags.
4333 For example:
4334
4335   print h1('Level 1 Header');
4336
4337 produces
4338
4339   <h1>Level 1 Header</h1>
4340
4341 There will be some times when you want to produce the start and end
4342 tags yourself.  In this case, you can use the form start_I<tag_name>
4343 and end_I<tag_name>, as in:
4344
4345   print start_h1,'Level 1 Header',end_h1;
4346
4347 With a few exceptions (described below), start_I<tag_name> and
4348 end_I<tag_name> functions are not generated automatically when you
4349 I<use CGI>.  However, you can specify the tags you want to generate
4350 I<start/end> functions for by putting an asterisk in front of their
4351 name, or, alternatively, requesting either "start_I<tag_name>" or
4352 "end_I<tag_name>" in the import list.
4353
4354 Example:
4355
4356   use CGI qw/:standard *table start_ul/;
4357
4358 In this example, the following functions are generated in addition to
4359 the standard ones:
4360
4361 =over 4
4362
4363 =item 1. start_table() (generates a <table> tag)
4364
4365 =item 2. end_table() (generates a </table> tag)
4366
4367 =item 3. start_ul() (generates a <ul> tag)
4368
4369 =item 4. end_ul() (generates a </ul> tag)
4370
4371 =back
4372
4373 =head1 GENERATING DYNAMIC DOCUMENTS
4374
4375 Most of CGI.pm's functions deal with creating documents on the fly.
4376 Generally you will produce the HTTP header first, followed by the
4377 document itself.  CGI.pm provides functions for generating HTTP
4378 headers of various types as well as for generating HTML.  For creating
4379 GIF images, see the GD.pm module.
4380
4381 Each of these functions produces a fragment of HTML or HTTP which you
4382 can print out directly so that it displays in the browser window,
4383 append to a string, or save to a file for later use.
4384
4385 =head2 CREATING A STANDARD HTTP HEADER:
4386
4387 Normally the first thing you will do in any CGI script is print out an
4388 HTTP header.  This tells the browser what type of document to expect,
4389 and gives other optional information, such as the language, expiration
4390 date, and whether to cache the document.  The header can also be
4391 manipulated for special purposes, such as server push and pay per view
4392 pages.
4393
4394         print $query->header;
4395
4396              -or-
4397
4398         print $query->header('image/gif');
4399
4400              -or-
4401
4402         print $query->header('text/html','204 No response');
4403
4404              -or-
4405
4406         print $query->header(-type=>'image/gif',
4407                              -nph=>1,
4408                              -status=>'402 Payment required',
4409                              -expires=>'+3d',
4410                              -cookie=>$cookie,
4411                              -charset=>'utf-7',
4412                              -attachment=>'foo.gif',
4413                              -Cost=>'$2.00');
4414
4415 header() returns the Content-type: header.  You can provide your own
4416 MIME type if you choose, otherwise it defaults to text/html.  An
4417 optional second parameter specifies the status code and a human-readable
4418 message.  For example, you can specify 204, "No response" to create a
4419 script that tells the browser to do nothing at all.
4420
4421 The last example shows the named argument style for passing arguments
4422 to the CGI methods using named parameters.  Recognized parameters are
4423 B<-type>, B<-status>, B<-expires>, and B<-cookie>.  Any other named
4424 parameters will be stripped of their initial hyphens and turned into
4425 header fields, allowing you to specify any HTTP header you desire.
4426 Internal underscores will be turned into hyphens:
4427
4428     print $query->header(-Content_length=>3002);
4429
4430 Most browsers will not cache the output from CGI scripts.  Every time
4431 the browser reloads the page, the script is invoked anew.  You can
4432 change this behavior with the B<-expires> parameter.  When you specify
4433 an absolute or relative expiration interval with this parameter, some
4434 browsers and proxy servers will cache the script's output until the
4435 indicated expiration date.  The following forms are all valid for the
4436 -expires field:
4437
4438         +30s                              30 seconds from now
4439         +10m                              ten minutes from now
4440         +1h                               one hour from now
4441         -1d                               yesterday (i.e. "ASAP!")
4442         now                               immediately
4443         +3M                               in three months
4444         +10y                              in ten years time
4445         Thursday, 25-Apr-1999 00:40:33 GMT  at the indicated time & date
4446
4447 The B<-cookie> parameter generates a header that tells the browser to provide
4448 a "magic cookie" during all subsequent transactions with your script.
4449 Netscape cookies have a special format that includes interesting attributes
4450 such as expiration time.  Use the cookie() method to create and retrieve
4451 session cookies.
4452
4453 The B<-nph> parameter, if set to a true value, will issue the correct
4454 headers to work with an NPH (no-parse-header) script.  This is important
4455 to use with certain servers that expect all their scripts to be NPH.
4456
4457 The B<-charset> parameter can be used to control the character set
4458 sent to the browser.  If not provided, defaults to ISO-8859-1.  As a
4459 side effect, this sets the charset() method as well.
4460
4461 The B<-attachment> parameter can be used to turn the page into an
4462 attachment.  Instead of displaying the page, some browsers will prompt
4463 the user to save it to disk.  The value of the argument is the
4464 suggested name for the saved file.  In order for this to work, you may
4465 have to set the B<-type> to "application/octet-stream".
4466
4467 =head2 GENERATING A REDIRECTION HEADER
4468
4469    print $query->redirect('http://somewhere.else/in/movie/land');
4470
4471 Sometimes you don't want to produce a document yourself, but simply
4472 redirect the browser elsewhere, perhaps choosing a URL based on the
4473 time of day or the identity of the user.  
4474
4475 The redirect() function redirects the browser to a different URL.  If
4476 you use redirection like this, you should B<not> print out a header as
4477 well.
4478
4479 One hint I can offer is that relative links may not work correctly
4480 when you generate a redirection to another document on your site.
4481 This is due to a well-intentioned optimization that some servers use.
4482 The solution to this is to use the full URL (including the http: part)
4483 of the document you are redirecting to.
4484
4485 You can also use named arguments:
4486
4487     print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4488                            -nph=>1);
4489
4490 The B<-nph> parameter, if set to a true value, will issue the correct
4491 headers to work with an NPH (no-parse-header) script.  This is important
4492 to use with certain servers, such as Microsoft Internet Explorer, which
4493 expect all their scripts to be NPH.
4494
4495 =head2 CREATING THE HTML DOCUMENT HEADER
4496
4497    print $query->start_html(-title=>'Secrets of the Pyramids',
4498                             -author=>'fred@capricorn.org',
4499                             -base=>'true',
4500                             -target=>'_blank',
4501                             -meta=>{'keywords'=>'pharaoh secret mummy',
4502                                     'copyright'=>'copyright 1996 King Tut'},
4503                             -style=>{'src'=>'/styles/style1.css'},
4504                             -BGCOLOR=>'blue');
4505
4506 After creating the HTTP header, most CGI scripts will start writing
4507 out an HTML document.  The start_html() routine creates the top of the
4508 page, along with a lot of optional information that controls the
4509 page's appearance and behavior.
4510
4511 This method returns a canned HTML header and the opening <body> tag.
4512 All parameters are optional.  In the named parameter form, recognized
4513 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4514 (see below for the explanation).  Any additional parameters you
4515 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4516 to the <body> tag.  Additional parameters must be proceeded by a
4517 hyphen.
4518
4519 The argument B<-xbase> allows you to provide an HREF for the <base> tag
4520 different from the current location, as in
4521
4522     -xbase=>"http://home.mcom.com/"
4523
4524 All relative links will be interpreted relative to this tag.
4525
4526 The argument B<-target> allows you to provide a default target frame
4527 for all the links and fill-out forms on the page.  B<This is a
4528 non-standard HTTP feature which only works with Netscape browsers!>
4529 See the Netscape documentation on frames for details of how to
4530 manipulate this.
4531
4532     -target=>"answer_window"
4533
4534 All relative links will be interpreted relative to this tag.
4535 You add arbitrary meta information to the header with the B<-meta>
4536 argument.  This argument expects a reference to an associative array
4537 containing name/value pairs of meta information.  These will be turned
4538 into a series of header <meta> tags that look something like this:
4539
4540     <meta name="keywords" content="pharaoh secret mummy">
4541     <meta name="description" content="copyright 1996 King Tut">
4542
4543 To create an HTTP-EQUIV type of <meta> tag, use B<-head>, described
4544 below.
4545
4546 The B<-style> argument is used to incorporate cascading stylesheets
4547 into your code.  See the section on CASCADING STYLESHEETS for more
4548 information.
4549
4550 The B<-lang> argument is used to incorporate a language attribute into
4551 the <html> tag.  The default if not specified is "en-US" for US
4552 English.  For example:
4553
4554     print $q->start_html(-lang=>'fr-CA');
4555
4556 The B<-encoding> argument can be used to specify the character set for
4557 XHTML.  It defaults to iso-8859-1 if not specified.
4558
4559 You can place other arbitrary HTML elements to the <head> section with the
4560 B<-head> tag.  For example, to place the rarely-used <link> element in the
4561 head section, use this:
4562
4563     print start_html(-head=>Link({-rel=>'next',
4564                                   -href=>'http://www.capricorn.com/s2.html'}));
4565
4566 To incorporate multiple HTML elements into the <head> section, just pass an
4567 array reference:
4568
4569     print start_html(-head=>[ 
4570                              Link({-rel=>'next',
4571                                    -href=>'http://www.capricorn.com/s2.html'}),
4572                              Link({-rel=>'previous',
4573                                    -href=>'http://www.capricorn.com/s1.html'})
4574                              ]
4575                      );
4576
4577 And here's how to create an HTTP-EQUIV <meta> tag:
4578
4579       print start_html(-head=>meta({-http_equiv => 'Content-Type',
4580                                     -content    => 'text/html'}))
4581
4582
4583 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4584 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4585 to add Netscape JavaScript calls to your pages.  B<-script> should
4586 point to a block of text containing JavaScript function definitions.
4587 This block will be placed within a <script> block inside the HTML (not
4588 HTTP) header.  The block is placed in the header in order to give your
4589 page a fighting chance of having all its JavaScript functions in place
4590 even if the user presses the stop button before the page has loaded
4591 completely.  CGI.pm attempts to format the script in such a way that
4592 JavaScript-naive browsers will not choke on the code: unfortunately
4593 there are some browsers, such as Chimera for Unix, that get confused
4594 by it nevertheless.
4595
4596 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4597 code to execute when the page is respectively opened and closed by the
4598 browser.  Usually these parameters are calls to functions defined in the
4599 B<-script> field:
4600
4601       $query = new CGI;
4602       print $query->header;
4603       $JSCRIPT=<<END;
4604       // Ask a silly question
4605       function riddle_me_this() {
4606          var r = prompt("What walks on four legs in the morning, " +
4607                        "two legs in the afternoon, " +
4608                        "and three legs in the evening?");
4609          response(r);
4610       }
4611       // Get a silly answer
4612       function response(answer) {
4613          if (answer == "man")
4614             alert("Right you are!");
4615          else
4616             alert("Wrong!  Guess again.");
4617       }
4618       END
4619       print $query->start_html(-title=>'The Riddle of the Sphinx',
4620                                -script=>$JSCRIPT);
4621
4622 Use the B<-noScript> parameter to pass some HTML text that will be displayed on 
4623 browsers that do not have JavaScript (or browsers where JavaScript is turned
4624 off).
4625
4626 Netscape 3.0 recognizes several attributes of the <script> tag,
4627 including LANGUAGE and SRC.  The latter is particularly interesting,
4628 as it allows you to keep the JavaScript code in a file or CGI script
4629 rather than cluttering up each page with the source.  To use these
4630 attributes pass a HASH reference in the B<-script> parameter containing
4631 one or more of -language, -src, or -code:
4632
4633     print $q->start_html(-title=>'The Riddle of the Sphinx',
4634                          -script=>{-language=>'JAVASCRIPT',
4635                                    -src=>'/javascript/sphinx.js'}
4636                          );
4637
4638     print $q->(-title=>'The Riddle of the Sphinx',
4639                -script=>{-language=>'PERLSCRIPT',
4640                          -code=>'print "hello world!\n;"'}
4641                );
4642
4643
4644 A final feature allows you to incorporate multiple <script> sections into the
4645 header.  Just pass the list of script sections as an array reference.
4646 this allows you to specify different source files for different dialects
4647 of JavaScript.  Example:     
4648
4649      print $q->start_html(-title=>'The Riddle of the Sphinx',
4650                           -script=>[
4651                                     { -language => 'JavaScript1.0',
4652                                       -src      => '/javascript/utilities10.js'
4653                                     },
4654                                     { -language => 'JavaScript1.1',
4655                                       -src      => '/javascript/utilities11.js'
4656                                     },
4657                                     { -language => 'JavaScript1.2',
4658                                       -src      => '/javascript/utilities12.js'
4659                                     },
4660                                     { -language => 'JavaScript28.2',
4661                                       -src      => '/javascript/utilities219.js'
4662                                     }
4663                                  ]
4664                              );
4665
4666 If this looks a bit extreme, take my advice and stick with straight CGI scripting.  
4667
4668 See
4669
4670    http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4671
4672 for more information about JavaScript.
4673
4674 The old-style positional parameters are as follows:
4675
4676 =over 4
4677
4678 =item B<Parameters:>
4679
4680 =item 1.
4681
4682 The title
4683
4684 =item 2.
4685
4686 The author's e-mail address (will create a <link rev="MADE"> tag if present
4687
4688 =item 3.
4689
4690 A 'true' flag if you want to include a <base> tag in the header.  This
4691 helps resolve relative addresses to absolute ones when the document is moved, 
4692 but makes the document hierarchy non-portable.  Use with care!
4693
4694 =item 4, 5, 6...
4695
4696 Any other parameters you want to include in the <body> tag.  This is a good
4697 place to put Netscape extensions, such as colors and wallpaper patterns.
4698
4699 =back
4700
4701 =head2 ENDING THE HTML DOCUMENT:
4702
4703         print $query->end_html
4704
4705 This ends an HTML document by printing the </body></html> tags.
4706
4707 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4708
4709     $myself = $query->self_url;
4710     print q(<a href="$myself">I'm talking to myself.</a>);
4711
4712 self_url() will return a URL, that, when selected, will reinvoke
4713 this script with all its state information intact.  This is most
4714 useful when you want to jump around within the document using
4715 internal anchors but you don't want to disrupt the current contents
4716 of the form(s).  Something like this will do the trick.
4717
4718      $myself = $query->self_url;
4719      print "<a href=\"$myself#table1\">See table 1</a>";
4720      print "<a href=\"$myself#table2\">See table 2</a>";
4721      print "<a href=\"$myself#yourself\">See for yourself</a>";
4722
4723 If you want more control over what's returned, using the B<url()>
4724 method instead.
4725
4726 You can also retrieve the unprocessed query string with query_string():
4727
4728     $the_string = $query->query_string;
4729
4730 =head2 OBTAINING THE SCRIPT'S URL
4731
4732     $full_url      = $query->url();
4733     $full_url      = $query->url(-full=>1);  #alternative syntax
4734     $relative_url  = $query->url(-relative=>1);
4735     $absolute_url  = $query->url(-absolute=>1);
4736     $url_with_path = $query->url(-path_info=>1);
4737     $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4738     $netloc        = $query->url(-base => 1);
4739
4740 B<url()> returns the script's URL in a variety of formats.  Called
4741 without any arguments, it returns the full form of the URL, including
4742 host name and port number
4743
4744     http://your.host.com/path/to/script.cgi
4745
4746 You can modify this format with the following named arguments:
4747
4748 =over 4
4749
4750 =item B<-absolute>
4751
4752 If true, produce an absolute URL, e.g.
4753
4754     /path/to/script.cgi
4755
4756 =item B<-relative>
4757
4758 Produce a relative URL.  This is useful if you want to reinvoke your
4759 script with different parameters. For example:
4760
4761     script.cgi
4762
4763 =item B<-full>
4764
4765 Produce the full URL, exactly as if called without any arguments.
4766 This overrides the -relative and -absolute arguments.
4767
4768 =item B<-path> (B<-path_info>)
4769
4770 Append the additional path information to the URL.  This can be
4771 combined with B<-full>, B<-absolute> or B<-relative>.  B<-path_info>
4772 is provided as a synonym.
4773
4774 =item B<-query> (B<-query_string>)
4775
4776 Append the query string to the URL.  This can be combined with
4777 B<-full>, B<-absolute> or B<-relative>.  B<-query_string> is provided
4778 as a synonym.
4779
4780 =item B<-base>
4781
4782 Generate just the protocol and net location, as in http://www.foo.com:8000
4783
4784 =back
4785
4786 =head2 MIXING POST AND URL PARAMETERS
4787
4788    $color = $query-&gt;url_param('color');
4789
4790 It is possible for a script to receive CGI parameters in the URL as
4791 well as in the fill-out form by creating a form that POSTs to a URL
4792 containing a query string (a "?" mark followed by arguments).  The
4793 B<param()> method will always return the contents of the POSTed
4794 fill-out form, ignoring the URL's query string.  To retrieve URL
4795 parameters, call the B<url_param()> method.  Use it in the same way as
4796 B<param()>.  The main difference is that it allows you to read the
4797 parameters, but not set them.
4798
4799
4800 Under no circumstances will the contents of the URL query string
4801 interfere with similarly-named CGI parameters in POSTed forms.  If you
4802 try to mix a URL query string with a form submitted with the GET
4803 method, the results will not be what you expect.
4804
4805 =head1 CREATING STANDARD HTML ELEMENTS:
4806
4807 CGI.pm defines general HTML shortcut methods for most, if not all of
4808 the HTML 3 and HTML 4 tags.  HTML shortcuts are named after a single
4809 HTML element and return a fragment of HTML text that you can then
4810 print or manipulate as you like.  Each shortcut returns a fragment of
4811 HTML code that you can append to a string, save to a file, or, most
4812 commonly, print out so that it displays in the browser window.
4813
4814 This example shows how to use the HTML methods:
4815
4816    $q = new CGI;
4817    print $q->blockquote(
4818                      "Many years ago on the island of",
4819                      $q->a({href=>"http://crete.org/"},"Crete"),
4820                      "there lived a Minotaur named",
4821                      $q->strong("Fred."),
4822                     ),
4823        $q->hr;
4824
4825 This results in the following HTML code (extra newlines have been
4826 added for readability):
4827
4828    <blockquote>
4829    Many years ago on the island of
4830    <a href="http://crete.org/">Crete</a> there lived
4831    a minotaur named <strong>Fred.</strong> 
4832    </blockquote>
4833    <hr>
4834
4835 If you find the syntax for calling the HTML shortcuts awkward, you can
4836 import them into your namespace and dispense with the object syntax
4837 completely (see the next section for more details):
4838
4839    use CGI ':standard';
4840    print blockquote(
4841       "Many years ago on the island of",
4842       a({href=>"http://crete.org/"},"Crete"),
4843       "there lived a minotaur named",
4844       strong("Fred."),
4845       ),
4846       hr;
4847
4848 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4849
4850 The HTML methods will accept zero, one or multiple arguments.  If you
4851 provide no arguments, you get a single tag:
4852
4853    print hr;    #  <hr>
4854
4855 If you provide one or more string arguments, they are concatenated
4856 together with spaces and placed between opening and closing tags:
4857
4858    print h1("Chapter","1"); # <h1>Chapter 1</h1>"
4859
4860 If the first argument is an associative array reference, then the keys
4861 and values of the associative array become the HTML tag's attributes:
4862
4863    print a({-href=>'fred.html',-target=>'_new'},
4864       "Open a new frame");
4865
4866             <a href="fred.html",target="_new">Open a new frame</a>
4867
4868 You may dispense with the dashes in front of the attribute names if
4869 you prefer:
4870
4871    print img {src=>'fred.gif',align=>'LEFT'};
4872
4873            <img align="LEFT" src="fred.gif">
4874
4875 Sometimes an HTML tag attribute has no argument.  For example, ordered
4876 lists can be marked as COMPACT.  The syntax for this is an argument
4877 that points to an undef string:
4878
4879    print ol({compact=>undef},li('one'),li('two'),li('three'));
4880
4881 Prior to CGI.pm version 2.41, providing an empty ('') string as an
4882 attribute argument was the same as providing undef.  However, this has
4883 changed in order to accommodate those who want to create tags of the form
4884 <img alt="">.  The difference is shown in these two pieces of code:
4885
4886      CODE                   RESULT
4887      img({alt=>undef})      <img alt>
4888      img({alt=>''})         <img alt="">
4889
4890 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
4891
4892 One of the cool features of the HTML shortcuts is that they are
4893 distributive.  If you give them an argument consisting of a
4894 B<reference> to a list, the tag will be distributed across each
4895 element of the list.  For example, here's one way to make an ordered
4896 list:
4897
4898    print ul(
4899              li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
4900            );
4901
4902 This example will result in HTML output that looks like this:
4903
4904    <ul>
4905      <li type="disc">Sneezy</li>
4906      <li type="disc">Doc</li>
4907      <li type="disc">Sleepy</li>
4908      <li type="disc">Happy</li>
4909    </ul>
4910
4911 This is extremely useful for creating tables.  For example:
4912
4913    print table({-border=>undef},
4914            caption('When Should You Eat Your Vegetables?'),
4915            Tr({-align=>CENTER,-valign=>TOP},
4916            [
4917               th(['Vegetable', 'Breakfast','Lunch','Dinner']),
4918               td(['Tomatoes' , 'no', 'yes', 'yes']),
4919               td(['Broccoli' , 'no', 'no',  'yes']),
4920               td(['Onions'   , 'yes','yes', 'yes'])
4921            ]
4922            )
4923         );
4924
4925 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
4926
4927 Consider this bit of code:
4928
4929    print blockquote(em('Hi'),'mom!'));
4930
4931 It will ordinarily return the string that you probably expect, namely:
4932
4933    <blockquote><em>Hi</em> mom!</blockquote>
4934
4935 Note the space between the element "Hi" and the element "mom!".
4936 CGI.pm puts the extra space there using array interpolation, which is
4937 controlled by the magic $" variable.  Sometimes this extra space is
4938 not what you want, for example, when you are trying to align a series
4939 of images.  In this case, you can simply change the value of $" to an
4940 empty string.
4941
4942    {
4943       local($") = '';
4944       print blockquote(em('Hi'),'mom!'));
4945     }
4946
4947 I suggest you put the code in a block as shown here.  Otherwise the
4948 change to $" will affect all subsequent code until you explicitly
4949 reset it.
4950
4951 =head2 NON-STANDARD HTML SHORTCUTS
4952
4953 A few HTML tags don't follow the standard pattern for various
4954 reasons.  
4955
4956 B<comment()> generates an HTML comment (<!-- comment -->).  Call it
4957 like
4958
4959     print comment('here is my comment');
4960
4961 Because of conflicts with built-in Perl functions, the following functions
4962 begin with initial caps:
4963
4964     Select
4965     Tr
4966     Link
4967     Delete
4968     Accept
4969     Sub
4970
4971 In addition, start_html(), end_html(), start_form(), end_form(),
4972 start_multipart_form() and all the fill-out form tags are special.
4973 See their respective sections.
4974
4975 =head2 AUTOESCAPING HTML
4976
4977 By default, all HTML that is emitted by the form-generating functions
4978 is passed through a function called escapeHTML():
4979
4980 =over 4
4981
4982 =item $escaped_string = escapeHTML("unescaped string");
4983
4984 Escape HTML formatting characters in a string.
4985
4986 =back
4987
4988 Provided that you have specified a character set of ISO-8859-1 (the
4989 default), the standard HTML escaping rules will be used.  The "<"
4990 character becomes "&lt;", ">" becomes "&gt;", "&" becomes "&amp;", and
4991 the quote character becomes "&quot;".  In addition, the hexadecimal
4992 0x8b and 0x9b characters, which some browsers incorrectly interpret
4993 as the left and right angle-bracket characters, are replaced by their
4994 numeric character entities ("&#8249" and "&#8250;").  If you manually change
4995 the charset, either by calling the charset() method explicitly or by
4996 passing a -charset argument to header(), then B<all> characters will
4997 be replaced by their numeric entities, since CGI.pm has no lookup
4998 table for all the possible encodings.
4999
5000 The automatic escaping does not apply to other shortcuts, such as
5001 h1().  You should call escapeHTML() yourself on untrusted data in
5002 order to protect your pages against nasty tricks that people may enter
5003 into guestbooks, etc..  To change the character set, use charset().
5004 To turn autoescaping off completely, use autoEscape(0):
5005
5006 =over 4
5007
5008 =item $charset = charset([$charset]);
5009
5010 Get or set the current character set.
5011
5012 =item $flag = autoEscape([$flag]);
5013
5014 Get or set the value of the autoescape flag.
5015
5016 =back
5017
5018 =head2 PRETTY-PRINTING HTML
5019
5020 By default, all the HTML produced by these functions comes out as one
5021 long line without carriage returns or indentation. This is yuck, but
5022 it does reduce the size of the documents by 10-20%.  To get
5023 pretty-printed output, please use L<CGI::Pretty>, a subclass
5024 contributed by Brian Paulsen.
5025
5026 =head1 CREATING FILL-OUT FORMS:
5027
5028 I<General note>  The various form-creating methods all return strings
5029 to the caller, containing the tag or tags that will create the requested
5030 form element.  You are responsible for actually printing out these strings.
5031 It's set up this way so that you can place formatting tags
5032 around the form elements.
5033
5034 I<Another note> The default values that you specify for the forms are only
5035 used the B<first> time the script is invoked (when there is no query
5036 string).  On subsequent invocations of the script (when there is a query
5037 string), the former values are used even if they are blank.  
5038
5039 If you want to change the value of a field from its previous value, you have two
5040 choices:
5041
5042 (1) call the param() method to set it.
5043
5044 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
5045 This forces the default value to be used, regardless of the previous value:
5046
5047    print $query->textfield(-name=>'field_name',
5048                            -default=>'starting value',
5049                            -override=>1,
5050                            -size=>50,
5051                            -maxlength=>80);
5052
5053 I<Yet another note> By default, the text and labels of form elements are
5054 escaped according to HTML rules.  This means that you can safely use
5055 "<CLICK ME>" as the label for a button.  However, it also interferes with
5056 your ability to incorporate special HTML character sequences, such as &Aacute;,
5057 into your fields.  If you wish to turn off automatic escaping, call the
5058 autoEscape() method with a false value immediately after creating the CGI object:
5059
5060    $query = new CGI;
5061    $query->autoEscape(undef);
5062
5063 =head2 CREATING AN ISINDEX TAG
5064
5065    print $query->isindex(-action=>$action);
5066
5067          -or-
5068
5069    print $query->isindex($action);
5070
5071 Prints out an <isindex> tag.  Not very exciting.  The parameter
5072 -action specifies the URL of the script to process the query.  The
5073 default is to process the query with the current script.
5074
5075 =head2 STARTING AND ENDING A FORM
5076
5077     print $query->start_form(-method=>$method,
5078                             -action=>$action,
5079                             -enctype=>$encoding);
5080       <... various form stuff ...>
5081     print $query->endform;
5082
5083         -or-
5084
5085     print $query->start_form($method,$action,$encoding);
5086       <... various form stuff ...>
5087     print $query->endform;
5088
5089 start_form() will return a <form> tag with the optional method,
5090 action and form encoding that you specify.  The defaults are:
5091
5092     method: POST
5093     action: this script
5094     enctype: application/x-www-form-urlencoded
5095
5096 endform() returns the closing </form> tag.  
5097
5098 Start_form()'s enctype argument tells the browser how to package the various
5099 fields of the form before sending the form to the server.  Two
5100 values are possible:
5101
5102 B<Note:> This method was previously named startform(), and startform()
5103 is still recognized as an alias.
5104
5105 =over 4
5106
5107 =item B<application/x-www-form-urlencoded>
5108
5109 This is the older type of encoding used by all browsers prior to
5110 Netscape 2.0.  It is compatible with many CGI scripts and is
5111 suitable for short fields containing text data.  For your
5112 convenience, CGI.pm stores the name of this encoding
5113 type in B<&CGI::URL_ENCODED>.
5114
5115 =item B<multipart/form-data>
5116
5117 This is the newer type of encoding introduced by Netscape 2.0.
5118 It is suitable for forms that contain very large fields or that
5119 are intended for transferring binary data.  Most importantly,
5120 it enables the "file upload" feature of Netscape 2.0 forms.  For
5121 your convenience, CGI.pm stores the name of this encoding type
5122 in B<&CGI::MULTIPART>
5123
5124 Forms that use this type of encoding are not easily interpreted
5125 by CGI scripts unless they use CGI.pm or another library designed
5126 to handle them.
5127
5128 =back
5129
5130 For compatibility, the start_form() method uses the older form of
5131 encoding by default.  If you want to use the newer form of encoding
5132 by default, you can call B<start_multipart_form()> instead of
5133 B<start_form()>.
5134
5135 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
5136 for use with JavaScript.  The -name parameter gives the
5137 form a name so that it can be identified and manipulated by
5138 JavaScript functions.  -onSubmit should point to a JavaScript
5139 function that will be executed just before the form is submitted to your
5140 server.  You can use this opportunity to check the contents of the form 
5141 for consistency and completeness.  If you find something wrong, you
5142 can put up an alert box or maybe fix things up yourself.  You can 
5143 abort the submission by returning false from this function.  
5144
5145 Usually the bulk of JavaScript functions are defined in a <script>
5146 block in the HTML header and -onSubmit points to one of these function
5147 call.  See start_html() for details.
5148
5149 =head2 CREATING A TEXT FIELD
5150
5151     print $query->textfield(-name=>'field_name',
5152                             -default=>'starting value',
5153                             -size=>50,
5154                             -maxlength=>80);
5155         -or-
5156
5157     print $query->textfield('field_name','starting value',50,80);
5158
5159 textfield() will return a text input field.  
5160
5161 =over 4
5162
5163 =item B<Parameters>
5164
5165 =item 1.
5166
5167 The first parameter is the required name for the field (-name).  
5168
5169 =item 2.
5170
5171 The optional second parameter is the default starting value for the field
5172 contents (-default).  
5173
5174 =item 3.
5175
5176 The optional third parameter is the size of the field in
5177       characters (-size).
5178
5179 =item 4.
5180
5181 The optional fourth parameter is the maximum number of characters the
5182       field will accept (-maxlength).
5183
5184 =back
5185
5186 As with all these methods, the field will be initialized with its 
5187 previous contents from earlier invocations of the script.
5188 When the form is processed, the value of the text field can be
5189 retrieved with:
5190
5191        $value = $query->param('foo');
5192
5193 If you want to reset it from its initial value after the script has been
5194 called once, you can do so like this:
5195
5196        $query->param('foo',"I'm taking over this value!");
5197
5198 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5199 value, you can force its current value by using the -override (alias -force)
5200 parameter:
5201
5202     print $query->textfield(-name=>'field_name',
5203                             -default=>'starting value',
5204                             -override=>1,
5205                             -size=>50,
5206                             -maxlength=>80);
5207
5208 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5209 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5210 parameters to register JavaScript event handlers.  The onChange
5211 handler will be called whenever the user changes the contents of the
5212 text field.  You can do text validation if you like.  onFocus and
5213 onBlur are called respectively when the insertion point moves into and
5214 out of the text field.  onSelect is called when the user changes the
5215 portion of the text that is selected.
5216
5217 =head2 CREATING A BIG TEXT FIELD
5218
5219    print $query->textarea(-name=>'foo',
5220                           -default=>'starting value',
5221                           -rows=>10,
5222                           -columns=>50);
5223
5224         -or
5225
5226    print $query->textarea('foo','starting value',10,50);
5227
5228 textarea() is just like textfield, but it allows you to specify
5229 rows and columns for a multiline text entry box.  You can provide
5230 a starting value for the field, which can be long and contain
5231 multiple lines.
5232
5233 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5234 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5235 recognized.  See textfield().
5236
5237 =head2 CREATING A PASSWORD FIELD
5238
5239    print $query->password_field(-name=>'secret',
5240                                 -value=>'starting value',
5241                                 -size=>50,
5242                                 -maxlength=>80);
5243         -or-
5244
5245    print $query->password_field('secret','starting value',50,80);
5246
5247 password_field() is identical to textfield(), except that its contents 
5248 will be starred out on the web page.
5249
5250 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5251 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5252 recognized.  See textfield().
5253
5254 =head2 CREATING A FILE UPLOAD FIELD
5255
5256     print $query->filefield(-name=>'uploaded_file',
5257                             -default=>'starting value',
5258                             -size=>50,
5259                             -maxlength=>80);
5260         -or-
5261
5262     print $query->filefield('uploaded_file','starting value',50,80);
5263
5264 filefield() will return a file upload field for Netscape 2.0 browsers.
5265 In order to take full advantage of this I<you must use the new 
5266 multipart encoding scheme> for the form.  You can do this either
5267 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5268 or by calling the new method B<start_multipart_form()> instead of
5269 vanilla B<start_form()>.
5270
5271 =over 4
5272
5273 =item B<Parameters>
5274
5275 =item 1.
5276
5277 The first parameter is the required name for the field (-name).  
5278
5279 =item 2.
5280
5281 The optional second parameter is the starting value for the field contents
5282 to be used as the default file name (-default).
5283
5284 For security reasons, browsers don't pay any attention to this field,
5285 and so the starting value will always be blank.  Worse, the field
5286 loses its "sticky" behavior and forgets its previous contents.  The
5287 starting value field is called for in the HTML specification, however,
5288 and possibly some browser will eventually provide support for it.
5289
5290 =item 3.
5291
5292 The optional third parameter is the size of the field in
5293 characters (-size).
5294
5295 =item 4.
5296
5297 The optional fourth parameter is the maximum number of characters the
5298 field will accept (-maxlength).
5299
5300 =back
5301
5302 When the form is processed, you can retrieve the entered filename
5303 by calling param():
5304
5305        $filename = $query->param('uploaded_file');
5306
5307 Different browsers will return slightly different things for the
5308 name.  Some browsers return the filename only.  Others return the full
5309 path to the file, using the path conventions of the user's machine.
5310 Regardless, the name returned is always the name of the file on the
5311 I<user's> machine, and is unrelated to the name of the temporary file
5312 that CGI.pm creates during upload spooling (see below).
5313
5314 The filename returned is also a file handle.  You can read the contents
5315 of the file using standard Perl file reading calls:
5316
5317         # Read a text file and print it out
5318         while (<$filename>) {
5319            print;
5320         }
5321
5322         # Copy a binary file to somewhere safe
5323         open (OUTFILE,">>/usr/local/web/users/feedback");
5324         while ($bytesread=read($filename,$buffer,1024)) {
5325            print OUTFILE $buffer;
5326         }
5327
5328 However, there are problems with the dual nature of the upload fields.
5329 If you C<use strict>, then Perl will complain when you try to use a
5330 string as a filehandle.  You can get around this by placing the file
5331 reading code in a block containing the C<no strict> pragma.  More
5332 seriously, it is possible for the remote user to type garbage into the
5333 upload field, in which case what you get from param() is not a
5334 filehandle at all, but a string.
5335
5336 To be safe, use the I<upload()> function (new in version 2.47).  When
5337 called with the name of an upload field, I<upload()> returns a
5338 filehandle, or undef if the parameter is not a valid filehandle.
5339
5340      $fh = $query->upload('uploaded_file');
5341      while (<$fh>) {
5342            print;
5343      }
5344
5345 In an array context, upload() will return an array of filehandles.
5346 This makes it possible to create forms that use the same name for
5347 multiple upload fields.
5348
5349 This is the recommended idiom.
5350
5351 When a file is uploaded the browser usually sends along some
5352 information along with it in the format of headers.  The information
5353 usually includes the MIME content type.  Future browsers may send
5354 other information as well (such as modification date and size). To
5355 retrieve this information, call uploadInfo().  It returns a reference to
5356 an associative array containing all the document headers.
5357
5358        $filename = $query->param('uploaded_file');
5359        $type = $query->uploadInfo($filename)->{'Content-Type'};
5360        unless ($type eq 'text/html') {
5361           die "HTML FILES ONLY!";
5362        }
5363
5364 If you are using a machine that recognizes "text" and "binary" data
5365 modes, be sure to understand when and how to use them (see the Camel book).  
5366 Otherwise you may find that binary files are corrupted during file
5367 uploads.
5368
5369 There are occasionally problems involving parsing the uploaded file.
5370 This usually happens when the user presses "Stop" before the upload is
5371 finished.  In this case, CGI.pm will return undef for the name of the
5372 uploaded file and set I<cgi_error()> to the string "400 Bad request
5373 (malformed multipart POST)".  This error message is designed so that
5374 you can incorporate it into a status code to be sent to the browser.
5375 Example:
5376
5377    $file = $query->upload('uploaded_file');
5378    if (!$file && $query->cgi_error) {
5379       print $query->header(-status=>$query->cgi_error);
5380       exit 0;
5381    }
5382
5383 You are free to create a custom HTML page to complain about the error,
5384 if you wish.
5385
5386 If you are using CGI.pm on a Windows platform and find that binary
5387 files get slightly larger when uploaded but that text files remain the
5388 same, then you have forgotten to activate binary mode on the output
5389 filehandle.  Be sure to call binmode() on any handle that you create
5390 to write the uploaded file to disk.
5391
5392 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5393 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5394 recognized.  See textfield() for details.
5395
5396 =head2 CREATING A POPUP MENU
5397
5398    print $query->popup_menu('menu_name',
5399                             ['eenie','meenie','minie'],
5400                             'meenie');
5401
5402       -or-
5403
5404    %labels = ('eenie'=>'your first choice',
5405               'meenie'=>'your second choice',
5406               'minie'=>'your third choice');
5407    %attributes = ('eenie'=>{'class'=>'class of first choice'});
5408    print $query->popup_menu('menu_name',
5409                             ['eenie','meenie','minie'],
5410           'meenie',\%labels,\%attributes);
5411
5412         -or (named parameter style)-
5413
5414    print $query->popup_menu(-name=>'menu_name',
5415                             -values=>['eenie','meenie','minie'],
5416                             -default=>'meenie',
5417           -labels=>\%labels,
5418           -attributes=>\%attributes);
5419
5420 popup_menu() creates a menu.
5421
5422 =over 4
5423
5424 =item 1.
5425
5426 The required first argument is the menu's name (-name).
5427
5428 =item 2.
5429
5430 The required second argument (-values) is an array B<reference>
5431 containing the list of menu items in the menu.  You can pass the
5432 method an anonymous array, as shown in the example, or a reference to
5433 a named array, such as "\@foo".
5434
5435 =item 3.
5436
5437 The optional third parameter (-default) is the name of the default
5438 menu choice.  If not specified, the first item will be the default.
5439 The values of the previous choice will be maintained across queries.
5440
5441 =item 4.
5442
5443 The optional fourth parameter (-labels) is provided for people who
5444 want to use different values for the user-visible label inside the
5445 popup menu and the value returned to your script.  It's a pointer to an
5446 associative array relating menu values to user-visible labels.  If you
5447 leave this parameter blank, the menu values will be displayed by
5448 default.  (You can also leave a label undefined if you want to).
5449
5450 =item 5.
5451
5452 The optional fifth parameter (-attributes) is provided to assign
5453 any of the common HTML attributes to an individual menu item. It's
5454 a pointer to an associative array relating menu values to another
5455 associative array with the attribute's name as the key and the
5456 attribute's value as the value.
5457
5458 =back
5459
5460 When the form is processed, the selected value of the popup menu can
5461 be retrieved using:
5462
5463       $popup_menu_value = $query->param('menu_name');
5464
5465 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5466 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5467 B<-onBlur>.  See the textfield() section for details on when these
5468 handlers are called.
5469
5470 =head2 CREATING AN OPTION GROUP
5471
5472 Named parameter style
5473
5474   print $query->popup_menu(-name=>'menu_name',
5475                   -values=>[qw/eenie meenie minie/,
5476                             $q->optgroup(-name=>'optgroup_name',
5477                                          -values ['moe','catch'],
5478                                          -attributes=>{'catch'=>{'class'=>'red'}}),
5479                   -labels=>{'eenie'=>'one',
5480                             'meenie'=>'two',
5481                             'minie'=>'three'},
5482                   -default=>'meenie');
5483
5484   Old style
5485   print $query->popup_menu('menu_name',
5486                   ['eenie','meenie','minie',
5487                    $q->optgroup('optgroup_name', ['moe', 'catch'],
5488                          {'catch'=>{'class'=>'red'}})],'meenie',
5489                   {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
5490
5491 optgroup creates an option group within a popup menu.
5492
5493 =over 4
5494
5495 =item 1.
5496
5497 The required first argument (B<-name>) is the label attribute of the
5498 optgroup and is B<not> inserted in the parameter list of the query.
5499
5500 =item 2.
5501
5502 The required second argument (B<-values>)  is an array reference
5503 containing the list of menu items in the menu.  You can pass the
5504 method an anonymous array, as shown in the example, or a reference
5505 to a named array, such as \@foo.  If you pass a HASH reference,
5506 the keys will be used for the menu values, and the values will be
5507 used for the menu labels (see -labels below).
5508
5509 =item 3.
5510
5511 The optional third parameter (B<-labels>) allows you to pass a reference
5512 to an associative array containing user-visible labels for one or more
5513 of the menu items.  You can use this when you want the user to see one
5514 menu string, but have the browser return your program a different one.
5515 If you don't specify this, the value string will be used instead
5516 ("eenie", "meenie" and "minie" in this example).  This is equivalent
5517 to using a hash reference for the -values parameter.
5518
5519 =item 4.
5520
5521 An optional fourth parameter (B<-labeled>) can be set to a true value
5522 and indicates that the values should be used as the label attribute
5523 for each option element within the optgroup.
5524
5525 =item 5.
5526
5527 An optional fifth parameter (-novals) can be set to a true value and
5528 indicates to suppress the val attribut in each option element within
5529 the optgroup.
5530
5531 See the discussion on optgroup at W3C
5532 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
5533 for details.
5534
5535 =item 6.
5536
5537 An optional sixth parameter (-attributes) is provided to assign
5538 any of the common HTML attributes to an individual menu item. It's
5539 a pointer to an associative array relating menu values to another
5540 associative array with the attribute's name as the key and the
5541 attribute's value as the value.
5542
5543 =head2 CREATING A SCROLLING LIST
5544
5545    print $query->scrolling_list('list_name',
5546                                 ['eenie','meenie','minie','moe'],
5547         ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
5548       -or-
5549
5550    print $query->scrolling_list('list_name',
5551                                 ['eenie','meenie','minie','moe'],
5552                                 ['eenie','moe'],5,'true',
5553         \%labels,%attributes);
5554
5555         -or-
5556
5557    print $query->scrolling_list(-name=>'list_name',
5558                                 -values=>['eenie','meenie','minie','moe'],
5559                                 -default=>['eenie','moe'],
5560                                 -size=>5,
5561                                 -multiple=>'true',
5562         -labels=>\%labels,
5563         -attributes=>\%attributes);
5564
5565 scrolling_list() creates a scrolling list.  
5566
5567 =over 4
5568
5569 =item B<Parameters:>
5570
5571 =item 1.
5572
5573 The first and second arguments are the list name (-name) and values
5574 (-values).  As in the popup menu, the second argument should be an
5575 array reference.
5576
5577 =item 2.
5578
5579 The optional third argument (-default) can be either a reference to a
5580 list containing the values to be selected by default, or can be a
5581 single value to select.  If this argument is missing or undefined,
5582 then nothing is selected when the list first appears.  In the named
5583 parameter version, you can use the synonym "-defaults" for this
5584 parameter.
5585
5586 =item 3.
5587
5588 The optional fourth argument is the size of the list (-size).
5589
5590 =item 4.
5591
5592 The optional fifth argument can be set to true to allow multiple
5593 simultaneous selections (-multiple).  Otherwise only one selection
5594 will be allowed at a time.
5595
5596 =item 5.
5597
5598 The optional sixth argument is a pointer to an associative array
5599 containing long user-visible labels for the list items (-labels).
5600 If not provided, the values will be displayed.
5601
5602 =item 6.
5603
5604 The optional sixth parameter (-attributes) is provided to assign
5605 any of the common HTML attributes to an individual menu item. It's
5606 a pointer to an associative array relating menu values to another
5607 associative array with the attribute's name as the key and the
5608 attribute's value as the value.
5609
5610 When this form is processed, all selected list items will be returned as
5611 a list under the parameter name 'list_name'.  The values of the
5612 selected items can be retrieved with:
5613
5614       @selected = $query->param('list_name');
5615
5616 =back
5617
5618 JAVASCRIPTING: scrolling_list() recognizes the following event
5619 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5620 and B<-onBlur>.  See textfield() for the description of when these
5621 handlers are called.
5622
5623 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5624
5625    print $query->checkbox_group(-name=>'group_name',
5626                                 -values=>['eenie','meenie','minie','moe'],
5627                                 -default=>['eenie','moe'],
5628                                 -linebreak=>'true',
5629         -labels=>\%labels,
5630         -attributes=>\%attributes);
5631
5632    print $query->checkbox_group('group_name',
5633                                 ['eenie','meenie','minie','moe'],
5634         ['eenie','moe'],'true',\%labels,
5635         {'moe'=>{'class'=>'red'}});
5636
5637    HTML3-COMPATIBLE BROWSERS ONLY:
5638
5639    print $query->checkbox_group(-name=>'group_name',
5640                                 -values=>['eenie','meenie','minie','moe'],
5641                                 -rows=2,-columns=>2);
5642
5643
5644 checkbox_group() creates a list of checkboxes that are related
5645 by the same name.
5646
5647 =over 4
5648
5649 =item B<Parameters:>
5650
5651 =item 1.
5652
5653 The first and second arguments are the checkbox name and values,
5654 respectively (-name and -values).  As in the popup menu, the second
5655 argument should be an array reference.  These values are used for the
5656 user-readable labels printed next to the checkboxes as well as for the
5657 values passed to your script in the query string.
5658
5659 =item 2.
5660
5661 The optional third argument (-default) can be either a reference to a
5662 list containing the values to be checked by default, or can be a
5663 single value to checked.  If this argument is missing or undefined,
5664 then nothing is selected when the list first appears.
5665
5666 =item 3.
5667
5668 The optional fourth argument (-linebreak) can be set to true to place
5669 line breaks between the checkboxes so that they appear as a vertical
5670 list.  Otherwise, they will be strung together on a horizontal line.
5671
5672 =item 4.
5673
5674 The optional fifth argument is a pointer to an associative array
5675 relating the checkbox values to the user-visible labels that will
5676 be printed next to them (-labels).  If not provided, the values will
5677 be used as the default.
5678
5679 =item 5.
5680
5681 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5682 the optional parameters B<-rows>, and B<-columns>.  These parameters
5683 cause checkbox_group() to return an HTML3 compatible table containing
5684 the checkbox group formatted with the specified number of rows and
5685 columns.  You can provide just the -columns parameter if you wish;
5686 checkbox_group will calculate the correct number of rows for you.
5687
5688 =item 6.
5689
5690 The optional sixth parameter (-attributes) is provided to assign
5691 any of the common HTML attributes to an individual menu item. It's
5692 a pointer to an associative array relating menu values to another
5693 associative array with the attribute's name as the key and the
5694 attribute's value as the value.
5695
5696 To include row and column headings in the returned table, you
5697 can use the B<-rowheaders> and B<-colheaders> parameters.  Both
5698 of these accept a pointer to an array of headings to use.
5699 The headings are just decorative.  They don't reorganize the
5700 interpretation of the checkboxes -- they're still a single named
5701 unit.
5702
5703 =back
5704
5705 When the form is processed, all checked boxes will be returned as
5706 a list under the parameter name 'group_name'.  The values of the
5707 "on" checkboxes can be retrieved with:
5708
5709       @turned_on = $query->param('group_name');
5710
5711 The value returned by checkbox_group() is actually an array of button
5712 elements.  You can capture them and use them within tables, lists,
5713 or in other creative ways:
5714
5715     @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
5716     &use_in_creative_way(@h);
5717
5718 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
5719 parameter.  This specifies a JavaScript code fragment or
5720 function call to be executed every time the user clicks on
5721 any of the buttons in the group.  You can retrieve the identity
5722 of the particular button clicked on using the "this" variable.
5723
5724 =head2 CREATING A STANDALONE CHECKBOX
5725
5726     print $query->checkbox(-name=>'checkbox_name',
5727                            -checked=>1,
5728                            -value=>'ON',
5729                            -label=>'CLICK ME');
5730
5731         -or-
5732
5733     print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
5734
5735 checkbox() is used to create an isolated checkbox that isn't logically
5736 related to any others.
5737
5738 =over 4
5739
5740 =item B<Parameters:>
5741
5742 =item 1.
5743
5744 The first parameter is the required name for the checkbox (-name).  It
5745 will also be used for the user-readable label printed next to the
5746 checkbox.
5747
5748 =item 2.
5749
5750 The optional second parameter (-checked) specifies that the checkbox
5751 is turned on by default.  Synonyms are -selected and -on.
5752
5753 =item 3.
5754
5755 The optional third parameter (-value) specifies the value of the
5756 checkbox when it is checked.  If not provided, the word "on" is
5757 assumed.
5758
5759 =item 4.
5760
5761 The optional fourth parameter (-label) is the user-readable label to
5762 be attached to the checkbox.  If not provided, the checkbox name is
5763 used.
5764
5765 =back
5766
5767 The value of the checkbox can be retrieved using:
5768
5769     $turned_on = $query->param('checkbox_name');
5770
5771 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5772 parameter.  See checkbox_group() for further details.
5773
5774 =head2 CREATING A RADIO BUTTON GROUP
5775
5776    print $query->radio_group(-name=>'group_name',
5777                              -values=>['eenie','meenie','minie'],
5778                              -default=>'meenie',
5779                              -linebreak=>'true',
5780            -labels=>\%labels,
5781            -attributes=>\%attributes);
5782
5783         -or-
5784
5785    print $query->radio_group('group_name',['eenie','meenie','minie'],
5786             'meenie','true',\%labels,\%attributes);
5787
5788
5789    HTML3-COMPATIBLE BROWSERS ONLY:
5790
5791    print $query->radio_group(-name=>'group_name',
5792                              -values=>['eenie','meenie','minie','moe'],
5793                              -rows=2,-columns=>2);
5794
5795 radio_group() creates a set of logically-related radio buttons
5796 (turning one member of the group on turns the others off)
5797
5798 =over 4
5799
5800 =item B<Parameters:>
5801
5802 =item 1.
5803
5804 The first argument is the name of the group and is required (-name).
5805
5806 =item 2.
5807
5808 The second argument (-values) is the list of values for the radio
5809 buttons.  The values and the labels that appear on the page are
5810 identical.  Pass an array I<reference> in the second argument, either
5811 using an anonymous array, as shown, or by referencing a named array as
5812 in "\@foo".
5813
5814 =item 3.
5815
5816 The optional third parameter (-default) is the name of the default
5817 button to turn on. If not specified, the first item will be the
5818 default.  You can provide a nonexistent button name, such as "-" to
5819 start up with no buttons selected.
5820
5821 =item 4.
5822
5823 The optional fourth parameter (-linebreak) can be set to 'true' to put
5824 line breaks between the buttons, creating a vertical list.
5825
5826 =item 5.
5827
5828 The optional fifth parameter (-labels) is a pointer to an associative
5829 array relating the radio button values to user-visible labels to be
5830 used in the display.  If not provided, the values themselves are
5831 displayed.
5832
5833 =item 6.
5834
5835 B<HTML3-compatible browsers> (such as Netscape) can take advantage 
5836 of the optional 
5837 parameters B<-rows>, and B<-columns>.  These parameters cause
5838 radio_group() to return an HTML3 compatible table containing
5839 the radio group formatted with the specified number of rows
5840 and columns.  You can provide just the -columns parameter if you
5841 wish; radio_group will calculate the correct number of rows
5842 for you.
5843
5844 =item 6.
5845
5846 The optional sixth parameter (-attributes) is provided to assign
5847 any of the common HTML attributes to an individual menu item. It's
5848 a pointer to an associative array relating menu values to another
5849 associative array with the attribute's name as the key and the
5850 attribute's value as the value.
5851
5852 To include row and column headings in the returned table, you
5853 can use the B<-rowheader> and B<-colheader> parameters.  Both
5854 of these accept a pointer to an array of headings to use.
5855 The headings are just decorative.  They don't reorganize the
5856 interpretation of the radio buttons -- they're still a single named
5857 unit.
5858
5859 =back
5860
5861 When the form is processed, the selected radio button can
5862 be retrieved using:
5863
5864       $which_radio_button = $query->param('group_name');
5865
5866 The value returned by radio_group() is actually an array of button
5867 elements.  You can capture them and use them within tables, lists,
5868 or in other creative ways:
5869
5870     @h = $query->radio_group(-name=>'group_name',-values=>\@values);
5871     &use_in_creative_way(@h);
5872
5873 =head2 CREATING A SUBMIT BUTTON 
5874
5875    print $query->submit(-name=>'button_name',
5876                         -value=>'value');
5877
5878         -or-
5879
5880    print $query->submit('button_name','value');
5881
5882 submit() will create the query submission button.  Every form
5883 should have one of these.
5884
5885 =over 4
5886
5887 =item B<Parameters:>
5888
5889 =item 1.
5890
5891 The first argument (-name) is optional.  You can give the button a
5892 name if you have several submission buttons in your form and you want
5893 to distinguish between them.  The name will also be used as the
5894 user-visible label.  Be aware that a few older browsers don't deal with this correctly and
5895 B<never> send back a value from a button.
5896
5897 =item 2.
5898
5899 The second argument (-value) is also optional.  This gives the button
5900 a value that will be passed to your script in the query string.
5901
5902 =back
5903
5904 You can figure out which button was pressed by using different
5905 values for each one:
5906
5907      $which_one = $query->param('button_name');
5908
5909 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
5910 parameter.  See checkbox_group() for further details.
5911
5912 =head2 CREATING A RESET BUTTON
5913
5914    print $query->reset
5915
5916 reset() creates the "reset" button.  Note that it restores the
5917 form to its value from the last time the script was called, 
5918 NOT necessarily to the defaults.
5919
5920 Note that this conflicts with the Perl reset() built-in.  Use
5921 CORE::reset() to get the original reset function.
5922
5923 =head2 CREATING A DEFAULT BUTTON
5924
5925    print $query->defaults('button_label')
5926
5927 defaults() creates a button that, when invoked, will cause the
5928 form to be completely reset to its defaults, wiping out all the
5929 changes the user ever made.
5930
5931 =head2 CREATING A HIDDEN FIELD
5932
5933         print $query->hidden(-name=>'hidden_name',
5934                              -default=>['value1','value2'...]);
5935
5936                 -or-
5937
5938         print $query->hidden('hidden_name','value1','value2'...);
5939
5940 hidden() produces a text field that can't be seen by the user.  It
5941 is useful for passing state variable information from one invocation
5942 of the script to the next.
5943
5944 =over 4
5945
5946 =item B<Parameters:>
5947
5948 =item 1.
5949
5950 The first argument is required and specifies the name of this
5951 field (-name).
5952
5953 =item 2.  
5954
5955 The second argument is also required and specifies its value
5956 (-default).  In the named parameter style of calling, you can provide
5957 a single value here or a reference to a whole list
5958
5959 =back
5960
5961 Fetch the value of a hidden field this way:
5962
5963      $hidden_value = $query->param('hidden_name');
5964
5965 Note, that just like all the other form elements, the value of a
5966 hidden field is "sticky".  If you want to replace a hidden field with
5967 some other values after the script has been called once you'll have to
5968 do it manually:
5969
5970      $query->param('hidden_name','new','values','here');
5971
5972 =head2 CREATING A CLICKABLE IMAGE BUTTON
5973
5974      print $query->image_button(-name=>'button_name',
5975                                 -src=>'/source/URL',
5976                                 -align=>'MIDDLE');      
5977
5978         -or-
5979
5980      print $query->image_button('button_name','/source/URL','MIDDLE');
5981
5982 image_button() produces a clickable image.  When it's clicked on the
5983 position of the click is returned to your script as "button_name.x"
5984 and "button_name.y", where "button_name" is the name you've assigned
5985 to it.
5986
5987 JAVASCRIPTING: image_button() recognizes the B<-onClick>
5988 parameter.  See checkbox_group() for further details.
5989
5990 =over 4
5991
5992 =item B<Parameters:>
5993
5994 =item 1.
5995
5996 The first argument (-name) is required and specifies the name of this
5997 field.
5998
5999 =item 2.
6000
6001 The second argument (-src) is also required and specifies the URL
6002
6003 =item 3.
6004
6005 The third option (-align, optional) is an alignment type, and may be
6006 TOP, BOTTOM or MIDDLE
6007
6008 =back
6009
6010 Fetch the value of the button this way:
6011      $x = $query->param('button_name.x');
6012      $y = $query->param('button_name.y');
6013
6014 =head2 CREATING A JAVASCRIPT ACTION BUTTON
6015
6016      print $query->button(-name=>'button_name',
6017                           -value=>'user visible label',
6018                           -onClick=>"do_something()");
6019
6020         -or-
6021
6022      print $query->button('button_name',"do_something()");
6023
6024 button() produces a button that is compatible with Netscape 2.0's
6025 JavaScript.  When it's pressed the fragment of JavaScript code
6026 pointed to by the B<-onClick> parameter will be executed.  On
6027 non-Netscape browsers this form element will probably not even
6028 display.
6029
6030 =head1 HTTP COOKIES
6031
6032 Netscape browsers versions 1.1 and higher, and all versions of
6033 Internet Explorer, support a so-called "cookie" designed to help
6034 maintain state within a browser session.  CGI.pm has several methods
6035 that support cookies.
6036
6037 A cookie is a name=value pair much like the named parameters in a CGI
6038 query string.  CGI scripts create one or more cookies and send
6039 them to the browser in the HTTP header.  The browser maintains a list
6040 of cookies that belong to a particular Web server, and returns them
6041 to the CGI script during subsequent interactions.
6042
6043 In addition to the required name=value pair, each cookie has several
6044 optional attributes:
6045
6046 =over 4
6047
6048 =item 1. an expiration time
6049
6050 This is a time/date string (in a special GMT format) that indicates
6051 when a cookie expires.  The cookie will be saved and returned to your
6052 script until this expiration date is reached if the user exits
6053 the browser and restarts it.  If an expiration date isn't specified, the cookie
6054 will remain active until the user quits the browser.
6055
6056 =item 2. a domain
6057
6058 This is a partial or complete domain name for which the cookie is 
6059 valid.  The browser will return the cookie to any host that matches
6060 the partial domain name.  For example, if you specify a domain name
6061 of ".capricorn.com", then the browser will return the cookie to
6062 Web servers running on any of the machines "www.capricorn.com", 
6063 "www2.capricorn.com", "feckless.capricorn.com", etc.  Domain names
6064 must contain at least two periods to prevent attempts to match
6065 on top level domains like ".edu".  If no domain is specified, then
6066 the browser will only return the cookie to servers on the host the
6067 cookie originated from.
6068
6069 =item 3. a path
6070
6071 If you provide a cookie path attribute, the browser will check it
6072 against your script's URL before returning the cookie.  For example,
6073 if you specify the path "/cgi-bin", then the cookie will be returned
6074 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
6075 and "/cgi-bin/customer_service/complain.pl", but not to the script
6076 "/cgi-private/site_admin.pl".  By default, path is set to "/", which
6077 causes the cookie to be sent to any CGI script on your site.
6078
6079 =item 4. a "secure" flag
6080
6081 If the "secure" attribute is set, the cookie will only be sent to your
6082 script if the CGI request is occurring on a secure channel, such as SSL.
6083
6084 =back
6085
6086 The interface to HTTP cookies is the B<cookie()> method:
6087
6088     $cookie = $query->cookie(-name=>'sessionID',
6089                              -value=>'xyzzy',
6090                              -expires=>'+1h',
6091                              -path=>'/cgi-bin/database',
6092                              -domain=>'.capricorn.org',
6093                              -secure=>1);
6094     print $query->header(-cookie=>$cookie);
6095
6096 B<cookie()> creates a new cookie.  Its parameters include:
6097
6098 =over 4
6099
6100 =item B<-name>
6101
6102 The name of the cookie (required).  This can be any string at all.
6103 Although browsers limit their cookie names to non-whitespace
6104 alphanumeric characters, CGI.pm removes this restriction by escaping
6105 and unescaping cookies behind the scenes.
6106
6107 =item B<-value>
6108
6109 The value of the cookie.  This can be any scalar value,
6110 array reference, or even associative array reference.  For example,
6111 you can store an entire associative array into a cookie this way:
6112
6113         $cookie=$query->cookie(-name=>'family information',
6114                                -value=>\%childrens_ages);
6115
6116 =item B<-path>
6117
6118 The optional partial path for which this cookie will be valid, as described
6119 above.
6120
6121 =item B<-domain>
6122
6123 The optional partial domain for which this cookie will be valid, as described
6124 above.
6125
6126 =item B<-expires>
6127
6128 The optional expiration date for this cookie.  The format is as described 
6129 in the section on the B<header()> method:
6130
6131         "+1h"  one hour from now
6132
6133 =item B<-secure>
6134
6135 If set to true, this cookie will only be used within a secure
6136 SSL session.
6137
6138 =back
6139
6140 The cookie created by cookie() must be incorporated into the HTTP
6141 header within the string returned by the header() method:
6142
6143         print $query->header(-cookie=>$my_cookie);
6144
6145 To create multiple cookies, give header() an array reference:
6146
6147         $cookie1 = $query->cookie(-name=>'riddle_name',
6148                                   -value=>"The Sphynx's Question");
6149         $cookie2 = $query->cookie(-name=>'answers',
6150                                   -value=>\%answers);
6151         print $query->header(-cookie=>[$cookie1,$cookie2]);
6152
6153 To retrieve a cookie, request it by name by calling cookie() method
6154 without the B<-value> parameter:
6155
6156         use CGI;
6157         $query = new CGI;
6158         $riddle = $query->cookie('riddle_name');
6159         %answers = $query->cookie('answers');
6160
6161 Cookies created with a single scalar value, such as the "riddle_name"
6162 cookie, will be returned in that form.  Cookies with array and hash
6163 values can also be retrieved.
6164
6165 The cookie and CGI namespaces are separate.  If you have a parameter
6166 named 'answers' and a cookie named 'answers', the values retrieved by
6167 param() and cookie() are independent of each other.  However, it's
6168 simple to turn a CGI parameter into a cookie, and vice-versa:
6169
6170    # turn a CGI parameter into a cookie
6171    $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
6172    # vice-versa
6173    $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
6174
6175 See the B<cookie.cgi> example script for some ideas on how to use
6176 cookies effectively.
6177
6178 =head1 WORKING WITH FRAMES
6179
6180 It's possible for CGI.pm scripts to write into several browser panels
6181 and windows using the HTML 4 frame mechanism.  There are three
6182 techniques for defining new frames programmatically:
6183
6184 =over 4
6185
6186 =item 1. Create a <Frameset> document
6187
6188 After writing out the HTTP header, instead of creating a standard
6189 HTML document using the start_html() call, create a <frameset> 
6190 document that defines the frames on the page.  Specify your script(s)
6191 (with appropriate parameters) as the SRC for each of the frames.
6192
6193 There is no specific support for creating <frameset> sections 
6194 in CGI.pm, but the HTML is very simple to write.  See the frame
6195 documentation in Netscape's home pages for details 
6196
6197   http://home.netscape.com/assist/net_sites/frames.html
6198
6199 =item 2. Specify the destination for the document in the HTTP header
6200
6201 You may provide a B<-target> parameter to the header() method:
6202
6203     print $q->header(-target=>'ResultsWindow');
6204
6205 This will tell the browser to load the output of your script into the
6206 frame named "ResultsWindow".  If a frame of that name doesn't already
6207 exist, the browser will pop up a new window and load your script's
6208 document into that.  There are a number of magic names that you can
6209 use for targets.  See the frame documents on Netscape's home pages for
6210 details.
6211
6212 =item 3. Specify the destination for the document in the <form> tag
6213
6214 You can specify the frame to load in the FORM tag itself.  With
6215 CGI.pm it looks like this:
6216
6217     print $q->start_form(-target=>'ResultsWindow');
6218
6219 When your script is reinvoked by the form, its output will be loaded
6220 into the frame named "ResultsWindow".  If one doesn't already exist
6221 a new window will be created.
6222
6223 =back
6224
6225 The script "frameset.cgi" in the examples directory shows one way to
6226 create pages in which the fill-out form and the response live in
6227 side-by-side frames.
6228
6229 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
6230
6231 CGI.pm has limited support for HTML3's cascading style sheets (css).
6232 To incorporate a stylesheet into your document, pass the
6233 start_html() method a B<-style> parameter.  The value of this
6234 parameter may be a scalar, in which case it is incorporated directly
6235 into a <style> section, or it may be a hash reference.  In the latter
6236 case you should provide the hash with one or more of B<-src> or
6237 B<-code>.  B<-src> points to a URL where an externally-defined
6238 stylesheet can be found.  B<-code> points to a scalar value to be
6239 incorporated into a <style> section.  Style definitions in B<-code>
6240 override similarly-named ones in B<-src>, hence the name "cascading."
6241
6242 You may also specify the type of the stylesheet by adding the optional
6243 B<-type> parameter to the hash pointed to by B<-style>.  If not
6244 specified, the style defaults to 'text/css'.
6245
6246 To refer to a style within the body of your document, add the
6247 B<-class> parameter to any HTML element:
6248
6249     print h1({-class=>'Fancy'},'Welcome to the Party');
6250
6251 Or define styles on the fly with the B<-style> parameter:
6252
6253     print h1({-style=>'Color: red;'},'Welcome to Hell');
6254
6255 You may also use the new B<span()> element to apply a style to a
6256 section of text:
6257
6258     print span({-style=>'Color: red;'},
6259                h1('Welcome to Hell'),
6260                "Where did that handbasket get to?"
6261                );
6262
6263 Note that you must import the ":html3" definitions to have the
6264 B<span()> method available.  Here's a quick and dirty example of using
6265 CSS's.  See the CSS specification at
6266 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
6267
6268     use CGI qw/:standard :html3/;
6269
6270     #here's a stylesheet incorporated directly into the page
6271     $newStyle=<<END;
6272     <!-- 
6273     P.Tip {
6274         margin-right: 50pt;
6275         margin-left: 50pt;
6276         color: red;
6277     }
6278     P.Alert {
6279         font-size: 30pt;
6280         font-family: sans-serif;
6281       color: red;
6282     }
6283     -->
6284     END
6285     print header();
6286     print start_html( -title=>'CGI with Style',
6287                       -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6288                                -code=>$newStyle}
6289                      );
6290     print h1('CGI with Style'),
6291           p({-class=>'Tip'},
6292             "Better read the cascading style sheet spec before playing with this!"),
6293           span({-style=>'color: magenta'},
6294                "Look Mom, no hands!",
6295                p(),
6296                "Whooo wee!"
6297                );
6298     print end_html;
6299
6300 Pass an array reference to B<-style> in order to incorporate multiple
6301 stylesheets into your document.
6302
6303 =head1 DEBUGGING
6304
6305 If you are running the script from the command line or in the perl
6306 debugger, you can pass the script a list of keywords or
6307 parameter=value pairs on the command line or from standard input (you
6308 don't have to worry about tricking your script into reading from
6309 environment variables).  You can pass keywords like this:
6310
6311     your_script.pl keyword1 keyword2 keyword3
6312
6313 or this:
6314
6315    your_script.pl keyword1+keyword2+keyword3
6316
6317 or this:
6318
6319     your_script.pl name1=value1 name2=value2
6320
6321 or this:
6322
6323     your_script.pl name1=value1&name2=value2
6324
6325 To turn off this feature, use the -no_debug pragma.
6326
6327 To test the POST method, you may enable full debugging with the -debug
6328 pragma.  This will allow you to feed newline-delimited name=value
6329 pairs to the script on standard input.
6330
6331 When debugging, you can use quotes and backslashes to escape 
6332 characters in the familiar shell manner, letting you place
6333 spaces and other funny characters in your parameter=value
6334 pairs:
6335
6336    your_script.pl "name1='I am a long value'" "name2=two\ words"
6337
6338 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6339
6340 The Dump() method produces a string consisting of all the query's
6341 name/value pairs formatted nicely as a nested list.  This is useful
6342 for debugging purposes:
6343
6344     print $query->Dump
6345
6346
6347 Produces something that looks like:
6348
6349     <ul>
6350     <li>name1
6351         <ul>
6352         <li>value1
6353         <li>value2
6354         </ul>
6355     <li>name2
6356         <ul>
6357         <li>value1
6358         </ul>
6359     </ul>
6360
6361 As a shortcut, you can interpolate the entire CGI object into a string
6362 and it will be replaced with the a nice HTML dump shown above:
6363
6364     $query=new CGI;
6365     print "<h2>Current Values</h2> $query\n";
6366
6367 =head1 FETCHING ENVIRONMENT VARIABLES
6368
6369 Some of the more useful environment variables can be fetched
6370 through this interface.  The methods are as follows:
6371
6372 =over 4
6373
6374 =item B<Accept()>
6375
6376 Return a list of MIME types that the remote browser accepts. If you
6377 give this method a single argument corresponding to a MIME type, as in
6378 $query->Accept('text/html'), it will return a floating point value
6379 corresponding to the browser's preference for this type from 0.0
6380 (don't want) to 1.0.  Glob types (e.g. text/*) in the browser's accept
6381 list are handled correctly.
6382
6383 Note that the capitalization changed between version 2.43 and 2.44 in
6384 order to avoid conflict with Perl's accept() function.
6385
6386 =item B<raw_cookie()>
6387
6388 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
6389 Netscape browsers version 1.1 and higher, and all versions of Internet
6390 Explorer.  Cookies have a special format, and this method call just
6391 returns the raw form (?cookie dough).  See cookie() for ways of
6392 setting and retrieving cooked cookies.
6393
6394 Called with no parameters, raw_cookie() returns the packed cookie
6395 structure.  You can separate it into individual cookies by splitting
6396 on the character sequence "; ".  Called with the name of a cookie,
6397 retrieves the B<unescaped> form of the cookie.  You can use the
6398 regular cookie() method to get the names, or use the raw_fetch()
6399 method from the CGI::Cookie module.
6400
6401 =item B<user_agent()>
6402
6403 Returns the HTTP_USER_AGENT variable.  If you give
6404 this method a single argument, it will attempt to
6405 pattern match on it, allowing you to do something
6406 like $query->user_agent(netscape);
6407
6408 =item B<path_info()>
6409
6410 Returns additional path information from the script URL.
6411 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6412 $query->path_info() returning "/additional/stuff".
6413
6414 NOTE: The Microsoft Internet Information Server
6415 is broken with respect to additional path information.  If
6416 you use the Perl DLL library, the IIS server will attempt to
6417 execute the additional path information as a Perl script.
6418 If you use the ordinary file associations mapping, the
6419 path information will be present in the environment, 
6420 but incorrect.  The best thing to do is to avoid using additional
6421 path information in CGI scripts destined for use with IIS.
6422
6423 =item B<path_translated()>
6424
6425 As per path_info() but returns the additional
6426 path information translated into a physical path, e.g.
6427 "/usr/local/etc/httpd/htdocs/additional/stuff".
6428
6429 The Microsoft IIS is broken with respect to the translated
6430 path as well.
6431
6432 =item B<remote_host()>
6433
6434 Returns either the remote host name or IP address.
6435 if the former is unavailable.
6436
6437 =item B<script_name()>
6438
6439 Return the script name as a partial URL, for self-refering
6440 scripts.
6441
6442 =item B<referer()>
6443
6444 Return the URL of the page the browser was viewing
6445 prior to fetching your script.  Not available for all
6446 browsers.
6447
6448 =item B<auth_type ()>
6449
6450 Return the authorization/verification method in use for this
6451 script, if any.
6452
6453 =item B<server_name ()>
6454
6455 Returns the name of the server, usually the machine's host
6456 name.
6457
6458 =item B<virtual_host ()>
6459
6460 When using virtual hosts, returns the name of the host that
6461 the browser attempted to contact
6462
6463 =item B<server_port ()>
6464
6465 Return the port that the server is listening on.
6466
6467 =item B<server_software ()>
6468
6469 Returns the server software and version number.
6470
6471 =item B<remote_user ()>
6472
6473 Return the authorization/verification name used for user
6474 verification, if this script is protected.
6475
6476 =item B<user_name ()>
6477
6478 Attempt to obtain the remote user's name, using a variety of different
6479 techniques.  This only works with older browsers such as Mosaic.
6480 Newer browsers do not report the user name for privacy reasons!
6481
6482 =item B<request_method()>
6483
6484 Returns the method used to access your script, usually
6485 one of 'POST', 'GET' or 'HEAD'.
6486
6487 =item B<content_type()>
6488
6489 Returns the content_type of data submitted in a POST, generally 
6490 multipart/form-data or application/x-www-form-urlencoded
6491
6492 =item B<http()>
6493
6494 Called with no arguments returns the list of HTTP environment
6495 variables, including such things as HTTP_USER_AGENT,
6496 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6497 like-named HTTP header fields in the request.  Called with the name of
6498 an HTTP header field, returns its value.  Capitalization and the use
6499 of hyphens versus underscores are not significant.
6500
6501 For example, all three of these examples are equivalent:
6502
6503    $requested_language = $q->http('Accept-language');
6504    $requested_language = $q->http('Accept_language');
6505    $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6506
6507 =item B<https()>
6508
6509 The same as I<http()>, but operates on the HTTPS environment variables
6510 present when the SSL protocol is in effect.  Can be used to determine
6511 whether SSL is turned on.
6512
6513 =back
6514
6515 =head1 USING NPH SCRIPTS
6516
6517 NPH, or "no-parsed-header", scripts bypass the server completely by
6518 sending the complete HTTP header directly to the browser.  This has
6519 slight performance benefits, but is of most use for taking advantage
6520 of HTTP extensions that are not directly supported by your server,
6521 such as server push and PICS headers.
6522
6523 Servers use a variety of conventions for designating CGI scripts as
6524 NPH.  Many Unix servers look at the beginning of the script's name for
6525 the prefix "nph-".  The Macintosh WebSTAR server and Microsoft's
6526 Internet Information Server, in contrast, try to decide whether a
6527 program is an NPH script by examining the first line of script output.
6528
6529
6530 CGI.pm supports NPH scripts with a special NPH mode.  When in this
6531 mode, CGI.pm will output the necessary extra header information when
6532 the header() and redirect() methods are
6533 called.
6534
6535 The Microsoft Internet Information Server requires NPH mode.  As of
6536 version 2.30, CGI.pm will automatically detect when the script is
6537 running under IIS and put itself into this mode.  You do not need to
6538 do this manually, although it won't hurt anything if you do.  However,
6539 note that if you have applied Service Pack 6, much of the
6540 functionality of NPH scripts, including the ability to redirect while
6541 setting a cookie, b<do not work at all> on IIS without a special patch
6542 from Microsoft.  See
6543 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
6544 Non-Parsed Headers Stripped From CGI Applications That Have nph-
6545 Prefix in Name.
6546
6547 =over 4
6548
6549 =item In the B<use> statement 
6550
6551 Simply add the "-nph" pragmato the list of symbols to be imported into
6552 your script:
6553
6554       use CGI qw(:standard -nph)
6555
6556 =item By calling the B<nph()> method:
6557
6558 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6559
6560       CGI->nph(1)
6561
6562 =item By using B<-nph> parameters
6563
6564 in the B<header()> and B<redirect()>  statements:
6565
6566       print $q->header(-nph=>1);
6567
6568 =back
6569
6570 =head1 Server Push
6571
6572 CGI.pm provides four simple functions for producing multipart
6573 documents of the type needed to implement server push.  These
6574 functions were graciously provided by Ed Jordan <ed@fidalgo.net>.  To
6575 import these into your namespace, you must import the ":push" set.
6576 You are also advised to put the script into NPH mode and to set $| to
6577 1 to avoid buffering problems.
6578
6579 Here is a simple script that demonstrates server push:
6580
6581   #!/usr/local/bin/perl
6582   use CGI qw/:push -nph/;
6583   $| = 1;
6584   print multipart_init(-boundary=>'----here we go!');
6585   foreach (0 .. 4) {
6586       print multipart_start(-type=>'text/plain'),
6587             "The current time is ",scalar(localtime),"\n";
6588       if ($_ < 4) {
6589               print multipart_end;
6590       } else {
6591               print multipart_final;
6592       }
6593       sleep 1;
6594   }
6595
6596 This script initializes server push by calling B<multipart_init()>.
6597 It then enters a loop in which it begins a new multipart section by
6598 calling B<multipart_start()>, prints the current local time,
6599 and ends a multipart section with B<multipart_end()>.  It then sleeps
6600 a second, and begins again. On the final iteration, it ends the
6601 multipart section with B<multipart_final()> rather than with
6602 B<multipart_end()>.
6603
6604 =over 4
6605
6606 =item multipart_init()
6607
6608   multipart_init(-boundary=>$boundary);
6609
6610 Initialize the multipart system.  The -boundary argument specifies
6611 what MIME boundary string to use to separate parts of the document.
6612 If not provided, CGI.pm chooses a reasonable boundary for you.
6613
6614 =item multipart_start()
6615
6616   multipart_start(-type=>$type)
6617
6618 Start a new part of the multipart document using the specified MIME
6619 type.  If not specified, text/html is assumed.
6620
6621 =item multipart_end()
6622
6623   multipart_end()
6624
6625 End a part.  You must remember to call multipart_end() once for each
6626 multipart_start(), except at the end of the last part of the multipart
6627 document when multipart_final() should be called instead of multipart_end().
6628
6629 =item multipart_final()
6630
6631   multipart_final()
6632
6633 End all parts.  You should call multipart_final() rather than
6634 multipart_end() at the end of the last part of the multipart document.
6635
6636 =back
6637
6638 Users interested in server push applications should also have a look
6639 at the CGI::Push module.
6640
6641 Only Netscape Navigator supports server push.  Internet Explorer
6642 browsers do not.
6643
6644 =head1 Avoiding Denial of Service Attacks
6645
6646 A potential problem with CGI.pm is that, by default, it attempts to
6647 process form POSTings no matter how large they are.  A wily hacker
6648 could attack your site by sending a CGI script a huge POST of many
6649 megabytes.  CGI.pm will attempt to read the entire POST into a
6650 variable, growing hugely in size until it runs out of memory.  While
6651 the script attempts to allocate the memory the system may slow down
6652 dramatically.  This is a form of denial of service attack.
6653
6654 Another possible attack is for the remote user to force CGI.pm to
6655 accept a huge file upload.  CGI.pm will accept the upload and store it
6656 in a temporary directory even if your script doesn't expect to receive
6657 an uploaded file.  CGI.pm will delete the file automatically when it
6658 terminates, but in the meantime the remote user may have filled up the
6659 server's disk space, causing problems for other programs.
6660
6661 The best way to avoid denial of service attacks is to limit the amount
6662 of memory, CPU time and disk space that CGI scripts can use.  Some Web
6663 servers come with built-in facilities to accomplish this. In other
6664 cases, you can use the shell I<limit> or I<ulimit>
6665 commands to put ceilings on CGI resource usage.
6666
6667
6668 CGI.pm also has some simple built-in protections against denial of
6669 service attacks, but you must activate them before you can use them.
6670 These take the form of two global variables in the CGI name space:
6671
6672 =over 4
6673
6674 =item B<$CGI::POST_MAX>
6675
6676 If set to a non-negative integer, this variable puts a ceiling
6677 on the size of POSTings, in bytes.  If CGI.pm detects a POST
6678 that is greater than the ceiling, it will immediately exit with an error
6679 message.  This value will affect both ordinary POSTs and
6680 multipart POSTs, meaning that it limits the maximum size of file
6681 uploads as well.  You should set this to a reasonably high
6682 value, such as 1 megabyte.
6683
6684 =item B<$CGI::DISABLE_UPLOADS>
6685
6686 If set to a non-zero value, this will disable file uploads
6687 completely.  Other fill-out form values will work as usual.
6688
6689 =back
6690
6691 You can use these variables in either of two ways.
6692
6693 =over 4
6694
6695 =item B<1. On a script-by-script basis>
6696
6697 Set the variable at the top of the script, right after the "use" statement:
6698
6699     use CGI qw/:standard/;
6700     use CGI::Carp 'fatalsToBrowser';
6701     $CGI::POST_MAX=1024 * 100;  # max 100K posts
6702     $CGI::DISABLE_UPLOADS = 1;  # no uploads
6703
6704 =item B<2. Globally for all scripts>
6705
6706 Open up CGI.pm, find the definitions for $POST_MAX and 
6707 $DISABLE_UPLOADS, and set them to the desired values.  You'll 
6708 find them towards the top of the file in a subroutine named 
6709 initialize_globals().
6710
6711 =back
6712
6713 An attempt to send a POST larger than $POST_MAX bytes will cause
6714 I<param()> to return an empty CGI parameter list.  You can test for
6715 this event by checking I<cgi_error()>, either after you create the CGI
6716 object or, if you are using the function-oriented interface, call
6717 <param()> for the first time.  If the POST was intercepted, then
6718 cgi_error() will return the message "413 POST too large".
6719
6720 This error message is actually defined by the HTTP protocol, and is
6721 designed to be returned to the browser as the CGI script's status
6722  code.  For example:
6723
6724    $uploaded_file = param('upload');
6725    if (!$uploaded_file && cgi_error()) {
6726       print header(-status=>cgi_error());
6727       exit 0;
6728    }
6729
6730 However it isn't clear that any browser currently knows what to do
6731 with this status code.  It might be better just to create an
6732 HTML page that warns the user of the problem.
6733
6734 =head1 COMPATIBILITY WITH CGI-LIB.PL
6735
6736 To make it easier to port existing programs that use cgi-lib.pl the
6737 compatibility routine "ReadParse" is provided.  Porting is simple:
6738
6739 OLD VERSION
6740     require "cgi-lib.pl";
6741     &ReadParse;
6742     print "The value of the antique is $in{antique}.\n";
6743
6744 NEW VERSION
6745     use CGI;
6746     CGI::ReadParse
6747     print "The value of the antique is $in{antique}.\n";
6748
6749 CGI.pm's ReadParse() routine creates a tied variable named %in,
6750 which can be accessed to obtain the query variables.  Like
6751 ReadParse, you can also provide your own variable.  Infrequently
6752 used features of ReadParse, such as the creation of @in and $in 
6753 variables, are not supported.
6754
6755 Once you use ReadParse, you can retrieve the query object itself
6756 this way:
6757
6758     $q = $in{CGI};
6759     print $q->textfield(-name=>'wow',
6760                         -value=>'does this really work?');
6761
6762 This allows you to start using the more interesting features
6763 of CGI.pm without rewriting your old scripts from scratch.
6764
6765 =head1 AUTHOR INFORMATION
6766
6767 Copyright 1995-1998, Lincoln D. Stein.  All rights reserved.  
6768
6769 This library is free software; you can redistribute it and/or modify
6770 it under the same terms as Perl itself.
6771
6772 Address bug reports and comments to: lstein@cshl.org.  When sending
6773 bug reports, please provide the version of CGI.pm, the version of
6774 Perl, the name and version of your Web server, and the name and
6775 version of the operating system you are using.  If the problem is even
6776 remotely browser dependent, please provide information about the
6777 affected browers as well.
6778
6779 =head1 CREDITS
6780
6781 Thanks very much to:
6782
6783 =over 4
6784
6785 =item Matt Heffron (heffron@falstaff.css.beckman.com)
6786
6787 =item James Taylor (james.taylor@srs.gov)
6788
6789 =item Scott Anguish <sanguish@digifix.com>
6790
6791 =item Mike Jewell (mlj3u@virginia.edu)
6792
6793 =item Timothy Shimmin (tes@kbs.citri.edu.au)
6794
6795 =item Joergen Haegg (jh@axis.se)
6796
6797 =item Laurent Delfosse (delfosse@delfosse.com)
6798
6799 =item Richard Resnick (applepi1@aol.com)
6800
6801 =item Craig Bishop (csb@barwonwater.vic.gov.au)
6802
6803 =item Tony Curtis (tc@vcpc.univie.ac.at)
6804
6805 =item Tim Bunce (Tim.Bunce@ig.co.uk)
6806
6807 =item Tom Christiansen (tchrist@convex.com)
6808
6809 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
6810
6811 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
6812
6813 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
6814
6815 =item Stephen Dahmen (joyfire@inxpress.net)
6816
6817 =item Ed Jordan (ed@fidalgo.net)
6818
6819 =item David Alan Pisoni (david@cnation.com)
6820
6821 =item Doug MacEachern (dougm@opengroup.org)
6822
6823 =item Robin Houston (robin@oneworld.org)
6824
6825 =item ...and many many more...
6826
6827 for suggestions and bug fixes.
6828
6829 =back
6830
6831 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
6832
6833
6834         #!/usr/local/bin/perl
6835
6836         use CGI;
6837
6838         $query = new CGI;
6839
6840         print $query->header;
6841         print $query->start_html("Example CGI.pm Form");
6842         print "<h1> Example CGI.pm Form</h1>\n";
6843         &print_prompt($query);
6844         &do_work($query);
6845         &print_tail;
6846         print $query->end_html;
6847
6848         sub print_prompt {
6849            my($query) = @_;
6850
6851            print $query->start_form;
6852            print "<em>What's your name?</em><br>";
6853            print $query->textfield('name');
6854            print $query->checkbox('Not my real name');
6855
6856            print "<p><em>Where can you find English Sparrows?</em><br>";
6857            print $query->checkbox_group(
6858                                  -name=>'Sparrow locations',
6859                                  -values=>[England,France,Spain,Asia,Hoboken],
6860                                  -linebreak=>'yes',
6861                                  -defaults=>[England,Asia]);
6862
6863            print "<p><em>How far can they fly?</em><br>",
6864                 $query->radio_group(
6865                         -name=>'how far',
6866                         -values=>['10 ft','1 mile','10 miles','real far'],
6867                         -default=>'1 mile');
6868
6869            print "<p><em>What's your favorite color?</em>  ";
6870            print $query->popup_menu(-name=>'Color',
6871                                     -values=>['black','brown','red','yellow'],
6872                                     -default=>'red');
6873
6874            print $query->hidden('Reference','Monty Python and the Holy Grail');
6875
6876            print "<p><em>What have you got there?</em><br>";
6877            print $query->scrolling_list(
6878                          -name=>'possessions',
6879                          -values=>['A Coconut','A Grail','An Icon',
6880                                    'A Sword','A Ticket'],
6881                          -size=>5,
6882                          -multiple=>'true');
6883
6884            print "<p><em>Any parting comments?</em><br>";
6885            print $query->textarea(-name=>'Comments',
6886                                   -rows=>10,
6887                                   -columns=>50);
6888
6889            print "<p>",$query->reset;
6890            print $query->submit('Action','Shout');
6891            print $query->submit('Action','Scream');
6892            print $query->endform;
6893            print "<hr>\n";
6894         }
6895
6896         sub do_work {
6897            my($query) = @_;
6898            my(@values,$key);
6899
6900            print "<h2>Here are the current settings in this form</h2>";
6901
6902            foreach $key ($query->param) {
6903               print "<strong>$key</strong> -> ";
6904               @values = $query->param($key);
6905               print join(", ",@values),"<br>\n";
6906           }
6907         }
6908
6909         sub print_tail {
6910            print <<END;
6911         <hr>
6912         <address>Lincoln D. Stein</address><br>
6913         <a href="/">Home Page</a>
6914         END
6915         }
6916
6917 =head1 BUGS
6918
6919 Please report them.
6920
6921 =head1 SEE ALSO
6922
6923 L<CGI::Carp>, L<CGI::Fast>, L<CGI::Pretty>
6924
6925 =cut
6926