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