2ae635ead24a11eaf77344aae4a1da9180b138cc
[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.35 1997/4/20 20:19 lstein Exp $';
32 $CGI::VERSION='2.35';
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($ENV{'GATEWAY_INTERFACE'}) && ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl/)) {
91     $NPH++;
92     $| = 1;
93     $SEQNO = 1;
94 }
95
96 # This is really "\r\n", but the meaning of \n is different
97 # in MacPerl, so we resort to octal here.
98 $CRLF = "\015\012";
99
100 if ($needs_binmode) {
101     $CGI::DefaultClass->binmode(main::STDOUT);
102     $CGI::DefaultClass->binmode(main::STDIN);
103     $CGI::DefaultClass->binmode(main::STDERR);
104 }
105
106 # Cute feature, but it broke when the overload mechanism changed...
107 # %OVERLOAD = ('""'=>'as_string');
108
109 %EXPORT_TAGS = (
110               ':html2'=>[h1..h6,qw/p br hr ol ul li dl dt dd menu code var strong em
111                          tt i b blockquote pre img a address cite samp dfn html head
112                          base body link nextid title meta kbd start_html end_html
113                          input Select option/],
114               ':html3'=>[qw/div table caption th td TR Tr super sub strike applet PARAM embed basefont/],
115               ':netscape'=>[qw/blink frameset frame script font fontsize center/],
116               ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group 
117                        submit reset defaults radio_group popup_menu button autoEscape
118                        scrolling_list image_button start_form end_form startform endform
119                        start_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
120               ':cgi'=>[qw/param path_info path_translated url self_url script_name cookie dump
121                        raw_cookie request_method query_string accept user_agent remote_host 
122                        remote_addr referer server_name server_software server_port server_protocol
123                        virtual_host remote_ident auth_type http
124                        remote_user user_name header redirect import_names put/],
125               ':ssl' => [qw/https/],
126               ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam/],
127               ':html' => [qw/:html2 :html3 :netscape/],
128               ':standard' => [qw/:html2 :form :cgi/],
129               ':all' => [qw/:html2 :html3 :netscape :form :cgi/]
130          );
131
132 # to import symbols into caller
133 sub import {
134     my $self = shift;
135     my ($callpack, $callfile, $callline) = caller;
136     foreach (@_) {
137         $NPH++, next if $_ eq ':nph';
138         foreach (&expand_tags($_)) {
139             tr/a-zA-Z0-9_//cd;  # don't allow weird function names
140             $EXPORT{$_}++;
141         }
142     }
143     # To allow overriding, search through the packages
144     # Till we find one in which the correct subroutine is defined.
145     my @packages = ($self,@{"$self\:\:ISA"});
146     foreach $sym (keys %EXPORT) {
147         my $pck;
148         my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
149         foreach $pck (@packages) {
150             if (defined(&{"$pck\:\:$sym"})) {
151                 $def = $pck;
152                 last;
153             }
154         }
155         *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
156     }
157 }
158
159 sub expand_tags {
160     my($tag) = @_;
161     my(@r);
162     return ($tag) unless $EXPORT_TAGS{$tag};
163     foreach (@{$EXPORT_TAGS{$tag}}) {
164         push(@r,&expand_tags($_));
165     }
166     return @r;
167 }
168
169 #### Method: new
170 # The new routine.  This will check the current environment
171 # for an existing query string, and initialize itself, if so.
172 ####
173 sub new {
174     my($class,$initializer) = @_;
175     my $self = {};
176     bless $self,ref $class || $class || $DefaultClass;
177     $CGI::DefaultClass->_reset_globals() if $MOD_PERL;
178     $initializer = to_filehandle($initializer) if $initializer;
179     $self->init($initializer);
180     return $self;
181 }
182
183 # We provide a DESTROY method so that the autoloader
184 # doesn't bother trying to find it.
185 sub DESTROY { }
186
187 #### Method: param
188 # Returns the value(s)of a named parameter.
189 # If invoked in a list context, returns the
190 # entire list.  Otherwise returns the first
191 # member of the list.
192 # If name is not provided, return a list of all
193 # the known parameters names available.
194 # If more than one argument is provided, the
195 # second and subsequent arguments are used to
196 # set the value of the parameter.
197 ####
198 sub param {
199     my($self,@p) = self_or_default(@_);
200     return $self->all_parameters unless @p;
201     my($name,$value,@other);
202
203     # For compatibility between old calling style and use_named_parameters() style, 
204     # we have to special case for a single parameter present.
205     if (@p > 1) {
206         ($name,$value,@other) = $self->rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
207         my(@values);
208
209         if (substr($p[0],0,1) eq '-' || $self->use_named_parameters) {
210             @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
211         } else {
212             foreach ($value,@other) {
213                 push(@values,$_) if defined($_);
214             }
215         }
216         # If values is provided, then we set it.
217         if (@values) {
218             $self->add_parameter($name);
219             $self->{$name}=[@values];
220         }
221     } else {
222         $name = $p[0];
223     }
224
225     return () unless defined($name) && $self->{$name};
226     return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
227 }
228
229 #### Method: delete
230 # Deletes the named parameter entirely.
231 ####
232 sub delete {
233     my($self,$name) = self_or_default(@_);
234     delete $self->{$name};
235     delete $self->{'.fieldnames'}->{$name};
236     @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
237     return wantarray ? () : undef;
238 }
239
240 sub self_or_default {
241     return @_ if defined($_[0]) && !ref($_[0]) && ($_[0] eq 'CGI');
242     unless (defined($_[0]) && 
243             ref($_[0]) &&
244             (ref($_[0]) eq 'CGI' ||
245              eval "\$_[0]->isaCGI()")) { # optimize for the common case
246         $CGI::DefaultClass->_reset_globals() 
247             if defined($Q) && $MOD_PERL && $CGI::DefaultClass->_new_request();
248         $Q = $CGI::DefaultClass->new unless defined($Q);
249         unshift(@_,$Q);
250     }
251     return @_;
252 }
253
254 sub _new_request {
255     return undef unless (defined(Apache->seqno()) or eval { require Apache });
256     if (Apache->seqno() != $SEQNO) {
257         $SEQNO = Apache->seqno();
258         return 1;
259     } else {
260         return undef;
261     }
262 }
263
264 sub _reset_globals {
265     undef $Q;
266     undef @QUERY_PARAM;
267 }
268
269 sub self_or_CGI {
270     local $^W=0;                # prevent a warning
271     if (defined($_[0]) &&
272         (substr(ref($_[0]),0,3) eq 'CGI' 
273          || eval "\$_[0]->isaCGI()")) {
274         return @_;
275     } else {
276         return ($DefaultClass,@_);
277     }
278 }
279
280 sub isaCGI {
281     return 1;
282 }
283
284 #### Method: import_names
285 # Import all parameters into the given namespace.
286 # Assumes namespace 'Q' if not specified
287 ####
288 sub import_names {
289     my($self,$namespace) = self_or_default(@_);
290     $namespace = 'Q' unless defined($namespace);
291     die "Can't import names into 'main'\n"
292         if $namespace eq 'main';
293     my($param,@value,$var);
294     foreach $param ($self->param) {
295         # protect against silly names
296         ($var = $param)=~tr/a-zA-Z0-9_/_/c;
297         $var = "${namespace}::$var";
298         @value = $self->param($param);
299         @{$var} = @value;
300         ${$var} = $value[0];
301     }
302 }
303
304 #### Method: use_named_parameters
305 # Force CGI.pm to use named parameter-style method calls
306 # rather than positional parameters.  The same effect
307 # will happen automatically if the first parameter
308 # begins with a -.
309 sub use_named_parameters {
310     my($self,$use_named) = self_or_default(@_);
311     return $self->{'.named'} unless defined ($use_named);
312
313     # stupidity to avoid annoying warnings
314     return $self->{'.named'}=$use_named;
315 }
316
317 ########################################
318 # THESE METHODS ARE MORE OR LESS PRIVATE
319 # GO TO THE __DATA__ SECTION TO SEE MORE
320 # PUBLIC METHODS
321 ########################################
322
323 # Initialize the query object from the environment.
324 # If a parameter list is found, this object will be set
325 # to an associative array in which parameter names are keys
326 # and the values are stored as lists
327 # If a keyword list is found, this method creates a bogus
328 # parameter list with the single parameter 'keywords'.
329
330 sub init {
331     my($self,$initializer) = @_;
332     my($query_string,@lines);
333     my($meth) = '';
334
335     # if we get called more than once, we want to initialize
336     # ourselves from the original query (which may be gone
337     # if it was read from STDIN originally.)
338     if (defined(@QUERY_PARAM) && !defined($initializer)) {
339
340         foreach (@QUERY_PARAM) {
341             $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
342         }
343         return;
344     }
345
346     $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
347
348     # If initializer is defined, then read parameters
349     # from it.
350   METHOD: {
351       if (defined($initializer)) {
352
353           if (ref($initializer) && ref($initializer) eq 'HASH') {
354               foreach (keys %$initializer) {
355                   $self->param('-name'=>$_,'-value'=>$initializer->{$_});
356               }
357               last METHOD;
358           }
359           
360           $initializer = $$initializer if ref($initializer);
361           if (defined(fileno($initializer))) {
362               while (<$initializer>) {
363                   chomp;
364                   last if /^=/;
365                   push(@lines,$_);
366               }
367               # massage back into standard format
368               if ("@lines" =~ /=/) {
369                   $query_string=join("&",@lines);
370               } else {
371                   $query_string=join("+",@lines);
372               }
373               last METHOD;
374           }
375           $query_string = $initializer;
376           last METHOD;
377       }
378           # If method is GET or HEAD, fetch the query from
379           # the environment.
380       if ($meth=~/^(GET|HEAD)$/) {
381         $query_string = $ENV{'QUERY_STRING'};
382         last METHOD;
383     }
384         
385       # If the method is POST, fetch the query from standard
386       # input.
387       if ($meth eq 'POST') {
388
389           if (defined($ENV{'CONTENT_TYPE'}) 
390               && 
391               $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|) {
392               my($boundary) = $ENV{'CONTENT_TYPE'}=~/boundary=(\S+)/;
393               $self->read_multipart($boundary,$ENV{'CONTENT_LENGTH'});
394
395           } else {
396
397               $self->read_from_client(\*STDIN,\$query_string,$ENV{'CONTENT_LENGTH'},0)
398                   if $ENV{'CONTENT_LENGTH'} > 0;
399
400           }
401           # Some people want to have their cake and eat it too!
402           # Uncomment this line to have the contents of the query string
403           # APPENDED to the POST data.
404           # $query_string .= ($query_string ? '&' : '') . $ENV{'QUERY_STRING'} if $ENV{'QUERY_STRING'};
405           last METHOD;
406       }
407           
408       # If neither is set, assume we're being debugged offline.
409       # Check the command line and then the standard input for data.
410       # We use the shellwords package in order to behave the way that
411       # UN*X programmers expect.
412       $query_string = &read_from_cmdline;
413   }
414     
415     # We now have the query string in hand.  We do slightly
416     # different things for keyword lists and parameter lists.
417     if ($query_string) {
418         if ($query_string =~ /=/) {
419             $self->parse_params($query_string);
420         } else {
421             $self->add_parameter('keywords');
422             $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
423         }
424     }
425
426     # Special case.  Erase everything if there is a field named
427     # .defaults.
428     if ($self->param('.defaults')) {
429         undef %{$self};
430     }
431
432     # Associative array containing our defined fieldnames
433     $self->{'.fieldnames'} = {};
434     foreach ($self->param('.cgifields')) {
435         $self->{'.fieldnames'}->{$_}++;
436     }
437     
438     # Clear out our default submission button flag if present
439     $self->delete('.submit');
440     $self->delete('.cgifields');
441     $self->save_request unless $initializer;
442
443 }
444
445
446 # FUNCTIONS TO OVERRIDE:
447
448 # Turn a string into a filehandle
449 sub to_filehandle {
450     my $string = shift;
451     if ($string && !ref($string)) {
452         my($package) = caller(1);
453         my($tmp) = $string=~/[':]/ ? $string : "$package\:\:$string"; 
454         return $tmp if defined(fileno($tmp));
455     }
456     return $string;
457 }
458
459 # Create a new multipart buffer
460 sub new_MultipartBuffer {
461     my($self,$boundary,$length,$filehandle) = @_;
462     return MultipartBuffer->new($self,$boundary,$length,$filehandle);
463 }
464
465 # Read data from a file handle
466 sub read_from_client {
467     my($self, $fh, $buff, $len, $offset) = @_;
468     local $^W=0;                # prevent a warning
469     return read($fh, $$buff, $len, $offset);
470 }
471
472 # put a filehandle into binary mode (DOS)
473 sub binmode {
474     binmode($_[1]);
475 }
476
477 # send output to the browser
478 sub put {
479     my($self,@p) = self_or_default(@_);
480     $self->print(@p);
481 }
482
483 # print to standard output (for overriding in mod_perl)
484 sub print {
485     shift;
486     CORE::print(@_);
487 }
488
489 # unescape URL-encoded data
490 sub unescape {
491     my($todecode) = @_;
492     $todecode =~ tr/+/ /;       # pluses become spaces
493     $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
494     return $todecode;
495 }
496
497 # URL-encode data
498 sub escape {
499     my($toencode) = @_;
500     $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
501     return $toencode;
502 }
503
504 sub save_request {
505     my($self) = @_;
506     # We're going to play with the package globals now so that if we get called
507     # again, we initialize ourselves in exactly the same way.  This allows
508     # us to have several of these objects.
509     @QUERY_PARAM = $self->param; # save list of parameters
510     foreach (@QUERY_PARAM) {
511         $QUERY_PARAM{$_}=$self->{$_};
512     }
513 }
514
515 sub parse_keywordlist {
516     my($self,$tosplit) = @_;
517     $tosplit = &unescape($tosplit); # unescape the keywords
518     $tosplit=~tr/+/ /;          # pluses to spaces
519     my(@keywords) = split(/\s+/,$tosplit);
520     return @keywords;
521 }
522
523 sub parse_params {
524     my($self,$tosplit) = @_;
525     my(@pairs) = split('&',$tosplit);
526     my($param,$value);
527     foreach (@pairs) {
528         ($param,$value) = split('=');
529         $param = &unescape($param);
530         $value = &unescape($value);
531         $self->add_parameter($param);
532         push (@{$self->{$param}},$value);
533     }
534 }
535
536 sub add_parameter {
537     my($self,$param)=@_;
538     push (@{$self->{'.parameters'}},$param) 
539         unless defined($self->{$param});
540 }
541
542 sub all_parameters {
543     my $self = shift;
544     return () unless defined($self) && $self->{'.parameters'};
545     return () unless @{$self->{'.parameters'}};
546     return @{$self->{'.parameters'}};
547 }
548
549 #### Method as_string
550 #
551 # synonym for "dump"
552 ####
553 sub as_string {
554     &dump(@_);
555 }
556
557 sub AUTOLOAD {
558     print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
559     my($func) = $AUTOLOAD;
560     my($pack,$func_name) = $func=~/(.+)::([^:]+)$/;
561     $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
562                 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
563
564     my($sub) = \%{"$pack\:\:SUBS"};
565     unless (%$sub) {
566         my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
567         eval "package $pack; $$auto";
568         die $@ if $@;
569     }
570     my($code) = $sub->{$func_name};
571
572     $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
573     if (!$code) {
574         if ($EXPORT{':any'} || 
575             $EXPORT{$func_name} || 
576             (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
577             && $EXPORT_OK{$func_name}) {
578             $code = $sub->{'HTML_FUNC'};
579             $code=~s/func_name/$func_name/mg;
580         }
581     }
582     die "Undefined subroutine $AUTOLOAD\n" unless $code;
583     eval "package $pack; $code";
584     if ($@) {
585         $@ =~ s/ at .*\n//;
586         die $@;
587     }
588     goto &{"$pack\:\:$func_name"};
589 }
590
591 # PRIVATE SUBROUTINE
592 # Smart rearrangement of parameters to allow named parameter
593 # calling.  We do the rearangement if:
594 # 1. The first parameter begins with a -
595 # 2. The use_named_parameters() method returns true
596 sub rearrange {
597     my($self,$order,@param) = @_;
598     return () unless @param;
599     
600     return @param unless (defined($param[0]) && substr($param[0],0,1) eq '-')
601         || $self->use_named_parameters;
602
603     my $i;
604     for ($i=0;$i<@param;$i+=2) {
605         $param[$i]=~s/^\-//;     # get rid of initial - if present
606         $param[$i]=~tr/a-z/A-Z/; # parameters are upper case
607     }
608     
609     my(%param) = @param;                # convert into associative array
610     my(@return_array);
611     
612     my($key)='';
613     foreach $key (@$order) {
614         my($value);
615         # this is an awful hack to fix spurious warnings when the
616         # -w switch is set.
617         if (ref($key) && ref($key) eq 'ARRAY') {
618             foreach (@$key) {
619                 last if defined($value);
620                 $value = $param{$_};
621                 delete $param{$_};
622             }
623         } else {
624             $value = $param{$key};
625             delete $param{$key};
626         }
627         push(@return_array,$value);
628     }
629     push (@return_array,$self->make_attributes(\%param)) if %param;
630     return (@return_array);
631 }
632
633 ###############################################################################
634 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
635 ###############################################################################
636 $AUTOLOADED_ROUTINES = '';      # get rid of -w warning
637 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
638
639 %SUBS = (
640
641 'URL_ENCODED'=> <<'END_OF_FUNC',
642 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
643 END_OF_FUNC
644
645 'MULTIPART' => <<'END_OF_FUNC',
646 sub MULTIPART {  'multipart/form-data'; }
647 END_OF_FUNC
648
649 'HTML_FUNC' => <<'END_OF_FUNC',
650 sub func_name { 
651
652     # handle various cases in which we're called
653     # most of this bizarre stuff is to avoid -w errors
654     shift if $_[0] && 
655         (!ref($_[0]) && $_[0] eq $CGI::DefaultClass) ||
656             (ref($_[0]) &&
657              (substr(ref($_[0]),0,3) eq 'CGI' ||
658               eval "\$_[0]->isaCGI()"));
659
660     my($attr) = '';
661     if (ref($_[0]) && ref($_[0]) eq 'HASH') {
662         my(@attr) = CGI::make_attributes('',shift);
663         $attr = " @attr" if @attr;
664     }
665     my($tag,$untag) = ("\U<func_name\E$attr>","\U</func_name>\E");
666     return $tag unless @_;
667     if (ref($_[0]) eq 'ARRAY') {
668         my(@r);
669         foreach (@{$_[0]}) {
670             push(@r,"$tag$_$untag");
671         }
672         return "@r";
673     } else {
674         return "$tag@_$untag";
675     }
676 }
677 END_OF_FUNC
678
679 #### Method: keywords
680 # Keywords acts a bit differently.  Calling it in a list context
681 # returns the list of keywords.  
682 # Calling it in a scalar context gives you the size of the list.
683 ####
684 'keywords' => <<'END_OF_FUNC',
685 sub keywords {
686     my($self,@values) = self_or_default(@_);
687     # If values is provided, then we set it.
688     $self->{'keywords'}=[@values] if @values;
689     my(@result) = @{$self->{'keywords'}};
690     @result;
691 }
692 END_OF_FUNC
693
694 # These are some tie() interfaces for compatibility
695 # with Steve Brenner's cgi-lib.pl routines
696 'ReadParse' => <<'END_OF_FUNC',
697 sub ReadParse {
698     local(*in);
699     if (@_) {
700         *in = $_[0];
701     } else {
702         my $pkg = caller();
703         *in=*{"${pkg}::in"};
704     }
705     tie(%in,CGI);
706 }
707 END_OF_FUNC
708
709 'PrintHeader' => <<'END_OF_FUNC',
710 sub PrintHeader {
711     my($self) = self_or_default(@_);
712     return $self->header();
713 }
714 END_OF_FUNC
715
716 'HtmlTop' => <<'END_OF_FUNC',
717 sub HtmlTop {
718     my($self,@p) = self_or_default(@_);
719     return $self->start_html(@p);
720 }
721 END_OF_FUNC
722
723 'HtmlBot' => <<'END_OF_FUNC',
724 sub HtmlBot {
725     my($self,@p) = self_or_default(@_);
726     return $self->end_html(@p);
727 }
728 END_OF_FUNC
729
730 'SplitParam' => <<'END_OF_FUNC',
731 sub SplitParam {
732     my ($param) = @_;
733     my (@params) = split ("\0", $param);
734     return (wantarray ? @params : $params[0]);
735 }
736 END_OF_FUNC
737
738 'MethGet' => <<'END_OF_FUNC',
739 sub MethGet {
740     return request_method() eq 'GET';
741 }
742 END_OF_FUNC
743
744 'MethPost' => <<'END_OF_FUNC',
745 sub MethPost {
746     return request_method() eq 'POST';
747 }
748 END_OF_FUNC
749
750 'TIEHASH' => <<'END_OF_FUNC',
751 sub TIEHASH { 
752     return new CGI;
753 }
754 END_OF_FUNC
755
756 'STORE' => <<'END_OF_FUNC',
757 sub STORE {
758     $_[0]->param($_[1],split("\0",$_[2]));
759 }
760 END_OF_FUNC
761
762 'FETCH' => <<'END_OF_FUNC',
763 sub FETCH {
764     return $_[0] if $_[1] eq 'CGI';
765     return undef unless defined $_[0]->param($_[1]);
766     return join("\0",$_[0]->param($_[1]));
767 }
768 END_OF_FUNC
769
770 'FIRSTKEY' => <<'END_OF_FUNC',
771 sub FIRSTKEY {
772     $_[0]->{'.iterator'}=0;
773     $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
774 }
775 END_OF_FUNC
776
777 'NEXTKEY' => <<'END_OF_FUNC',
778 sub NEXTKEY {
779     $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
780 }
781 END_OF_FUNC
782
783 'EXISTS' => <<'END_OF_FUNC',
784 sub EXISTS {
785     exists $_[0]->{$_[1]};
786 }
787 END_OF_FUNC
788
789 'DELETE' => <<'END_OF_FUNC',
790 sub DELETE {
791     $_[0]->delete($_[1]);
792 }
793 END_OF_FUNC
794
795 'CLEAR' => <<'END_OF_FUNC',
796 sub CLEAR {
797     %{$_[0]}=();
798 }
799 ####
800 END_OF_FUNC
801
802 ####
803 # Append a new value to an existing query
804 ####
805 'append' => <<'EOF',
806 sub append {
807     my($self,@p) = @_;
808     my($name,$value) = $self->rearrange([NAME,[VALUE,VALUES]],@p);
809     my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
810     if (@values) {
811         $self->add_parameter($name);
812         push(@{$self->{$name}},@values);
813     }
814     return $self->param($name);
815 }
816 EOF
817
818 #### Method: delete_all
819 # Delete all parameters
820 ####
821 'delete_all' => <<'EOF',
822 sub delete_all {
823     my($self) = self_or_default(@_);
824     undef %{$self};
825 }
826 EOF
827
828 #### Method: autoescape
829 # If you want to turn off the autoescaping features,
830 # call this method with undef as the argument
831 'autoEscape' => <<'END_OF_FUNC',
832 sub autoEscape {
833     my($self,$escape) = self_or_default(@_);
834     $self->{'dontescape'}=!$escape;
835 }
836 END_OF_FUNC
837
838
839 #### Method: version
840 # Return the current version
841 ####
842 'version' => <<'END_OF_FUNC',
843 sub version {
844     return $VERSION;
845 }
846 END_OF_FUNC
847
848 'make_attributes' => <<'END_OF_FUNC',
849 sub make_attributes {
850     my($self,$attr) = @_;
851     return () unless $attr && ref($attr) && ref($attr) eq 'HASH';
852     my(@att);
853     foreach (keys %{$attr}) {
854         my($key) = $_;
855         $key=~s/^\-//;     # get rid of initial - if present
856         $key=~tr/a-z/A-Z/; # parameters are upper case
857         push(@att,$attr->{$_} ne '' ? qq/$key="$attr->{$_}"/ : qq/$key/);
858     }
859     return @att;
860 }
861 END_OF_FUNC
862
863 #### Method: dump
864 # Returns a string in which all the known parameter/value 
865 # pairs are represented as nested lists, mainly for the purposes 
866 # of debugging.
867 ####
868 'dump' => <<'END_OF_FUNC',
869 sub dump {
870     my($self) = self_or_default(@_);
871     my($param,$value,@result);
872     return '<UL></UL>' unless $self->param;
873     push(@result,"<UL>");
874     foreach $param ($self->param) {
875         my($name)=$self->escapeHTML($param);
876         push(@result,"<LI><STRONG>$param</STRONG>");
877         push(@result,"<UL>");
878         foreach $value ($self->param($param)) {
879             $value = $self->escapeHTML($value);
880             push(@result,"<LI>$value");
881         }
882         push(@result,"</UL>");
883     }
884     push(@result,"</UL>\n");
885     return join("\n",@result);
886 }
887 END_OF_FUNC
888
889
890 #### Method: save
891 # Write values out to a filehandle in such a way that they can
892 # be reinitialized by the filehandle form of the new() method
893 ####
894 'save' => <<'END_OF_FUNC',
895 sub save {
896     my($self,$filehandle) = self_or_default(@_);
897     my($param);
898     my($package) = caller;
899 # Check that this still works!
900 #    $filehandle = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
901     $filehandle = to_filehandle($filehandle);
902     foreach $param ($self->param) {
903         my($escaped_param) = &escape($param);
904         my($value);
905         foreach $value ($self->param($param)) {
906             print $filehandle "$escaped_param=",escape($value),"\n";
907         }
908     }
909     print $filehandle "=\n";    # end of record
910 }
911 END_OF_FUNC
912
913
914 #### Method: header
915 # Return a Content-Type: style header
916 #
917 ####
918 'header' => <<'END_OF_FUNC',
919 sub header {
920     my($self,@p) = self_or_default(@_);
921     my(@header);
922
923     my($type,$status,$cookie,$target,$expires,$nph,@other) = 
924         $self->rearrange([TYPE,STATUS,[COOKIE,COOKIES],TARGET,EXPIRES,NPH],@p);
925
926     # rearrange() was designed for the HTML portion, so we
927     # need to fix it up a little.
928     foreach (@other) {
929         next unless my($header,$value) = /([^\s=]+)=(.+)/;
930         substr($header,1,1000)=~tr/A-Z/a-z/;
931         ($value)=$value=~/^"(.*)"$/;
932         $_ = "$header: $value";
933     }
934
935     $type = $type || 'text/html';
936
937     push(@header,'HTTP/1.0 ' . ($status || '200 OK')) if $nph || $NPH;
938     push(@header,"Status: $status") if $status;
939     push(@header,"Window-target: $target") if $target;
940     # push all the cookies -- there may be several
941     if ($cookie) {
942         my(@cookie) = ref($cookie) ? @{$cookie} : $cookie;
943         foreach (@cookie) {
944             push(@header,"Set-cookie: $_");
945         }
946     }
947     # if the user indicates an expiration time, then we need
948     # both an Expires and a Date header (so that the browser is
949     # uses OUR clock)
950     push(@header,"Expires: " . &expires($expires)) if $expires;
951     push(@header,"Date: " . &expires(0)) if $expires;
952     push(@header,"Pragma: no-cache") if $self->cache();
953     push(@header,@other);
954     push(@header,"Content-type: $type");
955
956     my $header = join($CRLF,@header);
957     return $header . "${CRLF}${CRLF}";
958 }
959 END_OF_FUNC
960
961
962 #### Method: cache
963 # Control whether header() will produce the no-cache
964 # Pragma directive.
965 ####
966 'cache' => <<'END_OF_FUNC',
967 sub cache {
968     my($self,$new_value) = self_or_default(@_);
969     $new_value = '' unless $new_value;
970     if ($new_value ne '') {
971         $self->{'cache'} = $new_value;
972     }
973     return $self->{'cache'};
974 }
975 END_OF_FUNC
976
977
978 #### Method: redirect
979 # Return a Location: style header
980 #
981 ####
982 'redirect' => <<'END_OF_FUNC',
983 sub redirect {
984     my($self,@p) = self_or_default(@_);
985     my($url,$target,$cookie,$nph,@other) = $self->rearrange([[URI,URL],TARGET,COOKIE,NPH],@p);
986     $url = $url || $self->self_url;
987     my(@o);
988     foreach (@other) { push(@o,split("=")); }
989     if($MOD_PERL or exists $self->{'.req'}) {
990         my $r = $self->{'.req'} || Apache->request;
991         $r->header_out(Location => $url);
992         $r->err_header_out(Location => $url);
993         $r->status(302);
994         return;
995     }
996     push(@o,
997          '-Status'=>'302 Found',
998          '-Location'=>$url,
999          '-URI'=>$url,
1000          '-nph'=>($nph||$NPH));
1001     push(@o,'-Target'=>$target) if $target;
1002     push(@o,'-Cookie'=>$cookie) if $cookie;
1003     return $self->header(@o);
1004 }
1005 END_OF_FUNC
1006
1007
1008 #### Method: start_html
1009 # Canned HTML header
1010 #
1011 # Parameters:
1012 # $title -> (optional) The title for this HTML document (-title)
1013 # $author -> (optional) e-mail address of the author (-author)
1014 # $base -> (optional) if set to true, will enter the BASE address of this document
1015 #          for resolving relative references (-base) 
1016 # $xbase -> (optional) alternative base at some remote location (-xbase)
1017 # $target -> (optional) target window to load all links into (-target)
1018 # $script -> (option) Javascript code (-script)
1019 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1020 # $meta -> (optional) Meta information tags
1021 # @other -> (optional) any other named parameters you'd like to incorporate into
1022 #           the <BODY> tag.
1023 ####
1024 'start_html' => <<'END_OF_FUNC',
1025 sub start_html {
1026     my($self,@p) = &self_or_default(@_);
1027     my($title,$author,$base,$xbase,$script,$noscript,$target,$meta,@other) = 
1028         $self->rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META],@p);
1029
1030     # strangely enough, the title needs to be escaped as HTML
1031     # while the author needs to be escaped as a URL
1032     $title = $self->escapeHTML($title || 'Untitled Document');
1033     $author = $self->escapeHTML($author);
1034     my(@result);
1035     push(@result,'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">');
1036     push(@result,"<HTML><HEAD><TITLE>$title</TITLE>");
1037     push(@result,"<LINK REV=MADE HREF=\"mailto:$author\">") if $author;
1038
1039     if ($base || $xbase || $target) {
1040         my $href = $xbase || $self->url();
1041         my $t = $target ? qq/ TARGET="$target"/ : '';
1042         push(@result,qq/<BASE HREF="$href"$t>/);
1043     }
1044
1045     if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1046         foreach (keys %$meta) { push(@result,qq(<META NAME="$_" CONTENT="$meta->{$_}">)); }
1047     }
1048     push(@result,<<END) if $script;
1049 <SCRIPT>
1050 <!-- Hide script from HTML-compliant browsers
1051 $script
1052 // End script hiding. -->
1053 </SCRIPT>
1054 END
1055     ;
1056     push(@result,<<END) if $noscript;
1057 <NOSCRIPT>
1058 $noscript
1059 </NOSCRIPT>
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         die "Malformed multipart POST\n" unless %header;
2336
2337         # In beta1 it was "Content-disposition".  In beta2 it's "Content-Disposition"
2338         # Sheesh.
2339         my($key) = $header{'Content-disposition'} ? 'Content-disposition' : 'Content-Disposition';
2340         my($param)= $header{$key}=~/ name="([^\"]*)"/;
2341
2342         # possible bug: our regular expression expects the filename= part to fall
2343         # at the end of the line.  Netscape doesn't escape quotation marks in file names!!!
2344         my($filename) = $header{$key}=~/ filename="(.*)"$/;
2345
2346         # add this parameter to our list
2347         $self->add_parameter($param);
2348
2349         # If no filename specified, then just read the data and assign it
2350         # to our parameter list.
2351         unless ($filename) {
2352             my($value) = $buffer->readBody;
2353             push(@{$self->{$param}},$value);
2354             next;
2355         }
2356
2357         # If we get here, then we are dealing with a potentially large
2358         # uploaded form.  Save the data to a temporary file, then open
2359         # the file for reading.
2360         my($tmpfile) = new TempFile;
2361         my $tmp = $tmpfile->as_string;
2362         
2363         open (OUT,">$tmp") || die "CGI open of $tmpfile: $!\n";
2364         $CGI::DefaultClass->binmode(OUT) if $CGI::needs_binmode;
2365         chmod 0666,$tmp;    # make sure anyone can delete it.
2366         my $data;
2367         while ($data = $buffer->read) {
2368             print OUT $data;
2369         }
2370         close OUT;
2371
2372         # Now create a new filehandle in the caller's namespace.
2373         # The name of this filehandle just happens to be identical
2374         # to the original filename (NOT the name of the temporary
2375         # file, which is hidden!)
2376         my($filehandle);
2377         if ($filename=~/^[a-zA-Z_]/) {
2378             my($frame,$cp)=(1);
2379             do { $cp = caller($frame++); } until !eval("'$cp'->isaCGI()");
2380             $filehandle = "$cp\:\:$filename";
2381         } else {
2382             $filehandle = "\:\:$filename";
2383         }
2384
2385         open($filehandle,$tmp) || die "CGI open of $tmp: $!\n";
2386         $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2387
2388         push(@{$self->{$param}},$filename);
2389
2390         # Under Unix, it would be safe to let the temporary file
2391         # be deleted immediately.  However, I fear that other operating
2392         # systems are not so forgiving.  Therefore we save a reference
2393         # to the temporary file in the CGI object so that the file
2394         # isn't unlinked until the CGI object itself goes out of
2395         # scope.  This is a bit hacky, but it has the interesting side
2396         # effect that one can access the name of the tmpfile by
2397         # asking for $query->{$query->param('foo')}, where 'foo'
2398         # is the name of the file upload field.
2399         $self->{'.tmpfiles'}->{$filename}= {
2400             name=>$tmpfile,
2401             info=>{%header}
2402         }
2403     }
2404 }
2405 END_OF_FUNC
2406
2407 'tmpFileName' => <<'END_OF_FUNC',
2408 sub tmpFileName {
2409     my($self,$filename) = self_or_default(@_);
2410     return $self->{'.tmpfiles'}->{$filename}->{name}->as_string;
2411 }
2412 END_OF_FUNC
2413
2414 'uploadInfo' => <<'END_OF_FUNC'
2415 sub uploadInfo {
2416     my($self,$filename) = self_or_default(@_);
2417     return $self->{'.tmpfiles'}->{$filename}->{info};
2418 }
2419 END_OF_FUNC
2420
2421 );
2422 END_OF_AUTOLOAD
2423 ;
2424
2425 # Globals and stubs for other packages that we use
2426 package MultipartBuffer;
2427
2428 # how many bytes to read at a time.  We use
2429 # a 5K buffer by default.
2430 $FILLUNIT = 1024 * 5;
2431 $TIMEOUT = 10*60;       # 10 minute timeout
2432 $SPIN_LOOP_MAX = 1000;  # bug fix for some Netscape servers
2433 $CRLF=$CGI::CRLF;
2434
2435 #reuse the autoload function
2436 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
2437
2438 ###############################################################################
2439 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2440 ###############################################################################
2441 $AUTOLOADED_ROUTINES = '';      # prevent -w error
2442 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2443 %SUBS =  (
2444
2445 'new' => <<'END_OF_FUNC',
2446 sub new {
2447     my($package,$interface,$boundary,$length,$filehandle) = @_;
2448     my $IN;
2449     if ($filehandle) {
2450         my($package) = caller;
2451         # force into caller's package if necessary
2452         $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle"; 
2453     }
2454     $IN = "main::STDIN" unless $IN;
2455
2456     $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
2457     
2458     # If the user types garbage into the file upload field,
2459     # then Netscape passes NOTHING to the server (not good).
2460     # We may hang on this read in that case. So we implement
2461     # a read timeout.  If nothing is ready to read
2462     # by then, we return.
2463
2464     # Netscape seems to be a little bit unreliable
2465     # about providing boundary strings.
2466     if ($boundary) {
2467
2468         # Under the MIME spec, the boundary consists of the 
2469         # characters "--" PLUS the Boundary string
2470         $boundary = "--$boundary";
2471         # Read the topmost (boundary) line plus the CRLF
2472         my($null) = '';
2473         $length -= $interface->read_from_client($IN,\$null,length($boundary)+2,0);
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     my($bad) = 0;
2503     do {
2504         $self->fillBuffer($FILLUNIT);
2505         $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
2506         $ok++ if $self->{BUFFER} eq '';
2507         $bad++ if !$ok && $self->{LENGTH} <= 0;
2508         $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT; 
2509     } until $ok || $bad;
2510     return () if $bad;
2511
2512     my($header) = substr($self->{BUFFER},0,$end+2);
2513     substr($self->{BUFFER},0,$end+4) = '';
2514     my %return;
2515     while ($header=~/^([\w-]+): (.*)$CRLF/mog) {
2516         $return{$1}=$2;
2517     }
2518     return %return;
2519 }
2520 END_OF_FUNC
2521
2522 # This reads and returns the body as a single scalar value.
2523 'readBody' => <<'END_OF_FUNC',
2524 sub readBody {
2525     my($self) = @_;
2526     my($data);
2527     my($returnval)='';
2528     while (defined($data = $self->read)) {
2529         $returnval .= $data;
2530     }
2531     return $returnval;
2532 }
2533 END_OF_FUNC
2534
2535 # This will read $bytes or until the boundary is hit, whichever happens
2536 # first.  After the boundary is hit, we return undef.  The next read will
2537 # skip over the boundary and begin reading again;
2538 'read' => <<'END_OF_FUNC',
2539 sub read {
2540     my($self,$bytes) = @_;
2541
2542     # default number of bytes to read
2543     $bytes = $bytes || $FILLUNIT;       
2544
2545     # Fill up our internal buffer in such a way that the boundary
2546     # is never split between reads.
2547     $self->fillBuffer($bytes);
2548
2549     # Find the boundary in the buffer (it may not be there).
2550     my $start = index($self->{BUFFER},$self->{BOUNDARY});
2551     # protect against malformed multipart POST operations
2552     die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
2553
2554     # If the boundary begins the data, then skip past it
2555     # and return undef.  The +2 here is a fiendish plot to
2556     # remove the CR/LF pair at the end of the boundary.
2557     if ($start == 0) {
2558
2559         # clear us out completely if we've hit the last boundary.
2560         if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
2561             $self->{BUFFER}='';
2562             $self->{LENGTH}=0;
2563             return undef;
2564         }
2565
2566         # just remove the boundary.
2567         substr($self->{BUFFER},0,length($self->{BOUNDARY})+2)='';
2568         return undef;
2569     }
2570
2571     my $bytesToReturn;    
2572     if ($start > 0) {           # read up to the boundary
2573         $bytesToReturn = $start > $bytes ? $bytes : $start;
2574     } else {    # read the requested number of bytes
2575         # leave enough bytes in the buffer to allow us to read
2576         # the boundary.  Thanks to Kevin Hendrick for finding
2577         # this one.
2578         $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
2579     }
2580
2581     my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
2582     substr($self->{BUFFER},0,$bytesToReturn)='';
2583     
2584     # If we hit the boundary, remove the CRLF from the end.
2585     return ($start > 0) ? substr($returnval,0,-2) : $returnval;
2586 }
2587 END_OF_FUNC
2588
2589
2590 # This fills up our internal buffer in such a way that the
2591 # boundary is never split between reads
2592 'fillBuffer' => <<'END_OF_FUNC',
2593 sub fillBuffer {
2594     my($self,$bytes) = @_;
2595     return unless $self->{LENGTH};
2596
2597     my($boundaryLength) = length($self->{BOUNDARY});
2598     my($bufferLength) = length($self->{BUFFER});
2599     my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
2600     $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
2601
2602     # Try to read some data.  We may hang here if the browser is screwed up.  
2603     my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
2604                                                          \$self->{BUFFER},
2605                                                          $bytesToRead,
2606                                                          $bufferLength);
2607
2608     # An apparent bug in the Apache server causes the read()
2609     # to return zero bytes repeatedly without blocking if the
2610     # remote user aborts during a file transfer.  I don't know how
2611     # they manage this, but the workaround is to abort if we get
2612     # more than SPIN_LOOP_MAX consecutive zero reads.
2613     if ($bytesRead == 0) {
2614         die  "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
2615             if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
2616     } else {
2617         $self->{ZERO_LOOP_COUNTER}=0;
2618     }
2619
2620     $self->{LENGTH} -= $bytesRead;
2621 }
2622 END_OF_FUNC
2623
2624
2625 # Return true when we've finished reading
2626 'eof' => <<'END_OF_FUNC'
2627 sub eof {
2628     my($self) = @_;
2629     return 1 if (length($self->{BUFFER}) == 0)
2630                  && ($self->{LENGTH} <= 0);
2631     undef;
2632 }
2633 END_OF_FUNC
2634
2635 );
2636 END_OF_AUTOLOAD
2637
2638 ####################################################################################
2639 ################################## TEMPORARY FILES #################################
2640 ####################################################################################
2641 package TempFile;
2642
2643 $SL = $CGI::SL;
2644 unless ($TMPDIRECTORY) {
2645     @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp","${SL}tmp","${SL}temp","${SL}Temporary Items");
2646     foreach (@TEMP) {
2647         do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
2648     }
2649 }
2650
2651 $TMPDIRECTORY  = "." unless $TMPDIRECTORY;
2652 $SEQUENCE="CGItemp${$}0000";
2653
2654 # cute feature, but overload implementation broke it
2655 # %OVERLOAD = ('""'=>'as_string');
2656 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
2657
2658 ###############################################################################
2659 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2660 ###############################################################################
2661 $AUTOLOADED_ROUTINES = '';      # prevent -w error
2662 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2663 %SUBS = (
2664
2665 'new' => <<'END_OF_FUNC',
2666 sub new {
2667     my($package) = @_;
2668     $SEQUENCE++;
2669     my $directory = "${TMPDIRECTORY}${SL}${SEQUENCE}";
2670     return bless \$directory;
2671 }
2672 END_OF_FUNC
2673
2674 'DESTROY' => <<'END_OF_FUNC',
2675 sub DESTROY {
2676     my($self) = @_;
2677     unlink $$self;              # get rid of the file
2678 }
2679 END_OF_FUNC
2680
2681 'as_string' => <<'END_OF_FUNC'
2682 sub as_string {
2683     my($self) = @_;
2684     return $$self;
2685 }
2686 END_OF_FUNC
2687
2688 );
2689 END_OF_AUTOLOAD
2690
2691 package CGI;
2692
2693 # We get a whole bunch of warnings about "possibly uninitialized variables"
2694 # when running with the -w switch.  Touch them all once to get rid of the
2695 # warnings.  This is ugly and I hate it.
2696 if ($^W) {
2697     $CGI::CGI = '';
2698     $CGI::CGI=<<EOF;
2699     $CGI::VERSION;
2700     $MultipartBuffer::SPIN_LOOP_MAX;
2701     $MultipartBuffer::CRLF;
2702     $MultipartBuffer::TIMEOUT;
2703     $MultipartBuffer::FILLUNIT;
2704     $TempFile::SEQUENCE;
2705 EOF
2706     ;
2707 }
2708
2709 $revision;
2710
2711 __END__
2712
2713 =head1 NAME
2714
2715 CGI - Simple Common Gateway Interface Class
2716
2717 =head1 SYNOPSIS
2718
2719   use CGI;
2720   # the rest is too complicated for a synopsis; keep reading
2721
2722 =head1 ABSTRACT
2723
2724 This perl library uses perl5 objects to make it easy to create
2725 Web fill-out forms and parse their contents.  This package
2726 defines CGI objects, entities that contain the values of the
2727 current query string and other state variables.
2728 Using a CGI object's methods, you can examine keywords and parameters
2729 passed to your script, and create forms whose initial values
2730 are taken from the current query (thereby preserving state
2731 information).
2732
2733 The current version of CGI.pm is available at
2734
2735   http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
2736   ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
2737
2738 =head1 INSTALLATION
2739
2740 CGI is a part of the base Perl installation.  However, you may need
2741 to install a newer version someday.  Therefore:
2742
2743 To install this package, just change to the directory in which this
2744 file is found and type the following:
2745
2746         perl Makefile.PL
2747         make
2748         make install
2749
2750 This will copy CGI.pm to your perl library directory for use by all
2751 perl scripts.  You probably must be root to do this.   Now you can
2752 load the CGI routines in your Perl scripts with the line:
2753
2754         use CGI;
2755
2756 If you don't have sufficient privileges to install CGI.pm in the Perl
2757 library directory, you can put CGI.pm into some convenient spot, such
2758 as your home directory, or in cgi-bin itself and prefix all Perl
2759 scripts that call it with something along the lines of the following
2760 preamble:
2761
2762         use lib '/home/davis/lib';
2763         use CGI;
2764
2765 If you are using a version of perl earlier than 5.002 (such as NT perl), use
2766 this instead:
2767
2768         BEGIN {
2769                 unshift(@INC,'/home/davis/lib');
2770         }
2771         use CGI;
2772
2773 The CGI distribution also comes with a cute module called L<CGI::Carp>.
2774 It redefines the die(), warn(), confess() and croak() error routines
2775 so that they write nicely formatted error messages into the server's
2776 error log (or to the output stream of your choice).  This avoids long
2777 hours of groping through the error and access logs, trying to figure
2778 out which CGI script is generating  error messages.  If you choose,
2779 you can even have fatal error messages echoed to the browser to avoid
2780 the annoying and uninformative "Server Error" message.
2781
2782 =head1 DESCRIPTION
2783
2784 =head2 CREATING A NEW QUERY OBJECT:
2785
2786      $query = new CGI;
2787
2788 This will parse the input (from both POST and GET methods) and store
2789 it into a perl5 object called $query.  
2790
2791 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
2792
2793      $query = new CGI(INPUTFILE);
2794
2795 If you provide a file handle to the new() method, it
2796 will read parameters from the file (or STDIN, or whatever).  The
2797 file can be in any of the forms describing below under debugging
2798 (i.e. a series of newline delimited TAG=VALUE pairs will work).
2799 Conveniently, this type of file is created by the save() method
2800 (see below).  Multiple records can be saved and restored.
2801
2802 Perl purists will be pleased to know that this syntax accepts
2803 references to file handles, or even references to filehandle globs,
2804 which is the "official" way to pass a filehandle:
2805
2806     $query = new CGI(\*STDIN);
2807
2808 You can also initialize the query object from an associative array
2809 reference:
2810
2811     $query = new CGI( {'dinosaur'=>'barney',
2812                        'song'=>'I love you',
2813                        'friends'=>[qw/Jessica George Nancy/]}
2814                     );
2815
2816 or from a properly formatted, URL-escaped query string:
2817
2818     $query = new CGI('dinosaur=barney&color=purple');
2819
2820 To create an empty query, initialize it from an empty string or hash:
2821
2822         $empty_query = new CGI("");
2823              -or-
2824         $empty_query = new CGI({});
2825
2826 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
2827
2828      @keywords = $query->keywords
2829
2830 If the script was invoked as the result of an <ISINDEX> search, the
2831 parsed keywords can be obtained as an array using the keywords() method.
2832
2833 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
2834
2835      @names = $query->param
2836
2837 If the script was invoked with a parameter list
2838 (e.g. "name1=value1&name2=value2&name3=value3"), the param()
2839 method will return the parameter names as a list.  If the
2840 script was invoked as an <ISINDEX> script, there will be a
2841 single parameter named 'keywords'.
2842
2843 NOTE: As of version 1.5, the array of parameter names returned will
2844 be in the same order as they were submitted by the browser.
2845 Usually this order is the same as the order in which the 
2846 parameters are defined in the form (however, this isn't part
2847 of the spec, and so isn't guaranteed).
2848
2849 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
2850
2851     @values = $query->param('foo');
2852
2853               -or-
2854
2855     $value = $query->param('foo');
2856
2857 Pass the param() method a single argument to fetch the value of the
2858 named parameter. If the parameter is multivalued (e.g. from multiple
2859 selections in a scrolling list), you can ask to receive an array.  Otherwise
2860 the method will return a single value.
2861
2862 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
2863
2864     $query->param('foo','an','array','of','values');
2865
2866 This sets the value for the named parameter 'foo' to an array of
2867 values.  This is one way to change the value of a field AFTER
2868 the script has been invoked once before.  (Another way is with
2869 the -override parameter accepted by all methods that generate
2870 form elements.)
2871
2872 param() also recognizes a named parameter style of calling described
2873 in more detail later:
2874
2875     $query->param(-name=>'foo',-values=>['an','array','of','values']);
2876
2877                               -or-
2878
2879     $query->param(-name=>'foo',-value=>'the value');
2880
2881 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
2882
2883    $query->append(-name=>;'foo',-values=>['yet','more','values']);
2884
2885 This adds a value or list of values to the named parameter.  The
2886 values are appended to the end of the parameter if it already exists.
2887 Otherwise the parameter is created.  Note that this method only
2888 recognizes the named argument calling syntax.
2889
2890 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
2891
2892    $query->import_names('R');
2893
2894 This creates a series of variables in the 'R' namespace.  For example,
2895 $R::foo, @R:foo.  For keyword lists, a variable @R::keywords will appear.
2896 If no namespace is given, this method will assume 'Q'.
2897 WARNING:  don't import anything into 'main'; this is a major security
2898 risk!!!!
2899
2900 In older versions, this method was called B<import()>.  As of version 2.20, 
2901 this name has been removed completely to avoid conflict with the built-in
2902 Perl module B<import> operator.
2903
2904 =head2 DELETING A PARAMETER COMPLETELY:
2905
2906     $query->delete('foo');
2907
2908 This completely clears a parameter.  It sometimes useful for
2909 resetting parameters that you don't want passed down between
2910 script invocations.
2911
2912 =head2 DELETING ALL PARAMETERS:
2913
2914 $query->delete_all();
2915
2916 This clears the CGI object completely.  It might be useful to ensure
2917 that all the defaults are taken when you create a fill-out form.
2918
2919 =head2 SAVING THE STATE OF THE FORM TO A FILE:
2920
2921     $query->save(FILEHANDLE)
2922
2923 This will write the current state of the form to the provided
2924 filehandle.  You can read it back in by providing a filehandle
2925 to the new() method.  Note that the filehandle can be a file, a pipe,
2926 or whatever!
2927
2928 The format of the saved file is:
2929
2930         NAME1=VALUE1
2931         NAME1=VALUE1'
2932         NAME2=VALUE2
2933         NAME3=VALUE3
2934         =
2935
2936 Both name and value are URL escaped.  Multi-valued CGI parameters are
2937 represented as repeated names.  A session record is delimited by a
2938 single = symbol.  You can write out multiple records and read them
2939 back in with several calls to B<new>.  You can do this across several
2940 sessions by opening the file in append mode, allowing you to create
2941 primitive guest books, or to keep a history of users' queries.  Here's
2942 a short example of creating multiple session records:
2943
2944    use CGI;
2945
2946    open (OUT,">>test.out") || die;
2947    $records = 5;
2948    foreach (0..$records) {
2949        my $q = new CGI;
2950        $q->param(-name=>'counter',-value=>$_);
2951        $q->save(OUT);
2952    }
2953    close OUT;
2954
2955    # reopen for reading
2956    open (IN,"test.out") || die;
2957    while (!eof(IN)) {
2958        my $q = new CGI(IN);
2959        print $q->param('counter'),"\n";
2960    }
2961
2962 The file format used for save/restore is identical to that used by the
2963 Whitehead Genome Center's data exchange format "Boulderio", and can be
2964 manipulated and even databased using Boulderio utilities.  See
2965         
2966   http://www.genome.wi.mit.edu/genome_software/other/boulder.html
2967
2968 for further details.
2969
2970 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
2971
2972     $myself = $query->self_url;
2973     print "<A HREF=$myself>I'm talking to myself.</A>";
2974
2975 self_url() will return a URL, that, when selected, will reinvoke
2976 this script with all its state information intact.  This is most
2977 useful when you want to jump around within the document using
2978 internal anchors but you don't want to disrupt the current contents
2979 of the form(s).  Something like this will do the trick.
2980
2981      $myself = $query->self_url;
2982      print "<A HREF=$myself#table1>See table 1</A>";
2983      print "<A HREF=$myself#table2>See table 2</A>";
2984      print "<A HREF=$myself#yourself>See for yourself</A>";
2985
2986 If you don't want to get the whole query string, call
2987 the method url() to return just the URL for the script:
2988
2989     $myself = $query->url;
2990     print "<A HREF=$myself>No query string in this baby!</A>\n";
2991
2992 You can also retrieve the unprocessed query string with query_string():
2993
2994     $the_string = $query->query_string;
2995
2996 =head2 COMPATIBILITY WITH CGI-LIB.PL
2997
2998 To make it easier to port existing programs that use cgi-lib.pl
2999 the compatibility routine "ReadParse" is provided.  Porting is
3000 simple:
3001
3002 OLD VERSION
3003     require "cgi-lib.pl";
3004     &ReadParse;
3005     print "The value of the antique is $in{antique}.\n";
3006
3007 NEW VERSION
3008     use CGI;
3009     CGI::ReadParse
3010     print "The value of the antique is $in{antique}.\n";
3011
3012 CGI.pm's ReadParse() routine creates a tied variable named %in,
3013 which can be accessed to obtain the query variables.  Like
3014 ReadParse, you can also provide your own variable.  Infrequently
3015 used features of ReadParse, such as the creation of @in and $in 
3016 variables, are not supported.
3017
3018 Once you use ReadParse, you can retrieve the query object itself
3019 this way:
3020
3021     $q = $in{CGI};
3022     print $q->textfield(-name=>'wow',
3023                         -value=>'does this really work?');
3024
3025 This allows you to start using the more interesting features
3026 of CGI.pm without rewriting your old scripts from scratch.
3027
3028 =head2 CALLING CGI FUNCTIONS THAT TAKE MULTIPLE ARGUMENTS
3029
3030 In versions of CGI.pm prior to 2.0, it could get difficult to remember
3031 the proper order of arguments in CGI function calls that accepted five
3032 or six different arguments.  As of 2.0, there's a better way to pass
3033 arguments to the various CGI functions.  In this style, you pass a
3034 series of name=>argument pairs, like this:
3035
3036    $field = $query->radio_group(-name=>'OS',
3037                                 -values=>[Unix,Windows,Macintosh],
3038                                 -default=>'Unix');
3039
3040 The advantages of this style are that you don't have to remember the
3041 exact order of the arguments, and if you leave out a parameter, in
3042 most cases it will default to some reasonable value.  If you provide
3043 a parameter that the method doesn't recognize, it will usually do
3044 something useful with it, such as incorporating it into the HTML form
3045 tag.  For example if Netscape decides next week to add a new
3046 JUSTIFICATION parameter to the text field tags, you can start using
3047 the feature without waiting for a new version of CGI.pm:
3048
3049    $field = $query->textfield(-name=>'State',
3050                               -default=>'gaseous',
3051                               -justification=>'RIGHT');
3052
3053 This will result in an HTML tag that looks like this:
3054
3055         <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
3056                JUSTIFICATION="RIGHT">
3057
3058 Parameter names are case insensitive: you can use -name, or -Name or
3059 -NAME.  You don't have to use the hyphen if you don't want to.  After
3060 creating a CGI object, call the B<use_named_parameters()> method with
3061 a nonzero value.  This will tell CGI.pm that you intend to use named
3062 parameters exclusively:
3063
3064    $query = new CGI;
3065    $query->use_named_parameters(1);
3066    $field = $query->radio_group('name'=>'OS',
3067                                 'values'=>['Unix','Windows','Macintosh'],
3068                                 'default'=>'Unix');
3069
3070 Actually, CGI.pm only looks for a hyphen in the first parameter.  So
3071 you can leave it off subsequent parameters if you like.  Something to
3072 be wary of is the potential that a string constant like "values" will
3073 collide with a keyword (and in fact it does!) While Perl usually
3074 figures out when you're referring to a function and when you're
3075 referring to a string, you probably should put quotation marks around
3076 all string constants just to play it safe.
3077
3078 =head2 CREATING THE HTTP HEADER:
3079
3080         print $query->header;
3081
3082              -or-
3083
3084         print $query->header('image/gif');
3085
3086              -or-
3087
3088         print $query->header('text/html','204 No response');
3089
3090              -or-
3091
3092         print $query->header(-type=>'image/gif',
3093                              -nph=>1,
3094                              -status=>'402 Payment required',
3095                              -expires=>'+3d',
3096                              -cookie=>$cookie,
3097                              -Cost=>'$2.00');
3098
3099 header() returns the Content-type: header.  You can provide your own
3100 MIME type if you choose, otherwise it defaults to text/html.  An
3101 optional second parameter specifies the status code and a human-readable
3102 message.  For example, you can specify 204, "No response" to create a
3103 script that tells the browser to do nothing at all.  If you want to
3104 add additional fields to the header, just tack them on to the end:
3105
3106     print $query->header('text/html','200 OK','Content-Length: 3002');
3107
3108 The last example shows the named argument style for passing arguments
3109 to the CGI methods using named parameters.  Recognized parameters are
3110 B<-type>, B<-status>, B<-expires>, and B<-cookie>.  Any other 
3111 parameters will be stripped of their initial hyphens and turned into
3112 header fields, allowing you to specify any HTTP header you desire.
3113
3114 Most browsers will not cache the output from CGI scripts.  Every time
3115 the browser reloads the page, the script is invoked anew.  You can
3116 change this behavior with the B<-expires> parameter.  When you specify
3117 an absolute or relative expiration interval with this parameter, some
3118 browsers and proxy servers will cache the script's output until the
3119 indicated expiration date.  The following forms are all valid for the
3120 -expires field:
3121
3122         +30s                              30 seconds from now
3123         +10m                              ten minutes from now
3124         +1h                               one hour from now
3125         -1d                               yesterday (i.e. "ASAP!")
3126         now                               immediately
3127         +3M                               in three months
3128         +10y                              in ten years time
3129         Thursday, 25-Apr-96 00:40:33 GMT  at the indicated time & date
3130
3131 (CGI::expires() is the static function call used internally that turns
3132 relative time intervals into HTTP dates.  You can call it directly if
3133 you wish.)
3134
3135 The B<-cookie> parameter generates a header that tells the browser to provide
3136 a "magic cookie" during all subsequent transactions with your script.
3137 Netscape cookies have a special format that includes interesting attributes
3138 such as expiration time.  Use the cookie() method to create and retrieve
3139 session cookies.
3140
3141 The B<-nph> parameter, if set to a true value, will issue the correct
3142 headers to work with a NPH (no-parse-header) script.  This is important
3143 to use with certain servers, such as Microsoft Internet Explorer, which
3144 expect all their scripts to be NPH.
3145
3146 =head2 GENERATING A REDIRECTION INSTRUCTION
3147
3148    print $query->redirect('http://somewhere.else/in/movie/land');
3149
3150 redirects the browser elsewhere.  If you use redirection like this,
3151 you should B<not> print out a header as well.  As of version 2.0, we
3152 produce both the unofficial Location: header and the official URI:
3153 header.  This should satisfy most servers and browsers.
3154
3155 One hint I can offer is that relative links may not work correctly
3156 when you generate a redirection to another document on your site.
3157 This is due to a well-intentioned optimization that some servers use.
3158 The solution to this is to use the full URL (including the http: part)
3159 of the document you are redirecting to.
3160
3161 You can use named parameters:
3162
3163     print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
3164                            -nph=>1);
3165
3166 The B<-nph> parameter, if set to a true value, will issue the correct
3167 headers to work with a NPH (no-parse-header) script.  This is important
3168 to use with certain servers, such as Microsoft Internet Explorer, which
3169 expect all their scripts to be NPH.
3170
3171
3172 =head2 CREATING THE HTML HEADER:
3173
3174    print $query->start_html(-title=>'Secrets of the Pyramids',
3175                             -author=>'fred@capricorn.org',
3176                             -base=>'true',
3177                             -target=>'_blank',
3178                             -meta=>{'keywords'=>'pharaoh secret mummy',
3179                                     'copyright'=>'copyright 1996 King Tut'},
3180                             -BGCOLOR=>'blue');
3181
3182    -or-
3183
3184    print $query->start_html('Secrets of the Pyramids',
3185                             'fred@capricorn.org','true',
3186                             'BGCOLOR="blue"');
3187
3188 This will return a canned HTML header and the opening <BODY> tag.  
3189 All parameters are optional.   In the named parameter form, recognized
3190 parameters are -title, -author, -base, -xbase and -target (see below for the
3191 explanation).  Any additional parameters you provide, such as the
3192 Netscape unofficial BGCOLOR attribute, are added to the <BODY> tag.
3193
3194 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
3195 different from the current location, as in
3196
3197     -xbase=>"http://home.mcom.com/"
3198
3199 All relative links will be interpreted relative to this tag.
3200
3201 The argument B<-target> allows you to provide a default target frame
3202 for all the links and fill-out forms on the page.  See the Netscape
3203 documentation on frames for details of how to manipulate this.
3204
3205     -target=>"answer_window"
3206
3207 All relative links will be interpreted relative to this tag.
3208 You add arbitrary meta information to the header with the B<-meta>
3209 argument.  This argument expects a reference to an associative array
3210 containing name/value pairs of meta information.  These will be turned
3211 into a series of header <META> tags that look something like this:
3212
3213     <META NAME="keywords" CONTENT="pharaoh secret mummy">
3214     <META NAME="description" CONTENT="copyright 1996 King Tut">
3215
3216 There is no support for the HTTP-EQUIV type of <META> tag.  This is
3217 because you can modify the HTTP header directly with the B<header()>
3218 method.
3219
3220 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad> and B<-onUnload> parameters
3221 are used to add Netscape JavaScript calls to your pages.  B<-script>
3222 should point to a block of text containing JavaScript function
3223 definitions.  This block will be placed within a <SCRIPT> block inside
3224 the HTML (not HTTP) header.  The block is placed in the header in
3225 order to give your page a fighting chance of having all its JavaScript
3226 functions in place even if the user presses the stop button before the
3227 page has loaded completely.  CGI.pm attempts to format the script in
3228 such a way that JavaScript-naive browsers will not choke on the code:
3229 unfortunately there are some browsers, such as Chimera for Unix, that
3230 get confused by it nevertheless.
3231
3232 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
3233 code to execute when the page is respectively opened and closed by the
3234 browser.  Usually these parameters are calls to functions defined in the
3235 B<-script> field:
3236
3237       $query = new CGI;
3238       print $query->header;
3239       $JSCRIPT=<<END;
3240       // Ask a silly question
3241       function riddle_me_this() {
3242          var r = prompt("What walks on four legs in the morning, " +
3243                        "two legs in the afternoon, " +
3244                        "and three legs in the evening?");
3245          response(r);
3246       }
3247       // Get a silly answer
3248       function response(answer) {
3249          if (answer == "man")
3250             alert("Right you are!");
3251          else
3252             alert("Wrong!  Guess again.");
3253       }
3254       END
3255       print $query->start_html(-title=>'The Riddle of the Sphinx',
3256                                -script=>$JSCRIPT);
3257
3258 Use the B<-noScript> parameter to pass some HTML text that will be displayed on 
3259 browsers that do not have JavaScript (or browsers where JavaScript is turned
3260 off).
3261
3262 See
3263
3264    http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
3265
3266 for more information about JavaScript.
3267
3268 The old-style positional parameters are as follows:
3269
3270 =over 4
3271
3272 =item B<Parameters:>
3273
3274 =item 1.
3275
3276 The title
3277
3278 =item 2.
3279
3280 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
3281
3282 =item 3.
3283
3284 A 'true' flag if you want to include a <BASE> tag in the header.  This
3285 helps resolve relative addresses to absolute ones when the document is moved, 
3286 but makes the document hierarchy non-portable.  Use with care!
3287
3288 =item 4, 5, 6...
3289
3290 Any other parameters you want to include in the <BODY> tag.  This is a good
3291 place to put Netscape extensions, such as colors and wallpaper patterns.
3292
3293 =back
3294
3295 =head2 ENDING THE HTML DOCUMENT:
3296
3297         print $query->end_html
3298
3299 This ends an HTML document by printing the </BODY></HTML> tags.
3300
3301 =head1 CREATING FORMS
3302
3303 I<General note>  The various form-creating methods all return strings
3304 to the caller, containing the tag or tags that will create the requested
3305 form element.  You are responsible for actually printing out these strings.
3306 It's set up this way so that you can place formatting tags
3307 around the form elements.
3308
3309 I<Another note> The default values that you specify for the forms are only
3310 used the B<first> time the script is invoked (when there is no query
3311 string).  On subsequent invocations of the script (when there is a query
3312 string), the former values are used even if they are blank.  
3313
3314 If you want to change the value of a field from its previous value, you have two
3315 choices:
3316
3317 (1) call the param() method to set it.
3318
3319 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
3320 This forces the default value to be used, regardless of the previous value:
3321
3322    print $query->textfield(-name=>'field_name',
3323                            -default=>'starting value',
3324                            -override=>1,
3325                            -size=>50,
3326                            -maxlength=>80);
3327
3328 I<Yet another note> By default, the text and labels of form elements are
3329 escaped according to HTML rules.  This means that you can safely use
3330 "<CLICK ME>" as the label for a button.  However, it also interferes with
3331 your ability to incorporate special HTML character sequences, such as &Aacute;,
3332 into your fields.  If you wish to turn off automatic escaping, call the
3333 autoEscape() method with a false value immediately after creating the CGI object:
3334
3335    $query = new CGI;
3336    $query->autoEscape(undef);
3337                              
3338
3339 =head2 CREATING AN ISINDEX TAG
3340
3341    print $query->isindex(-action=>$action);
3342
3343          -or-
3344
3345    print $query->isindex($action);
3346
3347 Prints out an <ISINDEX> tag.  Not very exciting.  The parameter
3348 -action specifies the URL of the script to process the query.  The
3349 default is to process the query with the current script.
3350
3351 =head2 STARTING AND ENDING A FORM
3352
3353     print $query->startform(-method=>$method,
3354                             -action=>$action,
3355                             -encoding=>$encoding);
3356       <... various form stuff ...>
3357     print $query->endform;
3358
3359         -or-
3360
3361     print $query->startform($method,$action,$encoding);
3362       <... various form stuff ...>
3363     print $query->endform;
3364
3365 startform() will return a <FORM> tag with the optional method,
3366 action and form encoding that you specify.  The defaults are:
3367         
3368     method: POST
3369     action: this script
3370     encoding: application/x-www-form-urlencoded
3371
3372 endform() returns the closing </FORM> tag.  
3373
3374 Startform()'s encoding method tells the browser how to package the various
3375 fields of the form before sending the form to the server.  Two
3376 values are possible:
3377
3378 =over 4
3379
3380 =item B<application/x-www-form-urlencoded>
3381
3382 This is the older type of encoding used by all browsers prior to
3383 Netscape 2.0.  It is compatible with many CGI scripts and is
3384 suitable for short fields containing text data.  For your
3385 convenience, CGI.pm stores the name of this encoding
3386 type in B<$CGI::URL_ENCODED>.
3387
3388 =item B<multipart/form-data>
3389
3390 This is the newer type of encoding introduced by Netscape 2.0.
3391 It is suitable for forms that contain very large fields or that
3392 are intended for transferring binary data.  Most importantly,
3393 it enables the "file upload" feature of Netscape 2.0 forms.  For
3394 your convenience, CGI.pm stores the name of this encoding type
3395 in B<$CGI::MULTIPART>
3396
3397 Forms that use this type of encoding are not easily interpreted
3398 by CGI scripts unless they use CGI.pm or another library designed
3399 to handle them.
3400
3401 =back
3402
3403 For compatibility, the startform() method uses the older form of
3404 encoding by default.  If you want to use the newer form of encoding
3405 by default, you can call B<start_multipart_form()> instead of
3406 B<startform()>.
3407
3408 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
3409 for use with JavaScript.  The -name parameter gives the
3410 form a name so that it can be identified and manipulated by
3411 JavaScript functions.  -onSubmit should point to a JavaScript
3412 function that will be executed just before the form is submitted to your
3413 server.  You can use this opportunity to check the contents of the form 
3414 for consistency and completeness.  If you find something wrong, you
3415 can put up an alert box or maybe fix things up yourself.  You can 
3416 abort the submission by returning false from this function.  
3417
3418 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
3419 block in the HTML header and -onSubmit points to one of these function
3420 call.  See start_html() for details.
3421
3422 =head2 CREATING A TEXT FIELD
3423
3424     print $query->textfield(-name=>'field_name',
3425                             -default=>'starting value',
3426                             -size=>50,
3427                             -maxlength=>80);
3428         -or-
3429
3430     print $query->textfield('field_name','starting value',50,80);
3431
3432 textfield() will return a text input field.  
3433
3434 =over 4
3435
3436 =item B<Parameters>
3437
3438 =item 1.
3439
3440 The first parameter is the required name for the field (-name).  
3441
3442 =item 2.
3443
3444 The optional second parameter is the default starting value for the field
3445 contents (-default).  
3446
3447 =item 3.
3448
3449 The optional third parameter is the size of the field in
3450       characters (-size).
3451
3452 =item 4.
3453
3454 The optional fourth parameter is the maximum number of characters the
3455       field will accept (-maxlength).
3456
3457 =back
3458
3459 As with all these methods, the field will be initialized with its 
3460 previous contents from earlier invocations of the script.
3461 When the form is processed, the value of the text field can be
3462 retrieved with:
3463
3464        $value = $query->param('foo');
3465
3466 If you want to reset it from its initial value after the script has been
3467 called once, you can do so like this:
3468
3469        $query->param('foo',"I'm taking over this value!");
3470
3471 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
3472 value, you can force its current value by using the -override (alias -force)
3473 parameter:
3474
3475     print $query->textfield(-name=>'field_name',
3476                             -default=>'starting value',
3477                             -override=>1,
3478                             -size=>50,
3479                             -maxlength=>80);
3480
3481 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>, B<-onBlur>
3482 and B<-onSelect> parameters to register JavaScript event handlers.
3483 The onChange handler will be called whenever the user changes the
3484 contents of the text field.  You can do text validation if you like.
3485 onFocus and onBlur are called respectively when the insertion point
3486 moves into and out of the text field.  onSelect is called when the
3487 user changes the portion of the text that is selected.
3488
3489 =head2 CREATING A BIG TEXT FIELD
3490
3491    print $query->textarea(-name=>'foo',
3492                           -default=>'starting value',
3493                           -rows=>10,
3494                           -columns=>50);
3495
3496         -or
3497
3498    print $query->textarea('foo','starting value',10,50);
3499
3500 textarea() is just like textfield, but it allows you to specify
3501 rows and columns for a multiline text entry box.  You can provide
3502 a starting value for the field, which can be long and contain
3503 multiple lines.
3504
3505 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3506 and B<-onSelect> parameters are recognized.  See textfield().
3507
3508 =head2 CREATING A PASSWORD FIELD
3509
3510    print $query->password_field(-name=>'secret',
3511                                 -value=>'starting value',
3512                                 -size=>50,
3513                                 -maxlength=>80);
3514         -or-
3515
3516    print $query->password_field('secret','starting value',50,80);
3517
3518 password_field() is identical to textfield(), except that its contents 
3519 will be starred out on the web page.
3520
3521 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3522 and B<-onSelect> parameters are recognized.  See textfield().
3523
3524 =head2 CREATING A FILE UPLOAD FIELD
3525
3526     print $query->filefield(-name=>'uploaded_file',
3527                             -default=>'starting value',
3528                             -size=>50,
3529                             -maxlength=>80);
3530         -or-
3531
3532     print $query->filefield('uploaded_file','starting value',50,80);
3533
3534 filefield() will return a file upload field for Netscape 2.0 browsers.
3535 In order to take full advantage of this I<you must use the new 
3536 multipart encoding scheme> for the form.  You can do this either
3537 by calling B<startform()> with an encoding type of B<$CGI::MULTIPART>,
3538 or by calling the new method B<start_multipart_form()> instead of
3539 vanilla B<startform()>.
3540
3541 =over 4
3542
3543 =item B<Parameters>
3544
3545 =item 1.
3546
3547 The first parameter is the required name for the field (-name).  
3548
3549 =item 2.
3550
3551 The optional second parameter is the starting value for the field contents
3552 to be used as the default file name (-default).
3553
3554 The beta2 version of Netscape 2.0 currently doesn't pay any attention
3555 to this field, and so the starting value will always be blank.  Worse,
3556 the field loses its "sticky" behavior and forgets its previous
3557 contents.  The starting value field is called for in the HTML
3558 specification, however, and possibly later versions of Netscape will
3559 honor it.
3560
3561 =item 3.
3562
3563 The optional third parameter is the size of the field in
3564 characters (-size).
3565
3566 =item 4.
3567
3568 The optional fourth parameter is the maximum number of characters the
3569 field will accept (-maxlength).
3570
3571 =back
3572
3573 When the form is processed, you can retrieve the entered filename
3574 by calling param().
3575
3576        $filename = $query->param('uploaded_file');
3577
3578 In Netscape Gold, the filename that gets returned is the full local filename
3579 on the B<remote user's> machine.  If the remote user is on a Unix
3580 machine, the filename will follow Unix conventions:
3581
3582         /path/to/the/file
3583
3584 On an MS-DOS/Windows and OS/2 machines, the filename will follow DOS conventions:
3585
3586         C:\PATH\TO\THE\FILE.MSW
3587
3588 On a Macintosh machine, the filename will follow Mac conventions:
3589
3590         HD 40:Desktop Folder:Sort Through:Reminders
3591
3592 The filename returned is also a file handle.  You can read the contents
3593 of the file using standard Perl file reading calls:
3594
3595         # Read a text file and print it out
3596         while (<$filename>) {
3597            print;
3598         }
3599
3600         # Copy a binary file to somewhere safe
3601         open (OUTFILE,">>/usr/local/web/users/feedback");
3602         while ($bytesread=read($filename,$buffer,1024)) {
3603            print OUTFILE $buffer;
3604         }
3605
3606 When a file is uploaded the browser usually sends along some
3607 information along with it in the format of headers.  The information
3608 usually includes the MIME content type.  Future browsers may send
3609 other information as well (such as modification date and size). To
3610 retrieve this information, call uploadInfo().  It returns a reference to
3611 an associative array containing all the document headers.
3612
3613        $filename = $query->param('uploaded_file');
3614        $type = $query->uploadInfo($filename)->{'Content-Type'};
3615        unless ($type eq 'text/html') {
3616           die "HTML FILES ONLY!";
3617        }
3618
3619 If you are using a machine that recognizes "text" and "binary" data
3620 modes, be sure to understand when and how to use them (see the Camel book).  
3621 Otherwise you may find that binary files are corrupted during file uploads.
3622
3623 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3624 and B<-onSelect> parameters are recognized.  See textfield()
3625 for details. 
3626
3627 =head2 CREATING A POPUP MENU
3628
3629    print $query->popup_menu('menu_name',
3630                             ['eenie','meenie','minie'],
3631                             'meenie');
3632
3633       -or-
3634
3635    %labels = ('eenie'=>'your first choice',
3636               'meenie'=>'your second choice',
3637               'minie'=>'your third choice');
3638    print $query->popup_menu('menu_name',
3639                             ['eenie','meenie','minie'],
3640                             'meenie',\%labels);
3641
3642         -or (named parameter style)-
3643
3644    print $query->popup_menu(-name=>'menu_name',
3645                             -values=>['eenie','meenie','minie'],
3646                             -default=>'meenie',
3647                             -labels=>\%labels);
3648
3649 popup_menu() creates a menu.
3650
3651 =over 4
3652
3653 =item 1.
3654
3655 The required first argument is the menu's name (-name).
3656
3657 =item 2.
3658
3659 The required second argument (-values) is an array B<reference>
3660 containing the list of menu items in the menu.  You can pass the
3661 method an anonymous array, as shown in the example, or a reference to
3662 a named array, such as "\@foo".
3663
3664 =item 3.
3665
3666 The optional third parameter (-default) is the name of the default
3667 menu choice.  If not specified, the first item will be the default.
3668 The values of the previous choice will be maintained across queries.
3669
3670 =item 4.
3671
3672 The optional fourth parameter (-labels) is provided for people who
3673 want to use different values for the user-visible label inside the
3674 popup menu nd the value returned to your script.  It's a pointer to an
3675 associative array relating menu values to user-visible labels.  If you
3676 leave this parameter blank, the menu values will be displayed by
3677 default.  (You can also leave a label undefined if you want to).
3678
3679 =back
3680
3681 When the form is processed, the selected value of the popup menu can
3682 be retrieved using:
3683
3684       $popup_menu_value = $query->param('menu_name');
3685
3686 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
3687 B<-onChange>, B<-onFocus>, and B<-onBlur>.  See the textfield()
3688 section for details on when these handlers are called.
3689
3690 =head2 CREATING A SCROLLING LIST
3691
3692    print $query->scrolling_list('list_name',
3693                                 ['eenie','meenie','minie','moe'],
3694                                 ['eenie','moe'],5,'true');
3695       -or-
3696
3697    print $query->scrolling_list('list_name',
3698                                 ['eenie','meenie','minie','moe'],
3699                                 ['eenie','moe'],5,'true',
3700                                 \%labels);
3701
3702         -or-
3703
3704    print $query->scrolling_list(-name=>'list_name',
3705                                 -values=>['eenie','meenie','minie','moe'],
3706                                 -default=>['eenie','moe'],
3707                                 -size=>5,
3708                                 -multiple=>'true',
3709                                 -labels=>\%labels);
3710
3711 scrolling_list() creates a scrolling list.  
3712
3713 =over 4
3714
3715 =item B<Parameters:>
3716
3717 =item 1.
3718
3719 The first and second arguments are the list name (-name) and values
3720 (-values).  As in the popup menu, the second argument should be an
3721 array reference.
3722
3723 =item 2.
3724
3725 The optional third argument (-default) can be either a reference to a
3726 list containing the values to be selected by default, or can be a
3727 single value to select.  If this argument is missing or undefined,
3728 then nothing is selected when the list first appears.  In the named
3729 parameter version, you can use the synonym "-defaults" for this
3730 parameter.
3731
3732 =item 3.
3733
3734 The optional fourth argument is the size of the list (-size).
3735
3736 =item 4.
3737
3738 The optional fifth argument can be set to true to allow multiple
3739 simultaneous selections (-multiple).  Otherwise only one selection
3740 will be allowed at a time.
3741
3742 =item 5.
3743
3744 The optional sixth argument is a pointer to an associative array
3745 containing long user-visible labels for the list items (-labels).
3746 If not provided, the values will be displayed.
3747
3748 When this form is processed, all selected list items will be returned as
3749 a list under the parameter name 'list_name'.  The values of the
3750 selected items can be retrieved with:
3751
3752       @selected = $query->param('list_name');
3753
3754 =back
3755
3756 JAVASCRIPTING: scrolling_list() recognizes the following event handlers:
3757 B<-onChange>, B<-onFocus>, and B<-onBlur>.  See textfield() for
3758 the description of when these handlers are called.
3759
3760 =head2 CREATING A GROUP OF RELATED CHECKBOXES
3761
3762    print $query->checkbox_group(-name=>'group_name',
3763                                 -values=>['eenie','meenie','minie','moe'],
3764                                 -default=>['eenie','moe'],
3765                                 -linebreak=>'true',
3766                                 -labels=>\%labels);
3767
3768    print $query->checkbox_group('group_name',
3769                                 ['eenie','meenie','minie','moe'],
3770                                 ['eenie','moe'],'true',\%labels);
3771
3772    HTML3-COMPATIBLE BROWSERS ONLY:
3773
3774    print $query->checkbox_group(-name=>'group_name',
3775                                 -values=>['eenie','meenie','minie','moe'],
3776                                 -rows=2,-columns=>2);
3777     
3778
3779 checkbox_group() creates a list of checkboxes that are related
3780 by the same name.
3781
3782 =over 4
3783
3784 =item B<Parameters:>
3785
3786 =item 1.
3787
3788 The first and second arguments are the checkbox name and values,
3789 respectively (-name and -values).  As in the popup menu, the second
3790 argument should be an array reference.  These values are used for the
3791 user-readable labels printed next to the checkboxes as well as for the
3792 values passed to your script in the query string.
3793
3794 =item 2.
3795
3796 The optional third argument (-default) can be either a reference to a
3797 list containing the values to be checked by default, or can be a
3798 single value to checked.  If this argument is missing or undefined,
3799 then nothing is selected when the list first appears.
3800
3801 =item 3.
3802
3803 The optional fourth argument (-linebreak) can be set to true to place
3804 line breaks between the checkboxes so that they appear as a vertical
3805 list.  Otherwise, they will be strung together on a horizontal line.
3806
3807 =item 4.
3808
3809 The optional fifth argument is a pointer to an associative array
3810 relating the checkbox values to the user-visible labels that will
3811 be printed next to them (-labels).  If not provided, the values will
3812 be used as the default.
3813
3814 =item 5.
3815
3816 B<HTML3-compatible browsers> (such as Netscape) can take advantage 
3817 of the optional 
3818 parameters B<-rows>, and B<-columns>.  These parameters cause
3819 checkbox_group() to return an HTML3 compatible table containing
3820 the checkbox group formatted with the specified number of rows
3821 and columns.  You can provide just the -columns parameter if you
3822 wish; checkbox_group will calculate the correct number of rows
3823 for you.
3824
3825 To include row and column headings in the returned table, you
3826 can use the B<-rowheader> and B<-colheader> parameters.  Both
3827 of these accept a pointer to an array of headings to use.
3828 The headings are just decorative.  They don't reorganize the
3829 interpretation of the checkboxes -- they're still a single named
3830 unit.
3831
3832 =back
3833
3834 When the form is processed, all checked boxes will be returned as
3835 a list under the parameter name 'group_name'.  The values of the
3836 "on" checkboxes can be retrieved with:
3837
3838       @turned_on = $query->param('group_name');
3839
3840 The value returned by checkbox_group() is actually an array of button
3841 elements.  You can capture them and use them within tables, lists,
3842 or in other creative ways:
3843
3844     @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
3845     &use_in_creative_way(@h);
3846
3847 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
3848 parameter.  This specifies a JavaScript code fragment or
3849 function call to be executed every time the user clicks on
3850 any of the buttons in the group.  You can retrieve the identity
3851 of the particular button clicked on using the "this" variable.
3852
3853 =head2 CREATING A STANDALONE CHECKBOX
3854
3855     print $query->checkbox(-name=>'checkbox_name',
3856                            -checked=>'checked',
3857                            -value=>'ON',
3858                            -label=>'CLICK ME');
3859
3860         -or-
3861
3862     print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
3863
3864 checkbox() is used to create an isolated checkbox that isn't logically
3865 related to any others.
3866
3867 =over 4
3868
3869 =item B<Parameters:>
3870
3871 =item 1.
3872
3873 The first parameter is the required name for the checkbox (-name).  It
3874 will also be used for the user-readable label printed next to the
3875 checkbox.
3876
3877 =item 2.
3878
3879 The optional second parameter (-checked) specifies that the checkbox
3880 is turned on by default.  Synonyms are -selected and -on.
3881
3882 =item 3.
3883
3884 The optional third parameter (-value) specifies the value of the
3885 checkbox when it is checked.  If not provided, the word "on" is
3886 assumed.
3887
3888 =item 4.
3889
3890 The optional fourth parameter (-label) is the user-readable label to
3891 be attached to the checkbox.  If not provided, the checkbox name is
3892 used.
3893
3894 =back
3895
3896 The value of the checkbox can be retrieved using:
3897
3898     $turned_on = $query->param('checkbox_name');
3899
3900 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
3901 parameter.  See checkbox_group() for further details.
3902
3903 =head2 CREATING A RADIO BUTTON GROUP
3904
3905    print $query->radio_group(-name=>'group_name',
3906                              -values=>['eenie','meenie','minie'],
3907                              -default=>'meenie',
3908                              -linebreak=>'true',
3909                              -labels=>\%labels);
3910
3911         -or-
3912
3913    print $query->radio_group('group_name',['eenie','meenie','minie'],
3914                                           'meenie','true',\%labels);
3915
3916
3917    HTML3-COMPATIBLE BROWSERS ONLY:
3918
3919    print $query->radio_group(-name=>'group_name',
3920                              -values=>['eenie','meenie','minie','moe'],
3921                              -rows=2,-columns=>2);
3922
3923 radio_group() creates a set of logically-related radio buttons
3924 (turning one member of the group on turns the others off)
3925
3926 =over 4
3927
3928 =item B<Parameters:>
3929
3930 =item 1.
3931
3932 The first argument is the name of the group and is required (-name).
3933
3934 =item 2.
3935
3936 The second argument (-values) is the list of values for the radio
3937 buttons.  The values and the labels that appear on the page are
3938 identical.  Pass an array I<reference> in the second argument, either
3939 using an anonymous array, as shown, or by referencing a named array as
3940 in "\@foo".
3941
3942 =item 3.
3943
3944 The optional third parameter (-default) is the name of the default
3945 button to turn on. If not specified, the first item will be the
3946 default.  You can provide a nonexistent button name, such as "-" to
3947 start up with no buttons selected.
3948
3949 =item 4.
3950
3951 The optional fourth parameter (-linebreak) can be set to 'true' to put
3952 line breaks between the buttons, creating a vertical list.
3953
3954 =item 5.
3955
3956 The optional fifth parameter (-labels) is a pointer to an associative
3957 array relating the radio button values to user-visible labels to be
3958 used in the display.  If not provided, the values themselves are
3959 displayed.
3960
3961 =item 6.
3962
3963 B<HTML3-compatible browsers> (such as Netscape) can take advantage 
3964 of the optional 
3965 parameters B<-rows>, and B<-columns>.  These parameters cause
3966 radio_group() to return an HTML3 compatible table containing
3967 the radio group formatted with the specified number of rows
3968 and columns.  You can provide just the -columns parameter if you
3969 wish; radio_group will calculate the correct number of rows
3970 for you.
3971
3972 To include row and column headings in the returned table, you
3973 can use the B<-rowheader> and B<-colheader> parameters.  Both
3974 of these accept a pointer to an array of headings to use.
3975 The headings are just decorative.  They don't reorganize the
3976 interpetation of the radio buttons -- they're still a single named
3977 unit.
3978
3979 =back
3980
3981 When the form is processed, the selected radio button can
3982 be retrieved using:
3983
3984       $which_radio_button = $query->param('group_name');
3985
3986 The value returned by radio_group() is actually an array of button
3987 elements.  You can capture them and use them within tables, lists,
3988 or in other creative ways:
3989
3990     @h = $query->radio_group(-name=>'group_name',-values=>\@values);
3991     &use_in_creative_way(@h);
3992
3993 =head2 CREATING A SUBMIT BUTTON 
3994
3995    print $query->submit(-name=>'button_name',
3996                         -value=>'value');
3997
3998         -or-
3999
4000    print $query->submit('button_name','value');
4001
4002 submit() will create the query submission button.  Every form
4003 should have one of these.
4004
4005 =over 4
4006
4007 =item B<Parameters:>
4008
4009 =item 1.
4010
4011 The first argument (-name) is optional.  You can give the button a
4012 name if you have several submission buttons in your form and you want
4013 to distinguish between them.  The name will also be used as the
4014 user-visible label.  Be aware that a few older browsers don't deal with this correctly and
4015 B<never> send back a value from a button.
4016
4017 =item 2.
4018
4019 The second argument (-value) is also optional.  This gives the button
4020 a value that will be passed to your script in the query string.
4021
4022 =back
4023
4024 You can figure out which button was pressed by using different
4025 values for each one:
4026
4027      $which_one = $query->param('button_name');
4028
4029 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
4030 parameter.  See checkbox_group() for further details.
4031
4032 =head2 CREATING A RESET BUTTON
4033
4034    print $query->reset
4035
4036 reset() creates the "reset" button.  Note that it restores the
4037 form to its value from the last time the script was called, 
4038 NOT necessarily to the defaults.
4039
4040 =head2 CREATING A DEFAULT BUTTON
4041
4042    print $query->defaults('button_label')
4043
4044 defaults() creates a button that, when invoked, will cause the
4045 form to be completely reset to its defaults, wiping out all the
4046 changes the user ever made.
4047
4048 =head2 CREATING A HIDDEN FIELD
4049
4050         print $query->hidden(-name=>'hidden_name',
4051                              -default=>['value1','value2'...]);
4052
4053                 -or-
4054
4055         print $query->hidden('hidden_name','value1','value2'...);
4056
4057 hidden() produces a text field that can't be seen by the user.  It
4058 is useful for passing state variable information from one invocation
4059 of the script to the next.
4060
4061 =over 4
4062
4063 =item B<Parameters:>
4064
4065 =item 1.
4066
4067 The first argument is required and specifies the name of this
4068 field (-name).
4069
4070 =item 2.  
4071
4072 The second argument is also required and specifies its value
4073 (-default).  In the named parameter style of calling, you can provide
4074 a single value here or a reference to a whole list
4075
4076 =back
4077
4078 Fetch the value of a hidden field this way:
4079
4080      $hidden_value = $query->param('hidden_name');
4081
4082 Note, that just like all the other form elements, the value of a
4083 hidden field is "sticky".  If you want to replace a hidden field with
4084 some other values after the script has been called once you'll have to
4085 do it manually:
4086
4087      $query->param('hidden_name','new','values','here');
4088
4089 =head2 CREATING A CLICKABLE IMAGE BUTTON
4090
4091      print $query->image_button(-name=>'button_name',
4092                                 -src=>'/source/URL',
4093                                 -align=>'MIDDLE');      
4094
4095         -or-
4096
4097      print $query->image_button('button_name','/source/URL','MIDDLE');
4098
4099 image_button() produces a clickable image.  When it's clicked on the
4100 position of the click is returned to your script as "button_name.x"
4101 and "button_name.y", where "button_name" is the name you've assigned
4102 to it.
4103
4104 JAVASCRIPTING: image_button() recognizes the B<-onClick>
4105 parameter.  See checkbox_group() for further details.
4106
4107 =over 4
4108
4109 =item B<Parameters:>
4110
4111 =item 1.
4112
4113 The first argument (-name) is required and specifies the name of this
4114 field.
4115
4116 =item 2.
4117
4118 The second argument (-src) is also required and specifies the URL
4119
4120 =item 3.
4121 The third option (-align, optional) is an alignment type, and may be
4122 TOP, BOTTOM or MIDDLE
4123
4124 =back
4125
4126 Fetch the value of the button this way:
4127      $x = $query->param('button_name.x');
4128      $y = $query->param('button_name.y');
4129
4130 =head2 CREATING A JAVASCRIPT ACTION BUTTON
4131
4132      print $query->button(-name=>'button_name',
4133                           -value=>'user visible label',
4134                           -onClick=>"do_something()");
4135
4136         -or-
4137
4138      print $query->button('button_name',"do_something()");
4139
4140 button() produces a button that is compatible with Netscape 2.0's
4141 JavaScript.  When it's pressed the fragment of JavaScript code
4142 pointed to by the B<-onClick> parameter will be executed.  On
4143 non-Netscape browsers this form element will probably not even
4144 display.
4145
4146 =head1 NETSCAPE COOKIES
4147
4148 Netscape browsers versions 1.1 and higher support a so-called
4149 "cookie" designed to help maintain state within a browser session.
4150 CGI.pm has several methods that support cookies.
4151
4152 A cookie is a name=value pair much like the named parameters in a CGI
4153 query string.  CGI scripts create one or more cookies and send
4154 them to the browser in the HTTP header.  The browser maintains a list
4155 of cookies that belong to a particular Web server, and returns them
4156 to the CGI script during subsequent interactions.
4157
4158 In addition to the required name=value pair, each cookie has several
4159 optional attributes:
4160
4161 =over 4
4162
4163 =item 1. an expiration time
4164
4165 This is a time/date string (in a special GMT format) that indicates
4166 when a cookie expires.  The cookie will be saved and returned to your
4167 script until this expiration date is reached if the user exits
4168 Netscape and restarts it.  If an expiration date isn't specified, the cookie
4169 will remain active until the user quits Netscape.
4170
4171 =item 2. a domain
4172
4173 This is a partial or complete domain name for which the cookie is 
4174 valid.  The browser will return the cookie to any host that matches
4175 the partial domain name.  For example, if you specify a domain name
4176 of ".capricorn.com", then Netscape will return the cookie to
4177 Web servers running on any of the machines "www.capricorn.com", 
4178 "www2.capricorn.com", "feckless.capricorn.com", etc.  Domain names
4179 must contain at least two periods to prevent attempts to match
4180 on top level domains like ".edu".  If no domain is specified, then
4181 the browser will only return the cookie to servers on the host the
4182 cookie originated from.
4183
4184 =item 3. a path
4185
4186 If you provide a cookie path attribute, the browser will check it
4187 against your script's URL before returning the cookie.  For example,
4188 if you specify the path "/cgi-bin", then the cookie will be returned
4189 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
4190 and "/cgi-bin/customer_service/complain.pl", but not to the script
4191 "/cgi-private/site_admin.pl".  By default, path is set to "/", which
4192 causes the cookie to be sent to any CGI script on your site.
4193
4194 =item 4. a "secure" flag
4195
4196 If the "secure" attribute is set, the cookie will only be sent to your
4197 script if the CGI request is occurring on a secure channel, such as SSL.
4198
4199 =back
4200
4201 The interface to Netscape cookies is the B<cookie()> method:
4202
4203     $cookie = $query->cookie(-name=>'sessionID',
4204                              -value=>'xyzzy',
4205                              -expires=>'+1h',
4206                              -path=>'/cgi-bin/database',
4207                              -domain=>'.capricorn.org',
4208                              -secure=>1);
4209     print $query->header(-cookie=>$cookie);
4210
4211 B<cookie()> creates a new cookie.  Its parameters include:
4212
4213 =over 4
4214
4215 =item B<-name>
4216
4217 The name of the cookie (required).  This can be any string at all.
4218 Although Netscape limits its cookie names to non-whitespace
4219 alphanumeric characters, CGI.pm removes this restriction by escaping
4220 and unescaping cookies behind the scenes.
4221
4222 =item B<-value>
4223
4224 The value of the cookie.  This can be any scalar value,
4225 array reference, or even associative array reference.  For example,
4226 you can store an entire associative array into a cookie this way:
4227
4228         $cookie=$query->cookie(-name=>'family information',
4229                                -value=>\%childrens_ages);
4230
4231 =item B<-path>
4232
4233 The optional partial path for which this cookie will be valid, as described
4234 above.
4235
4236 =item B<-domain>
4237
4238 The optional partial domain for which this cookie will be valid, as described
4239 above.
4240
4241 =item B<-expires>
4242
4243 The optional expiration date for this cookie.  The format is as described 
4244 in the section on the B<header()> method:
4245
4246         "+1h"  one hour from now
4247
4248 =item B<-secure>
4249
4250 If set to true, this cookie will only be used within a secure
4251 SSL session.
4252
4253 =back
4254
4255 The cookie created by cookie() must be incorporated into the HTTP
4256 header within the string returned by the header() method:
4257
4258         print $query->header(-cookie=>$my_cookie);
4259
4260 To create multiple cookies, give header() an array reference:
4261
4262         $cookie1 = $query->cookie(-name=>'riddle_name',
4263                                   -value=>"The Sphynx's Question");
4264         $cookie2 = $query->cookie(-name=>'answers',
4265                                   -value=>\%answers);
4266         print $query->header(-cookie=>[$cookie1,$cookie2]);
4267
4268 To retrieve a cookie, request it by name by calling cookie()
4269 method without the B<-value> parameter:
4270
4271         use CGI;
4272         $query = new CGI;
4273         %answers = $query->cookie(-name=>'answers');
4274         # $query->cookie('answers') will work too!
4275
4276 The cookie and CGI namespaces are separate.  If you have a parameter
4277 named 'answers' and a cookie named 'answers', the values retrieved by
4278 param() and cookie() are independent of each other.  However, it's
4279 simple to turn a CGI parameter into a cookie, and vice-versa:
4280
4281    # turn a CGI parameter into a cookie
4282    $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
4283    # vice-versa
4284    $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
4285
4286 See the B<cookie.cgi> example script for some ideas on how to use
4287 cookies effectively.
4288
4289 B<NOTE:> There appear to be some (undocumented) restrictions on
4290 Netscape cookies.  In Netscape 2.01, at least, I haven't been able to
4291 set more than three cookies at a time.  There may also be limits on
4292 the length of cookies.  If you need to store a lot of information,
4293 it's probably better to create a unique session ID, store it in a
4294 cookie, and use the session ID to locate an external file/database
4295 saved on the server's side of the connection.
4296
4297 =head1 WORKING WITH NETSCAPE FRAMES
4298
4299 It's possible for CGI.pm scripts to write into several browser
4300 panels and windows using Netscape's frame mechanism.  
4301 There are three techniques for defining new frames programmatically:
4302
4303 =over 4
4304
4305 =item 1. Create a <Frameset> document
4306
4307 After writing out the HTTP header, instead of creating a standard
4308 HTML document using the start_html() call, create a <FRAMESET> 
4309 document that defines the frames on the page.  Specify your script(s)
4310 (with appropriate parameters) as the SRC for each of the frames.
4311
4312 There is no specific support for creating <FRAMESET> sections 
4313 in CGI.pm, but the HTML is very simple to write.  See the frame
4314 documentation in Netscape's home pages for details 
4315
4316   http://home.netscape.com/assist/net_sites/frames.html
4317
4318 =item 2. Specify the destination for the document in the HTTP header
4319
4320 You may provide a B<-target> parameter to the header() method:
4321    
4322     print $q->header(-target=>'ResultsWindow');
4323
4324 This will tell Netscape to load the output of your script into the
4325 frame named "ResultsWindow".  If a frame of that name doesn't
4326 already exist, Netscape will pop up a new window and load your
4327 script's document into that.  There are a number of magic names
4328 that you can use for targets.  See the frame documents on Netscape's
4329 home pages for details.
4330
4331 =item 3. Specify the destination for the document in the <FORM> tag
4332
4333 You can specify the frame to load in the FORM tag itself.  With
4334 CGI.pm it looks like this:
4335
4336     print $q->startform(-target=>'ResultsWindow');
4337
4338 When your script is reinvoked by the form, its output will be loaded
4339 into the frame named "ResultsWindow".  If one doesn't already exist
4340 a new window will be created.
4341
4342 =back
4343
4344 The script "frameset.cgi" in the examples directory shows one way to
4345 create pages in which the fill-out form and the response live in
4346 side-by-side frames.
4347
4348 =head1 DEBUGGING
4349
4350 If you are running the script
4351 from the command line or in the perl debugger, you can pass the script
4352 a list of keywords or parameter=value pairs on the command line or 
4353 from standard input (you don't have to worry about tricking your
4354 script into reading from environment variables).
4355 You can pass keywords like this:
4356
4357     your_script.pl keyword1 keyword2 keyword3
4358
4359 or this:
4360
4361    your_script.pl keyword1+keyword2+keyword3
4362
4363 or this:
4364
4365     your_script.pl name1=value1 name2=value2
4366
4367 or this:
4368
4369     your_script.pl name1=value1&name2=value2
4370
4371 or even as newline-delimited parameters on standard input.
4372
4373 When debugging, you can use quotes and backslashes to escape 
4374 characters in the familiar shell manner, letting you place
4375 spaces and other funny characters in your parameter=value
4376 pairs:
4377
4378    your_script.pl "name1='I am a long value'" "name2=two\ words"
4379
4380 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
4381
4382 The dump() method produces a string consisting of all the query's
4383 name/value pairs formatted nicely as a nested list.  This is useful
4384 for debugging purposes:
4385
4386     print $query->dump
4387     
4388
4389 Produces something that looks like:
4390
4391     <UL>
4392     <LI>name1
4393         <UL>
4394         <LI>value1
4395         <LI>value2
4396         </UL>
4397     <LI>name2
4398         <UL>
4399         <LI>value1
4400         </UL>
4401     </UL>
4402
4403 You can pass a value of 'true' to dump() in order to get it to
4404 print the results out as plain text, suitable for incorporating
4405 into a <PRE> section.
4406
4407 As a shortcut, as of version 1.56 you can interpolate the entire CGI
4408 object into a string and it will be replaced with the a nice HTML dump
4409 shown above:
4410
4411     $query=new CGI;
4412     print "<H2>Current Values</H2> $query\n";
4413
4414 =head1 FETCHING ENVIRONMENT VARIABLES
4415
4416 Some of the more useful environment variables can be fetched
4417 through this interface.  The methods are as follows:
4418
4419 =over 4
4420
4421 =item B<accept()>
4422
4423 Return a list of MIME types that the remote browser
4424 accepts. If you give this method a single argument
4425 corresponding to a MIME type, as in
4426 $query->accept('text/html'), it will return a
4427 floating point value corresponding to the browser's
4428 preference for this type from 0.0 (don't want) to 1.0.
4429 Glob types (e.g. text/*) in the browser's accept list
4430 are handled correctly.
4431
4432 =item B<raw_cookie()>
4433
4434 Returns the HTTP_COOKIE variable, an HTTP extension
4435 implemented by Netscape browsers version 1.1
4436 and higher.  Cookies have a special format, and this 
4437 method call just returns the raw form (?cookie dough).
4438 See cookie() for ways of setting and retrieving
4439 cooked cookies.
4440
4441 =item B<user_agent()>
4442
4443 Returns the HTTP_USER_AGENT variable.  If you give
4444 this method a single argument, it will attempt to
4445 pattern match on it, allowing you to do something
4446 like $query->user_agent(netscape);
4447
4448 =item B<path_info()>
4449
4450 Returns additional path information from the script URL.
4451 E.G. fetching /cgi-bin/your_script/additional/stuff will
4452 result in $query->path_info() returning
4453 "additional/stuff".
4454
4455 NOTE: The Microsoft Internet Information Server
4456 is broken with respect to additional path information.  If
4457 you use the Perl DLL library, the IIS server will attempt to
4458 execute the additional path information as a Perl script.
4459 If you use the ordinary file associations mapping, the
4460 path information will be present in the environment, 
4461 but incorrect.  The best thing to do is to avoid using additional
4462 path information in CGI scripts destined for use with IIS.
4463
4464 =item B<path_translated()>
4465
4466 As per path_info() but returns the additional
4467 path information translated into a physical path, e.g.
4468 "/usr/local/etc/httpd/htdocs/additional/stuff".
4469
4470 The Microsoft IIS is broken with respect to the translated
4471 path as well.
4472
4473 =item B<remote_host()>
4474
4475 Returns either the remote host name or IP address.
4476 if the former is unavailable.
4477
4478 =item B<script_name()>
4479 Return the script name as a partial URL, for self-refering
4480 scripts.
4481
4482 =item B<referer()>
4483
4484 Return the URL of the page the browser was viewing
4485 prior to fetching your script.  Not available for all
4486 browsers.
4487
4488 =item B<auth_type ()>
4489
4490 Return the authorization/verification method in use for this
4491 script, if any.
4492
4493 =item B<server_name ()>
4494
4495 Returns the name of the server, usually the machine's host
4496 name.
4497
4498 =item B<virtual_host ()>
4499
4500 When using virtual hosts, returns the name of the host that
4501 the browser attempted to contact
4502
4503 =item B<server_software ()>
4504
4505 Returns the server software and version number.
4506
4507 =item B<remote_user ()>
4508
4509 Return the authorization/verification name used for user
4510 verification, if this script is protected.
4511
4512 =item B<user_name ()>
4513
4514 Attempt to obtain the remote user's name, using a variety
4515 of different techniques.  This only works with older browsers
4516 such as Mosaic.  Netscape does not reliably report the user
4517 name!
4518
4519 =item B<request_method()>
4520
4521 Returns the method used to access your script, usually
4522 one of 'POST', 'GET' or 'HEAD'.
4523
4524 =back
4525
4526 =head1 CREATING HTML ELEMENTS
4527
4528 In addition to its shortcuts for creating form elements, CGI.pm
4529 defines general HTML shortcut methods as well.  HTML shortcuts are
4530 named after a single HTML element and return a fragment of HTML text
4531 that you can then print or manipulate as you like.
4532
4533 This example shows how to use the HTML methods:
4534
4535         $q = new CGI;
4536         print $q->blockquote(
4537                              "Many years ago on the island of",
4538                              $q->a({href=>"http://crete.org/"},"Crete"),
4539                              "there lived a minotaur named",
4540                              $q->strong("Fred."),
4541                             ),
4542                $q->hr;
4543
4544 This results in the following HTML code (extra newlines have been
4545 added for readability):
4546
4547         <blockquote>
4548         Many years ago on the island of
4549         <a HREF="http://crete.org/">Crete</a> there lived
4550         a minotaur named <strong>Fred.</strong> 
4551         </blockquote>
4552         <hr>
4553
4554 If you find the syntax for calling the HTML shortcuts awkward, you can
4555 import them into your namespace and dispense with the object syntax
4556 completely (see the next section for more details):
4557
4558         use CGI shortcuts;      # IMPORT HTML SHORTCUTS
4559         print blockquote(
4560                      "Many years ago on the island of",
4561                      a({href=>"http://crete.org/"},"Crete"),
4562                      "there lived a minotaur named",
4563                      strong("Fred."),
4564                      ),
4565                hr;
4566
4567 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4568
4569 The HTML methods will accept zero, one or multiple arguments.  If you
4570 provide no arguments, you get a single tag:
4571
4572         print hr;  
4573         #  gives "<hr>"
4574
4575 If you provide one or more string arguments, they are concatenated
4576 together with spaces and placed between opening and closing tags:
4577
4578         print h1("Chapter","1"); 
4579         # gives "<h1>Chapter 1</h1>"
4580
4581 If the first argument is an associative array reference, then the keys
4582 and values of the associative array become the HTML tag's attributes:
4583
4584         print a({href=>'fred.html',target=>'_new'},
4585                 "Open a new frame");
4586         # gives <a href="fred.html",target="_new">Open a new frame</a>
4587
4588 You are free to use CGI.pm-style dashes in front of the attribute
4589 names if you prefer:
4590
4591         print img {-src=>'fred.gif',-align=>'LEFT'};
4592         # gives <img ALIGN="LEFT" SRC="fred.gif">
4593
4594 =head2 Generating new HTML tags
4595
4596 Since no mere mortal can keep up with Netscape and Microsoft as they
4597 battle it out for control of HTML, the code that generates HTML tags
4598 is general and extensible.  You can create new HTML tags freely just
4599 by referring to them on the import line:
4600
4601         use CGI shortcuts,winkin,blinkin,nod;
4602
4603 Now, in addition to the standard CGI shortcuts, you've created HTML
4604 tags named "winkin", "blinkin" and "nod".  You can use them like this:
4605
4606         print blinkin {color=>'blue',rate=>'fast'},"Yahoo!";
4607         # <blinkin COLOR="blue" RATE="fast">Yahoo!</blinkin>
4608
4609 =head1 IMPORTING CGI METHOD CALLS INTO YOUR NAME SPACE
4610
4611 As a convenience, you can import most of the CGI method calls directly
4612 into your name space.  The syntax for doing this is:
4613
4614         use CGI <list of methods>;
4615
4616 The listed methods will be imported into the current package; you can
4617 call them directly without creating a CGI object first.  This example
4618 shows how to import the B<param()> and B<header()>
4619 methods, and then use them directly:
4620
4621         use CGI param,header;
4622         print header('text/plain');
4623         $zipcode = param('zipcode');
4624
4625 You can import groups of methods by referring to a number of special
4626 names:
4627
4628 =over 4
4629
4630 =item B<cgi>
4631
4632 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4633 and the like.
4634
4635 =item B<form>
4636
4637 Import all fill-out form generating methods, such as B<textfield()>.
4638
4639 =item B<html2>
4640
4641 Import all methods that generate HTML 2.0 standard elements.
4642
4643 =item B<html3>
4644
4645 Import all methods that generate HTML 3.0 proposed elements (such as
4646 <table>, <super> and <sub>).
4647
4648 =item B<netscape>
4649
4650 Import all methods that generate Netscape-specific HTML extensions.
4651
4652 =item B<shortcuts>
4653
4654 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4655 'netscape')...
4656
4657 =item B<standard>
4658
4659 Import "standard" features, 'html2', 'form' and 'cgi'.
4660
4661 =item B<all>
4662
4663 Import all the available methods.  For the full list, see the CGI.pm
4664 code, where the variable %TAGS is defined.
4665
4666 =back
4667
4668 Note that in the interests of execution speed CGI.pm does B<not> use
4669 the standard L<Exporter> syntax for specifying load symbols.  This may
4670 change in the future.
4671
4672 If you import any of the state-maintaining CGI or form-generating
4673 methods, a default CGI object will be created and initialized
4674 automatically the first time you use any of the methods that require
4675 one to be present.  This includes B<param()>, B<textfield()>,
4676 B<submit()> and the like.  (If you need direct access to the CGI
4677 object, you can find it in the global variable B<$CGI::Q>).  By
4678 importing CGI.pm methods, you can create visually elegant scripts:
4679
4680    use CGI standard,html2;
4681    print 
4682        header,
4683        start_html('Simple Script'),
4684        h1('Simple Script'),
4685        start_form,
4686        "What's your name? ",textfield('name'),p,
4687        "What's the combination?",
4688        checkbox_group(-name=>'words',
4689                       -values=>['eenie','meenie','minie','moe'],
4690                       -defaults=>['eenie','moe']),p,
4691        "What's your favorite color?",
4692        popup_menu(-name=>'color',
4693                   -values=>['red','green','blue','chartreuse']),p,
4694        submit,
4695        end_form,
4696        hr,"\n";
4697
4698     if (param) {
4699        print 
4700            "Your name is ",em(param('name')),p,
4701            "The keywords are: ",em(join(", ",param('words'))),p,
4702            "Your favorite color is ",em(param('color')),".\n";
4703     }
4704     print end_html;
4705
4706 =head1 USING NPH SCRIPTS
4707
4708 NPH, or "no-parsed-header", scripts bypass the server completely by
4709 sending the complete HTTP header directly to the browser.  This has
4710 slight performance benefits, but is of most use for taking advantage
4711 of HTTP extensions that are not directly supported by your server,
4712 such as server push and PICS headers.
4713
4714 Servers use a variety of conventions for designating CGI scripts as
4715 NPH.  Many Unix servers look at the beginning of the script's name for
4716 the prefix "nph-".  The Macintosh WebSTAR server and Microsoft's
4717 Internet Information Server, in contrast, try to decide whether a
4718 program is an NPH script by examining the first line of script output.
4719
4720
4721 CGI.pm supports NPH scripts with a special NPH mode.  When in this
4722 mode, CGI.pm will output the necessary extra header information when
4723 the header() and redirect() methods are
4724 called.
4725
4726 The Microsoft Internet Information Server requires NPH mode.  As of version
4727 2.30, CGI.pm will automatically detect when the script is running under IIS
4728 and put itself into this mode.  You do not need to do this manually, although
4729 it won't hurt anything if you do.
4730
4731 There are a number of ways to put CGI.pm into NPH mode:
4732
4733 =over 4
4734
4735 =item In the B<use> statement
4736 Simply add ":nph" to the list of symbols to be imported into your script:
4737
4738       use CGI qw(:standard :nph)
4739
4740 =item By calling the B<nph()> method:
4741
4742 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
4743
4744       CGI->nph(1)
4745
4746 =item By using B<-nph> parameters in the B<header()> and B<redirect()>  statements:
4747
4748       print $q->header(-nph=&gt;1);
4749
4750 =back
4751
4752 =head1 AUTHOR INFORMATION
4753
4754 Copyright 1995,1996, Lincoln D. Stein.  All rights reserved.  It may
4755 be used and modified freely, but I do request that this copyright
4756 notice remain attached to the file.  You may modify this module as you
4757 wish, but if you redistribute a modified version, please attach a note
4758 listing the modifications you have made.
4759
4760 Address bug reports and comments to:
4761 lstein@genome.wi.mit.edu
4762
4763 =head1 CREDITS
4764
4765 Thanks very much to:
4766
4767 =over 4
4768
4769 =item Matt Heffron (heffron@falstaff.css.beckman.com)
4770
4771 =item James Taylor (james.taylor@srs.gov)
4772
4773 =item Scott Anguish <sanguish@digifix.com>
4774
4775 =item Mike Jewell (mlj3u@virginia.edu)
4776
4777 =item Timothy Shimmin (tes@kbs.citri.edu.au)
4778
4779 =item Joergen Haegg (jh@axis.se)
4780
4781 =item Laurent Delfosse (delfosse@csgrad1.cs.wvu.edu)
4782
4783 =item Richard Resnick (applepi1@aol.com)
4784
4785 =item Craig Bishop (csb@barwonwater.vic.gov.au)
4786
4787 =item Tony Curtis (tc@vcpc.univie.ac.at)
4788
4789 =item Tim Bunce (Tim.Bunce@ig.co.uk)
4790
4791 =item Tom Christiansen (tchrist@convex.com)
4792
4793 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
4794
4795 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
4796
4797 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
4798
4799 =item Stephen Dahmen (joyfire@inxpress.net)
4800
4801 =item Ed Jordan (ed@fidalgo.net)
4802
4803 =item David Alan Pisoni (david@cnation.com)
4804
4805 =item ...and many many more...
4806
4807 for suggestions and bug fixes.
4808
4809 =back
4810
4811 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
4812
4813
4814         #!/usr/local/bin/perl
4815      
4816         use CGI;
4817  
4818         $query = new CGI;
4819
4820         print $query->header;
4821         print $query->start_html("Example CGI.pm Form");
4822         print "<H1> Example CGI.pm Form</H1>\n";
4823         &print_prompt($query);
4824         &do_work($query);
4825         &print_tail;
4826         print $query->end_html;
4827  
4828         sub print_prompt {
4829            my($query) = @_;
4830  
4831            print $query->startform;
4832            print "<EM>What's your name?</EM><BR>";
4833            print $query->textfield('name');
4834            print $query->checkbox('Not my real name');
4835  
4836            print "<P><EM>Where can you find English Sparrows?</EM><BR>";
4837            print $query->checkbox_group(
4838                                  -name=>'Sparrow locations',
4839                                  -values=>[England,France,Spain,Asia,Hoboken],
4840                                  -linebreak=>'yes',
4841                                  -defaults=>[England,Asia]);
4842  
4843            print "<P><EM>How far can they fly?</EM><BR>",
4844                 $query->radio_group(
4845                         -name=>'how far',
4846                         -values=>['10 ft','1 mile','10 miles','real far'],
4847                         -default=>'1 mile');
4848  
4849            print "<P><EM>What's your favorite color?</EM>  ";
4850            print $query->popup_menu(-name=>'Color',
4851                                     -values=>['black','brown','red','yellow'],
4852                                     -default=>'red');
4853  
4854            print $query->hidden('Reference','Monty Python and the Holy Grail');
4855  
4856            print "<P><EM>What have you got there?</EM><BR>";
4857            print $query->scrolling_list(
4858                          -name=>'possessions',
4859                          -values=>['A Coconut','A Grail','An Icon',
4860                                    'A Sword','A Ticket'],
4861                          -size=>5,
4862                          -multiple=>'true');
4863  
4864            print "<P><EM>Any parting comments?</EM><BR>";
4865            print $query->textarea(-name=>'Comments',
4866                                   -rows=>10,
4867                                   -columns=>50);
4868  
4869            print "<P>",$query->reset;
4870            print $query->submit('Action','Shout');
4871            print $query->submit('Action','Scream');
4872            print $query->endform;
4873            print "<HR>\n";
4874         }
4875  
4876         sub do_work {
4877            my($query) = @_;
4878            my(@values,$key);
4879
4880            print "<H2>Here are the current settings in this form</H2>";
4881
4882            foreach $key ($query->param) {
4883               print "<STRONG>$key</STRONG> -> ";
4884               @values = $query->param($key);
4885               print join(", ",@values),"<BR>\n";
4886           }
4887         }
4888  
4889         sub print_tail {
4890            print <<END;
4891         <HR>
4892         <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
4893         <A HREF="/">Home Page</A>
4894         END
4895         }
4896
4897 =head1 BUGS
4898
4899 This module has grown large and monolithic.  Furthermore it's doing many
4900 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
4901 are also done in the LWP modules. It should be discarded in favor of
4902 the CGI::* modules, but somehow I continue to work on it.
4903
4904 Note that the code is truly contorted in order to avoid spurious
4905 warnings when programs are run with the B<-w> switch.
4906
4907 =head1 SEE ALSO
4908
4909 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
4910 L<CGI::Base>, L<CGI::Form>, L<CGI::Apache>, L<CGI::Switch>,
4911 L<CGI::Push>, L<CGI::Fast>
4912
4913 =cut
4914