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