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