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