19e1f018e59f096197f573dfa7aec5ae6d362483
[p5sagit/p5-mst-13.2.git] / lib / CGI.pm
1 package CGI;
2 require 5.001;
3
4 # See the bottom of this file for the POD documentation.  Search for the
5 # string '=head'.
6
7 # You can run this file through either pod2man or pod2html to produce pretty
8 # documentation in manual or html file format (these utilities are part of the
9 # Perl 5 distribution).
10
11 # Copyright 1995-1997 Lincoln D. Stein.  All rights reserved.
12 # It may be used and modified freely, but I do request that this copyright
13 # notice remain attached to the file.  You may modify this module as you 
14 # wish, but if you redistribute a modified version, please attach a note
15 # listing the modifications you have made.
16
17 # The most recent version and complete docs are available at:
18 #   http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
19 #   ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
20
21 # Set this to 1 to enable copious autoloader debugging messages
22 $AUTOLOAD_DEBUG=0;
23
24 # Set this to 1 to enable NPH scripts
25 # or: 
26 #    1) use CGI qw(:nph)
27 #    2) $CGI::nph(1)
28 #    3) print header(-nph=>1)
29 $NPH=0;
30
31 $CGI::revision = '$Id: CGI.pm,v 2.32 1997/3/19 10:10 lstein Exp $';
32 $CGI::VERSION='2.3201';
33
34 # OVERRIDE THE OS HERE IF CGI.pm GUESSES WRONG
35 # $OS = 'UNIX';
36 # $OS = 'MACINTOSH';
37 # $OS = 'WINDOWS';
38 # $OS = 'VMS';
39 # $OS = 'OS2';
40
41 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
42 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
43 # $TempFile::TMPDIRECTORY = '/usr/tmp';
44
45 # ------------------ START OF THE LIBRARY ------------
46
47 # FIGURE OUT THE OS WE'RE RUNNING UNDER
48 # Some systems support the $^O variable.  If not
49 # available then require() the Config library
50 unless ($OS) {
51     unless ($OS = $^O) {
52         require Config;
53         $OS = $Config::Config{'osname'};
54     }
55 }
56 if ($OS=~/Win/i) {
57     $OS = 'WINDOWS';
58 } elsif ($OS=~/vms/i) {
59     $OS = 'VMS';
60 } elsif ($OS=~/Mac/i) {
61     $OS = 'MACINTOSH';
62 } elsif ($OS=~/os2/i) {
63     $OS = 'OS2';
64 } else {
65     $OS = 'UNIX';
66 }
67
68 # Some OS logic.  Binary mode enabled on DOS, NT and VMS
69 $needs_binmode = $OS=~/^(WINDOWS|VMS|OS2)/;
70
71 # This is the default class for the CGI object to use when all else fails.
72 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
73 # This is where to look for autoloaded routines.
74 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
75
76 # The path separator is a slash, backslash or semicolon, depending
77 # on the paltform.
78 $SL = {
79     UNIX=>'/',
80     OS2=>'\\',
81     WINDOWS=>'\\',
82     MACINTOSH=>':',
83     VMS=>'\\'
84     }->{$OS};
85
86 # Turn on NPH scripts by default when running under IIS server!
87 $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
88
89 # Turn on special checking for Doug MacEachern's modperl
90 if (defined($MOD_PERL = $ENV{'GATEWAY_INTERFACE'}) &&
91     $MOD_PERL =~ /^CGI-Perl/)
92 {
93     $NPH++;
94     $| = 1;
95     $SEQNO = 1;
96 }
97
98 # This is really "\r\n", but the meaning of \n is different
99 # in MacPerl, so we resort to octal here.
100 $CRLF = "\015\012";
101
102 if ($needs_binmode) {
103     $CGI::DefaultClass->binmode(main::STDOUT);
104     $CGI::DefaultClass->binmode(main::STDIN);
105     $CGI::DefaultClass->binmode(main::STDERR);
106 }
107
108 # Cute feature, but it broke when the overload mechanism changed...
109 # %OVERLOAD = ('""'=>'as_string');
110
111 %EXPORT_TAGS = (
112               ':html2'=>[h1..h6,qw/p br hr ol ul li dl dt dd menu code var strong em
113                          tt i b blockquote pre img a address cite samp dfn html head
114                          base body link nextid title meta kbd start_html end_html
115                          input Select option/],
116               ':html3'=>[qw/div table caption th td TR Tr super sub strike applet PARAM embed basefont/],
117               ':netscape'=>[qw/blink frameset frame script font fontsize center/],
118               ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group 
119                        submit reset defaults radio_group popup_menu button autoEscape
120                        scrolling_list image_button start_form end_form startform endform
121                        start_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
122               ':cgi'=>[qw/param path_info path_translated url self_url script_name cookie dump
123                        raw_cookie request_method query_string accept user_agent remote_host 
124                        remote_addr referer server_name server_software server_port server_protocol
125                        virtual_host remote_ident auth_type http
126                        remote_user user_name header redirect import_names put/],
127               ':ssl' => [qw/https/],
128               ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam/],
129               ':html' => [qw/:html2 :html3 :netscape/],
130               ':standard' => [qw/:html2 :form :cgi/],
131               ':all' => [qw/:html2 :html3 :netscape :form :cgi/]
132          );
133
134 # to import symbols into caller
135 sub import {
136     my $self = shift;
137     my ($callpack, $callfile, $callline) = caller;
138     foreach (@_) {
139         $NPH++, next if $_ eq ':nph';
140         foreach (&expand_tags($_)) {
141             tr/a-zA-Z0-9_//cd;  # don't allow weird function names
142             $EXPORT{$_}++;
143         }
144     }
145     # To allow overriding, search through the packages
146     # Till we find one in which the correct subroutine is defined.
147     my @packages = ($self,@{"$self\:\:ISA"});
148     foreach $sym (keys %EXPORT) {
149         my $pck;
150         my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
151         foreach $pck (@packages) {
152             if (defined(&{"$pck\:\:$sym"})) {
153                 $def = $pck;
154                 last;
155             }
156         }
157         *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
158     }
159 }
160
161 sub expand_tags {
162     my($tag) = @_;
163     my(@r);
164     return ($tag) unless $EXPORT_TAGS{$tag};
165     foreach (@{$EXPORT_TAGS{$tag}}) {
166         push(@r,&expand_tags($_));
167     }
168     return @r;
169 }
170
171 #### Method: new
172 # The new routine.  This will check the current environment
173 # for an existing query string, and initialize itself, if so.
174 ####
175 sub new {
176     my($class,$initializer) = @_;
177     my $self = {};
178     bless $self,ref $class || $class || $DefaultClass;
179     $CGI::DefaultClass->_reset_globals() if $MOD_PERL;
180     $initializer = to_filehandle($initializer) if $initializer;
181     $self->init($initializer);
182     return $self;
183 }
184
185 # We provide a DESTROY method so that the autoloader
186 # doesn't bother trying to find it.
187 sub DESTROY { }
188
189 #### Method: param
190 # Returns the value(s)of a named parameter.
191 # If invoked in a list context, returns the
192 # entire list.  Otherwise returns the first
193 # member of the list.
194 # If name is not provided, return a list of all
195 # the known parameters names available.
196 # If more than one argument is provided, the
197 # second and subsequent arguments are used to
198 # set the value of the parameter.
199 ####
200 sub param {
201     my($self,@p) = self_or_default(@_);
202     return $self->all_parameters unless @p;
203     my($name,$value,@other);
204
205     # For compatibility between old calling style and use_named_parameters() style, 
206     # we have to special case for a single parameter present.
207     if (@p > 1) {
208         ($name,$value,@other) = $self->rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
209         my(@values);
210
211         if (substr($p[0],0,1) eq '-' || $self->use_named_parameters) {
212             @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
213         } else {
214             foreach ($value,@other) {
215                 push(@values,$_) if defined($_);
216             }
217         }
218         # If values is provided, then we set it.
219         if (@values) {
220             $self->add_parameter($name);
221             $self->{$name}=[@values];
222         }
223     } else {
224         $name = $p[0];
225     }
226
227     return () unless defined($name) && $self->{$name};
228     return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
229 }
230
231 #### Method: delete
232 # Deletes the named parameter entirely.
233 ####
234 sub delete {
235     my($self,$name) = self_or_default(@_);
236     delete $self->{$name};
237     delete $self->{'.fieldnames'}->{$name};
238     @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
239     return wantarray ? () : undef;
240 }
241
242 sub self_or_default {
243     return @_ if defined($_[0]) && !ref($_[0]) && ($_[0] eq 'CGI');
244     unless (defined($_[0]) && 
245             ref($_[0]) &&
246             (ref($_[0]) eq 'CGI' ||
247              eval "\$_[0]->isaCGI()")) { # optimize for the common case
248         $CGI::DefaultClass->_reset_globals() 
249             if defined($Q) && $MOD_PERL && $CGI::DefaultClass->_new_request();
250         $Q = $CGI::DefaultClass->new unless defined($Q);
251         unshift(@_,$Q);
252     }
253     return @_;
254 }
255
256 sub _new_request {
257     return undef unless (defined(Apache->seqno()) or eval { require Apache });
258     if (Apache->seqno() != $SEQNO) {
259         $SEQNO = Apache->seqno();
260         return 1;
261     } else {
262         return undef;
263     }
264 }
265
266 sub _reset_globals {
267     undef $Q;
268     undef @QUERY_PARAM;
269 }
270
271 sub self_or_CGI {
272     local $^W=0;                # prevent a warning
273     if (defined($_[0]) &&
274         (substr(ref($_[0]),0,3) eq 'CGI' 
275          || eval "\$_[0]->isaCGI()")) {
276         return @_;
277     } else {
278         return ($DefaultClass,@_);
279     }
280 }
281
282 sub isaCGI {
283     return 1;
284 }
285
286 #### Method: import_names
287 # Import all parameters into the given namespace.
288 # Assumes namespace 'Q' if not specified
289 ####
290 sub import_names {
291     my($self,$namespace) = self_or_default(@_);
292     $namespace = 'Q' unless defined($namespace);
293     die "Can't import names into 'main'\n"
294         if $namespace eq 'main';
295     my($param,@value,$var);
296     foreach $param ($self->param) {
297         # protect against silly names
298         ($var = $param)=~tr/a-zA-Z0-9_/_/c;
299         $var = "${namespace}::$var";
300         @value = $self->param($param);
301         @{$var} = @value;
302         ${$var} = $value[0];
303     }
304 }
305
306 #### Method: use_named_parameters
307 # Force CGI.pm to use named parameter-style method calls
308 # rather than positional parameters.  The same effect
309 # will happen automatically if the first parameter
310 # begins with a -.
311 sub use_named_parameters {
312     my($self,$use_named) = self_or_default(@_);
313     return $self->{'.named'} unless defined ($use_named);
314
315     # stupidity to avoid annoying warnings
316     return $self->{'.named'}=$use_named;
317 }
318
319 ########################################
320 # THESE METHODS ARE MORE OR LESS PRIVATE
321 # GO TO THE __DATA__ SECTION TO SEE MORE
322 # PUBLIC METHODS
323 ########################################
324
325 # Initialize the query object from the environment.
326 # If a parameter list is found, this object will be set
327 # to an associative array in which parameter names are keys
328 # and the values are stored as lists
329 # If a keyword list is found, this method creates a bogus
330 # parameter list with the single parameter 'keywords'.
331
332 sub init {
333     my($self,$initializer) = @_;
334     my($query_string,@lines);
335     my($meth) = '';
336
337     # if we get called more than once, we want to initialize
338     # ourselves from the original query (which may be gone
339     # if it was read from STDIN originally.)
340     if (defined(@QUERY_PARAM) && !defined($initializer)) {
341
342         foreach (@QUERY_PARAM) {
343             $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
344         }
345         return;
346     }
347
348     $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
349
350     # If initializer is defined, then read parameters
351     # from it.
352   METHOD: {
353       if (defined($initializer)) {
354
355           if (ref($initializer) && ref($initializer) eq 'HASH') {
356               foreach (keys %$initializer) {
357                   $self->param('-name'=>$_,'-value'=>$initializer->{$_});
358               }
359               last METHOD;
360           }
361           
362           $initializer = $$initializer if ref($initializer);
363           if (defined(fileno($initializer))) {
364               while (<$initializer>) {
365                   chomp;
366                   last if /^=/;
367                   push(@lines,$_);
368               }
369               # massage back into standard format
370               if ("@lines" =~ /=/) {
371                   $query_string=join("&",@lines);
372               } else {
373                   $query_string=join("+",@lines);
374               }
375               last METHOD;
376           }
377           $query_string = $initializer;
378           last METHOD;
379       }
380           # If method is GET or HEAD, fetch the query from
381           # the environment.
382       if ($meth=~/^(GET|HEAD)$/) {
383         $query_string = $ENV{'QUERY_STRING'};
384         last METHOD;
385     }
386         
387       # If the method is POST, fetch the query from standard
388       # input.
389       if ($meth eq 'POST') {
390
391           if (defined($ENV{'CONTENT_TYPE'}) 
392               && 
393               $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|) {
394               my($boundary) = $ENV{'CONTENT_TYPE'}=~/boundary=(\S+)/;
395               $self->read_multipart($boundary,$ENV{'CONTENT_LENGTH'});
396
397           } else {
398
399               $self->read_from_client(\*STDIN,\$query_string,$ENV{'CONTENT_LENGTH'},0)
400                   if $ENV{'CONTENT_LENGTH'} > 0;
401
402           }
403           # Some people want to have their cake and eat it too!
404           # Uncomment this line to have the contents of the query string
405           # APPENDED to the POST data.
406           # $query_string .= ($query_string ? '&' : '') . $ENV{'QUERY_STRING'} if $ENV{'QUERY_STRING'};
407           last METHOD;
408       }
409           
410       # If neither is set, assume we're being debugged offline.
411       # Check the command line and then the standard input for data.
412       # We use the shellwords package in order to behave the way that
413       # UN*X programmers expect.
414       $query_string = &read_from_cmdline;
415   }
416     
417     # We now have the query string in hand.  We do slightly
418     # different things for keyword lists and parameter lists.
419     if ($query_string) {
420         if ($query_string =~ /=/) {
421             $self->parse_params($query_string);
422         } else {
423             $self->add_parameter('keywords');
424             $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
425         }
426     }
427
428     # Special case.  Erase everything if there is a field named
429     # .defaults.
430     if ($self->param('.defaults')) {
431         undef %{$self};
432     }
433
434     # Associative array containing our defined fieldnames
435     $self->{'.fieldnames'} = {};
436     foreach ($self->param('.cgifields')) {
437         $self->{'.fieldnames'}->{$_}++;
438     }
439     
440     # Clear out our default submission button flag if present
441     $self->delete('.submit');
442     $self->delete('.cgifields');
443     $self->save_request unless $initializer;
444
445 }
446
447
448 # FUNCTIONS TO OVERRIDE:
449
450 # Turn a string into a filehandle
451 sub to_filehandle {
452     my $string = shift;
453     if ($string && !ref($string)) {
454         my($package) = caller(1);
455         my($tmp) = $string=~/[':]/ ? $string : "$package\:\:$string"; 
456         return $tmp if defined(fileno($tmp));
457     }
458     return $string;
459 }
460
461 # Create a new multipart buffer
462 sub new_MultipartBuffer {
463     my($self,$boundary,$length,$filehandle) = @_;
464     return MultipartBuffer->new($self,$boundary,$length,$filehandle);
465 }
466
467 # Read data from a file handle
468 sub read_from_client {
469     my($self, $fh, $buff, $len, $offset) = @_;
470     local $^W=0;                # prevent a warning
471     return read($fh, $$buff, $len, $offset);
472 }
473
474 # put a filehandle into binary mode (DOS)
475 sub binmode {
476     binmode($_[1]);
477 }
478
479 # send output to the browser
480 sub put {
481     my($self,@p) = self_or_default(@_);
482     $self->print(@p);
483 }
484
485 # print to standard output (for overriding in mod_perl)
486 sub print {
487     shift;
488     CORE::print(@_);
489 }
490
491 # unescape URL-encoded data
492 sub unescape {
493     my($todecode) = @_;
494     $todecode =~ tr/+/ /;       # pluses become spaces
495     $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
496     return $todecode;
497 }
498
499 # URL-encode data
500 sub escape {
501     my($toencode) = @_;
502     $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
503     return $toencode;
504 }
505
506 sub save_request {
507     my($self) = @_;
508     # We're going to play with the package globals now so that if we get called
509     # again, we initialize ourselves in exactly the same way.  This allows
510     # us to have several of these objects.
511     @QUERY_PARAM = $self->param; # save list of parameters
512     foreach (@QUERY_PARAM) {
513         $QUERY_PARAM{$_}=$self->{$_};
514     }
515 }
516
517 sub parse_keywordlist {
518     my($self,$tosplit) = @_;
519     $tosplit = &unescape($tosplit); # unescape the keywords
520     $tosplit=~tr/+/ /;          # pluses to spaces
521     my(@keywords) = split(/\s+/,$tosplit);
522     return @keywords;
523 }
524
525 sub parse_params {
526     my($self,$tosplit) = @_;
527     my(@pairs) = split('&',$tosplit);
528     my($param,$value);
529     foreach (@pairs) {
530         ($param,$value) = split('=');
531         $param = &unescape($param);
532         $value = &unescape($value);
533         $self->add_parameter($param);
534         push (@{$self->{$param}},$value);
535     }
536 }
537
538 sub add_parameter {
539     my($self,$param)=@_;
540     push (@{$self->{'.parameters'}},$param) 
541         unless defined($self->{$param});
542 }
543
544 sub all_parameters {
545     my $self = shift;
546     return () unless defined($self) && $self->{'.parameters'};
547     return () unless @{$self->{'.parameters'}};
548     return @{$self->{'.parameters'}};
549 }
550
551
552
553 #### Method as_string
554 #
555 # synonym for "dump"
556 ####
557 sub as_string {
558     &dump(@_);
559 }
560
561 sub AUTOLOAD {
562     print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
563     my($func) = $AUTOLOAD;
564     my($pack,$func_name) = $func=~/(.+)::([^:]+)$/;
565     $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
566                 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
567
568     my($sub) = \%{"$pack\:\:SUBS"};
569     unless (%$sub) {
570         my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
571         eval "package $pack; $$auto";
572         die $@ if $@;
573     }
574     my($code) = $sub->{$func_name};
575
576     $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
577     if (!$code) {
578         if ($EXPORT{':any'} || 
579             $EXPORT{$func_name} || 
580             (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
581             && $EXPORT_OK{$func_name}) {
582             $code = $sub->{'HTML_FUNC'};
583             $code=~s/func_name/$func_name/mg;
584         }
585     }
586     die "Undefined subroutine $AUTOLOAD\n" unless $code;
587     eval "package $pack; $code";
588     if ($@) {
589         $@ =~ s/ at .*\n//;
590         die $@;
591     }
592     goto &{"$pack\:\:$func_name"};
593 }
594
595 # PRIVATE SUBROUTINE
596 # Smart rearrangement of parameters to allow named parameter
597 # calling.  We do the rearangement if:
598 # 1. The first parameter begins with a -
599 # 2. The use_named_parameters() method returns true
600 sub rearrange {
601     my($self,$order,@param) = @_;
602     return () unless @param;
603     
604     return @param unless (defined($param[0]) && substr($param[0],0,1) eq '-')
605         || $self->use_named_parameters;
606
607     my $i;
608     for ($i=0;$i<@param;$i+=2) {
609         $param[$i]=~s/^\-//;     # get rid of initial - if present
610         $param[$i]=~tr/a-z/A-Z/; # parameters are upper case
611     }
612     
613     my(%param) = @param;                # convert into associative array
614     my(@return_array);
615     
616     my($key)='';
617     foreach $key (@$order) {
618         my($value);
619         # this is an awful hack to fix spurious warnings when the
620         # -w switch is set.
621         if (ref($key) && ref($key) eq 'ARRAY') {
622             foreach (@$key) {
623                 last if defined($value);
624                 $value = $param{$_};
625                 delete $param{$_};
626             }
627         } else {
628             $value = $param{$key};
629             delete $param{$key};
630         }
631         push(@return_array,$value);
632     }
633     push (@return_array,$self->make_attributes(\%param)) if %param;
634     return (@return_array);
635 }
636
637 ###############################################################################
638 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
639 ###############################################################################
640 $AUTOLOADED_ROUTINES = '';      # get rid of -w warning
641 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
642
643 %SUBS = (
644
645 'URL_ENCODED'=> <<'END_OF_FUNC',
646 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
647 END_OF_FUNC
648
649 'MULTIPART' => <<'END_OF_FUNC',
650 sub MULTIPART {  'multipart/form-data'; }
651 END_OF_FUNC
652
653 'HTML_FUNC' => <<'END_OF_FUNC',
654 sub func_name { 
655
656     # handle various cases in which we're called
657     # most of this bizarre stuff is to avoid -w errors
658     shift if $_[0] && 
659         (!ref($_[0]) && $_[0] eq $CGI::DefaultClass) ||
660             (ref($_[0]) &&
661              (substr(ref($_[0]),0,3) eq 'CGI' ||
662               eval "\$_[0]->isaCGI()"));
663
664     my($attr) = '';
665     if (ref($_[0]) && ref($_[0]) eq 'HASH') {
666         my(@attr) = CGI::make_attributes('',shift);
667         $attr = " @attr" if @attr;
668     }
669     my($tag,$untag) = ("\U<func_name\E$attr>","\U</func_name>\E");
670     return $tag unless @_;
671     if (ref($_[0]) eq 'ARRAY') {
672         my(@r);
673         foreach (@{$_[0]}) {
674             push(@r,"$tag$_$untag");
675         }
676         return "@r";
677     } else {
678         return "$tag@_$untag";
679     }
680 }
681 END_OF_FUNC
682
683 #### Method: keywords
684 # Keywords acts a bit differently.  Calling it in a list context
685 # returns the list of keywords.  
686 # Calling it in a scalar context gives you the size of the list.
687 ####
688 'keywords' => <<'END_OF_FUNC',
689 sub keywords {
690     my($self,@values) = self_or_default(@_);
691     # If values is provided, then we set it.
692     $self->{'keywords'}=[@values] if @values;
693     my(@result) = @{$self->{'keywords'}};
694     @result;
695 }
696 END_OF_FUNC
697
698 # These are some tie() interfaces for compatibility
699 # with Steve Brenner's cgi-lib.pl routines
700 'ReadParse' => <<'END_OF_FUNC',
701 sub ReadParse {
702     local(*in);
703     if (@_) {
704         *in = $_[0];
705     } else {
706         my $pkg = caller();
707         *in=*{"${pkg}::in"};
708     }
709     tie(%in,CGI);
710 }
711 END_OF_FUNC
712
713 'PrintHeader' => <<'END_OF_FUNC',
714 sub PrintHeader {
715     my($self) = self_or_default(@_);
716     return $self->header();
717 }
718 END_OF_FUNC
719
720 'HtmlTop' => <<'END_OF_FUNC',
721 sub HtmlTop {
722     my($self,@p) = self_or_default(@_);
723     return $self->start_html(@p);
724 }
725 END_OF_FUNC
726
727 'HtmlBot' => <<'END_OF_FUNC',
728 sub HtmlBot {
729     my($self,@p) = self_or_default(@_);
730     return $self->end_html(@p);
731 }
732 END_OF_FUNC
733
734 'SplitParam' => <<'END_OF_FUNC',
735 sub SplitParam {
736     my ($param) = @_;
737     my (@params) = split ("\0", $param);
738     return (wantarray ? @params : $params[0]);
739 }
740 END_OF_FUNC
741
742 'MethGet' => <<'END_OF_FUNC',
743 sub MethGet {
744     return request_method() eq 'GET';
745 }
746 END_OF_FUNC
747
748 'MethPost' => <<'END_OF_FUNC',
749 sub MethPost {
750     return request_method() eq 'POST';
751 }
752 END_OF_FUNC
753
754 'TIEHASH' => <<'END_OF_FUNC',
755 sub TIEHASH { 
756     return new CGI;
757 }
758 END_OF_FUNC
759
760 'STORE' => <<'END_OF_FUNC',
761 sub STORE {
762     $_[0]->param($_[1],split("\0",$_[2]));
763 }
764 END_OF_FUNC
765
766 'FETCH' => <<'END_OF_FUNC',
767 sub FETCH {
768     return $_[0] if $_[1] eq 'CGI';
769     return undef unless defined $_[0]->param($_[1]);
770     return join("\0",$_[0]->param($_[1]));
771 }
772 END_OF_FUNC
773
774 'FIRSTKEY' => <<'END_OF_FUNC',
775 sub FIRSTKEY {
776     $_[0]->{'.iterator'}=0;
777     $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
778 }
779 END_OF_FUNC
780
781 'NEXTKEY' => <<'END_OF_FUNC',
782 sub NEXTKEY {
783     $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
784 }
785 END_OF_FUNC
786
787 'EXISTS' => <<'END_OF_FUNC',
788 sub EXISTS {
789     exists $_[0]->{$_[1]};
790 }
791 END_OF_FUNC
792
793 'DELETE' => <<'END_OF_FUNC',
794 sub DELETE {
795     $_[0]->delete($_[1]);
796 }
797 END_OF_FUNC
798
799 'CLEAR' => <<'END_OF_FUNC',
800 sub CLEAR {
801     %{$_[0]}=();
802 }
803 ####
804 END_OF_FUNC
805
806 ####
807 # Append a new value to an existing query
808 ####
809 'append' => <<'EOF',
810 sub append {
811     my($self,@p) = @_;
812     my($name,$value) = $self->rearrange([NAME,[VALUE,VALUES]],@p);
813     my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
814     if (@values) {
815         $self->add_parameter($name);
816         push(@{$self->{$name}},@values);
817     }
818     return $self->param($name);
819 }
820 EOF
821
822 #### Method: delete_all
823 # Delete all parameters
824 ####
825 'delete_all' => <<'EOF',
826 sub delete_all {
827     my($self) = self_or_default(@_);
828     undef %{$self};
829 }
830 EOF
831
832 #### Method: autoescape
833 # If you want to turn off the autoescaping features,
834 # call this method with undef as the argument
835 'autoEscape' => <<'END_OF_FUNC',
836 sub autoEscape {
837     my($self,$escape) = self_or_default(@_);
838     $self->{'dontescape'}=!$escape;
839 }
840 END_OF_FUNC
841
842
843 #### Method: version
844 # Return the current version
845 ####
846 'version' => <<'END_OF_FUNC',
847 sub version {
848     return $VERSION;
849 }
850 END_OF_FUNC
851
852 'make_attributes' => <<'END_OF_FUNC',
853 sub make_attributes {
854     my($self,$attr) = @_;
855     return () unless $attr && ref($attr) && ref($attr) eq 'HASH';
856     my(@att);
857     foreach (keys %{$attr}) {
858         my($key) = $_;
859         $key=~s/^\-//;     # get rid of initial - if present
860         $key=~tr/a-z/A-Z/; # parameters are upper case
861         push(@att,$attr->{$_} ne '' ? qq/$key="$attr->{$_}"/ : qq/$key/);
862     }
863     return @att;
864 }
865 END_OF_FUNC
866
867 #### Method: dump
868 # Returns a string in which all the known parameter/value 
869 # pairs are represented as nested lists, mainly for the purposes 
870 # of debugging.
871 ####
872 'dump' => <<'END_OF_FUNC',
873 sub dump {
874     my($self) = self_or_default(@_);
875     my($param,$value,@result);
876     return '<UL></UL>' unless $self->param;
877     push(@result,"<UL>");
878     foreach $param ($self->param) {
879         my($name)=$self->escapeHTML($param);
880         push(@result,"<LI><STRONG>$param</STRONG>");
881         push(@result,"<UL>");
882         foreach $value ($self->param($param)) {
883             $value = $self->escapeHTML($value);
884             push(@result,"<LI>$value");
885         }
886         push(@result,"</UL>");
887     }
888     push(@result,"</UL>\n");
889     return join("\n",@result);
890 }
891 END_OF_FUNC
892
893
894 #### Method: save
895 # Write values out to a filehandle in such a way that they can
896 # be reinitialized by the filehandle form of the new() method
897 ####
898 'save' => <<'END_OF_FUNC',
899 sub save {
900     my($self,$filehandle) = self_or_default(@_);
901     my($param);
902     my($package) = caller;
903 # Check that this still works!
904 #    $filehandle = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
905     $filehandle = to_filehandle($filehandle);
906     foreach $param ($self->param) {
907         my($escaped_param) = &escape($param);
908         my($value);
909         foreach $value ($self->param($param)) {
910             print $filehandle "$escaped_param=",escape($value),"\n";
911         }
912     }
913     print $filehandle "=\n";    # end of record
914 }
915 END_OF_FUNC
916
917
918 #### Method: header
919 # Return a Content-Type: style header
920 #
921 ####
922 'header' => <<'END_OF_FUNC',
923 sub header {
924     my($self,@p) = self_or_default(@_);
925     my(@header);
926
927     my($type,$status,$cookie,$target,$expires,$nph,@other) = 
928         $self->rearrange([TYPE,STATUS,[COOKIE,COOKIES],TARGET,EXPIRES,NPH],@p);
929
930     # rearrange() was designed for the HTML portion, so we
931     # need to fix it up a little.
932     foreach (@other) {
933         next unless my($header,$value) = /([^\s=]+)=(.+)/;
934         substr($header,1,1000)=~tr/A-Z/a-z/;
935         ($value)=$value=~/^"(.*)"$/;
936         $_ = "$header: $value";
937     }
938
939     $type = $type || 'text/html';
940
941     push(@header,'HTTP/1.0 ' . ($status || '200 OK')) if $nph || $NPH;
942     push(@header,"Status: $status") if $status;
943     push(@header,"Window-target: $target") if $target;
944     # push all the cookies -- there may be several
945     if ($cookie) {
946         my(@cookie) = ref($cookie) ? @{$cookie} : $cookie;
947         foreach (@cookie) {
948             push(@header,"Set-cookie: $_");
949         }
950     }
951     # if the user indicates an expiration time, then we need
952     # both an Expires and a Date header (so that the browser is
953     # uses OUR clock)
954     push(@header,"Expires: " . &expires($expires)) if $expires;
955     push(@header,"Date: " . &expires(0)) if $expires;
956     push(@header,"Pragma: no-cache") if $self->cache();
957     push(@header,@other);
958     push(@header,"Content-type: $type");
959
960     my $header = join($CRLF,@header);
961     return $header . "${CRLF}${CRLF}";
962 }
963 END_OF_FUNC
964
965
966 #### Method: cache
967 # Control whether header() will produce the no-cache
968 # Pragma directive.
969 ####
970 'cache' => <<'END_OF_FUNC',
971 sub cache {
972     my($self,$new_value) = self_or_default(@_);
973     $new_value = '' unless $new_value;
974     if ($new_value ne '') {
975         $self->{'cache'} = $new_value;
976     }
977     return $self->{'cache'};
978 }
979 END_OF_FUNC
980
981
982 #### Method: redirect
983 # Return a Location: style header
984 #
985 ####
986 'redirect' => <<'END_OF_FUNC',
987 sub redirect {
988     my($self,@p) = self_or_default(@_);
989     my($url,$target,$cookie,$nph,@other) = $self->rearrange([[URI,URL],TARGET,COOKIE,NPH],@p);
990     $url = $url || $self->self_url;
991     my(@o);
992     foreach (@other) { push(@o,split("=")); }
993     if($MOD_PERL or exists $self->{'.req'}) {
994         my $r = $self->{'.req'} || Apache->request;
995         $r->header_out(Location => $url);
996         $r->err_header_out(Location => $url);
997         $r->status(302);
998         return;
999     }
1000     else {
1001         push(@o,
1002          '-Status'=>'302 Found',
1003          '-Location'=>$url,
1004          '-nph'=>($nph||$NPH),
1005         );
1006     }
1007     push(@o, '-URI'=>$url);
1008     push(@o,'-Target'=>$target) if $target;
1009     push(@o,'-Cookie'=>$cookie) if $cookie;
1010     return $self->header(@o);
1011 }
1012 END_OF_FUNC
1013
1014
1015 #### Method: start_html
1016 # Canned HTML header
1017 #
1018 # Parameters:
1019 # $title -> (optional) The title for this HTML document (-title)
1020 # $author -> (optional) e-mail address of the author (-author)
1021 # $base -> (optional) if set to true, will enter the BASE address of this document
1022 #          for resolving relative references (-base) 
1023 # $xbase -> (optional) alternative base at some remote location (-xbase)
1024 # $target -> (optional) target window to load all links into (-target)
1025 # $script -> (option) Javascript code (-script)
1026 # $meta -> (optional) Meta information tags
1027 # @other -> (optional) any other named parameters you'd like to incorporate into
1028 #           the <BODY> tag.
1029 ####
1030 'start_html' => <<'END_OF_FUNC',
1031 sub start_html {
1032     my($self,@p) = &self_or_default(@_);
1033     my($title,$author,$base,$xbase,$script,$target,$meta,@other) = 
1034         $self->rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,TARGET,META],@p);
1035
1036     # strangely enough, the title needs to be escaped as HTML
1037     # while the author needs to be escaped as a URL
1038     $title = $self->escapeHTML($title || 'Untitled Document');
1039     $author = $self->escapeHTML($author);
1040     my(@result);
1041     push(@result,'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">');
1042     push(@result,"<HTML><HEAD><TITLE>$title</TITLE>");
1043     push(@result,"<LINK REV=MADE HREF=\"mailto:$author\">") if $author;
1044
1045     if ($base || $xbase || $target) {
1046         my $href = $xbase || $self->url();
1047         my $t = $target ? qq/ TARGET="$target"/ : '';
1048         push(@result,qq/<BASE HREF="$href"$t>/);
1049     }
1050
1051     if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1052         foreach (keys %$meta) { push(@result,qq(<META NAME="$_" CONTENT="$meta->{$_}">)); }
1053     }
1054     push(@result,<<END) if $script;
1055 <SCRIPT>
1056 <!-- Hide script from HTML-compliant browsers
1057 $script
1058 // End script hiding. -->
1059 </SCRIPT>
1060 END
1061     ;
1062     my($other) = @other ? " @other" : '';
1063     push(@result,"</HEAD><BODY$other>");
1064     return join("\n",@result);
1065 }
1066 END_OF_FUNC
1067
1068
1069 #### Method: end_html
1070 # End an HTML document.
1071 # Trivial method for completeness.  Just returns "</BODY>"
1072 ####
1073 'end_html' => <<'END_OF_FUNC',
1074 sub end_html {
1075     return "</BODY></HTML>";
1076 }
1077 END_OF_FUNC
1078
1079
1080 ################################
1081 # METHODS USED IN BUILDING FORMS
1082 ################################
1083
1084 #### Method: isindex
1085 # Just prints out the isindex tag.
1086 # Parameters:
1087 #  $action -> optional URL of script to run
1088 # Returns:
1089 #   A string containing a <ISINDEX> tag
1090 'isindex' => <<'END_OF_FUNC',
1091 sub isindex {
1092     my($self,@p) = self_or_default(@_);
1093     my($action,@other) = $self->rearrange([ACTION],@p);
1094     $action = qq/ACTION="$action"/ if $action;
1095     my($other) = @other ? " @other" : '';
1096     return "<ISINDEX $action$other>";
1097 }
1098 END_OF_FUNC
1099
1100
1101 #### Method: startform
1102 # Start a form
1103 # Parameters:
1104 #   $method -> optional submission method to use (GET or POST)
1105 #   $action -> optional URL of script to run
1106 #   $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1107 'startform' => <<'END_OF_FUNC',
1108 sub startform {
1109     my($self,@p) = self_or_default(@_);
1110
1111     my($method,$action,$enctype,@other) = 
1112         $self->rearrange([METHOD,ACTION,ENCTYPE],@p);
1113
1114     $method = $method || 'POST';
1115     $enctype = $enctype || &URL_ENCODED;
1116     $action = $action ? qq/ACTION="$action"/ : $method eq 'GET' ?
1117         'ACTION="'.$self->script_name.'"' : '';
1118     my($other) = @other ? " @other" : '';
1119     $self->{'.parametersToAdd'}={};
1120     return qq/<FORM METHOD="$method" $action ENCTYPE="$enctype"$other>\n/;
1121 }
1122 END_OF_FUNC
1123
1124
1125 #### Method: start_form
1126 # synonym for startform
1127 'start_form' => <<'END_OF_FUNC',
1128 sub start_form {
1129     &startform;
1130 }
1131 END_OF_FUNC
1132
1133
1134 #### Method: start_multipart_form
1135 # synonym for startform
1136 'start_multipart_form' => <<'END_OF_FUNC',
1137 sub start_multipart_form {
1138     my($self,@p) = self_or_default(@_);
1139     if ($self->use_named_parameters || 
1140         (defined($param[0]) && substr($param[0],0,1) eq '-')) {
1141         my(%p) = @p;
1142         $p{'-enctype'}=&MULTIPART;
1143         return $self->startform(%p);
1144     } else {
1145         my($method,$action,@other) = 
1146             $self->rearrange([METHOD,ACTION],@p);
1147         return $self->startform($method,$action,&MULTIPART,@other);
1148     }
1149 }
1150 END_OF_FUNC
1151
1152
1153 #### Method: endform
1154 # End a form
1155 'endform' => <<'END_OF_FUNC',
1156 sub endform {
1157     my($self,@p) = self_or_default(@_);    
1158     return ($self->get_fields,"</FORM>");
1159 }
1160 END_OF_FUNC
1161
1162
1163 #### Method: end_form
1164 # synonym for endform
1165 'end_form' => <<'END_OF_FUNC',
1166 sub end_form {
1167     &endform;
1168 }
1169 END_OF_FUNC
1170
1171
1172 #### Method: textfield
1173 # Parameters:
1174 #   $name -> Name of the text field
1175 #   $default -> Optional default value of the field if not
1176 #                already defined.
1177 #   $size ->  Optional width of field in characaters.
1178 #   $maxlength -> Optional maximum number of characters.
1179 # Returns:
1180 #   A string containing a <INPUT TYPE="text"> field
1181 #
1182 'textfield' => <<'END_OF_FUNC',
1183 sub textfield {
1184     my($self,@p) = self_or_default(@_);
1185     my($name,$default,$size,$maxlength,$override,@other) = 
1186         $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1187
1188     my $current = $override ? $default : 
1189         (defined($self->param($name)) ? $self->param($name) : $default);
1190
1191     $current = defined($current) ? $self->escapeHTML($current) : '';
1192     $name = defined($name) ? $self->escapeHTML($name) : '';
1193     my($s) = defined($size) ? qq/ SIZE=$size/ : '';
1194     my($m) = defined($maxlength) ? qq/ MAXLENGTH=$maxlength/ : '';
1195     my($other) = @other ? " @other" : '';    
1196     return qq/<INPUT TYPE="text" NAME="$name" VALUE="$current"$s$m$other>/;
1197 }
1198 END_OF_FUNC
1199
1200
1201 #### Method: filefield
1202 # Parameters:
1203 #   $name -> Name of the file upload field
1204 #   $size ->  Optional width of field in characaters.
1205 #   $maxlength -> Optional maximum number of characters.
1206 # Returns:
1207 #   A string containing a <INPUT TYPE="text"> field
1208 #
1209 'filefield' => <<'END_OF_FUNC',
1210 sub filefield {
1211     my($self,@p) = self_or_default(@_);
1212
1213     my($name,$default,$size,$maxlength,$override,@other) = 
1214         $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1215
1216     $current = $override ? $default :
1217         (defined($self->param($name)) ? $self->param($name) : $default);
1218
1219     $name = defined($name) ? $self->escapeHTML($name) : '';
1220     my($s) = defined($size) ? qq/ SIZE=$size/ : '';
1221     my($m) = defined($maxlength) ? qq/ MAXLENGTH=$maxlength/ : '';
1222     $current = defined($current) ? $self->escapeHTML($current) : '';
1223     $other = ' ' . join(" ",@other);
1224     return qq/<INPUT TYPE="file" NAME="$name" VALUE="$current"$s$m$other>/;
1225 }
1226 END_OF_FUNC
1227
1228
1229 #### Method: password
1230 # Create a "secret password" entry field
1231 # Parameters:
1232 #   $name -> Name of the field
1233 #   $default -> Optional default value of the field if not
1234 #                already defined.
1235 #   $size ->  Optional width of field in characters.
1236 #   $maxlength -> Optional maximum characters that can be entered.
1237 # Returns:
1238 #   A string containing a <INPUT TYPE="password"> field
1239 #
1240 'password_field' => <<'END_OF_FUNC',
1241 sub password_field {
1242     my ($self,@p) = self_or_default(@_);
1243
1244     my($name,$default,$size,$maxlength,$override,@other) = 
1245         $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1246
1247     my($current) =  $override ? $default :
1248         (defined($self->param($name)) ? $self->param($name) : $default);
1249
1250     $name = defined($name) ? $self->escapeHTML($name) : '';
1251     $current = defined($current) ? $self->escapeHTML($current) : '';
1252     my($s) = defined($size) ? qq/ SIZE=$size/ : '';
1253     my($m) = defined($maxlength) ? qq/ MAXLENGTH=$maxlength/ : '';
1254     my($other) = @other ? " @other" : '';
1255     return qq/<INPUT TYPE="password" NAME="$name" VALUE="$current"$s$m$other>/;
1256 }
1257 END_OF_FUNC
1258
1259
1260 #### Method: textarea
1261 # Parameters:
1262 #   $name -> Name of the text field
1263 #   $default -> Optional default value of the field if not
1264 #                already defined.
1265 #   $rows ->  Optional number of rows in text area
1266 #   $columns -> Optional number of columns in text area
1267 # Returns:
1268 #   A string containing a <TEXTAREA></TEXTAREA> tag
1269 #
1270 'textarea' => <<'END_OF_FUNC',
1271 sub textarea {
1272     my($self,@p) = self_or_default(@_);
1273     
1274     my($name,$default,$rows,$cols,$override,@other) =
1275         $self->rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1276
1277     my($current)= $override ? $default :
1278         (defined($self->param($name)) ? $self->param($name) : $default);
1279
1280     $name = defined($name) ? $self->escapeHTML($name) : '';
1281     $current = defined($current) ? $self->escapeHTML($current) : '';
1282     my($r) = $rows ? " ROWS=$rows" : '';
1283     my($c) = $cols ? " COLS=$cols" : '';
1284     my($other) = @other ? " @other" : '';
1285     return qq{<TEXTAREA NAME="$name"$r$c$other>$current</TEXTAREA>};
1286 }
1287 END_OF_FUNC
1288
1289
1290 #### Method: button
1291 # Create a javascript button.
1292 # Parameters:
1293 #   $name ->  (optional) Name for the button. (-name)
1294 #   $value -> (optional) Value of the button when selected (and visible name) (-value)
1295 #   $onclick -> (optional) Text of the JavaScript to run when the button is
1296 #                clicked.
1297 # Returns:
1298 #   A string containing a <INPUT TYPE="button"> tag
1299 ####
1300 'button' => <<'END_OF_FUNC',
1301 sub button {
1302     my($self,@p) = self_or_default(@_);
1303
1304     my($label,$value,$script,@other) = $self->rearrange([NAME,[VALUE,LABEL],
1305                                                          [ONCLICK,SCRIPT]],@p);
1306
1307     $label=$self->escapeHTML($label);
1308     $value=$self->escapeHTML($value);
1309     $script=$self->escapeHTML($script);
1310
1311     my($name) = '';
1312     $name = qq/ NAME="$label"/ if $label;
1313     $value = $value || $label;
1314     my($val) = '';
1315     $val = qq/ VALUE="$value"/ if $value;
1316     $script = qq/ ONCLICK="$script"/ if $script;
1317     my($other) = @other ? " @other" : '';
1318     return qq/<INPUT TYPE="button"$name$val$script$other>/;
1319 }
1320 END_OF_FUNC
1321
1322
1323 #### Method: submit
1324 # Create a "submit query" button.
1325 # Parameters:
1326 #   $name ->  (optional) Name for the button.
1327 #   $value -> (optional) Value of the button when selected (also doubles as label).
1328 #   $label -> (optional) Label printed on the button(also doubles as the value).
1329 # Returns:
1330 #   A string containing a <INPUT TYPE="submit"> tag
1331 ####
1332 'submit' => <<'END_OF_FUNC',
1333 sub submit {
1334     my($self,@p) = self_or_default(@_);
1335
1336     my($label,$value,@other) = $self->rearrange([NAME,[VALUE,LABEL]],@p);
1337
1338     $label=$self->escapeHTML($label);
1339     $value=$self->escapeHTML($value);
1340
1341     my($name) = ' NAME=".submit"';
1342     $name = qq/ NAME="$label"/ if $label;
1343     $value = $value || $label;
1344     my($val) = '';
1345     $val = qq/ VALUE="$value"/ if defined($value);
1346     my($other) = @other ? " @other" : '';
1347     return qq/<INPUT TYPE="submit"$name$val$other>/;
1348 }
1349 END_OF_FUNC
1350
1351
1352 #### Method: reset
1353 # Create a "reset" button.
1354 # Parameters:
1355 #   $name -> (optional) Name for the button.
1356 # Returns:
1357 #   A string containing a <INPUT TYPE="reset"> tag
1358 ####
1359 'reset' => <<'END_OF_FUNC',
1360 sub reset {
1361     my($self,@p) = self_or_default(@_);
1362     my($label,@other) = $self->rearrange([NAME],@p);
1363     $label=$self->escapeHTML($label);
1364     my($value) = defined($label) ? qq/ VALUE="$label"/ : '';
1365     my($other) = @other ? " @other" : '';
1366     return qq/<INPUT TYPE="reset"$value$other>/;
1367 }
1368 END_OF_FUNC
1369
1370
1371 #### Method: defaults
1372 # Create a "defaults" button.
1373 # Parameters:
1374 #   $name -> (optional) Name for the button.
1375 # Returns:
1376 #   A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
1377 #
1378 # Note: this button has a special meaning to the initialization script,
1379 # and tells it to ERASE the current query string so that your defaults
1380 # are used again!
1381 ####
1382 'defaults' => <<'END_OF_FUNC',
1383 sub defaults {
1384     my($self,@p) = self_or_default(@_);
1385
1386     my($label,@other) = $self->rearrange([[NAME,VALUE]],@p);
1387
1388     $label=$self->escapeHTML($label);
1389     $label = $label || "Defaults";
1390     my($value) = qq/ VALUE="$label"/;
1391     my($other) = @other ? " @other" : '';
1392     return qq/<INPUT TYPE="submit" NAME=".defaults"$value$other>/;
1393 }
1394 END_OF_FUNC
1395
1396
1397 #### Method: checkbox
1398 # Create a checkbox that is not logically linked to any others.
1399 # The field value is "on" when the button is checked.
1400 # Parameters:
1401 #   $name -> Name of the checkbox
1402 #   $checked -> (optional) turned on by default if true
1403 #   $value -> (optional) value of the checkbox, 'on' by default
1404 #   $label -> (optional) a user-readable label printed next to the box.
1405 #             Otherwise the checkbox name is used.
1406 # Returns:
1407 #   A string containing a <INPUT TYPE="checkbox"> field
1408 ####
1409 'checkbox' => <<'END_OF_FUNC',
1410 sub checkbox {
1411     my($self,@p) = self_or_default(@_);
1412
1413     my($name,$checked,$value,$label,$override,@other) = 
1414         $self->rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1415     
1416     if (!$override && defined($self->param($name))) {
1417         $value = $self->param($name) unless defined $value;
1418         $checked = $self->param($name) eq $value ? ' CHECKED' : '';
1419     } else {
1420         $checked = $checked ? ' CHECKED' : '';
1421         $value = defined $value ? $value : 'on';
1422     }
1423     my($the_label) = defined $label ? $label : $name;
1424     $name = $self->escapeHTML($name);
1425     $value = $self->escapeHTML($value);
1426     $the_label = $self->escapeHTML($the_label);
1427     my($other) = @other ? " @other" : '';
1428     $self->register_parameter($name);
1429     return <<END;
1430 <INPUT TYPE="checkbox" NAME="$name" VALUE="$value"$checked$other>$the_label
1431 END
1432 }
1433 END_OF_FUNC
1434
1435
1436 #### Method: checkbox_group
1437 # Create a list of logically-linked checkboxes.
1438 # Parameters:
1439 #   $name -> Common name for all the check boxes
1440 #   $values -> A pointer to a regular array containing the
1441 #             values for each checkbox in the group.
1442 #   $defaults -> (optional)
1443 #             1. If a pointer to a regular array of checkbox values,
1444 #             then this will be used to decide which
1445 #             checkboxes to turn on by default.
1446 #             2. If a scalar, will be assumed to hold the
1447 #             value of a single checkbox in the group to turn on. 
1448 #   $linebreak -> (optional) Set to true to place linebreaks
1449 #             between the buttons.
1450 #   $labels -> (optional)
1451 #             A pointer to an associative array of labels to print next to each checkbox
1452 #             in the form $label{'value'}="Long explanatory label".
1453 #             Otherwise the provided values are used as the labels.
1454 # Returns:
1455 #   An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1456 ####
1457 'checkbox_group' => <<'END_OF_FUNC',
1458 sub checkbox_group {
1459     my($self,@p) = self_or_default(@_);
1460
1461     my($name,$values,$defaults,$linebreak,$labels,$rows,$columns,
1462        $rowheaders,$colheaders,$override,$nolabels,@other) =
1463         $self->rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1464                           LINEBREAK,LABELS,ROWS,[COLUMNS,COLS],
1465                           ROWHEADERS,COLHEADERS,
1466                           [OVERRIDE,FORCE],NOLABELS],@p);
1467
1468     my($checked,$break,$result,$label);
1469
1470     my(%checked) = $self->previous_or_default($name,$defaults,$override);
1471
1472     $break = $linebreak ? "<BR>" : '';
1473     $name=$self->escapeHTML($name);
1474
1475     # Create the elements
1476     my(@elements);
1477     my(@values) = $values ? @$values : $self->param($name);
1478     my($other) = @other ? " @other" : '';
1479     foreach (@values) {
1480         $checked = $checked{$_} ? ' CHECKED' : '';
1481         $label = '';
1482         unless (defined($nolabels) && $nolabels) {
1483             $label = $_;
1484             $label = $labels->{$_} if defined($labels) && $labels->{$_};
1485             $label = $self->escapeHTML($label);
1486         }
1487         $_ = $self->escapeHTML($_);
1488         push(@elements,qq/<INPUT TYPE="checkbox" NAME="$name" VALUE="$_"$checked$other>${label} ${break}/);
1489     }
1490     $self->register_parameter($name);
1491     return wantarray ? @elements : join('',@elements) unless $columns;
1492     return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1493 }
1494 END_OF_FUNC
1495
1496
1497 # Escape HTML -- used internally
1498 'escapeHTML' => <<'END_OF_FUNC',
1499 sub escapeHTML {
1500     my($self,$toencode) = @_;
1501     return undef unless defined($toencode);
1502     return $toencode if $self->{'dontescape'};
1503     $toencode=~s/&/&amp;/g;
1504     $toencode=~s/\"/&quot;/g;
1505     $toencode=~s/>/&gt;/g;
1506     $toencode=~s/</&lt;/g;
1507     return $toencode;
1508 }
1509 END_OF_FUNC
1510
1511
1512 # Internal procedure - don't use
1513 '_tableize' => <<'END_OF_FUNC',
1514 sub _tableize {
1515     my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1516     my($result);
1517
1518     $rows = int(0.99 + @elements/$columns) unless $rows;
1519     # rearrange into a pretty table
1520     $result = "<TABLE>";
1521     my($row,$column);
1522     unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
1523     $result .= "<TR>" if @{$colheaders};
1524     foreach (@{$colheaders}) {
1525         $result .= "<TH>$_</TH>";
1526     }
1527     for ($row=0;$row<$rows;$row++) {
1528         $result .= "<TR>";
1529         $result .= "<TH>$rowheaders->[$row]</TH>" if @$rowheaders;
1530         for ($column=0;$column<$columns;$column++) {
1531             $result .= "<TD>" . $elements[$column*$rows + $row] . "</TD>";
1532         }
1533         $result .= "</TR>";
1534     }
1535     $result .= "</TABLE>";
1536     return $result;
1537 }
1538 END_OF_FUNC
1539
1540
1541 #### Method: radio_group
1542 # Create a list of logically-linked radio buttons.
1543 # Parameters:
1544 #   $name -> Common name for all the buttons.
1545 #   $values -> A pointer to a regular array containing the
1546 #             values for each button in the group.
1547 #   $default -> (optional) Value of the button to turn on by default.  Pass '-'
1548 #               to turn _nothing_ on.
1549 #   $linebreak -> (optional) Set to true to place linebreaks
1550 #             between the buttons.
1551 #   $labels -> (optional)
1552 #             A pointer to an associative array of labels to print next to each checkbox
1553 #             in the form $label{'value'}="Long explanatory label".
1554 #             Otherwise the provided values are used as the labels.
1555 # Returns:
1556 #   An ARRAY containing a series of <INPUT TYPE="radio"> fields
1557 ####
1558 'radio_group' => <<'END_OF_FUNC',
1559 sub radio_group {
1560     my($self,@p) = self_or_default(@_);
1561
1562     my($name,$values,$default,$linebreak,$labels,
1563        $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
1564         $self->rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,
1565                           ROWS,[COLUMNS,COLS],
1566                           ROWHEADERS,COLHEADERS,
1567                           [OVERRIDE,FORCE],NOLABELS],@p);
1568     my($result,$checked);
1569
1570     if (!$override && defined($self->param($name))) {
1571         $checked = $self->param($name);
1572     } else {
1573         $checked = $default;
1574     }
1575     # If no check array is specified, check the first by default
1576     $checked = $values->[0] unless $checked;
1577     $name=$self->escapeHTML($name);
1578
1579     my(@elements);
1580     my(@values) = $values ? @$values : $self->param($name);
1581     my($other) = @other ? " @other" : '';
1582     foreach (@values) {
1583         my($checkit) = $checked eq $_ ? ' CHECKED' : '';
1584         my($break) = $linebreak ? '<BR>' : '';
1585         my($label)='';
1586         unless (defined($nolabels) && $nolabels) {
1587             $label = $_;
1588             $label = $labels->{$_} if defined($labels) && $labels->{$_};
1589             $label = $self->escapeHTML($label);
1590         }
1591         $_=$self->escapeHTML($_);
1592         push(@elements,qq/<INPUT TYPE="radio" NAME="$name" VALUE="$_"$checkit$other>${label} ${break}/);
1593     }
1594     $self->register_parameter($name);
1595     return wantarray ? @elements : join('',@elements) unless $columns;
1596     return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1597 }
1598 END_OF_FUNC
1599
1600
1601 #### Method: popup_menu
1602 # Create a popup menu.
1603 # Parameters:
1604 #   $name -> Name for all the menu
1605 #   $values -> A pointer to a regular array containing the
1606 #             text of each menu item.
1607 #   $default -> (optional) Default item to display
1608 #   $labels -> (optional)
1609 #             A pointer to an associative array of labels to print next to each checkbox
1610 #             in the form $label{'value'}="Long explanatory label".
1611 #             Otherwise the provided values are used as the labels.
1612 # Returns:
1613 #   A string containing the definition of a popup menu.
1614 ####
1615 'popup_menu' => <<'END_OF_FUNC',
1616 sub popup_menu {
1617     my($self,@p) = self_or_default(@_);
1618
1619     my($name,$values,$default,$labels,$override,@other) =
1620         $self->rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
1621     my($result,$selected);
1622
1623     if (!$override && defined($self->param($name))) {
1624         $selected = $self->param($name);
1625     } else {
1626         $selected = $default;
1627     }
1628     $name=$self->escapeHTML($name);
1629     my($other) = @other ? " @other" : '';
1630
1631     my(@values) = $values ? @$values : $self->param($name);
1632     $result = qq/<SELECT NAME="$name"$other>\n/;
1633     foreach (@values) {
1634         my($selectit) = defined($selected) ? ($selected eq $_ ? 'SELECTED' : '' ) : '';
1635         my($label) = $_;
1636         $label = $labels->{$_} if defined($labels) && $labels->{$_};
1637         my($value) = $self->escapeHTML($_);
1638         $label=$self->escapeHTML($label);
1639         $result .= "<OPTION $selectit VALUE=\"$value\">$label\n";
1640     }
1641
1642     $result .= "</SELECT>\n";
1643     return $result;
1644 }
1645 END_OF_FUNC
1646
1647
1648 #### Method: scrolling_list
1649 # Create a scrolling list.
1650 # Parameters:
1651 #   $name -> name for the list
1652 #   $values -> A pointer to a regular array containing the
1653 #             values for each option line in the list.
1654 #   $defaults -> (optional)
1655 #             1. If a pointer to a regular array of options,
1656 #             then this will be used to decide which
1657 #             lines to turn on by default.
1658 #             2. Otherwise holds the value of the single line to turn on.
1659 #   $size -> (optional) Size of the list.
1660 #   $multiple -> (optional) If set, allow multiple selections.
1661 #   $labels -> (optional)
1662 #             A pointer to an associative array of labels to print next to each checkbox
1663 #             in the form $label{'value'}="Long explanatory label".
1664 #             Otherwise the provided values are used as the labels.
1665 # Returns:
1666 #   A string containing the definition of a scrolling list.
1667 ####
1668 'scrolling_list' => <<'END_OF_FUNC',
1669 sub scrolling_list {
1670     my($self,@p) = self_or_default(@_);
1671     my($name,$values,$defaults,$size,$multiple,$labels,$override,@other)
1672         = $self->rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1673                             SIZE,MULTIPLE,LABELS,[OVERRIDE,FORCE]],@p);
1674
1675     my($result);
1676     my(@values) = $values ? @$values : $self->param($name);
1677     $size = $size || scalar(@values);
1678
1679     my(%selected) = $self->previous_or_default($name,$defaults,$override);
1680     my($is_multiple) = $multiple ? ' MULTIPLE' : '';
1681     my($has_size) = $size ? " SIZE=$size" : '';
1682     my($other) = @other ? " @other" : '';
1683
1684     $name=$self->escapeHTML($name);
1685     $result = qq/<SELECT NAME="$name"$has_size$is_multiple$other>\n/;
1686     foreach (@values) {
1687         my($selectit) = $selected{$_} ? 'SELECTED' : '';
1688         my($label) = $_;
1689         $label = $labels->{$_} if defined($labels) && $labels->{$_};
1690         $label=$self->escapeHTML($label);
1691         my($value)=$self->escapeHTML($_);
1692         $result .= "<OPTION $selectit VALUE=\"$value\">$label\n";
1693     }
1694     $result .= "</SELECT>\n";
1695     $self->register_parameter($name);
1696     return $result;
1697 }
1698 END_OF_FUNC
1699
1700
1701 #### Method: hidden
1702 # Parameters:
1703 #   $name -> Name of the hidden field
1704 #   @default -> (optional) Initial values of field (may be an array)
1705 #      or
1706 #   $default->[initial values of field]
1707 # Returns:
1708 #   A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
1709 ####
1710 'hidden' => <<'END_OF_FUNC',
1711 sub hidden {
1712     my($self,@p) = self_or_default(@_);
1713
1714     # this is the one place where we departed from our standard
1715     # calling scheme, so we have to special-case (darn)
1716     my(@result,@value);
1717     my($name,$default,$override,@other) = 
1718         $self->rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
1719
1720     my $do_override = 0;
1721     if ( substr($p[0],0,1) eq '-' || $self->use_named_parameters ) {
1722         @value = ref($default) ? @{$default} : $default;
1723         $do_override = $override;
1724     } else {
1725         foreach ($default,$override,@other) {
1726             push(@value,$_) if defined($_);
1727         }
1728     }
1729
1730     # use previous values if override is not set
1731     my @prev = $self->param($name);
1732     @value = @prev if !$do_override && @prev;
1733
1734     $name=$self->escapeHTML($name);
1735     foreach (@value) {
1736         $_=$self->escapeHTML($_);
1737         push(@result,qq/<INPUT TYPE="hidden" NAME="$name" VALUE="$_">/);
1738     }
1739     return wantarray ? @result : join('',@result);
1740 }
1741 END_OF_FUNC
1742
1743
1744 #### Method: image_button
1745 # Parameters:
1746 #   $name -> Name of the button
1747 #   $src ->  URL of the image source
1748 #   $align -> Alignment style (TOP, BOTTOM or MIDDLE)
1749 # Returns:
1750 #   A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
1751 ####
1752 'image_button' => <<'END_OF_FUNC',
1753 sub image_button {
1754     my($self,@p) = self_or_default(@_);
1755
1756     my($name,$src,$alignment,@other) =
1757         $self->rearrange([NAME,SRC,ALIGN],@p);
1758
1759     my($align) = $alignment ? " ALIGN=\U$alignment" : '';
1760     my($other) = @other ? " @other" : '';
1761     $name=$self->escapeHTML($name);
1762     return qq/<INPUT TYPE="image" NAME="$name" SRC="$src"$align$other>/;
1763 }
1764 END_OF_FUNC
1765
1766
1767 #### Method: self_url
1768 # Returns a URL containing the current script and all its
1769 # param/value pairs arranged as a query.  You can use this
1770 # to create a link that, when selected, will reinvoke the
1771 # script with all its state information preserved.
1772 ####
1773 'self_url' => <<'END_OF_FUNC',
1774 sub self_url {
1775     my($self) = self_or_default(@_);
1776     my($query_string) = $self->query_string;
1777     my $protocol = $self->protocol();
1778     my $name = "$protocol://" . $self->server_name;
1779     $name .= ":" . $self->server_port
1780         unless $self->server_port == 80;
1781     $name .= $self->script_name;
1782     $name .= $self->path_info if $self->path_info;
1783     return $name unless $query_string;
1784     return "$name?$query_string";
1785 }
1786 END_OF_FUNC
1787
1788
1789 # This is provided as a synonym to self_url() for people unfortunate
1790 # enough to have incorporated it into their programs already!
1791 'state' => <<'END_OF_FUNC',
1792 sub state {
1793     &self_url;
1794 }
1795 END_OF_FUNC
1796
1797
1798 #### Method: url
1799 # Like self_url, but doesn't return the query string part of
1800 # the URL.
1801 ####
1802 'url' => <<'END_OF_FUNC',
1803 sub url {
1804     my($self) = self_or_default(@_);
1805     my $protocol = $self->protocol();
1806     my $name = "$protocol://" . $self->server_name;
1807     $name .= ":" . $self->server_port
1808         unless $self->server_port == 80;
1809     $name .= $self->script_name;
1810     return $name;
1811 }
1812
1813 END_OF_FUNC
1814
1815 #### Method: cookie
1816 # Set or read a cookie from the specified name.
1817 # Cookie can then be passed to header().
1818 # Usual rules apply to the stickiness of -value.
1819 #  Parameters:
1820 #   -name -> name for this cookie (optional)
1821 #   -value -> value of this cookie (scalar, array or hash) 
1822 #   -path -> paths for which this cookie is valid (optional)
1823 #   -domain -> internet domain in which this cookie is valid (optional)
1824 #   -secure -> if true, cookie only passed through secure channel (optional)
1825 #   -expires -> expiry date in format Wdy, DD-Mon-YY HH:MM:SS GMT (optional)
1826 ####
1827 'cookie' => <<'END_OF_FUNC',
1828 # temporary, for debugging.
1829 sub cookie {
1830     my($self,@p) = self_or_default(@_);
1831     my($name,$value,$path,$domain,$secure,$expires) =
1832         $self->rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
1833
1834
1835     # if no value is supplied, then we retrieve the
1836     # value of the cookie, if any.  For efficiency, we cache the parsed
1837     # cookie in our state variables.
1838     unless (defined($value)) {
1839         unless ($self->{'.cookies'}) {
1840             my(@pairs) = split("; ",$self->raw_cookie);
1841             foreach (@pairs) {
1842                 my($key,$value) = split("=");
1843                 my(@values) = map unescape($_),split('&',$value);
1844                 $self->{'.cookies'}->{unescape($key)} = [@values];
1845             }
1846         }
1847
1848         # If no name is supplied, then retrieve the names of all our cookies.
1849         return () unless $self->{'.cookies'};
1850         return wantarray ? @{$self->{'.cookies'}->{$name}} : $self->{'.cookies'}->{$name}->[0]
1851             if defined($name) && $name ne '';
1852         return keys %{$self->{'.cookies'}};
1853     }
1854     my(@values);
1855
1856     # Pull out our parameters.
1857     if (ref($value)) {
1858         if (ref($value) eq 'ARRAY') {
1859             @values = @$value;
1860         } elsif (ref($value) eq 'HASH') {
1861             @values = %$value;
1862         }
1863     } else {
1864         @values = ($value);
1865     }
1866     @values = map escape($_),@values;
1867
1868     # I.E. requires the path to be present.
1869     ($path = $ENV{'SCRIPT_NAME'})=~s![^/]+$!! unless $path;
1870
1871     my(@constant_values);
1872     push(@constant_values,"domain=$domain") if $domain;
1873     push(@constant_values,"path=$path") if $path;
1874     push(@constant_values,"expires=".&expires($expires)) if $expires;
1875     push(@constant_values,'secure') if $secure;
1876
1877     my($key) = &escape($name);
1878     my($cookie) = join("=",$key,join("&",@values));
1879     return join("; ",$cookie,@constant_values);
1880 }
1881 END_OF_FUNC
1882
1883
1884 # This internal routine creates an expires string exactly some number of
1885 # hours from the current time in GMT.  This is the format
1886 # required by Netscape cookies, and I think it works for the HTTP
1887 # Expires: header as well.
1888 'expires' => <<'END_OF_FUNC',
1889 sub expires {
1890     my($time) = @_;
1891     my(@MON)=qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
1892     my(@WDAY) = qw/Sunday Monday Tuesday Wednesday Thursday Friday Saturday/;
1893     my(%mult) = ('s'=>1,
1894                  'm'=>60,
1895                  'h'=>60*60,
1896                  'd'=>60*60*24,
1897                  'M'=>60*60*24*30,
1898                  'y'=>60*60*24*365);
1899     # format for time can be in any of the forms...
1900     # "now" -- expire immediately
1901     # "+180s" -- in 180 seconds
1902     # "+2m" -- in 2 minutes
1903     # "+12h" -- in 12 hours
1904     # "+1d"  -- in 1 day
1905     # "+3M"  -- in 3 months
1906     # "+2y"  -- in 2 years
1907     # "-3m"  -- 3 minutes ago(!)
1908     # If you don't supply one of these forms, we assume you are
1909     # specifying the date yourself
1910     my($offset);
1911     if (!$time || ($time eq 'now')) {
1912         $offset = 0;
1913     } elsif ($time=~/^([+-]?\d+)([mhdMy]?)/) {
1914         $offset = ($mult{$2} || 1)*$1;
1915     } else {
1916         return $time;
1917     }
1918     my($sec,$min,$hour,$mday,$mon,$year,$wday) = gmtime(time+$offset);
1919     $year += 1900 unless $year < 100;
1920     return sprintf("%s, %02d-%s-%02d %02d:%02d:%02d GMT",
1921                    $WDAY[$wday],$mday,$MON[$mon],$year,$hour,$min,$sec);
1922 }
1923 END_OF_FUNC
1924
1925
1926 ###############################################
1927 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
1928 ###############################################
1929
1930 #### Method: path_info
1931 # Return the extra virtual path information provided
1932 # after the URL (if any)
1933 ####
1934 'path_info' => <<'END_OF_FUNC',
1935 sub path_info {
1936     return $ENV{'PATH_INFO'};
1937 }
1938 END_OF_FUNC
1939
1940
1941 #### Method: request_method
1942 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
1943 ####
1944 'request_method' => <<'END_OF_FUNC',
1945 sub request_method {
1946     return $ENV{'REQUEST_METHOD'};
1947 }
1948 END_OF_FUNC
1949
1950 #### Method: path_translated
1951 # Return the physical path information provided
1952 # by the URL (if any)
1953 ####
1954 'path_translated' => <<'END_OF_FUNC',
1955 sub path_translated {
1956     return $ENV{'PATH_TRANSLATED'};
1957 }
1958 END_OF_FUNC
1959
1960
1961 #### Method: query_string
1962 # Synthesize a query string from our current
1963 # parameters
1964 ####
1965 'query_string' => <<'END_OF_FUNC',
1966 sub query_string {
1967     my($self) = self_or_default(@_);
1968     my($param,$value,@pairs);
1969     foreach $param ($self->param) {
1970         my($eparam) = &escape($param);
1971         foreach $value ($self->param($param)) {
1972             $value = &escape($value);
1973             push(@pairs,"$eparam=$value");
1974         }
1975     }
1976     return join("&",@pairs);
1977 }
1978 END_OF_FUNC
1979
1980
1981 #### Method: accept
1982 # Without parameters, returns an array of the
1983 # MIME types the browser accepts.
1984 # With a single parameter equal to a MIME
1985 # type, will return undef if the browser won't
1986 # accept it, 1 if the browser accepts it but
1987 # doesn't give a preference, or a floating point
1988 # value between 0.0 and 1.0 if the browser
1989 # declares a quantitative score for it.
1990 # This handles MIME type globs correctly.
1991 ####
1992 'accept' => <<'END_OF_FUNC',
1993 sub accept {
1994     my($self,$search) = self_or_CGI(@_);
1995     my(%prefs,$type,$pref,$pat);
1996     
1997     my(@accept) = split(',',$self->http('accept'));
1998
1999     foreach (@accept) {
2000         ($pref) = /q=(\d\.\d+|\d+)/;
2001         ($type) = m#(\S+/[^;]+)#;
2002         next unless $type;
2003         $prefs{$type}=$pref || 1;
2004     }
2005
2006     return keys %prefs unless $search;
2007     
2008     # if a search type is provided, we may need to
2009     # perform a pattern matching operation.
2010     # The MIME types use a glob mechanism, which
2011     # is easily translated into a perl pattern match
2012
2013     # First return the preference for directly supported
2014     # types:
2015     return $prefs{$search} if $prefs{$search};
2016
2017     # Didn't get it, so try pattern matching.
2018     foreach (keys %prefs) {
2019         next unless /\*/;       # not a pattern match
2020         ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2021         $pat =~ s/\*/.*/g; # turn it into a pattern
2022         return $prefs{$_} if $search=~/$pat/;
2023     }
2024 }
2025 END_OF_FUNC
2026
2027
2028 #### Method: user_agent
2029 # If called with no parameters, returns the user agent.
2030 # If called with one parameter, does a pattern match (case
2031 # insensitive) on the user agent.
2032 ####
2033 'user_agent' => <<'END_OF_FUNC',
2034 sub user_agent {
2035     my($self,$match)=self_or_CGI(@_);
2036     return $self->http('user_agent') unless $match;
2037     return $self->http('user_agent') =~ /$match/i;
2038 }
2039 END_OF_FUNC
2040
2041
2042 #### Method: cookie
2043 # Returns the magic cookie for the session.
2044 # To set the magic cookie for new transations,
2045 # try print $q->header('-Set-cookie'=>'my cookie')
2046 ####
2047 'raw_cookie' => <<'END_OF_FUNC',
2048 sub raw_cookie {
2049     my($self) = self_or_CGI(@_);
2050     return $self->http('cookie') || $ENV{'COOKIE'} || '';
2051 }
2052 END_OF_FUNC
2053
2054 #### Method: virtual_host
2055 # Return the name of the virtual_host, which
2056 # is not always the same as the server
2057 ######
2058 'virtual_host' => <<'END_OF_FUNC',
2059 sub virtual_host {
2060     return http('host') || server_name();
2061 }
2062 END_OF_FUNC
2063
2064 #### Method: remote_host
2065 # Return the name of the remote host, or its IP
2066 # address if unavailable.  If this variable isn't
2067 # defined, it returns "localhost" for debugging
2068 # purposes.
2069 ####
2070 'remote_host' => <<'END_OF_FUNC',
2071 sub remote_host {
2072     return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'} 
2073     || 'localhost';
2074 }
2075 END_OF_FUNC
2076
2077
2078 #### Method: remote_addr
2079 # Return the IP addr of the remote host.
2080 ####
2081 'remote_addr' => <<'END_OF_FUNC',
2082 sub remote_addr {
2083     return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2084 }
2085 END_OF_FUNC
2086
2087
2088 #### Method: script_name
2089 # Return the partial URL to this script for
2090 # self-referencing scripts.  Also see
2091 # self_url(), which returns a URL with all state information
2092 # preserved.
2093 ####
2094 'script_name' => <<'END_OF_FUNC',
2095 sub script_name {
2096     return $ENV{'SCRIPT_NAME'} if $ENV{'SCRIPT_NAME'};
2097     # These are for debugging
2098     return "/$0" unless $0=~/^\//;
2099     return $0;
2100 }
2101 END_OF_FUNC
2102
2103
2104 #### Method: referer
2105 # Return the HTTP_REFERER: useful for generating
2106 # a GO BACK button.
2107 ####
2108 'referer' => <<'END_OF_FUNC',
2109 sub referer {
2110     my($self) = self_or_CGI(@_);
2111     return $self->http('referer');
2112 }
2113 END_OF_FUNC
2114
2115
2116 #### Method: server_name
2117 # Return the name of the server
2118 ####
2119 'server_name' => <<'END_OF_FUNC',
2120 sub server_name {
2121     return $ENV{'SERVER_NAME'} || 'localhost';
2122 }
2123 END_OF_FUNC
2124
2125 #### Method: server_software
2126 # Return the name of the server software
2127 ####
2128 'server_software' => <<'END_OF_FUNC',
2129 sub server_software {
2130     return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2131 }
2132 END_OF_FUNC
2133
2134 #### Method: server_port
2135 # Return the tcp/ip port the server is running on
2136 ####
2137 'server_port' => <<'END_OF_FUNC',
2138 sub server_port {
2139     return $ENV{'SERVER_PORT'} || 80; # for debugging
2140 }
2141 END_OF_FUNC
2142
2143 #### Method: server_protocol
2144 # Return the protocol (usually HTTP/1.0)
2145 ####
2146 'server_protocol' => <<'END_OF_FUNC',
2147 sub server_protocol {
2148     return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2149 }
2150 END_OF_FUNC
2151
2152 #### Method: http
2153 # Return the value of an HTTP variable, or
2154 # the list of variables if none provided
2155 ####
2156 'http' => <<'END_OF_FUNC',
2157 sub http {
2158     my ($self,$parameter) = self_or_CGI(@_);
2159     return $ENV{$parameter} if $parameter=~/^HTTP/;
2160     return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2161     my(@p);
2162     foreach (keys %ENV) {
2163         push(@p,$_) if /^HTTP/;
2164     }
2165     return @p;
2166 }
2167 END_OF_FUNC
2168
2169 #### Method: https
2170 # Return the value of HTTPS
2171 ####
2172 'https' => <<'END_OF_FUNC',
2173 sub https {
2174     local($^W)=0;
2175     my ($self,$parameter) = self_or_CGI(@_);
2176     return $ENV{HTTPS} unless $parameter;
2177     return $ENV{$parameter} if $parameter=~/^HTTPS/;
2178     return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2179     my(@p);
2180     foreach (keys %ENV) {
2181         push(@p,$_) if /^HTTPS/;
2182     }
2183     return @p;
2184 }
2185 END_OF_FUNC
2186
2187 #### Method: protocol
2188 # Return the protocol (http or https currently)
2189 ####
2190 'protocol' => <<'END_OF_FUNC',
2191 sub protocol {
2192     local($^W)=0;
2193     my $self = shift;
2194     return 'https' if $self->https() eq 'ON'; 
2195     return 'https' if $self->server_port == 443;
2196     my $prot = $self->server_protocol;
2197     my($protocol,$version) = split('/',$prot);
2198     return "\L$protocol\E";
2199 }
2200 END_OF_FUNC
2201
2202 #### Method: remote_ident
2203 # Return the identity of the remote user
2204 # (but only if his host is running identd)
2205 ####
2206 'remote_ident' => <<'END_OF_FUNC',
2207 sub remote_ident {
2208     return $ENV{'REMOTE_IDENT'};
2209 }
2210 END_OF_FUNC
2211
2212
2213 #### Method: auth_type
2214 # Return the type of use verification/authorization in use, if any.
2215 ####
2216 'auth_type' => <<'END_OF_FUNC',
2217 sub auth_type {
2218     return $ENV{'AUTH_TYPE'};
2219 }
2220 END_OF_FUNC
2221
2222
2223 #### Method: remote_user
2224 # Return the authorization name used for user
2225 # verification.
2226 ####
2227 'remote_user' => <<'END_OF_FUNC',
2228 sub remote_user {
2229     return $ENV{'REMOTE_USER'};
2230 }
2231 END_OF_FUNC
2232
2233
2234 #### Method: user_name
2235 # Try to return the remote user's name by hook or by
2236 # crook
2237 ####
2238 'user_name' => <<'END_OF_FUNC',
2239 sub user_name {
2240     my ($self) = self_or_CGI(@_);
2241     return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2242 }
2243 END_OF_FUNC
2244
2245 #### Method: nph
2246 # Set or return the NPH global flag
2247 ####
2248 'nph' => <<'END_OF_FUNC',
2249 sub nph {
2250     my ($self,$param) = self_or_CGI(@_);
2251     $CGI::nph = $param if defined($param);
2252     return $CGI::nph;
2253 }
2254 END_OF_FUNC
2255
2256 # -------------- really private subroutines -----------------
2257 'previous_or_default' => <<'END_OF_FUNC',
2258 sub previous_or_default {
2259     my($self,$name,$defaults,$override) = @_;
2260     my(%selected);
2261
2262     if (!$override && ($self->{'.fieldnames'}->{$name} || 
2263                        defined($self->param($name)) ) ) {
2264         grep($selected{$_}++,$self->param($name));
2265     } elsif (defined($defaults) && ref($defaults) && 
2266              (ref($defaults) eq 'ARRAY')) {
2267         grep($selected{$_}++,@{$defaults});
2268     } else {
2269         $selected{$defaults}++ if defined($defaults);
2270     }
2271
2272     return %selected;
2273 }
2274 END_OF_FUNC
2275
2276 'register_parameter' => <<'END_OF_FUNC',
2277 sub register_parameter {
2278     my($self,$param) = @_;
2279     $self->{'.parametersToAdd'}->{$param}++;
2280 }
2281 END_OF_FUNC
2282
2283 'get_fields' => <<'END_OF_FUNC',
2284 sub get_fields {
2285     my($self) = @_;
2286     return $self->hidden('-name'=>'.cgifields',
2287                          '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2288                          '-override'=>1);
2289 }
2290 END_OF_FUNC
2291
2292 'read_from_cmdline' => <<'END_OF_FUNC',
2293 sub read_from_cmdline {
2294     require "shellwords.pl";
2295     my($input,@words);
2296     my($query_string);
2297     if (@ARGV) {
2298         $input = join(" ",@ARGV);
2299     } else {
2300         print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2301         chomp(@lines = <>); # remove newlines
2302         $input = join(" ",@lines);
2303     }
2304
2305     # minimal handling of escape characters
2306     $input=~s/\\=/%3D/g;
2307     $input=~s/\\&/%26/g;
2308     
2309     @words = &shellwords($input);
2310     if ("@words"=~/=/) {
2311         $query_string = join('&',@words);
2312     } else {
2313         $query_string = join('+',@words);
2314     }
2315     return $query_string;
2316 }
2317 END_OF_FUNC
2318
2319 #####
2320 # subroutine: read_multipart
2321 #
2322 # Read multipart data and store it into our parameters.
2323 # An interesting feature is that if any of the parts is a file, we
2324 # create a temporary file and open up a filehandle on it so that the
2325 # caller can read from it if necessary.
2326 #####
2327 'read_multipart' => <<'END_OF_FUNC',
2328 sub read_multipart {
2329     my($self,$boundary,$length) = @_;
2330     my($buffer) = $self->new_MultipartBuffer($boundary,$length);
2331     return unless $buffer;
2332     my(%header,$body);
2333     while (!$buffer->eof) {
2334         %header = $buffer->readHeader;
2335
2336         # In beta1 it was "Content-disposition".  In beta2 it's "Content-Disposition"
2337         # Sheesh.
2338         my($key) = $header{'Content-disposition'} ? 'Content-disposition' : 'Content-Disposition';
2339         my($param)= $header{$key}=~/ name="([^\"]*)"/;
2340
2341         # possible bug: our regular expression expects the filename= part to fall
2342         # at the end of the line.  Netscape doesn't escape quotation marks in file names!!!
2343         my($filename) = $header{$key}=~/ filename="(.*)"$/;
2344
2345         # add this parameter to our list
2346         $self->add_parameter($param);
2347
2348         # If no filename specified, then just read the data and assign it
2349         # to our parameter list.
2350         unless ($filename) {
2351             my($value) = $buffer->readBody;
2352             push(@{$self->{$param}},$value);
2353             next;
2354         }
2355
2356         # If we get here, then we are dealing with a potentially large
2357         # uploaded form.  Save the data to a temporary file, then open
2358         # the file for reading.
2359         my($tmpfile) = new TempFile;
2360         my $tmp = $tmpfile->as_string;
2361         
2362         open (OUT,">$tmp") || die "CGI open of $tmpfile: $!\n";
2363         $CGI::DefaultClass->binmode(OUT) if $CGI::needs_binmode;
2364         chmod 0666,$tmp;    # make sure anyone can delete it.
2365         my $data;
2366         while ($data = $buffer->read) {
2367             print OUT $data;
2368         }
2369         close OUT;
2370
2371         # Now create a new filehandle in the caller's namespace.
2372         # The name of this filehandle just happens to be identical
2373         # to the original filename (NOT the name of the temporary
2374         # file, which is hidden!)
2375         my($filehandle);
2376         if ($filename=~/^[a-zA-Z_]/) {
2377             my($frame,$cp)=(1);
2378             do { $cp = caller($frame++); } until !eval("'$cp'->isaCGI()");
2379             $filehandle = "$cp\:\:$filename";
2380         } else {
2381             $filehandle = "\:\:$filename";
2382         }
2383
2384         open($filehandle,$tmp) || die "CGI open of $tmp: $!\n";
2385         $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2386
2387         push(@{$self->{$param}},$filename);
2388
2389         # Under Unix, it would be safe to let the temporary file
2390         # be deleted immediately.  However, I fear that other operating
2391         # systems are not so forgiving.  Therefore we save a reference
2392         # to the temporary file in the CGI object so that the file
2393         # isn't unlinked until the CGI object itself goes out of
2394         # scope.  This is a bit hacky, but it has the interesting side
2395         # effect that one can access the name of the tmpfile by
2396         # asking for $query->{$query->param('foo')}, where 'foo'
2397         # is the name of the file upload field.
2398         $self->{'.tmpfiles'}->{$filename}= {
2399             name=>$tmpfile,
2400             info=>{%header}
2401         }
2402     }
2403 }
2404 END_OF_FUNC
2405
2406 'tmpFileName' => <<'END_OF_FUNC',
2407 sub tmpFileName {
2408     my($self,$filename) = self_or_default(@_);
2409     return $self->{'.tmpfiles'}->{$filename}->{name}->as_string;
2410 }
2411 END_OF_FUNC
2412
2413 'uploadInfo' => <<'END_OF_FUNC'
2414 sub uploadInfo {
2415     my($self,$filename) = self_or_default(@_);
2416     return $self->{'.tmpfiles'}->{$filename}->{info};
2417 }
2418 END_OF_FUNC
2419
2420 );
2421 END_OF_AUTOLOAD
2422 ;
2423
2424 # Globals and stubs for other packages that we use
2425 package MultipartBuffer;
2426
2427 # how many bytes to read at a time.  We use
2428 # a 5K buffer by default.
2429 $FILLUNIT = 1024 * 5;
2430 $TIMEOUT = 10*60;       # 10 minute timeout
2431 $SPIN_LOOP_MAX = 1000;  # bug fix for some Netscape servers
2432 $CRLF=$CGI::CRLF;
2433
2434 #reuse the autoload function
2435 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
2436
2437 ###############################################################################
2438 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2439 ###############################################################################
2440 $AUTOLOADED_ROUTINES = '';      # prevent -w error
2441 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2442 %SUBS =  (
2443
2444 'new' => <<'END_OF_FUNC',
2445 sub new {
2446     my($package,$interface,$boundary,$length,$filehandle) = @_;
2447     my $IN;
2448     if ($filehandle) {
2449         my($package) = caller;
2450         # force into caller's package if necessary
2451         $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle"; 
2452     }
2453     $IN = "main::STDIN" unless $IN;
2454
2455     $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
2456     
2457     # If the user types garbage into the file upload field,
2458     # then Netscape passes NOTHING to the server (not good).
2459     # We may hang on this read in that case. So we implement
2460     # a read timeout.  If nothing is ready to read
2461     # by then, we return.
2462
2463     # Netscape seems to be a little bit unreliable
2464     # about providing boundary strings.
2465     if ($boundary) {
2466
2467         # Under the MIME spec, the boundary consists of the 
2468         # characters "--" PLUS the Boundary string
2469         $boundary = "--$boundary";
2470         # Read the topmost (boundary) line plus the CRLF
2471         my($null) = '';
2472         $length -= $interface->read_from_client($IN,\$null,length($boundary)+2,0);
2473
2474     } else { # otherwise we find it ourselves
2475         my($old);
2476         ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
2477         $boundary = <$IN>;      # BUG: This won't work correctly under mod_perl
2478         $length -= length($boundary);
2479         chomp($boundary);               # remove the CRLF
2480         $/ = $old;                      # restore old line separator
2481     }
2482
2483     my $self = {LENGTH=>$length,
2484                 BOUNDARY=>$boundary,
2485                 IN=>$IN,
2486                 INTERFACE=>$interface,
2487                 BUFFER=>'',
2488             };
2489
2490     $FILLUNIT = length($boundary)
2491         if length($boundary) > $FILLUNIT;
2492
2493     return bless $self,ref $package || $package;
2494 }
2495 END_OF_FUNC
2496
2497 'readHeader' => <<'END_OF_FUNC',
2498 sub readHeader {
2499     my($self) = @_;
2500     my($end);
2501     my($ok) = 0;
2502     do {
2503         $self->fillBuffer($FILLUNIT);
2504         $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
2505         $ok++ if $self->{BUFFER} eq '';
2506         $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT; 
2507     } until $ok;
2508
2509     my($header) = substr($self->{BUFFER},0,$end+2);
2510     substr($self->{BUFFER},0,$end+4) = '';
2511     my %return;
2512     while ($header=~/^([\w-]+): (.*)$CRLF/mog) {
2513         $return{$1}=$2;
2514     }
2515     return %return;
2516 }
2517 END_OF_FUNC
2518
2519 # This reads and returns the body as a single scalar value.
2520 'readBody' => <<'END_OF_FUNC',
2521 sub readBody {
2522     my($self) = @_;
2523     my($data);
2524     my($returnval)='';
2525     while (defined($data = $self->read)) {
2526         $returnval .= $data;
2527     }
2528     return $returnval;
2529 }
2530 END_OF_FUNC
2531
2532 # This will read $bytes or until the boundary is hit, whichever happens
2533 # first.  After the boundary is hit, we return undef.  The next read will
2534 # skip over the boundary and begin reading again;
2535 'read' => <<'END_OF_FUNC',
2536 sub read {
2537     my($self,$bytes) = @_;
2538
2539     # default number of bytes to read
2540     $bytes = $bytes || $FILLUNIT;       
2541
2542     # Fill up our internal buffer in such a way that the boundary
2543     # is never split between reads.
2544     $self->fillBuffer($bytes);
2545
2546     # Find the boundary in the buffer (it may not be there).
2547     my $start = index($self->{BUFFER},$self->{BOUNDARY});
2548
2549     # If the boundary begins the data, then skip past it
2550     # and return undef.  The +2 here is a fiendish plot to
2551     # remove the CR/LF pair at the end of the boundary.
2552     if ($start == 0) {
2553
2554         # clear us out completely if we've hit the last boundary.
2555         if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
2556             $self->{BUFFER}='';
2557             $self->{LENGTH}=0;
2558             return undef;
2559         }
2560
2561         # just remove the boundary.
2562         substr($self->{BUFFER},0,length($self->{BOUNDARY})+2)='';
2563         return undef;
2564     }
2565
2566     my $bytesToReturn;    
2567     if ($start > 0) {           # read up to the boundary
2568         $bytesToReturn = $start > $bytes ? $bytes : $start;
2569     } else {    # read the requested number of bytes
2570         # leave enough bytes in the buffer to allow us to read
2571         # the boundary.  Thanks to Kevin Hendrick for finding
2572         # this one.
2573         $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
2574     }
2575
2576     my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
2577     substr($self->{BUFFER},0,$bytesToReturn)='';
2578     
2579     # If we hit the boundary, remove the CRLF from the end.
2580     return ($start > 0) ? substr($returnval,0,-2) : $returnval;
2581 }
2582 END_OF_FUNC
2583
2584
2585 # This fills up our internal buffer in such a way that the
2586 # boundary is never split between reads
2587 'fillBuffer' => <<'END_OF_FUNC',
2588 sub fillBuffer {
2589     my($self,$bytes) = @_;
2590     return unless $self->{LENGTH};
2591
2592     my($boundaryLength) = length($self->{BOUNDARY});
2593     my($bufferLength) = length($self->{BUFFER});
2594     my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
2595     $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
2596
2597     # Try to read some data.  We may hang here if the browser is screwed up.  
2598     my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
2599                                                          \$self->{BUFFER},
2600                                                          $bytesToRead,
2601                                                          $bufferLength);
2602
2603     # An apparent bug in the Netscape Commerce server causes the read()
2604     # to return zero bytes repeatedly without blocking if the
2605     # remote user aborts during a file transfer.  I don't know how
2606     # they manage this, but the workaround is to abort if we get
2607     # more than SPIN_LOOP_MAX consecutive zero reads.
2608     if ($bytesRead == 0) {
2609         die  "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
2610             if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
2611     } else {
2612         $self->{ZERO_LOOP_COUNTER}=0;
2613     }
2614
2615     $self->{LENGTH} -= $bytesRead;
2616 }
2617 END_OF_FUNC
2618
2619
2620 # Return true when we've finished reading
2621 'eof' => <<'END_OF_FUNC'
2622 sub eof {
2623     my($self) = @_;
2624     return 1 if (length($self->{BUFFER}) == 0)
2625                  && ($self->{LENGTH} <= 0);
2626     undef;
2627 }
2628 END_OF_FUNC
2629
2630 );
2631 END_OF_AUTOLOAD
2632
2633 ####################################################################################
2634 ################################## TEMPORARY FILES #################################
2635 ####################################################################################
2636 package TempFile;
2637
2638 $SL = $CGI::SL;
2639 unless ($TMPDIRECTORY) {
2640     @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp","${SL}tmp","${SL}temp","${SL}Temporary Items");
2641     foreach (@TEMP) {
2642         do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
2643     }
2644 }
2645
2646 $TMPDIRECTORY  = "." unless $TMPDIRECTORY;
2647 $SEQUENCE="CGItemp${$}0000";
2648
2649 # cute feature, but overload implementation broke it
2650 # %OVERLOAD = ('""'=>'as_string');
2651 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
2652
2653 ###############################################################################
2654 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2655 ###############################################################################
2656 $AUTOLOADED_ROUTINES = '';      # prevent -w error
2657 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2658 %SUBS = (
2659
2660 'new' => <<'END_OF_FUNC',
2661 sub new {
2662     my($package) = @_;
2663     $SEQUENCE++;
2664     my $directory = "${TMPDIRECTORY}${SL}${SEQUENCE}";
2665     return bless \$directory;
2666 }
2667 END_OF_FUNC
2668
2669 'DESTROY' => <<'END_OF_FUNC',
2670 sub DESTROY {
2671     my($self) = @_;
2672     unlink $$self;              # get rid of the file
2673 }
2674 END_OF_FUNC
2675
2676 'as_string' => <<'END_OF_FUNC'
2677 sub as_string {
2678     my($self) = @_;
2679     return $$self;
2680 }
2681 END_OF_FUNC
2682
2683 );
2684 END_OF_AUTOLOAD
2685
2686 package CGI;
2687
2688 # We get a whole bunch of warnings about "possibly uninitialized variables"
2689 # when running with the -w switch.  Touch them all once to get rid of the
2690 # warnings.  This is ugly and I hate it.
2691 if ($^W) {
2692     $CGI::CGI = '';
2693     $CGI::CGI=<<EOF;
2694     $CGI::VERSION;
2695     $MultipartBuffer::SPIN_LOOP_MAX;
2696     $MultipartBuffer::CRLF;
2697     $MultipartBuffer::TIMEOUT;
2698     $MultipartBuffer::FILLUNIT;
2699     $TempFile::SEQUENCE;
2700 EOF
2701     ;
2702 }
2703
2704 $revision;
2705
2706 __END__
2707
2708 =head1 NAME
2709
2710 CGI - Simple Common Gateway Interface Class
2711
2712 =head1 SYNOPSIS
2713
2714   use CGI;
2715   # the rest is too complicated for a synopsis; keep reading
2716
2717 =head1 ABSTRACT
2718
2719 This perl library uses perl5 objects to make it easy to create
2720 Web fill-out forms and parse their contents.  This package
2721 defines CGI objects, entities that contain the values of the
2722 current query string and other state variables.
2723 Using a CGI object's methods, you can examine keywords and parameters
2724 passed to your script, and create forms whose initial values
2725 are taken from the current query (thereby preserving state
2726 information).
2727
2728 The current version of CGI.pm is available at
2729
2730   http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
2731   ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
2732
2733 =head1 INSTALLATION:
2734
2735 To install this package, just change to the directory in which this
2736 file is found and type the following:
2737
2738         perl Makefile.PL
2739         make
2740         make install
2741
2742 This will copy CGI.pm to your perl library directory for use by all
2743 perl scripts.  You probably must be root to do this.   Now you can
2744 load the CGI routines in your Perl scripts with the line:
2745
2746         use CGI;
2747
2748 If you don't have sufficient privileges to install CGI.pm in the Perl
2749 library directory, you can put CGI.pm into some convenient spot, such
2750 as your home directory, or in cgi-bin itself and prefix all Perl
2751 scripts that call it with something along the lines of the following
2752 preamble:
2753
2754         use lib '/home/davis/lib';
2755         use CGI;
2756
2757 If you are using a version of perl earlier than 5.002 (such as NT perl), use
2758 this instead:
2759
2760         BEGIN {
2761                 unshift(@INC,'/home/davis/lib');
2762         }
2763         use CGI;
2764
2765 The CGI distribution also comes with a cute module called L<CGI::Carp>.
2766 It redefines the die(), warn(), confess() and croak() error routines
2767 so that they write nicely formatted error messages into the server's
2768 error log (or to the output stream of your choice).  This avoids long
2769 hours of groping through the error and access logs, trying to figure
2770 out which CGI script is generating  error messages.  If you choose,
2771 you can even have fatal error messages echoed to the browser to avoid
2772 the annoying and uninformative "Server Error" message.
2773
2774 =head1 DESCRIPTION
2775
2776 =head2 CREATING A NEW QUERY OBJECT:
2777
2778      $query = new CGI;
2779
2780 This will parse the input (from both POST and GET methods) and store
2781 it into a perl5 object called $query.  
2782
2783 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
2784
2785      $query = new CGI(INPUTFILE);
2786
2787 If you provide a file handle to the new() method, it
2788 will read parameters from the file (or STDIN, or whatever).  The
2789 file can be in any of the forms describing below under debugging
2790 (i.e. a series of newline delimited TAG=VALUE pairs will work).
2791 Conveniently, this type of file is created by the save() method
2792 (see below).  Multiple records can be saved and restored.
2793
2794 Perl purists will be pleased to know that this syntax accepts
2795 references to file handles, or even references to filehandle globs,
2796 which is the "official" way to pass a filehandle:
2797
2798     $query = new CGI(\*STDIN);
2799
2800 You can also initialize the query object from an associative array
2801 reference:
2802
2803     $query = new CGI( {'dinosaur'=>'barney',
2804                        'song'=>'I love you',
2805                        'friends'=>[qw/Jessica George Nancy/]}
2806                     );
2807
2808 or from a properly formatted, URL-escaped query string:
2809
2810     $query = new CGI('dinosaur=barney&color=purple');
2811
2812 To create an empty query, initialize it from an empty string or hash:
2813
2814         $empty_query = new CGI("");
2815              -or-
2816         $empty_query = new CGI({});
2817
2818 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
2819
2820      @keywords = $query->keywords
2821
2822 If the script was invoked as the result of an <ISINDEX> search, the
2823 parsed keywords can be obtained as an array using the keywords() method.
2824
2825 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
2826
2827      @names = $query->param
2828
2829 If the script was invoked with a parameter list
2830 (e.g. "name1=value1&name2=value2&name3=value3"), the param()
2831 method will return the parameter names as a list.  If the
2832 script was invoked as an <ISINDEX> script, there will be a
2833 single parameter named 'keywords'.
2834
2835 NOTE: As of version 1.5, the array of parameter names returned will
2836 be in the same order as they were submitted by the browser.
2837 Usually this order is the same as the order in which the 
2838 parameters are defined in the form (however, this isn't part
2839 of the spec, and so isn't guaranteed).
2840
2841 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
2842
2843     @values = $query->param('foo');
2844
2845               -or-
2846
2847     $value = $query->param('foo');
2848
2849 Pass the param() method a single argument to fetch the value of the
2850 named parameter. If the parameter is multivalued (e.g. from multiple
2851 selections in a scrolling list), you can ask to receive an array.  Otherwise
2852 the method will return a single value.
2853
2854 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
2855
2856     $query->param('foo','an','array','of','values');
2857
2858 This sets the value for the named parameter 'foo' to an array of
2859 values.  This is one way to change the value of a field AFTER
2860 the script has been invoked once before.  (Another way is with
2861 the -override parameter accepted by all methods that generate
2862 form elements.)
2863
2864 param() also recognizes a named parameter style of calling described
2865 in more detail later:
2866
2867     $query->param(-name=>'foo',-values=>['an','array','of','values']);
2868
2869                               -or-
2870
2871     $query->param(-name=>'foo',-value=>'the value');
2872
2873 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
2874
2875    $query->append(-name=>;'foo',-values=>['yet','more','values']);
2876
2877 This adds a value or list of values to the named parameter.  The
2878 values are appended to the end of the parameter if it already exists.
2879 Otherwise the parameter is created.  Note that this method only
2880 recognizes the named argument calling syntax.
2881
2882 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
2883
2884    $query->import_names('R');
2885
2886 This creates a series of variables in the 'R' namespace.  For example,
2887 $R::foo, @R:foo.  For keyword lists, a variable @R::keywords will appear.
2888 If no namespace is given, this method will assume 'Q'.
2889 WARNING:  don't import anything into 'main'; this is a major security
2890 risk!!!!
2891
2892 In older versions, this method was called B<import()>.  As of version 2.20, 
2893 this name has been removed completely to avoid conflict with the built-in
2894 Perl module B<import> operator.
2895
2896 =head2 DELETING A PARAMETER COMPLETELY:
2897
2898     $query->delete('foo');
2899
2900 This completely clears a parameter.  It sometimes useful for
2901 resetting parameters that you don't want passed down between
2902 script invocations.
2903
2904 =head2 DELETING ALL PARAMETERS:
2905
2906 $query->delete_all();
2907
2908 This clears the CGI object completely.  It might be useful to ensure
2909 that all the defaults are taken when you create a fill-out form.
2910
2911 =head2 SAVING THE STATE OF THE FORM TO A FILE:
2912
2913     $query->save(FILEHANDLE)
2914
2915 This will write the current state of the form to the provided
2916 filehandle.  You can read it back in by providing a filehandle
2917 to the new() method.  Note that the filehandle can be a file, a pipe,
2918 or whatever!
2919
2920 The format of the saved file is:
2921
2922         NAME1=VALUE1
2923         NAME1=VALUE1'
2924         NAME2=VALUE2
2925         NAME3=VALUE3
2926         =
2927
2928 Both name and value are URL escaped.  Multi-valued CGI parameters are
2929 represented as repeated names.  A session record is delimited by a
2930 single = symbol.  You can write out multiple records and read them
2931 back in with several calls to B<new>.  You can do this across several
2932 sessions by opening the file in append mode, allowing you to create
2933 primitive guest books, or to keep a history of users' queries.  Here's
2934 a short example of creating multiple session records:
2935
2936    use CGI;
2937
2938    open (OUT,">>test.out") || die;
2939    $records = 5;
2940    foreach (0..$records) {
2941        my $q = new CGI;
2942        $q->param(-name=>'counter',-value=>$_);
2943        $q->save(OUT);
2944    }
2945    close OUT;
2946
2947    # reopen for reading
2948    open (IN,"test.out") || die;
2949    while (!eof(IN)) {
2950        my $q = new CGI(IN);
2951        print $q->param('counter'),"\n";
2952    }
2953
2954 The file format used for save/restore is identical to that used by the
2955 Whitehead Genome Center's data exchange format "Boulderio", and can be
2956 manipulated and even databased using Boulderio utilities.  See
2957         
2958   http://www.genome.wi.mit.edu/genome_software/other/boulder.html
2959
2960 for further details.
2961
2962 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
2963
2964     $myself = $query->self_url;
2965     print "<A HREF=$myself>I'm talking to myself.</A>";
2966
2967 self_url() will return a URL, that, when selected, will reinvoke
2968 this script with all its state information intact.  This is most
2969 useful when you want to jump around within the document using
2970 internal anchors but you don't want to disrupt the current contents
2971 of the form(s).  Something like this will do the trick.
2972
2973      $myself = $query->self_url;
2974      print "<A HREF=$myself#table1>See table 1</A>";
2975      print "<A HREF=$myself#table2>See table 2</A>";
2976      print "<A HREF=$myself#yourself>See for yourself</A>";
2977
2978 If you don't want to get the whole query string, call
2979 the method url() to return just the URL for the script:
2980
2981     $myself = $query->url;
2982     print "<A HREF=$myself>No query string in this baby!</A>\n";
2983
2984 You can also retrieve the unprocessed query string with query_string():
2985
2986     $the_string = $query->query_string;
2987
2988 =head2 COMPATIBILITY WITH CGI-LIB.PL
2989
2990 To make it easier to port existing programs that use cgi-lib.pl
2991 the compatibility routine "ReadParse" is provided.  Porting is
2992 simple:
2993
2994 OLD VERSION
2995     require "cgi-lib.pl";
2996     &ReadParse;
2997     print "The value of the antique is $in{antique}.\n";
2998
2999 NEW VERSION
3000     use CGI;
3001     CGI::ReadParse
3002     print "The value of the antique is $in{antique}.\n";
3003
3004 CGI.pm's ReadParse() routine creates a tied variable named %in,
3005 which can be accessed to obtain the query variables.  Like
3006 ReadParse, you can also provide your own variable.  Infrequently
3007 used features of ReadParse, such as the creation of @in and $in 
3008 variables, are not supported.
3009
3010 Once you use ReadParse, you can retrieve the query object itself
3011 this way:
3012
3013     $q = $in{CGI};
3014     print $q->textfield(-name=>'wow',
3015                         -value=>'does this really work?');
3016
3017 This allows you to start using the more interesting features
3018 of CGI.pm without rewriting your old scripts from scratch.
3019
3020 =head2 CALLING CGI FUNCTIONS THAT TAKE MULTIPLE ARGUMENTS
3021
3022 In versions of CGI.pm prior to 2.0, it could get difficult to remember
3023 the proper order of arguments in CGI function calls that accepted five
3024 or six different arguments.  As of 2.0, there's a better way to pass
3025 arguments to the various CGI functions.  In this style, you pass a
3026 series of name=>argument pairs, like this:
3027
3028    $field = $query->radio_group(-name=>'OS',
3029                                 -values=>[Unix,Windows,Macintosh],
3030                                 -default=>'Unix');
3031
3032 The advantages of this style are that you don't have to remember the
3033 exact order of the arguments, and if you leave out a parameter, in
3034 most cases it will default to some reasonable value.  If you provide
3035 a parameter that the method doesn't recognize, it will usually do
3036 something useful with it, such as incorporating it into the HTML form
3037 tag.  For example if Netscape decides next week to add a new
3038 JUSTIFICATION parameter to the text field tags, you can start using
3039 the feature without waiting for a new version of CGI.pm:
3040
3041    $field = $query->textfield(-name=>'State',
3042                               -default=>'gaseous',
3043                               -justification=>'RIGHT');
3044
3045 This will result in an HTML tag that looks like this:
3046
3047         <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
3048                JUSTIFICATION="RIGHT">
3049
3050 Parameter names are case insensitive: you can use -name, or -Name or
3051 -NAME.  You don't have to use the hyphen if you don't want to.  After
3052 creating a CGI object, call the B<use_named_parameters()> method with
3053 a nonzero value.  This will tell CGI.pm that you intend to use named
3054 parameters exclusively:
3055
3056    $query = new CGI;
3057    $query->use_named_parameters(1);
3058    $field = $query->radio_group('name'=>'OS',
3059                                 'values'=>['Unix','Windows','Macintosh'],
3060                                 'default'=>'Unix');
3061
3062 Actually, CGI.pm only looks for a hyphen in the first parameter.  So
3063 you can leave it off subsequent parameters if you like.  Something to
3064 be wary of is the potential that a string constant like "values" will
3065 collide with a keyword (and in fact it does!) While Perl usually
3066 figures out when you're referring to a function and when you're
3067 referring to a string, you probably should put quotation marks around
3068 all string constants just to play it safe.
3069
3070 =head2 CREATING THE HTTP HEADER:
3071
3072         print $query->header;
3073
3074              -or-
3075
3076         print $query->header('image/gif');
3077
3078              -or-
3079
3080         print $query->header('text/html','204 No response');
3081
3082              -or-
3083
3084         print $query->header(-type=>'image/gif',
3085                              -nph=>1,
3086                              -status=>'402 Payment required',
3087                              -expires=>'+3d',
3088                              -cookie=>$cookie,
3089                              -Cost=>'$2.00');
3090
3091 header() returns the Content-type: header.  You can provide your own
3092 MIME type if you choose, otherwise it defaults to text/html.  An
3093 optional second parameter specifies the status code and a human-readable
3094 message.  For example, you can specify 204, "No response" to create a
3095 script that tells the browser to do nothing at all.  If you want to
3096 add additional fields to the header, just tack them on to the end:
3097
3098     print $query->header('text/html','200 OK','Content-Length: 3002');
3099
3100 The last example shows the named argument style for passing arguments
3101 to the CGI methods using named parameters.  Recognized parameters are
3102 B<-type>, B<-status>, B<-expires>, and B<-cookie>.  Any other 
3103 parameters will be stripped of their initial hyphens and turned into
3104 header fields, allowing you to specify any HTTP header you desire.
3105
3106 Most browsers will not cache the output from CGI scripts.  Every time
3107 the browser reloads the page, the script is invoked anew.  You can
3108 change this behavior with the B<-expires> parameter.  When you specify
3109 an absolute or relative expiration interval with this parameter, some
3110 browsers and proxy servers will cache the script's output until the
3111 indicated expiration date.  The following forms are all valid for the
3112 -expires field:
3113
3114         +30s                              30 seconds from now
3115         +10m                              ten minutes from now
3116         +1h                               one hour from now
3117         -1d                               yesterday (i.e. "ASAP!")
3118         now                               immediately
3119         +3M                               in three months
3120         +10y                              in ten years time
3121         Thursday, 25-Apr-96 00:40:33 GMT  at the indicated time & date
3122
3123 (CGI::expires() is the static function call used internally that turns
3124 relative time intervals into HTTP dates.  You can call it directly if
3125 you wish.)
3126
3127 The B<-cookie> parameter generates a header that tells the browser to provide
3128 a "magic cookie" during all subsequent transactions with your script.
3129 Netscape cookies have a special format that includes interesting attributes
3130 such as expiration time.  Use the cookie() method to create and retrieve
3131 session cookies.
3132
3133 The B<-nph> parameter, if set to a true value, will issue the correct
3134 headers to work with a NPH (no-parse-header) script.  This is important
3135 to use with certain servers, such as Microsoft Internet Explorer, which
3136 expect all their scripts to be NPH.
3137
3138 =head2 GENERATING A REDIRECTION INSTRUCTION
3139
3140    print $query->redirect('http://somewhere.else/in/movie/land');
3141
3142 redirects the browser elsewhere.  If you use redirection like this,
3143 you should B<not> print out a header as well.  As of version 2.0, we
3144 produce both the unofficial Location: header and the official URI:
3145 header.  This should satisfy most servers and browsers.
3146
3147 One hint I can offer is that relative links may not work correctly
3148 when when you generate a redirection to another document on your site.
3149 This is due to a well-intentioned optimization that some servers use.
3150 The solution to this is to use the full URL (including the http: part)
3151 of the document you are redirecting to.
3152
3153 You can use named parameters:
3154
3155     print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
3156                            -nph=>1);
3157
3158 The B<-nph> parameter, if set to a true value, will issue the correct
3159 headers to work with a NPH (no-parse-header) script.  This is important
3160 to use with certain servers, such as Microsoft Internet Explorer, which
3161 expect all their scripts to be NPH.
3162
3163
3164 =head2 CREATING THE HTML HEADER:
3165
3166    print $query->start_html(-title=>'Secrets of the Pyramids',
3167                             -author=>'fred@capricorn.org',
3168                             -base=>'true',
3169                             -target=>'_blank',
3170                             -meta=>{'keywords'=>'pharaoh secret mummy',
3171                                     'copyright'=>'copyright 1996 King Tut'},
3172                             -BGCOLOR=>'blue');
3173
3174    -or-
3175
3176    print $query->start_html('Secrets of the Pyramids',
3177                             'fred@capricorn.org','true',
3178                             'BGCOLOR="blue"');
3179
3180 This will return a canned HTML header and the opening <BODY> tag.  
3181 All parameters are optional.   In the named parameter form, recognized
3182 parameters are -title, -author, -base, -xbase and -target (see below for the
3183 explanation).  Any additional parameters you provide, such as the
3184 Netscape unofficial BGCOLOR attribute, are added to the <BODY> tag.
3185
3186 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
3187 different from the current location, as in
3188
3189     -xbase=>"http://home.mcom.com/"
3190
3191 All relative links will be interpreted relative to this tag.
3192
3193 The argument B<-target> allows you to provide a default target frame
3194 for all the links and fill-out forms on the page.  See the Netscape
3195 documentation on frames for details of how to manipulate this.
3196
3197     -target=>"answer_window"
3198
3199 All relative links will be interpreted relative to this tag.
3200 You add arbitrary meta information to the header with the B<-meta>
3201 argument.  This argument expects a reference to an associative array
3202 containing name/value pairs of meta information.  These will be turned
3203 into a series of header <META> tags that look something like this:
3204
3205     <META NAME="keywords" CONTENT="pharaoh secret mummy">
3206     <META NAME="description" CONTENT="copyright 1996 King Tut">
3207
3208 There is no support for the HTTP-EQUIV type of <META> tag.  This is
3209 because you can modify the HTTP header directly with the B<header()>
3210 method.
3211
3212 JAVASCRIPTING: The B<-script>, B<-onLoad> and B<-onUnload> parameters
3213 are used to add Netscape JavaScript calls to your pages.  B<-script>
3214 should point to a block of text containing JavaScript function
3215 definitions.  This block will be placed within a <SCRIPT> block inside
3216 the HTML (not HTTP) header.  The block is placed in the header in
3217 order to give your page a fighting chance of having all its JavaScript
3218 functions in place even if the user presses the stop button before the
3219 page has loaded completely.  CGI.pm attempts to format the script in
3220 such a way that JavaScript-naive browsers will not choke on the code:
3221 unfortunately there are some browsers, such as Chimera for Unix, that
3222 get confused by it nevertheless.
3223
3224 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
3225 code to execute when the page is respectively opened and closed by the
3226 browser.  Usually these parameters are calls to functions defined in the
3227 B<-script> field:
3228
3229       $query = new CGI;
3230       print $query->header;
3231       $JSCRIPT=<<END;
3232       // Ask a silly question
3233       function riddle_me_this() {
3234          var r = prompt("What walks on four legs in the morning, " +
3235                        "two legs in the afternoon, " +
3236                        "and three legs in the evening?");
3237          response(r);
3238       }
3239       // Get a silly answer
3240       function response(answer) {
3241          if (answer == "man")
3242             alert("Right you are!");
3243          else
3244             alert("Wrong!  Guess again.");
3245       }
3246       END
3247       print $query->start_html(-title=>'The Riddle of the Sphinx',
3248                                -script=>$JSCRIPT);
3249
3250 See
3251
3252    http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
3253
3254 for more information about JavaScript.
3255
3256 The old-style positional parameters are as follows:
3257
3258 =over 4
3259
3260 =item B<Parameters:>
3261
3262 =item 1.
3263
3264 The title
3265
3266 =item 2.
3267
3268 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
3269
3270 =item 3.
3271
3272 A 'true' flag if you want to include a <BASE> tag in the header.  This
3273 helps resolve relative addresses to absolute ones when the document is moved, 
3274 but makes the document hierarchy non-portable.  Use with care!
3275
3276 =item 4, 5, 6...
3277
3278 Any other parameters you want to include in the <BODY> tag.  This is a good
3279 place to put Netscape extensions, such as colors and wallpaper patterns.
3280
3281 =back
3282
3283 =head2 ENDING THE HTML DOCUMENT:
3284
3285         print $query->end_html
3286
3287 This ends an HTML document by printing the </BODY></HTML> tags.
3288
3289 =head1 CREATING FORMS:
3290
3291 I<General note>  The various form-creating methods all return strings
3292 to the caller, containing the tag or tags that will create the requested
3293 form element.  You are responsible for actually printing out these strings.
3294 It's set up this way so that you can place formatting tags
3295 around the form elements.
3296
3297 I<Another note> The default values that you specify for the forms are only
3298 used the B<first> time the script is invoked (when there is no query
3299 string).  On subsequent invocations of the script (when there is a query
3300 string), the former values are used even if they are blank.  
3301
3302 If you want to change the value of a field from its previous value, you have two
3303 choices:
3304
3305 (1) call the param() method to set it.
3306
3307 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
3308 This forces the default value to be used, regardless of the previous value:
3309
3310    print $query->textfield(-name=>'field_name',
3311                            -default=>'starting value',
3312                            -override=>1,
3313                            -size=>50,
3314                            -maxlength=>80);
3315
3316 I<Yet another note> By default, the text and labels of form elements are
3317 escaped according to HTML rules.  This means that you can safely use
3318 "<CLICK ME>" as the label for a button.  However, it also interferes with
3319 your ability to incorporate special HTML character sequences, such as &Aacute;,
3320 into your fields.  If you wish to turn off automatic escaping, call the
3321 autoEscape() method with a false value immediately after creating the CGI object:
3322
3323    $query = new CGI;
3324    $query->autoEscape(undef);
3325                              
3326
3327 =head2 CREATING AN ISINDEX TAG
3328
3329    print $query->isindex(-action=>$action);
3330
3331          -or-
3332
3333    print $query->isindex($action);
3334
3335 Prints out an <ISINDEX> tag.  Not very exciting.  The parameter
3336 -action specifies the URL of the script to process the query.  The
3337 default is to process the query with the current script.
3338
3339 =head2 STARTING AND ENDING A FORM
3340
3341     print $query->startform(-method=>$method,
3342                             -action=>$action,
3343                             -encoding=>$encoding);
3344       <... various form stuff ...>
3345     print $query->endform;
3346
3347         -or-
3348
3349     print $query->startform($method,$action,$encoding);
3350       <... various form stuff ...>
3351     print $query->endform;
3352
3353 startform() will return a <FORM> tag with the optional method,
3354 action and form encoding that you specify.  The defaults are:
3355         
3356     method: POST
3357     action: this script
3358     encoding: application/x-www-form-urlencoded
3359
3360 endform() returns the closing </FORM> tag.  
3361
3362 Startform()'s encoding method tells the browser how to package the various
3363 fields of the form before sending the form to the server.  Two
3364 values are possible:
3365
3366 =over 4
3367
3368 =item B<application/x-www-form-urlencoded>
3369
3370 This is the older type of encoding used by all browsers prior to
3371 Netscape 2.0.  It is compatible with many CGI scripts and is
3372 suitable for short fields containing text data.  For your
3373 convenience, CGI.pm stores the name of this encoding
3374 type in B<$CGI::URL_ENCODED>.
3375
3376 =item B<multipart/form-data>
3377
3378 This is the newer type of encoding introduced by Netscape 2.0.
3379 It is suitable for forms that contain very large fields or that
3380 are intended for transferring binary data.  Most importantly,
3381 it enables the "file upload" feature of Netscape 2.0 forms.  For
3382 your convenience, CGI.pm stores the name of this encoding type
3383 in B<$CGI::MULTIPART>
3384
3385 Forms that use this type of encoding are not easily interpreted
3386 by CGI scripts unless they use CGI.pm or another library designed
3387 to handle them.
3388
3389 =back
3390
3391 For compatibility, the startform() method uses the older form of
3392 encoding by default.  If you want to use the newer form of encoding
3393 by default, you can call B<start_multipart_form()> instead of
3394 B<startform()>.
3395
3396 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
3397 for use with JavaScript.  The -name parameter gives the
3398 form a name so that it can be identified and manipulated by
3399 JavaScript functions.  -onSubmit should point to a JavaScript
3400 function that will be executed just before the form is submitted to your
3401 server.  You can use this opportunity to check the contents of the form 
3402 for consistency and completeness.  If you find something wrong, you
3403 can put up an alert box or maybe fix things up yourself.  You can 
3404 abort the submission by returning false from this function.  
3405
3406 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
3407 block in the HTML header and -onSubmit points to one of these function
3408 call.  See start_html() for details.
3409
3410 =head2 CREATING A TEXT FIELD
3411
3412     print $query->textfield(-name=>'field_name',
3413                             -default=>'starting value',
3414                             -size=>50,
3415                             -maxlength=>80);
3416         -or-
3417
3418     print $query->textfield('field_name','starting value',50,80);
3419
3420 textfield() will return a text input field.  
3421
3422 =over 4
3423
3424 =item B<Parameters>
3425
3426 =item 1.
3427
3428 The first parameter is the required name for the field (-name).  
3429
3430 =item 2.
3431
3432 The optional second parameter is the default starting value for the field
3433 contents (-default).  
3434
3435 =item 3.
3436
3437 The optional third parameter is the size of the field in
3438       characters (-size).
3439
3440 =item 4.
3441
3442 The optional fourth parameter is the maximum number of characters the
3443       field will accept (-maxlength).
3444
3445 =back
3446
3447 As with all these methods, the field will be initialized with its 
3448 previous contents from earlier invocations of the script.
3449 When the form is processed, the value of the text field can be
3450 retrieved with:
3451
3452        $value = $query->param('foo');
3453
3454 If you want to reset it from its initial value after the script has been
3455 called once, you can do so like this:
3456
3457        $query->param('foo',"I'm taking over this value!");
3458
3459 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
3460 value, you can force its current value by using the -override (alias -force)
3461 parameter:
3462
3463     print $query->textfield(-name=>'field_name',
3464                             -default=>'starting value',
3465                             -override=>1,
3466                             -size=>50,
3467                             -maxlength=>80);
3468
3469 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>, B<-onBlur>
3470 and B<-onSelect> parameters to register JavaScript event handlers.
3471 The onChange handler will be called whenever the user changes the
3472 contents of the text field.  You can do text validation if you like.
3473 onFocus and onBlur are called respectively when the insertion point
3474 moves into and out of the text field.  onSelect is called when the
3475 user changes the portion of the text that is selected.
3476
3477 =head2 CREATING A BIG TEXT FIELD
3478
3479    print $query->textarea(-name=>'foo',
3480                           -default=>'starting value',
3481                           -rows=>10,
3482                           -columns=>50);
3483
3484         -or
3485
3486    print $query->textarea('foo','starting value',10,50);
3487
3488 textarea() is just like textfield, but it allows you to specify
3489 rows and columns for a multiline text entry box.  You can provide
3490 a starting value for the field, which can be long and contain
3491 multiple lines.
3492
3493 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3494 and B<-onSelect> parameters are recognized.  See textfield().
3495
3496 =head2 CREATING A PASSWORD FIELD
3497
3498    print $query->password_field(-name=>'secret',
3499                                 -value=>'starting value',
3500                                 -size=>50,
3501                                 -maxlength=>80);
3502         -or-
3503
3504    print $query->password_field('secret','starting value',50,80);
3505
3506 password_field() is identical to textfield(), except that its contents 
3507 will be starred out on the web page.
3508
3509 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3510 and B<-onSelect> parameters are recognized.  See textfield().
3511
3512 =head2 CREATING A FILE UPLOAD FIELD
3513
3514     print $query->filefield(-name=>'uploaded_file',
3515                             -default=>'starting value',
3516                             -size=>50,
3517                             -maxlength=>80);
3518         -or-
3519
3520     print $query->filefield('uploaded_file','starting value',50,80);
3521
3522 filefield() will return a file upload field for Netscape 2.0 browsers.
3523 In order to take full advantage of this I<you must use the new 
3524 multipart encoding scheme> for the form.  You can do this either
3525 by calling B<startform()> with an encoding type of B<$CGI::MULTIPART>,
3526 or by calling the new method B<start_multipart_form()> instead of
3527 vanilla B<startform()>.
3528
3529 =over 4
3530
3531 =item B<Parameters>
3532
3533 =item 1.
3534
3535 The first parameter is the required name for the field (-name).  
3536
3537 =item 2.
3538
3539 The optional second parameter is the starting value for the field contents
3540 to be used as the default file name (-default).
3541
3542 The beta2 version of Netscape 2.0 currently doesn't pay any attention
3543 to this field, and so the starting value will always be blank.  Worse,
3544 the field loses its "sticky" behavior and forgets its previous
3545 contents.  The starting value field is called for in the HTML
3546 specification, however, and possibly later versions of Netscape will
3547 honor it.
3548
3549 =item 3.
3550
3551 The optional third parameter is the size of the field in
3552 characters (-size).
3553
3554 =item 4.
3555
3556 The optional fourth parameter is the maximum number of characters the
3557 field will accept (-maxlength).
3558
3559 =back
3560
3561 When the form is processed, you can retrieve the entered filename
3562 by calling param().
3563
3564        $filename = $query->param('uploaded_file');
3565
3566 In Netscape Gold, the filename that gets returned is the full local filename
3567 on the B<remote user's> machine.  If the remote user is on a Unix
3568 machine, the filename will follow Unix conventions:
3569
3570         /path/to/the/file
3571
3572 On an MS-DOS/Windows and OS/2 machines, the filename will follow DOS conventions:
3573
3574         C:\PATH\TO\THE\FILE.MSW
3575
3576 On a Macintosh machine, the filename will follow Mac conventions:
3577
3578         HD 40:Desktop Folder:Sort Through:Reminders
3579
3580 The filename returned is also a file handle.  You can read the contents
3581 of the file using standard Perl file reading calls:
3582
3583         # Read a text file and print it out
3584         while (<$filename>) {
3585            print;
3586         }
3587
3588         # Copy a binary file to somewhere safe
3589         open (OUTFILE,">>/usr/local/web/users/feedback");
3590         while ($bytesread=read($filename,$buffer,1024)) {
3591            print OUTFILE $buffer;
3592         }
3593
3594 When a file is uploaded the browser usually sends along some
3595 information along with it in the format of headers.  The information
3596 usually includes the MIME content type.  Future browsers may send
3597 other information as well (such as modification date and size). To
3598 retrieve this information, call uploadInfo().  It returns a reference to
3599 an associative array containing all the document headers.
3600
3601        $filename = $query->param('uploaded_file');
3602        $type = $query->uploadInfo($filename)->{'Content-Type'};
3603        unless ($type eq 'text/html') {
3604           die "HTML FILES ONLY!";
3605        }
3606
3607 If you are using a machine that recognizes "text" and "binary" data
3608 modes, be sure to understand when and how to use them (see the Camel book).  
3609 Otherwise you may find that binary files are corrupted during file uploads.
3610
3611 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3612 and B<-onSelect> parameters are recognized.  See textfield()
3613 for details. 
3614
3615 =head2 CREATING A POPUP MENU
3616
3617    print $query->popup_menu('menu_name',
3618                             ['eenie','meenie','minie'],
3619                             'meenie');
3620
3621       -or-
3622
3623    %labels = ('eenie'=>'your first choice',
3624               'meenie'=>'your second choice',
3625               'minie'=>'your third choice');
3626    print $query->popup_menu('menu_name',
3627                             ['eenie','meenie','minie'],
3628                             'meenie',\%labels);
3629
3630         -or (named parameter style)-
3631
3632    print $query->popup_menu(-name=>'menu_name',
3633                             -values=>['eenie','meenie','minie'],
3634                             -default=>'meenie',
3635                             -labels=>\%labels);
3636
3637 popup_menu() creates a menu.
3638
3639 =over 4
3640
3641 =item 1.
3642
3643 The required first argument is the menu's name (-name).
3644
3645 =item 2.
3646
3647 The required second argument (-values) is an array B<reference>
3648 containing the list of menu items in the menu.  You can pass the
3649 method an anonymous array, as shown in the example, or a reference to
3650 a named array, such as "\@foo".
3651
3652 =item 3.
3653
3654 The optional third parameter (-default) is the name of the default
3655 menu choice.  If not specified, the first item will be the default.
3656 The values of the previous choice will be maintained across queries.
3657
3658 =item 4.
3659
3660 The optional fourth parameter (-labels) is provided for people who
3661 want to use different values for the user-visible label inside the
3662 popup menu nd the value returned to your script.  It's a pointer to an
3663 associative array relating menu values to user-visible labels.  If you
3664 leave this parameter blank, the menu values will be displayed by
3665 default.  (You can also leave a label undefined if you want to).
3666
3667 =back
3668
3669 When the form is processed, the selected value of the popup menu can
3670 be retrieved using:
3671
3672       $popup_menu_value = $query->param('menu_name');
3673
3674 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
3675 B<-onChange>, B<-onFocus>, and B<-onBlur>.  See the textfield()
3676 section for details on when these handlers are called.
3677
3678 =head2 CREATING A SCROLLING LIST
3679
3680    print $query->scrolling_list('list_name',
3681                                 ['eenie','meenie','minie','moe'],
3682                                 ['eenie','moe'],5,'true');
3683       -or-
3684
3685    print $query->scrolling_list('list_name',
3686                                 ['eenie','meenie','minie','moe'],
3687                                 ['eenie','moe'],5,'true',
3688                                 \%labels);
3689
3690         -or-
3691
3692    print $query->scrolling_list(-name=>'list_name',
3693                                 -values=>['eenie','meenie','minie','moe'],
3694                                 -default=>['eenie','moe'],
3695                                 -size=>5,
3696                                 -multiple=>'true',
3697                                 -labels=>\%labels);
3698
3699 scrolling_list() creates a scrolling list.  
3700
3701 =over 4
3702
3703 =item B<Parameters:>
3704
3705 =item 1.
3706
3707 The first and second arguments are the list name (-name) and values
3708 (-values).  As in the popup menu, the second argument should be an
3709 array reference.
3710
3711 =item 2.
3712
3713 The optional third argument (-default) can be either a reference to a
3714 list containing the values to be selected by default, or can be a
3715 single value to select.  If this argument is missing or undefined,
3716 then nothing is selected when the list first appears.  In the named
3717 parameter version, you can use the synonym "-defaults" for this
3718 parameter.
3719
3720 =item 3.
3721
3722 The optional fourth argument is the size of the list (-size).
3723
3724 =item 4.
3725
3726 The optional fifth argument can be set to true to allow multiple
3727 simultaneous selections (-multiple).  Otherwise only one selection
3728 will be allowed at a time.
3729
3730 =item 5.
3731
3732 The optional sixth argument is a pointer to an associative array
3733 containing long user-visible labels for the list items (-labels).
3734 If not provided, the values will be displayed.
3735
3736 When this form is processed, all selected list items will be returned as
3737 a list under the parameter name 'list_name'.  The values of the
3738 selected items can be retrieved with:
3739
3740       @selected = $query->param('list_name');
3741
3742 =back
3743
3744 JAVASCRIPTING: scrolling_list() recognizes the following event handlers:
3745 B<-onChange>, B<-onFocus>, and B<-onBlur>.  See textfield() for
3746 the description of when these handlers are called.
3747
3748 =head2 CREATING A GROUP OF RELATED CHECKBOXES
3749
3750    print $query->checkbox_group(-name=>'group_name',
3751                                 -values=>['eenie','meenie','minie','moe'],
3752                                 -default=>['eenie','moe'],
3753                                 -linebreak=>'true',
3754                                 -labels=>\%labels);
3755
3756    print $query->checkbox_group('group_name',
3757                                 ['eenie','meenie','minie','moe'],
3758                                 ['eenie','moe'],'true',\%labels);
3759
3760    HTML3-COMPATIBLE BROWSERS ONLY:
3761
3762    print $query->checkbox_group(-name=>'group_name',
3763                                 -values=>['eenie','meenie','minie','moe'],
3764                                 -rows=2,-columns=>2);
3765     
3766
3767 checkbox_group() creates a list of checkboxes that are related
3768 by the same name.
3769
3770 =over 4
3771
3772 =item B<Parameters:>
3773
3774 =item 1.
3775
3776 The first and second arguments are the checkbox name and values,
3777 respectively (-name and -values).  As in the popup menu, the second
3778 argument should be an array reference.  These values are used for the
3779 user-readable labels printed next to the checkboxes as well as for the
3780 values passed to your script in the query string.
3781
3782 =item 2.
3783
3784 The optional third argument (-default) can be either a reference to a
3785 list containing the values to be checked by default, or can be a
3786 single value to checked.  If this argument is missing or undefined,
3787 then nothing is selected when the list first appears.
3788
3789 =item 3.
3790
3791 The optional fourth argument (-linebreak) can be set to true to place
3792 line breaks between the checkboxes so that they appear as a vertical
3793 list.  Otherwise, they will be strung together on a horizontal line.
3794
3795 =item 4.
3796
3797 The optional fifth argument is a pointer to an associative array
3798 relating the checkbox values to the user-visible labels that will will
3799 be printed next to them (-labels).  If not provided, the values will
3800 be used as the default.
3801
3802 =item 5.
3803
3804 B<HTML3-compatible browsers> (such as Netscape) can take advantage 
3805 of the optional 
3806 parameters B<-rows>, and B<-columns>.  These parameters cause
3807 checkbox_group() to return an HTML3 compatible table containing
3808 the checkbox group formatted with the specified number of rows
3809 and columns.  You can provide just the -columns parameter if you
3810 wish; checkbox_group will calculate the correct number of rows
3811 for you.
3812
3813 To include row and column headings in the returned table, you
3814 can use the B<-rowheader> and B<-colheader> parameters.  Both
3815 of these accept a pointer to an array of headings to use.
3816 The headings are just decorative.  They don't reorganize the
3817 interpretation of the checkboxes -- they're still a single named
3818 unit.
3819
3820 =back
3821
3822 When the form is processed, all checked boxes will be returned as
3823 a list under the parameter name 'group_name'.  The values of the
3824 "on" checkboxes can be retrieved with:
3825
3826       @turned_on = $query->param('group_name');
3827
3828 The value returned by checkbox_group() is actually an array of button
3829 elements.  You can capture them and use them within tables, lists,
3830 or in other creative ways:
3831
3832     @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
3833     &use_in_creative_way(@h);
3834
3835 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
3836 parameter.  This specifies a JavaScript code fragment or
3837 function call to be executed every time the user clicks on
3838 any of the buttons in the group.  You can retrieve the identity
3839 of the particular button clicked on using the "this" variable.
3840
3841 =head2 CREATING A STANDALONE CHECKBOX
3842
3843     print $query->checkbox(-name=>'checkbox_name',
3844                            -checked=>'checked',
3845                            -value=>'ON',
3846                            -label=>'CLICK ME');
3847
3848         -or-
3849
3850     print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
3851
3852 checkbox() is used to create an isolated checkbox that isn't logically
3853 related to any others.
3854
3855 =over 4
3856
3857 =item B<Parameters:>
3858
3859 =item 1.
3860
3861 The first parameter is the required name for the checkbox (-name).  It
3862 will also be used for the user-readable label printed next to the
3863 checkbox.
3864
3865 =item 2.
3866
3867 The optional second parameter (-checked) specifies that the checkbox
3868 is turned on by default.  Synonyms are -selected and -on.
3869
3870 =item 3.
3871
3872 The optional third parameter (-value) specifies the value of the
3873 checkbox when it is checked.  If not provided, the word "on" is
3874 assumed.
3875
3876 =item 4.
3877
3878 The optional fourth parameter (-label) is the user-readable label to
3879 be attached to the checkbox.  If not provided, the checkbox name is
3880 used.
3881
3882 =back
3883
3884 The value of the checkbox can be retrieved using:
3885
3886     $turned_on = $query->param('checkbox_name');
3887
3888 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
3889 parameter.  See checkbox_group() for further details.
3890
3891 =head2 CREATING A RADIO BUTTON GROUP
3892
3893    print $query->radio_group(-name=>'group_name',
3894                              -values=>['eenie','meenie','minie'],
3895                              -default=>'meenie',
3896                              -linebreak=>'true',
3897                              -labels=>\%labels);
3898
3899         -or-
3900
3901    print $query->radio_group('group_name',['eenie','meenie','minie'],
3902                                           'meenie','true',\%labels);
3903
3904
3905    HTML3-COMPATIBLE BROWSERS ONLY:
3906
3907    print $query->radio_group(-name=>'group_name',
3908                              -values=>['eenie','meenie','minie','moe'],
3909                              -rows=2,-columns=>2);
3910
3911 radio_group() creates a set of logically-related radio buttons
3912 (turning one member of the group on turns the others off)
3913
3914 =over 4
3915
3916 =item B<Parameters:>
3917
3918 =item 1.
3919
3920 The first argument is the name of the group and is required (-name).
3921
3922 =item 2.
3923
3924 The second argument (-values) is the list of values for the radio
3925 buttons.  The values and the labels that appear on the page are
3926 identical.  Pass an array I<reference> in the second argument, either
3927 using an anonymous array, as shown, or by referencing a named array as
3928 in "\@foo".
3929
3930 =item 3.
3931
3932 The optional third parameter (-default) is the name of the default
3933 button to turn on. If not specified, the first item will be the
3934 default.  You can provide a nonexistent button name, such as "-" to
3935 start up with no buttons selected.
3936
3937 =item 4.
3938
3939 The optional fourth parameter (-linebreak) can be set to 'true' to put
3940 line breaks between the buttons, creating a vertical list.
3941
3942 =item 5.
3943
3944 The optional fifth parameter (-labels) is a pointer to an associative
3945 array relating the radio button values to user-visible labels to be
3946 used in the display.  If not provided, the values themselves are
3947 displayed.
3948
3949 =item 6.
3950
3951 B<HTML3-compatible browsers> (such as Netscape) can take advantage 
3952 of the optional 
3953 parameters B<-rows>, and B<-columns>.  These parameters cause
3954 radio_group() to return an HTML3 compatible table containing
3955 the radio group formatted with the specified number of rows
3956 and columns.  You can provide just the -columns parameter if you
3957 wish; radio_group will calculate the correct number of rows
3958 for you.
3959
3960 To include row and column headings in the returned table, you
3961 can use the B<-rowheader> and B<-colheader> parameters.  Both
3962 of these accept a pointer to an array of headings to use.
3963 The headings are just decorative.  They don't reorganize the
3964 interpetation of the radio buttons -- they're still a single named
3965 unit.
3966
3967 =back
3968
3969 When the form is processed, the selected radio button can
3970 be retrieved using:
3971
3972       $which_radio_button = $query->param('group_name');
3973
3974 The value returned by radio_group() is actually an array of button
3975 elements.  You can capture them and use them within tables, lists,
3976 or in other creative ways:
3977
3978     @h = $query->radio_group(-name=>'group_name',-values=>\@values);
3979     &use_in_creative_way(@h);
3980
3981 =head2 CREATING A SUBMIT BUTTON 
3982
3983    print $query->submit(-name=>'button_name',
3984                         -value=>'value');
3985
3986         -or-
3987
3988    print $query->submit('button_name','value');
3989
3990 submit() will create the query submission button.  Every form
3991 should have one of these.
3992
3993 =over 4
3994
3995 =item B<Parameters:>
3996
3997 =item 1.
3998
3999 The first argument (-name) is optional.  You can give the button a
4000 name if you have several submission buttons in your form and you want
4001 to distinguish between them.  The name will also be used as the
4002 user-visible label.  Be aware that a few older browsers don't deal with this correctly and
4003 B<never> send back a value from a button.
4004
4005 =item 2.
4006
4007 The second argument (-value) is also optional.  This gives the button
4008 a value that will be passed to your script in the query string.
4009
4010 =back
4011
4012 You can figure out which button was pressed by using different
4013 values for each one:
4014
4015      $which_one = $query->param('button_name');
4016
4017 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
4018 parameter.  See checkbox_group() for further details.
4019
4020 =head2 CREATING A RESET BUTTON
4021
4022    print $query->reset
4023
4024 reset() creates the "reset" button.  Note that it restores the
4025 form to its value from the last time the script was called, 
4026 NOT necessarily to the defaults.
4027
4028 =head2 CREATING A DEFAULT BUTTON
4029
4030    print $query->defaults('button_label')
4031
4032 defaults() creates a button that, when invoked, will cause the
4033 form to be completely reset to its defaults, wiping out all the
4034 changes the user ever made.
4035
4036 =head2 CREATING A HIDDEN FIELD
4037
4038         print $query->hidden(-name=>'hidden_name',
4039                              -default=>['value1','value2'...]);
4040
4041                 -or-
4042
4043         print $query->hidden('hidden_name','value1','value2'...);
4044
4045 hidden() produces a text field that can't be seen by the user.  It
4046 is useful for passing state variable information from one invocation
4047 of the script to the next.
4048
4049 =over 4
4050
4051 =item B<Parameters:>
4052
4053 =item 1.
4054
4055 The first argument is required and specifies the name of this
4056 field (-name).
4057
4058 =item 2.  
4059
4060 The second argument is also required and specifies its value
4061 (-default).  In the named parameter style of calling, you can provide
4062 a single value here or a reference to a whole list
4063
4064 =back
4065
4066 Fetch the value of a hidden field this way:
4067
4068      $hidden_value = $query->param('hidden_name');
4069
4070 Note, that just like all the other form elements, the value of a
4071 hidden field is "sticky".  If you want to replace a hidden field with
4072 some other values after the script has been called once you'll have to
4073 do it manually:
4074
4075      $query->param('hidden_name','new','values','here');
4076
4077 =head2 CREATING A CLICKABLE IMAGE BUTTON
4078
4079      print $query->image_button(-name=>'button_name',
4080                                 -src=>'/source/URL',
4081                                 -align=>'MIDDLE');      
4082
4083         -or-
4084
4085      print $query->image_button('button_name','/source/URL','MIDDLE');
4086
4087 image_button() produces a clickable image.  When it's clicked on the
4088 position of the click is returned to your script as "button_name.x"
4089 and "button_name.y", where "button_name" is the name you've assigned
4090 to it.
4091
4092 JAVASCRIPTING: image_button() recognizes the B<-onClick>
4093 parameter.  See checkbox_group() for further details.
4094
4095 =over 4
4096
4097 =item B<Parameters:>
4098
4099 =item 1.
4100
4101 The first argument (-name) is required and specifies the name of this
4102 field.
4103
4104 =item 2.
4105
4106 The second argument (-src) is also required and specifies the URL
4107
4108 =item 3.
4109 The third option (-align, optional) is an alignment type, and may be
4110 TOP, BOTTOM or MIDDLE
4111
4112 =back
4113
4114 Fetch the value of the button this way:
4115      $x = $query->param('button_name.x');
4116      $y = $query->param('button_name.y');
4117
4118 =head2 CREATING A JAVASCRIPT ACTION BUTTON
4119
4120      print $query->button(-name=>'button_name',
4121                           -value=>'user visible label',
4122                           -onClick=>"do_something()");
4123
4124         -or-
4125
4126      print $query->button('button_name',"do_something()");
4127
4128 button() produces a button that is compatible with Netscape 2.0's
4129 JavaScript.  When it's pressed the fragment of JavaScript code
4130 pointed to by the B<-onClick> parameter will be executed.  On
4131 non-Netscape browsers this form element will probably not even
4132 display.
4133
4134 =head1 NETSCAPE COOKIES
4135
4136 Netscape browsers versions 1.1 and higher support a so-called
4137 "cookie" designed to help maintain state within a browser session.
4138 CGI.pm has several methods that support cookies.
4139
4140 A cookie is a name=value pair much like the named parameters in a CGI
4141 query string.  CGI scripts create one or more cookies and send
4142 them to the browser in the HTTP header.  The browser maintains a list
4143 of cookies that belong to a particular Web server, and returns them
4144 to the CGI script during subsequent interactions.
4145
4146 In addition to the required name=value pair, each cookie has several
4147 optional attributes:
4148
4149 =over 4
4150
4151 =item 1. an expiration time
4152
4153 This is a time/date string (in a special GMT format) that indicates
4154 when a cookie expires.  The cookie will be saved and returned to your
4155 script until this expiration date is reached if the user exits
4156 Netscape and restarts it.  If an expiration date isn't specified, the cookie
4157 will remain active until the user quits Netscape.
4158
4159 =item 2. a domain
4160
4161 This is a partial or complete domain name for which the cookie is 
4162 valid.  The browser will return the cookie to any host that matches
4163 the partial domain name.  For example, if you specify a domain name
4164 of ".capricorn.com", then Netscape will return the cookie to
4165 Web servers running on any of the machines "www.capricorn.com", 
4166 "www2.capricorn.com", "feckless.capricorn.com", etc.  Domain names
4167 must contain at least two periods to prevent attempts to match
4168 on top level domains like ".edu".  If no domain is specified, then
4169 the browser will only return the cookie to servers on the host the
4170 cookie originated from.
4171
4172 =item 3. a path
4173
4174 If you provide a cookie path attribute, the browser will check it
4175 against your script's URL before returning the cookie.  For example,
4176 if you specify the path "/cgi-bin", then the cookie will be returned
4177 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
4178 and "/cgi-bin/customer_service/complain.pl", but not to the script
4179 "/cgi-private/site_admin.pl".  By default, path is set to "/", which
4180 causes the cookie to be sent to any CGI script on your site.
4181
4182 =item 4. a "secure" flag
4183
4184 If the "secure" attribute is set, the cookie will only be sent to your
4185 script if the CGI request is occurring on a secure channel, such as SSL.
4186
4187 =back
4188
4189 The interface to Netscape cookies is the B<cookie()> method:
4190
4191     $cookie = $query->cookie(-name=>'sessionID',
4192                              -value=>'xyzzy',
4193                              -expires=>'+1h',
4194                              -path=>'/cgi-bin/database',
4195                              -domain=>'.capricorn.org',
4196                              -secure=>1);
4197     print $query->header(-cookie=>$cookie);
4198
4199 B<cookie()> creates a new cookie.  Its parameters include:
4200
4201 =over 4
4202
4203 =item B<-name>
4204
4205 The name of the cookie (required).  This can be any string at all.
4206 Although Netscape limits its cookie names to non-whitespace
4207 alphanumeric characters, CGI.pm removes this restriction by escaping
4208 and unescaping cookies behind the scenes.
4209
4210 =item B<-value>
4211
4212 The value of the cookie.  This can be any scalar value,
4213 array reference, or even associative array reference.  For example,
4214 you can store an entire associative array into a cookie this way:
4215
4216         $cookie=$query->cookie(-name=>'family information',
4217                                -value=>\%childrens_ages);
4218
4219 =item B<-path>
4220
4221 The optional partial path for which this cookie will be valid, as described
4222 above.
4223
4224 =item B<-domain>
4225
4226 The optional partial domain for which this cookie will be valid, as described
4227 above.
4228
4229 =item B<-expires>
4230
4231 The optional expiration date for this cookie.  The format is as described 
4232 in the section on the B<header()> method:
4233
4234         "+1h"  one hour from now
4235
4236 =item B<-secure>
4237
4238 If set to true, this cookie will only be used within a secure
4239 SSL session.
4240
4241 =back
4242
4243 The cookie created by cookie() must be incorporated into the HTTP
4244 header within the string returned by the header() method:
4245
4246         print $query->header(-cookie=>$my_cookie);
4247
4248 To create multiple cookies, give header() an array reference:
4249
4250         $cookie1 = $query->cookie(-name=>'riddle_name',
4251                                   -value=>"The Sphynx's Question");
4252         $cookie2 = $query->cookie(-name=>'answers',
4253                                   -value=>\%answers);
4254         print $query->header(-cookie=>[$cookie1,$cookie2]);
4255
4256 To retrieve a cookie, request it by name by calling cookie()
4257 method without the B<-value> parameter:
4258
4259         use CGI;
4260         $query = new CGI;
4261         %answers = $query->cookie(-name=>'answers');
4262         # $query->cookie('answers') will work too!
4263
4264 The cookie and CGI namespaces are separate.  If you have a parameter
4265 named 'answers' and a cookie named 'answers', the values retrieved by
4266 param() and cookie() are independent of each other.  However, it's
4267 simple to turn a CGI parameter into a cookie, and vice-versa:
4268
4269    # turn a CGI parameter into a cookie
4270    $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
4271    # vice-versa
4272    $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
4273
4274 See the B<cookie.cgi> example script for some ideas on how to use
4275 cookies effectively.
4276
4277 B<NOTE:> There appear to be some (undocumented) restrictions on
4278 Netscape cookies.  In Netscape 2.01, at least, I haven't been able to
4279 set more than three cookies at a time.  There may also be limits on
4280 the length of cookies.  If you need to store a lot of information,
4281 it's probably better to create a unique session ID, store it in a
4282 cookie, and use the session ID to locate an external file/database
4283 saved on the server's side of the connection.
4284
4285 =head1 WORKING WITH NETSCAPE FRAMES
4286
4287 It's possible for CGI.pm scripts to write into several browser
4288 panels and windows using Netscape's frame mechanism.  
4289 There are three techniques for defining new frames programmatically:
4290
4291 =over 4
4292
4293 =item 1. Create a <Frameset> document
4294
4295 After writing out the HTTP header, instead of creating a standard
4296 HTML document using the start_html() call, create a <FRAMESET> 
4297 document that defines the frames on the page.  Specify your script(s)
4298 (with appropriate parameters) as the SRC for each of the frames.
4299
4300 There is no specific support for creating <FRAMESET> sections 
4301 in CGI.pm, but the HTML is very simple to write.  See the frame
4302 documentation in Netscape's home pages for details 
4303
4304   http://home.netscape.com/assist/net_sites/frames.html
4305
4306 =item 2. Specify the destination for the document in the HTTP header
4307
4308 You may provide a B<-target> parameter to the header() method:
4309    
4310     print $q->header(-target=>'ResultsWindow');
4311
4312 This will tell Netscape to load the output of your script into the
4313 frame named "ResultsWindow".  If a frame of that name doesn't
4314 already exist, Netscape will pop up a new window and load your
4315 script's document into that.  There are a number of magic names
4316 that you can use for targets.  See the frame documents on Netscape's
4317 home pages for details.
4318
4319 =item 3. Specify the destination for the document in the <FORM> tag
4320
4321 You can specify the frame to load in the FORM tag itself.  With
4322 CGI.pm it looks like this:
4323
4324     print $q->startform(-target=>'ResultsWindow');
4325
4326 When your script is reinvoked by the form, its output will be loaded
4327 into the frame named "ResultsWindow".  If one doesn't already exist
4328 a new window will be created.
4329
4330 =back
4331
4332 The script "frameset.cgi" in the examples directory shows one way to
4333 create pages in which the fill-out form and the response live in
4334 side-by-side frames.
4335
4336 =head1 DEBUGGING
4337
4338 If you are running the script
4339 from the command line or in the perl debugger, you can pass the script
4340 a list of keywords or parameter=value pairs on the command line or 
4341 from standard input (you don't have to worry about tricking your
4342 script into reading from environment variables).
4343 You can pass keywords like this:
4344
4345     your_script.pl keyword1 keyword2 keyword3
4346
4347 or this:
4348
4349    your_script.pl keyword1+keyword2+keyword3
4350
4351 or this:
4352
4353     your_script.pl name1=value1 name2=value2
4354
4355 or this:
4356
4357     your_script.pl name1=value1&name2=value2
4358
4359 or even as newline-delimited parameters on standard input.
4360
4361 When debugging, you can use quotes and backslashes to escape 
4362 characters in the familiar shell manner, letting you place
4363 spaces and other funny characters in your parameter=value
4364 pairs:
4365
4366    your_script.pl "name1='I am a long value'" "name2=two\ words"
4367
4368 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
4369
4370 The dump() method produces a string consisting of all the query's
4371 name/value pairs formatted nicely as a nested list.  This is useful
4372 for debugging purposes:
4373
4374     print $query->dump
4375     
4376
4377 Produces something that looks like:
4378
4379     <UL>
4380     <LI>name1
4381         <UL>
4382         <LI>value1
4383         <LI>value2
4384         </UL>
4385     <LI>name2
4386         <UL>
4387         <LI>value1
4388         </UL>
4389     </UL>
4390
4391 You can pass a value of 'true' to dump() in order to get it to
4392 print the results out as plain text, suitable for incorporating
4393 into a <PRE> section.
4394
4395 As a shortcut, as of version 1.56 you can interpolate the entire 
4396 CGI object into a string and it will be replaced with the
4397 the a nice HTML dump shown above:
4398
4399     $query=new CGI;
4400     print "<H2>Current Values</H2> $query\n";
4401
4402 =head1 FETCHING ENVIRONMENT VARIABLES
4403
4404 Some of the more useful environment variables can be fetched
4405 through this interface.  The methods are as follows:
4406
4407 =over 4
4408
4409 =item B<accept()>
4410
4411 Return a list of MIME types that the remote browser
4412 accepts. If you give this method a single argument
4413 corresponding to a MIME type, as in
4414 $query->accept('text/html'), it will return a
4415 floating point value corresponding to the browser's
4416 preference for this type from 0.0 (don't want) to 1.0.
4417 Glob types (e.g. text/*) in the browser's accept list
4418 are handled correctly.
4419
4420 =item B<raw_cookie()>
4421
4422 Returns the HTTP_COOKIE variable, an HTTP extension
4423 implemented by Netscape browsers version 1.1
4424 and higher.  Cookies have a special format, and this 
4425 method call just returns the raw form (?cookie dough).
4426 See cookie() for ways of setting and retrieving
4427 cooked cookies.
4428
4429 =item B<user_agent()>
4430
4431 Returns the HTTP_USER_AGENT variable.  If you give
4432 this method a single argument, it will attempt to
4433 pattern match on it, allowing you to do something
4434 like $query->user_agent(netscape);
4435
4436 =item B<path_info()>
4437
4438 Returns additional path information from the script URL.
4439 E.G. fetching /cgi-bin/your_script/additional/stuff will
4440 result in $query->path_info() returning
4441 "additional/stuff".
4442
4443 NOTE: The Microsoft Internet Information Server
4444 is broken with respect to additional path information.  If
4445 you use the Perl DLL library, the IIS server will attempt to
4446 execute the additional path information as a Perl script.
4447 If you use the ordinary file associations mapping, the
4448 path information will be present in the environment, 
4449 but incorrect.  The best thing to do is to avoid using additional
4450 path information in CGI scripts destined for use with IIS.
4451
4452 =item B<path_translated()>
4453
4454 As per path_info() but returns the additional
4455 path information translated into a physical path, e.g.
4456 "/usr/local/etc/httpd/htdocs/additional/stuff".
4457
4458 The Microsoft IIS is broken with respect to the translated
4459 path as well.
4460
4461 =item B<remote_host()>
4462
4463 Returns either the remote host name or IP address.
4464 if the former is unavailable.
4465
4466 =item B<script_name()>
4467 Return the script name as a partial URL, for self-refering
4468 scripts.
4469
4470 =item B<referer()>
4471
4472 Return the URL of the page the browser was viewing
4473 prior to fetching your script.  Not available for all
4474 browsers.
4475
4476 =item B<auth_type ()>
4477
4478 Return the authorization/verification method in use for this
4479 script, if any.
4480
4481 =item B<server_name ()>
4482
4483 Returns the name of the server, usually the machine's host
4484 name.
4485
4486 =item B<virtual_host ()>
4487
4488 When using virtual hosts, returns the name of the host that
4489 the browser attempted to contact
4490
4491 =item B<server_software ()>
4492
4493 Returns the server software and version number.
4494
4495 =item B<remote_user ()>
4496
4497 Return the authorization/verification name used for user
4498 verification, if this script is protected.
4499
4500 =item B<user_name ()>
4501
4502 Attempt to obtain the remote user's name, using a variety
4503 of different techniques.  This only works with older browsers
4504 such as Mosaic.  Netscape does not reliably report the user
4505 name!
4506
4507 =item B<request_method()>
4508
4509 Returns the method used to access your script, usually
4510 one of 'POST', 'GET' or 'HEAD'.
4511
4512 =back
4513
4514 =head1 CREATING HTML ELEMENTS:
4515
4516 In addition to its shortcuts for creating form elements, CGI.pm
4517 defines general HTML shortcut methods as well.  HTML shortcuts are
4518 named after a single HTML element and return a fragment of HTML text
4519 that you can then print or manipulate as you like.
4520
4521 This example shows how to use the HTML methods:
4522
4523         $q = new CGI;
4524         print $q->blockquote(
4525                              "Many years ago on the island of",
4526                              $q->a({href=>"http://crete.org/"},"Crete"),
4527                              "there lived a minotaur named",
4528                              $q->strong("Fred."),
4529                             ),
4530                $q->hr;
4531
4532 This results in the following HTML code (extra newlines have been
4533 added for readability):
4534
4535         <blockquote>
4536         Many years ago on the island of
4537         <a HREF="http://crete.org/">Crete</a> there lived
4538         a minotaur named <strong>Fred.</strong> 
4539         </blockquote>
4540         <hr>
4541
4542 If you find the syntax for calling the HTML shortcuts awkward, you can
4543 import them into your namespace and dispense with the object syntax
4544 completely (see the next section for more details):
4545
4546         use CGI shortcuts;      # IMPORT HTML SHORTCUTS
4547         print blockquote(
4548                      "Many years ago on the island of",
4549                      a({href=>"http://crete.org/"},"Crete"),
4550                      "there lived a minotaur named",
4551                      strong("Fred."),
4552                      ),
4553                hr;
4554
4555 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4556
4557 The HTML methods will accept zero, one or multiple arguments.  If you
4558 provide no arguments, you get a single tag:
4559
4560         print hr;  
4561         #  gives "<hr>"
4562
4563 If you provide one or more string arguments, they are concatenated
4564 together with spaces and placed between opening and closing tags:
4565
4566         print h1("Chapter","1"); 
4567         # gives "<h1>Chapter 1</h1>"
4568
4569 If the first argument is an associative array reference, then the keys
4570 and values of the associative array become the HTML tag's attributes:
4571
4572         print a({href=>'fred.html',target=>'_new'},
4573                 "Open a new frame");
4574         # gives <a href="fred.html",target="_new">Open a new frame</a>
4575
4576 You are free to use CGI.pm-style dashes in front of the attribute
4577 names if you prefer:
4578
4579         print img {-src=>'fred.gif',-align=>'LEFT'};
4580         # gives <img ALIGN="LEFT" SRC="fred.gif">
4581
4582 =head2 Generating new HTML tags
4583
4584 Since no mere mortal can keep up with Netscape and Microsoft as they
4585 battle it out for control of HTML, the code that generates HTML tags
4586 is general and extensible.  You can create new HTML tags freely just
4587 by referring to them on the import line:
4588
4589         use CGI shortcuts,winkin,blinkin,nod;
4590
4591 Now, in addition to the standard CGI shortcuts, you've created HTML
4592 tags named "winkin", "blinkin" and "nod".  You can use them like this:
4593
4594         print blinkin {color=>'blue',rate=>'fast'},"Yahoo!";
4595         # <blinkin COLOR="blue" RATE="fast">Yahoo!</blinkin>
4596
4597 =head1 IMPORTING CGI METHOD CALLS INTO YOUR NAME SPACE
4598
4599 As a convenience, you can import most of the CGI method calls directly
4600 into your name space.  The syntax for doing this is:
4601
4602         use CGI <list of methods>;
4603
4604 The listed methods will be imported into the current package; you can
4605 call them directly without creating a CGI object first.  This example
4606 shows how to import the B<param()> and B<header()>
4607 methods, and then use them directly:
4608
4609         use CGI param,header;
4610         print header('text/plain');
4611         $zipcode = param('zipcode');
4612
4613 You can import groups of methods by referring to a number of special
4614 names:
4615
4616 =over 4
4617
4618 =item B<cgi>
4619
4620 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4621 and the like.
4622
4623 =item B<form>
4624
4625 Import all fill-out form generating methods, such as B<textfield()>.
4626
4627 =item B<html2>
4628
4629 Import all methods that generate HTML 2.0 standard elements.
4630
4631 =item B<html3>
4632
4633 Import all methods that generate HTML 3.0 proposed elements (such as
4634 <table>, <super> and <sub>).
4635
4636 =item B<netscape>
4637
4638 Import all methods that generate Netscape-specific HTML extensions.
4639
4640 =item B<shortcuts>
4641
4642 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4643 'netscape')...
4644
4645 =item B<standard>
4646
4647 Import "standard" features, 'html2', 'form' and 'cgi'.
4648
4649 =item B<all>
4650
4651 Import all the available methods.  For the full list, see the CGI.pm
4652 code, where the variable %TAGS is defined.
4653
4654 =back
4655
4656 Note that in the interests of execution speed CGI.pm does B<not> use
4657 the standard L<Exporter> syntax for specifying load symbols.  This may
4658 change in the future.
4659
4660 If you import any of the state-maintaining CGI or form-generating
4661 methods, a default CGI object will be created and initialized
4662 automatically the first time you use any of the methods that require
4663 one to be present.  This includes B<param()>, B<textfield()>,
4664 B<submit()> and the like.  (If you need direct access to the CGI
4665 object, you can find it in the global variable B<$CGI::Q>).  By
4666 importing CGI.pm methods, you can create visually elegant scripts:
4667
4668    use CGI standard,html2;
4669    print 
4670        header,
4671        start_html('Simple Script'),
4672        h1('Simple Script'),
4673        start_form,
4674        "What's your name? ",textfield('name'),p,
4675        "What's the combination?",
4676        checkbox_group(-name=>'words',
4677                       -values=>['eenie','meenie','minie','moe'],
4678                       -defaults=>['eenie','moe']),p,
4679        "What's your favorite color?",
4680        popup_menu(-name=>'color',
4681                   -values=>['red','green','blue','chartreuse']),p,
4682        submit,
4683        end_form,
4684        hr,"\n";
4685
4686     if (param) {
4687        print 
4688            "Your name is ",em(param('name')),p,
4689            "The keywords are: ",em(join(", ",param('words'))),p,
4690            "Your favorite color is ",em(param('color')),".\n";
4691     }
4692     print end_html;
4693
4694 =head1 USING NPH SCRIPTS
4695
4696 NPH, or "no-parsed-header", scripts bypass the server completely by
4697 sending the complete HTTP header directly to the browser.  This has
4698 slight performance benefits, but is of most use for taking advantage
4699 of HTTP extensions that are not directly supported by your server,
4700 such as server push and PICS headers.
4701
4702 Servers use a variety of conventions for designating CGI scripts as
4703 NPH.  Many Unix servers look at the beginning of the script's name for
4704 the prefix "nph-".  The Macintosh WebSTAR server and Microsoft's
4705 Internet Information Server, in contrast, try to decide whether a
4706 program is an NPH script by examining the first line of script output.
4707
4708
4709 CGI.pm supports NPH scripts with a special NPH mode.  When in this
4710 mode, CGI.pm will output the necessary extra header information when
4711 the header() and redirect() methods are
4712 called.
4713
4714 The Microsoft Internet Information Server requires NPH mode.  As of version
4715 2.30, CGI.pm will automatically detect when the script is running under IIS
4716 and put itself into this mode.  You do not need to do this manually, although
4717 it won't hurt anything if you do.
4718
4719 There are a number of ways to put CGI.pm into NPH mode:
4720
4721 =over 4
4722
4723 =item In the B<use> statement
4724 Simply add ":nph" to the list of symbols to be imported into your script:
4725
4726       use CGI qw(:standard :nph)
4727
4728 =item By calling the B<nph()> method:
4729
4730 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
4731
4732       CGI->nph(1)
4733
4734 =item By using B<-nph> parameters in the B<header()> and B<redirect()>  statements:
4735
4736       print $q->header(-nph=&gt;1);
4737
4738 =back
4739
4740 =head1 AUTHOR INFORMATION
4741
4742 Copyright 1995,1996, Lincoln D. Stein.  All rights reserved.  It may
4743 be used and modified freely, but I do request that this copyright
4744 notice remain attached to the file.  You may modify this module as you
4745 wish, but if you redistribute a modified version, please attach a note
4746 listing the modifications you have made.
4747
4748 Address bug reports and comments to:
4749 lstein@genome.wi.mit.edu
4750
4751 =head1 CREDITS
4752
4753 Thanks very much to:
4754
4755 =over 4
4756
4757 =item Matt Heffron (heffron@falstaff.css.beckman.com)
4758
4759 =item James Taylor (james.taylor@srs.gov)
4760
4761 =item Scott Anguish <sanguish@digifix.com>
4762
4763 =item Mike Jewell (mlj3u@virginia.edu)
4764
4765 =item Timothy Shimmin (tes@kbs.citri.edu.au)
4766
4767 =item Joergen Haegg (jh@axis.se)
4768
4769 =item Laurent Delfosse (delfosse@csgrad1.cs.wvu.edu)
4770
4771 =item Richard Resnick (applepi1@aol.com)
4772
4773 =item Craig Bishop (csb@barwonwater.vic.gov.au)
4774
4775 =item Tony Curtis (tc@vcpc.univie.ac.at)
4776
4777 =item Tim Bunce (Tim.Bunce@ig.co.uk)
4778
4779 =item Tom Christiansen (tchrist@convex.com)
4780
4781 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
4782
4783 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
4784
4785 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
4786
4787 =item Stephen Dahmen (joyfire@inxpress.net)
4788
4789 =item Ed Jordan (ed@fidalgo.net)
4790
4791 =item David Alan Pisoni (david@cnation.com)
4792
4793 =item ...and many many more...
4794
4795 for suggestions and bug fixes.
4796
4797 =back
4798
4799 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
4800
4801
4802         #!/usr/local/bin/perl
4803      
4804         use CGI;
4805  
4806         $query = new CGI;
4807
4808         print $query->header;
4809         print $query->start_html("Example CGI.pm Form");
4810         print "<H1> Example CGI.pm Form</H1>\n";
4811         &print_prompt($query);
4812         &do_work($query);
4813         &print_tail;
4814         print $query->end_html;
4815  
4816         sub print_prompt {
4817            my($query) = @_;
4818  
4819            print $query->startform;
4820            print "<EM>What's your name?</EM><BR>";
4821            print $query->textfield('name');
4822            print $query->checkbox('Not my real name');
4823  
4824            print "<P><EM>Where can you find English Sparrows?</EM><BR>";
4825            print $query->checkbox_group(
4826                                  -name=>'Sparrow locations',
4827                                  -values=>[England,France,Spain,Asia,Hoboken],
4828                                  -linebreak=>'yes',
4829                                  -defaults=>[England,Asia]);
4830  
4831            print "<P><EM>How far can they fly?</EM><BR>",
4832                 $query->radio_group(
4833                         -name=>'how far',
4834                         -values=>['10 ft','1 mile','10 miles','real far'],
4835                         -default=>'1 mile');
4836  
4837            print "<P><EM>What's your favorite color?</EM>  ";
4838            print $query->popup_menu(-name=>'Color',
4839                                     -values=>['black','brown','red','yellow'],
4840                                     -default=>'red');
4841  
4842            print $query->hidden('Reference','Monty Python and the Holy Grail');
4843  
4844            print "<P><EM>What have you got there?</EM><BR>";
4845            print $query->scrolling_list(
4846                          -name=>'possessions',
4847                          -values=>['A Coconut','A Grail','An Icon',
4848                                    'A Sword','A Ticket'],
4849                          -size=>5,
4850                          -multiple=>'true');
4851  
4852            print "<P><EM>Any parting comments?</EM><BR>";
4853            print $query->textarea(-name=>'Comments',
4854                                   -rows=>10,
4855                                   -columns=>50);
4856  
4857            print "<P>",$query->reset;
4858            print $query->submit('Action','Shout');
4859            print $query->submit('Action','Scream');
4860            print $query->endform;
4861            print "<HR>\n";
4862         }
4863  
4864         sub do_work {
4865            my($query) = @_;
4866            my(@values,$key);
4867
4868            print "<H2>Here are the current settings in this form</H2>";
4869
4870            foreach $key ($query->param) {
4871               print "<STRONG>$key</STRONG> -> ";
4872               @values = $query->param($key);
4873               print join(", ",@values),"<BR>\n";
4874           }
4875         }
4876  
4877         sub print_tail {
4878            print <<END;
4879         <HR>
4880         <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
4881         <A HREF="/">Home Page</A>
4882         END
4883         }
4884
4885 =head1 BUGS
4886
4887 This module has grown large and monolithic.  Furthermore it's doing many
4888 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
4889 are also done in the LWP modules. It should be discarded in favor of
4890 the CGI::* modules, but somehow I continue to work on it.
4891
4892 Note that the code is truly contorted in order to avoid spurious
4893 warnings when programs are run with the B<-w> switch.
4894
4895 =head1 SEE ALSO
4896
4897 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
4898 L<CGI::Base>, L<CGI::Form>, L<CGI::Apache>, L<CGI::Switch>,
4899 L<CGI::Push>, L<CGI::Fast>
4900
4901 =cut
4902