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