4 # See the bottom of this file for the POD documentation. Search for the
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).
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.
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/
21 # Set this to 1 to enable copious autoloader debugging messages
24 # Set this to 1 to enable NPH scripts
28 # 3) print header(-nph=>1)
31 $CGI::revision = '$Id: CGI.pm,v 2.34 1997/4/7 7:23 lstein Exp $';
32 $CGI::VERSION='2.3401';
34 # OVERRIDE THE OS HERE IF CGI.pm GUESSES WRONG
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';
45 # ------------------ START OF THE LIBRARY ------------
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
53 $OS = $Config::Config{'osname'};
58 } elsif ($OS=~/vms/i) {
60 } elsif ($OS=~/Mac/i) {
62 } elsif ($OS=~/os2/i) {
68 # Some OS logic. Binary mode enabled on DOS, NT and VMS
69 $needs_binmode = $OS=~/^(WINDOWS|VMS|OS2)/;
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;
76 # The path separator is a slash, backslash or semicolon, depending
86 # Turn on NPH scripts by default when running under IIS server!
87 $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
89 # Turn on special checking for Doug MacEachern's modperl
90 if (defined($ENV{'GATEWAY_INTERFACE'}) && ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl/)) {
96 # This is really "\r\n", but the meaning of \n is different
97 # in MacPerl, so we resort to octal here.
100 if ($needs_binmode) {
101 $CGI::DefaultClass->binmode(main::STDOUT);
102 $CGI::DefaultClass->binmode(main::STDIN);
103 $CGI::DefaultClass->binmode(main::STDERR);
106 # Cute feature, but it broke when the overload mechanism changed...
107 # %OVERLOAD = ('""'=>'as_string');
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/]
132 # to import symbols into caller
135 my ($callpack, $callfile, $callline) = caller;
137 $NPH++, next if $_ eq ':nph';
138 foreach (&expand_tags($_)) {
139 tr/a-zA-Z0-9_//cd; # don't allow weird function names
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) {
148 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
149 foreach $pck (@packages) {
150 if (defined(&{"$pck\:\:$sym"})) {
155 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
162 return ($tag) unless $EXPORT_TAGS{$tag};
163 foreach (@{$EXPORT_TAGS{$tag}}) {
164 push(@r,&expand_tags($_));
170 # The new routine. This will check the current environment
171 # for an existing query string, and initialize itself, if so.
174 my($class,$initializer) = @_;
176 bless $self,ref $class || $class || $DefaultClass;
177 $initializer = to_filehandle($initializer) if $initializer;
178 $self->init($initializer);
182 # We provide a DESTROY method so that the autoloader
183 # doesn't bother trying to find it.
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.
198 my($self,@p) = self_or_default(@_);
199 return $self->all_parameters unless @p;
200 my($name,$value,@other);
202 # For compatibility between old calling style and use_named_parameters() style,
203 # we have to special case for a single parameter present.
205 ($name,$value,@other) = $self->rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
208 if (substr($p[0],0,1) eq '-' || $self->use_named_parameters) {
209 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
211 foreach ($value,@other) {
212 push(@values,$_) if defined($_);
215 # If values is provided, then we set it.
217 $self->add_parameter($name);
218 $self->{$name}=[@values];
224 return () unless defined($name) && $self->{$name};
225 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
229 # Deletes the named parameter entirely.
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;
239 sub self_or_default {
240 return @_ if defined($_[0]) && !ref($_[0]) && ($_[0] eq 'CGI');
241 unless (defined($_[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);
254 return undef unless (defined(Apache->seqno()) or eval { require Apache });
255 if (Apache->seqno() != $SEQNO) {
256 $SEQNO = Apache->seqno();
269 local $^W=0; # prevent a warning
270 if (defined($_[0]) &&
271 (substr(ref($_[0]),0,3) eq 'CGI'
272 || eval "\$_[0]->isaCGI()")) {
275 return ($DefaultClass,@_);
283 #### Method: import_names
284 # Import all parameters into the given namespace.
285 # Assumes namespace 'Q' if not specified
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);
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
308 sub use_named_parameters {
309 my($self,$use_named) = self_or_default(@_);
310 return $self->{'.named'} unless defined ($use_named);
312 # stupidity to avoid annoying warnings
313 return $self->{'.named'}=$use_named;
316 ########################################
317 # THESE METHODS ARE MORE OR LESS PRIVATE
318 # GO TO THE __DATA__ SECTION TO SEE MORE
320 ########################################
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'.
330 my($self,$initializer) = @_;
331 my($query_string,@lines);
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)) {
339 foreach (@QUERY_PARAM) {
340 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
345 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
347 # If initializer is defined, then read parameters
350 if (defined($initializer)) {
352 if (ref($initializer) && ref($initializer) eq 'HASH') {
353 foreach (keys %$initializer) {
354 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
359 $initializer = $$initializer if ref($initializer);
360 if (defined(fileno($initializer))) {
361 while (<$initializer>) {
366 # massage back into standard format
367 if ("@lines" =~ /=/) {
368 $query_string=join("&",@lines);
370 $query_string=join("+",@lines);
374 $query_string = $initializer;
377 # If method is GET or HEAD, fetch the query from
379 if ($meth=~/^(GET|HEAD)$/) {
380 $query_string = $ENV{'QUERY_STRING'};
384 # If the method is POST, fetch the query from standard
386 if ($meth eq 'POST') {
388 if (defined($ENV{'CONTENT_TYPE'})
390 $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|) {
391 my($boundary) = $ENV{'CONTENT_TYPE'}=~/boundary=(\S+)/;
392 $self->read_multipart($boundary,$ENV{'CONTENT_LENGTH'});
396 $self->read_from_client(\*STDIN,\$query_string,$ENV{'CONTENT_LENGTH'},0)
397 if $ENV{'CONTENT_LENGTH'} > 0;
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'};
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;
414 # We now have the query string in hand. We do slightly
415 # different things for keyword lists and parameter lists.
417 if ($query_string =~ /=/) {
418 $self->parse_params($query_string);
420 $self->add_parameter('keywords');
421 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
425 # Special case. Erase everything if there is a field named
427 if ($self->param('.defaults')) {
431 # Associative array containing our defined fieldnames
432 $self->{'.fieldnames'} = {};
433 foreach ($self->param('.cgifields')) {
434 $self->{'.fieldnames'}->{$_}++;
437 # Clear out our default submission button flag if present
438 $self->delete('.submit');
439 $self->delete('.cgifields');
440 $self->save_request unless $initializer;
445 # FUNCTIONS TO OVERRIDE:
447 # Turn a string into a filehandle
450 if ($string && !ref($string)) {
451 my($package) = caller(1);
452 my($tmp) = $string=~/[':]/ ? $string : "$package\:\:$string";
453 return $tmp if defined(fileno($tmp));
458 # Create a new multipart buffer
459 sub new_MultipartBuffer {
460 my($self,$boundary,$length,$filehandle) = @_;
461 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
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);
471 # put a filehandle into binary mode (DOS)
476 # send output to the browser
478 my($self,@p) = self_or_default(@_);
482 # print to standard output (for overriding in mod_perl)
488 # unescape URL-encoded data
491 $todecode =~ tr/+/ /; # pluses become spaces
492 $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
499 $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
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->{$_};
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);
523 my($self,$tosplit) = @_;
524 my(@pairs) = split('&',$tosplit);
527 ($param,$value) = split('=');
528 $param = &unescape($param);
529 $value = &unescape($value);
530 $self->add_parameter($param);
531 push (@{$self->{$param}},$value);
537 push (@{$self->{'.parameters'}},$param)
538 unless defined($self->{$param});
543 return () unless defined($self) && $self->{'.parameters'};
544 return () unless @{$self->{'.parameters'}};
545 return @{$self->{'.parameters'}};
550 #### Method as_string
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"});
565 my($sub) = \%{"$pack\:\:SUBS"};
567 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
568 eval "package $pack; $$auto";
571 my($code) = $sub->{$func_name};
573 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
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;
583 die "Undefined subroutine $AUTOLOAD\n" unless $code;
584 eval "package $pack; $code";
589 goto &{"$pack\:\:$func_name"};
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
598 my($self,$order,@param) = @_;
599 return () unless @param;
601 return @param unless (defined($param[0]) && substr($param[0],0,1) eq '-')
602 || $self->use_named_parameters;
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
610 my(%param) = @param; # convert into associative array
614 foreach $key (@$order) {
616 # this is an awful hack to fix spurious warnings when the
618 if (ref($key) && ref($key) eq 'ARRAY') {
620 last if defined($value);
625 $value = $param{$key};
628 push(@return_array,$value);
630 push (@return_array,$self->make_attributes(\%param)) if %param;
631 return (@return_array);
634 ###############################################################################
635 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
636 ###############################################################################
637 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
638 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
642 'URL_ENCODED'=> <<'END_OF_FUNC',
643 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
646 'MULTIPART' => <<'END_OF_FUNC',
647 sub MULTIPART { 'multipart/form-data'; }
650 'HTML_FUNC' => <<'END_OF_FUNC',
653 # handle various cases in which we're called
654 # most of this bizarre stuff is to avoid -w errors
656 (!ref($_[0]) && $_[0] eq $CGI::DefaultClass) ||
658 (substr(ref($_[0]),0,3) eq 'CGI' ||
659 eval "\$_[0]->isaCGI()"));
662 if (ref($_[0]) && ref($_[0]) eq 'HASH') {
663 my(@attr) = CGI::make_attributes('',shift);
664 $attr = " @attr" if @attr;
666 my($tag,$untag) = ("\U<func_name\E$attr>","\U</func_name>\E");
667 return $tag unless @_;
668 if (ref($_[0]) eq 'ARRAY') {
671 push(@r,"$tag$_$untag");
675 return "$tag@_$untag";
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.
685 'keywords' => <<'END_OF_FUNC',
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'}};
695 # These are some tie() interfaces for compatibility
696 # with Steve Brenner's cgi-lib.pl routines
697 'ReadParse' => <<'END_OF_FUNC',
710 'PrintHeader' => <<'END_OF_FUNC',
712 my($self) = self_or_default(@_);
713 return $self->header();
717 'HtmlTop' => <<'END_OF_FUNC',
719 my($self,@p) = self_or_default(@_);
720 return $self->start_html(@p);
724 'HtmlBot' => <<'END_OF_FUNC',
726 my($self,@p) = self_or_default(@_);
727 return $self->end_html(@p);
731 'SplitParam' => <<'END_OF_FUNC',
734 my (@params) = split ("\0", $param);
735 return (wantarray ? @params : $params[0]);
739 'MethGet' => <<'END_OF_FUNC',
741 return request_method() eq 'GET';
745 'MethPost' => <<'END_OF_FUNC',
747 return request_method() eq 'POST';
751 'TIEHASH' => <<'END_OF_FUNC',
757 'STORE' => <<'END_OF_FUNC',
759 $_[0]->param($_[1],split("\0",$_[2]));
763 'FETCH' => <<'END_OF_FUNC',
765 return $_[0] if $_[1] eq 'CGI';
766 return undef unless defined $_[0]->param($_[1]);
767 return join("\0",$_[0]->param($_[1]));
771 'FIRSTKEY' => <<'END_OF_FUNC',
773 $_[0]->{'.iterator'}=0;
774 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
778 'NEXTKEY' => <<'END_OF_FUNC',
780 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
784 'EXISTS' => <<'END_OF_FUNC',
786 exists $_[0]->{$_[1]};
790 'DELETE' => <<'END_OF_FUNC',
792 $_[0]->delete($_[1]);
796 'CLEAR' => <<'END_OF_FUNC',
804 # Append a new value to an existing query
809 my($name,$value) = $self->rearrange([NAME,[VALUE,VALUES]],@p);
810 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
812 $self->add_parameter($name);
813 push(@{$self->{$name}},@values);
815 return $self->param($name);
819 #### Method: delete_all
820 # Delete all parameters
822 'delete_all' => <<'EOF',
824 my($self) = self_or_default(@_);
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',
834 my($self,$escape) = self_or_default(@_);
835 $self->{'dontescape'}=!$escape;
841 # Return the current version
843 'version' => <<'END_OF_FUNC',
849 'make_attributes' => <<'END_OF_FUNC',
850 sub make_attributes {
851 my($self,$attr) = @_;
852 return () unless $attr && ref($attr) && ref($attr) eq 'HASH';
854 foreach (keys %{$attr}) {
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/);
865 # Returns a string in which all the known parameter/value
866 # pairs are represented as nested lists, mainly for the purposes
869 'dump' => <<'END_OF_FUNC',
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");
883 push(@result,"</UL>");
885 push(@result,"</UL>\n");
886 return join("\n",@result);
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
895 'save' => <<'END_OF_FUNC',
897 my($self,$filehandle) = self_or_default(@_);
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);
906 foreach $value ($self->param($param)) {
907 print $filehandle "$escaped_param=",escape($value),"\n";
910 print $filehandle "=\n"; # end of record
916 # Return a Content-Type: style header
919 'header' => <<'END_OF_FUNC',
921 my($self,@p) = self_or_default(@_);
924 my($type,$status,$cookie,$target,$expires,$nph,@other) =
925 $self->rearrange([TYPE,STATUS,[COOKIE,COOKIES],TARGET,EXPIRES,NPH],@p);
927 # rearrange() was designed for the HTML portion, so we
928 # need to fix it up a little.
930 next unless my($header,$value) = /([^\s=]+)=(.+)/;
931 substr($header,1,1000)=~tr/A-Z/a-z/;
932 ($value)=$value=~/^"(.*)"$/;
933 $_ = "$header: $value";
936 $type = $type || 'text/html';
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
943 my(@cookie) = ref($cookie) ? @{$cookie} : $cookie;
945 push(@header,"Set-cookie: $_");
948 # if the user indicates an expiration time, then we need
949 # both an Expires and a Date header (so that the browser is
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");
957 my $header = join($CRLF,@header);
958 return $header . "${CRLF}${CRLF}";
964 # Control whether header() will produce the no-cache
967 'cache' => <<'END_OF_FUNC',
969 my($self,$new_value) = self_or_default(@_);
970 $new_value = '' unless $new_value;
971 if ($new_value ne '') {
972 $self->{'cache'} = $new_value;
974 return $self->{'cache'};
979 #### Method: redirect
980 # Return a Location: style header
983 'redirect' => <<'END_OF_FUNC',
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;
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);
998 '-Status'=>'302 Found',
1001 '-nph'=>($nph||$NPH));
1002 push(@o,'-Target'=>$target) if $target;
1003 push(@o,'-Cookie'=>$cookie) if $cookie;
1004 return $self->header(@o);
1009 #### Method: start_html
1010 # Canned HTML header
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
1024 'start_html' => <<'END_OF_FUNC',
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);
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);
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;
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>/);
1045 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1046 foreach (keys %$meta) { push(@result,qq(<META NAME="$_" CONTENT="$meta->{$_}">)); }
1048 push(@result,<<END) if $script;
1050 <!-- Hide script from HTML-compliant browsers
1052 // End script hiding. -->
1056 my($other) = @other ? " @other" : '';
1057 push(@result,"</HEAD><BODY$other>");
1058 return join("\n",@result);
1063 #### Method: end_html
1064 # End an HTML document.
1065 # Trivial method for completeness. Just returns "</BODY>"
1067 'end_html' => <<'END_OF_FUNC',
1069 return "</BODY></HTML>";
1074 ################################
1075 # METHODS USED IN BUILDING FORMS
1076 ################################
1078 #### Method: isindex
1079 # Just prints out the isindex tag.
1081 # $action -> optional URL of script to run
1083 # A string containing a <ISINDEX> tag
1084 'isindex' => <<'END_OF_FUNC',
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>";
1095 #### Method: startform
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',
1103 my($self,@p) = self_or_default(@_);
1105 my($method,$action,$enctype,@other) =
1106 $self->rearrange([METHOD,ACTION,ENCTYPE],@p);
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/;
1119 #### Method: start_form
1120 # synonym for startform
1121 'start_form' => <<'END_OF_FUNC',
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 '-')) {
1136 $p{'-enctype'}=&MULTIPART;
1137 return $self->startform(%p);
1139 my($method,$action,@other) =
1140 $self->rearrange([METHOD,ACTION],@p);
1141 return $self->startform($method,$action,&MULTIPART,@other);
1147 #### Method: endform
1149 'endform' => <<'END_OF_FUNC',
1151 my($self,@p) = self_or_default(@_);
1152 return ($self->get_fields,"</FORM>");
1157 #### Method: end_form
1158 # synonym for endform
1159 'end_form' => <<'END_OF_FUNC',
1166 #### Method: textfield
1168 # $name -> Name of the text field
1169 # $default -> Optional default value of the field if not
1171 # $size -> Optional width of field in characaters.
1172 # $maxlength -> Optional maximum number of characters.
1174 # A string containing a <INPUT TYPE="text"> field
1176 'textfield' => <<'END_OF_FUNC',
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);
1182 my $current = $override ? $default :
1183 (defined($self->param($name)) ? $self->param($name) : $default);
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>/;
1195 #### Method: filefield
1197 # $name -> Name of the file upload field
1198 # $size -> Optional width of field in characaters.
1199 # $maxlength -> Optional maximum number of characters.
1201 # A string containing a <INPUT TYPE="text"> field
1203 'filefield' => <<'END_OF_FUNC',
1205 my($self,@p) = self_or_default(@_);
1207 my($name,$default,$size,$maxlength,$override,@other) =
1208 $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1210 $current = $override ? $default :
1211 (defined($self->param($name)) ? $self->param($name) : $default);
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>/;
1223 #### Method: password
1224 # Create a "secret password" entry field
1226 # $name -> Name of the field
1227 # $default -> Optional default value of the field if not
1229 # $size -> Optional width of field in characters.
1230 # $maxlength -> Optional maximum characters that can be entered.
1232 # A string containing a <INPUT TYPE="password"> field
1234 'password_field' => <<'END_OF_FUNC',
1235 sub password_field {
1236 my ($self,@p) = self_or_default(@_);
1238 my($name,$default,$size,$maxlength,$override,@other) =
1239 $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1241 my($current) = $override ? $default :
1242 (defined($self->param($name)) ? $self->param($name) : $default);
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>/;
1254 #### Method: textarea
1256 # $name -> Name of the text field
1257 # $default -> Optional default value of the field if not
1259 # $rows -> Optional number of rows in text area
1260 # $columns -> Optional number of columns in text area
1262 # A string containing a <TEXTAREA></TEXTAREA> tag
1264 'textarea' => <<'END_OF_FUNC',
1266 my($self,@p) = self_or_default(@_);
1268 my($name,$default,$rows,$cols,$override,@other) =
1269 $self->rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1271 my($current)= $override ? $default :
1272 (defined($self->param($name)) ? $self->param($name) : $default);
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>};
1285 # Create a javascript button.
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
1292 # A string containing a <INPUT TYPE="button"> tag
1294 'button' => <<'END_OF_FUNC',
1296 my($self,@p) = self_or_default(@_);
1298 my($label,$value,$script,@other) = $self->rearrange([NAME,[VALUE,LABEL],
1299 [ONCLICK,SCRIPT]],@p);
1301 $label=$self->escapeHTML($label);
1302 $value=$self->escapeHTML($value);
1303 $script=$self->escapeHTML($script);
1306 $name = qq/ NAME="$label"/ if $label;
1307 $value = $value || $label;
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>/;
1318 # Create a "submit query" button.
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).
1324 # A string containing a <INPUT TYPE="submit"> tag
1326 'submit' => <<'END_OF_FUNC',
1328 my($self,@p) = self_or_default(@_);
1330 my($label,$value,@other) = $self->rearrange([NAME,[VALUE,LABEL]],@p);
1332 $label=$self->escapeHTML($label);
1333 $value=$self->escapeHTML($value);
1335 my($name) = ' NAME=".submit"';
1336 $name = qq/ NAME="$label"/ if $label;
1337 $value = $value || $label;
1339 $val = qq/ VALUE="$value"/ if defined($value);
1340 my($other) = @other ? " @other" : '';
1341 return qq/<INPUT TYPE="submit"$name$val$other>/;
1347 # Create a "reset" button.
1349 # $name -> (optional) Name for the button.
1351 # A string containing a <INPUT TYPE="reset"> tag
1353 'reset' => <<'END_OF_FUNC',
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>/;
1365 #### Method: defaults
1366 # Create a "defaults" button.
1368 # $name -> (optional) Name for the button.
1370 # A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
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
1376 'defaults' => <<'END_OF_FUNC',
1378 my($self,@p) = self_or_default(@_);
1380 my($label,@other) = $self->rearrange([[NAME,VALUE]],@p);
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>/;
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.
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.
1401 # A string containing a <INPUT TYPE="checkbox"> field
1403 'checkbox' => <<'END_OF_FUNC',
1405 my($self,@p) = self_or_default(@_);
1407 my($name,$checked,$value,$label,$override,@other) =
1408 $self->rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1410 if (!$override && defined($self->param($name))) {
1411 $value = $self->param($name) unless defined $value;
1412 $checked = $self->param($name) eq $value ? ' CHECKED' : '';
1414 $checked = $checked ? ' CHECKED' : '';
1415 $value = defined $value ? $value : 'on';
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);
1424 <INPUT TYPE="checkbox" NAME="$name" VALUE="$value"$checked$other>$the_label
1430 #### Method: checkbox_group
1431 # Create a list of logically-linked checkboxes.
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.
1449 # An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1451 'checkbox_group' => <<'END_OF_FUNC',
1452 sub checkbox_group {
1453 my($self,@p) = self_or_default(@_);
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);
1462 my($checked,$break,$result,$label);
1464 my(%checked) = $self->previous_or_default($name,$defaults,$override);
1466 $break = $linebreak ? "<BR>" : '';
1467 $name=$self->escapeHTML($name);
1469 # Create the elements
1471 my(@values) = $values ? @$values : $self->param($name);
1472 my($other) = @other ? " @other" : '';
1474 $checked = $checked{$_} ? ' CHECKED' : '';
1476 unless (defined($nolabels) && $nolabels) {
1478 $label = $labels->{$_} if defined($labels) && $labels->{$_};
1479 $label = $self->escapeHTML($label);
1481 $_ = $self->escapeHTML($_);
1482 push(@elements,qq/<INPUT TYPE="checkbox" NAME="$name" VALUE="$_"$checked$other>${label} ${break}/);
1484 $self->register_parameter($name);
1485 return wantarray ? @elements : join('',@elements) unless $columns;
1486 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1491 # Escape HTML -- used internally
1492 'escapeHTML' => <<'END_OF_FUNC',
1494 my($self,$toencode) = @_;
1495 return undef unless defined($toencode);
1496 return $toencode if $self->{'dontescape'};
1497 $toencode=~s/&/&/g;
1498 $toencode=~s/\"/"/g;
1499 $toencode=~s/>/>/g;
1500 $toencode=~s/</</g;
1506 # Internal procedure - don't use
1507 '_tableize' => <<'END_OF_FUNC',
1509 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1512 $rows = int(0.99 + @elements/$columns) unless $rows;
1513 # rearrange into a pretty table
1514 $result = "<TABLE>";
1516 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
1517 $result .= "<TR>" if @{$colheaders};
1518 foreach (@{$colheaders}) {
1519 $result .= "<TH>$_</TH>";
1521 for ($row=0;$row<$rows;$row++) {
1523 $result .= "<TH>$rowheaders->[$row]</TH>" if @$rowheaders;
1524 for ($column=0;$column<$columns;$column++) {
1525 $result .= "<TD>" . $elements[$column*$rows + $row] . "</TD>";
1529 $result .= "</TABLE>";
1535 #### Method: radio_group
1536 # Create a list of logically-linked radio buttons.
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.
1550 # An ARRAY containing a series of <INPUT TYPE="radio"> fields
1552 'radio_group' => <<'END_OF_FUNC',
1554 my($self,@p) = self_or_default(@_);
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);
1564 if (!$override && defined($self->param($name))) {
1565 $checked = $self->param($name);
1567 $checked = $default;
1569 # If no check array is specified, check the first by default
1570 $checked = $values->[0] unless $checked;
1571 $name=$self->escapeHTML($name);
1574 my(@values) = $values ? @$values : $self->param($name);
1575 my($other) = @other ? " @other" : '';
1577 my($checkit) = $checked eq $_ ? ' CHECKED' : '';
1578 my($break) = $linebreak ? '<BR>' : '';
1580 unless (defined($nolabels) && $nolabels) {
1582 $label = $labels->{$_} if defined($labels) && $labels->{$_};
1583 $label = $self->escapeHTML($label);
1585 $_=$self->escapeHTML($_);
1586 push(@elements,qq/<INPUT TYPE="radio" NAME="$name" VALUE="$_"$checkit$other>${label} ${break}/);
1588 $self->register_parameter($name);
1589 return wantarray ? @elements : join('',@elements) unless $columns;
1590 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1595 #### Method: popup_menu
1596 # Create a popup menu.
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.
1607 # A string containing the definition of a popup menu.
1609 'popup_menu' => <<'END_OF_FUNC',
1611 my($self,@p) = self_or_default(@_);
1613 my($name,$values,$default,$labels,$override,@other) =
1614 $self->rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
1615 my($result,$selected);
1617 if (!$override && defined($self->param($name))) {
1618 $selected = $self->param($name);
1620 $selected = $default;
1622 $name=$self->escapeHTML($name);
1623 my($other) = @other ? " @other" : '';
1625 my(@values) = $values ? @$values : $self->param($name);
1626 $result = qq/<SELECT NAME="$name"$other>\n/;
1628 my($selectit) = defined($selected) ? ($selected eq $_ ? 'SELECTED' : '' ) : '';
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";
1636 $result .= "</SELECT>\n";
1642 #### Method: scrolling_list
1643 # Create a scrolling list.
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.
1660 # A string containing the definition of a scrolling list.
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);
1670 my(@values) = $values ? @$values : $self->param($name);
1671 $size = $size || scalar(@values);
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" : '';
1678 $name=$self->escapeHTML($name);
1679 $result = qq/<SELECT NAME="$name"$has_size$is_multiple$other>\n/;
1681 my($selectit) = $selected{$_} ? 'SELECTED' : '';
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";
1688 $result .= "</SELECT>\n";
1689 $self->register_parameter($name);
1697 # $name -> Name of the hidden field
1698 # @default -> (optional) Initial values of field (may be an array)
1700 # $default->[initial values of field]
1702 # A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
1704 'hidden' => <<'END_OF_FUNC',
1706 my($self,@p) = self_or_default(@_);
1708 # this is the one place where we departed from our standard
1709 # calling scheme, so we have to special-case (darn)
1711 my($name,$default,$override,@other) =
1712 $self->rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
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;
1719 foreach ($default,$override,@other) {
1720 push(@value,$_) if defined($_);
1724 # use previous values if override is not set
1725 my @prev = $self->param($name);
1726 @value = @prev if !$do_override && @prev;
1728 $name=$self->escapeHTML($name);
1730 $_=$self->escapeHTML($_);
1731 push(@result,qq/<INPUT TYPE="hidden" NAME="$name" VALUE="$_">/);
1733 return wantarray ? @result : join('',@result);
1738 #### Method: image_button
1740 # $name -> Name of the button
1741 # $src -> URL of the image source
1742 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
1744 # A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
1746 'image_button' => <<'END_OF_FUNC',
1748 my($self,@p) = self_or_default(@_);
1750 my($name,$src,$alignment,@other) =
1751 $self->rearrange([NAME,SRC,ALIGN],@p);
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>/;
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.
1767 'self_url' => <<'END_OF_FUNC',
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";
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',
1793 # Like self_url, but doesn't return the query string part of
1796 'url' => <<'END_OF_FUNC',
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;
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.
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)
1821 'cookie' => <<'END_OF_FUNC',
1822 # temporary, for debugging.
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);
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);
1836 my($key,$value) = split("=");
1837 my(@values) = map unescape($_),split('&',$value);
1838 $self->{'.cookies'}->{unescape($key)} = [@values];
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'}};
1850 # Pull out our parameters.
1852 if (ref($value) eq 'ARRAY') {
1854 } elsif (ref($value) eq 'HASH') {
1860 @values = map escape($_),@values;
1862 # I.E. requires the path to be present.
1863 ($path = $ENV{'SCRIPT_NAME'})=~s![^/]+$!! unless $path;
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;
1871 my($key) = &escape($name);
1872 my($cookie) = join("=",$key,join("&",@values));
1873 return join("; ",$cookie,@constant_values);
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',
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,
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
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
1905 if (!$time || ($time eq 'now')) {
1907 } elsif ($time=~/^([+-]?\d+)([mhdMy]?)/) {
1908 $offset = ($mult{$2} || 1)*$1;
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);
1920 ###############################################
1921 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
1922 ###############################################
1924 #### Method: path_info
1925 # Return the extra virtual path information provided
1926 # after the URL (if any)
1928 'path_info' => <<'END_OF_FUNC',
1930 return $ENV{'PATH_INFO'};
1935 #### Method: request_method
1936 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
1938 'request_method' => <<'END_OF_FUNC',
1939 sub request_method {
1940 return $ENV{'REQUEST_METHOD'};
1944 #### Method: path_translated
1945 # Return the physical path information provided
1946 # by the URL (if any)
1948 'path_translated' => <<'END_OF_FUNC',
1949 sub path_translated {
1950 return $ENV{'PATH_TRANSLATED'};
1955 #### Method: query_string
1956 # Synthesize a query string from our current
1959 'query_string' => <<'END_OF_FUNC',
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");
1970 return join("&",@pairs);
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.
1986 'accept' => <<'END_OF_FUNC',
1988 my($self,$search) = self_or_CGI(@_);
1989 my(%prefs,$type,$pref,$pat);
1991 my(@accept) = split(',',$self->http('accept'));
1994 ($pref) = /q=(\d\.\d+|\d+)/;
1995 ($type) = m#(\S+/[^;]+)#;
1997 $prefs{$type}=$pref || 1;
2000 return keys %prefs unless $search;
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
2007 # First return the preference for directly supported
2009 return $prefs{$search} if $prefs{$search};
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/;
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.
2027 'user_agent' => <<'END_OF_FUNC',
2029 my($self,$match)=self_or_CGI(@_);
2030 return $self->http('user_agent') unless $match;
2031 return $self->http('user_agent') =~ /$match/i;
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')
2041 'raw_cookie' => <<'END_OF_FUNC',
2043 my($self) = self_or_CGI(@_);
2044 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2048 #### Method: virtual_host
2049 # Return the name of the virtual_host, which
2050 # is not always the same as the server
2052 'virtual_host' => <<'END_OF_FUNC',
2054 return http('host') || server_name();
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
2064 'remote_host' => <<'END_OF_FUNC',
2066 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2072 #### Method: remote_addr
2073 # Return the IP addr of the remote host.
2075 'remote_addr' => <<'END_OF_FUNC',
2077 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
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
2088 'script_name' => <<'END_OF_FUNC',
2090 return $ENV{'SCRIPT_NAME'} if $ENV{'SCRIPT_NAME'};
2091 # These are for debugging
2092 return "/$0" unless $0=~/^\//;
2098 #### Method: referer
2099 # Return the HTTP_REFERER: useful for generating
2102 'referer' => <<'END_OF_FUNC',
2104 my($self) = self_or_CGI(@_);
2105 return $self->http('referer');
2110 #### Method: server_name
2111 # Return the name of the server
2113 'server_name' => <<'END_OF_FUNC',
2115 return $ENV{'SERVER_NAME'} || 'localhost';
2119 #### Method: server_software
2120 # Return the name of the server software
2122 'server_software' => <<'END_OF_FUNC',
2123 sub server_software {
2124 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2128 #### Method: server_port
2129 # Return the tcp/ip port the server is running on
2131 'server_port' => <<'END_OF_FUNC',
2133 return $ENV{'SERVER_PORT'} || 80; # for debugging
2137 #### Method: server_protocol
2138 # Return the protocol (usually HTTP/1.0)
2140 'server_protocol' => <<'END_OF_FUNC',
2141 sub server_protocol {
2142 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2147 # Return the value of an HTTP variable, or
2148 # the list of variables if none provided
2150 'http' => <<'END_OF_FUNC',
2152 my ($self,$parameter) = self_or_CGI(@_);
2153 return $ENV{$parameter} if $parameter=~/^HTTP/;
2154 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2156 foreach (keys %ENV) {
2157 push(@p,$_) if /^HTTP/;
2164 # Return the value of HTTPS
2166 'https' => <<'END_OF_FUNC',
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;
2174 foreach (keys %ENV) {
2175 push(@p,$_) if /^HTTPS/;
2181 #### Method: protocol
2182 # Return the protocol (http or https currently)
2184 'protocol' => <<'END_OF_FUNC',
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";
2196 #### Method: remote_ident
2197 # Return the identity of the remote user
2198 # (but only if his host is running identd)
2200 'remote_ident' => <<'END_OF_FUNC',
2202 return $ENV{'REMOTE_IDENT'};
2207 #### Method: auth_type
2208 # Return the type of use verification/authorization in use, if any.
2210 'auth_type' => <<'END_OF_FUNC',
2212 return $ENV{'AUTH_TYPE'};
2217 #### Method: remote_user
2218 # Return the authorization name used for user
2221 'remote_user' => <<'END_OF_FUNC',
2223 return $ENV{'REMOTE_USER'};
2228 #### Method: user_name
2229 # Try to return the remote user's name by hook or by
2232 'user_name' => <<'END_OF_FUNC',
2234 my ($self) = self_or_CGI(@_);
2235 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2240 # Set or return the NPH global flag
2242 'nph' => <<'END_OF_FUNC',
2244 my ($self,$param) = self_or_CGI(@_);
2245 $CGI::nph = $param if defined($param);
2250 # -------------- really private subroutines -----------------
2251 'previous_or_default' => <<'END_OF_FUNC',
2252 sub previous_or_default {
2253 my($self,$name,$defaults,$override) = @_;
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});
2263 $selected{$defaults}++ if defined($defaults);
2270 'register_parameter' => <<'END_OF_FUNC',
2271 sub register_parameter {
2272 my($self,$param) = @_;
2273 $self->{'.parametersToAdd'}->{$param}++;
2277 'get_fields' => <<'END_OF_FUNC',
2280 return $self->hidden('-name'=>'.cgifields',
2281 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2286 'read_from_cmdline' => <<'END_OF_FUNC',
2287 sub read_from_cmdline {
2288 require "shellwords.pl";
2292 $input = join(" ",@ARGV);
2294 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2295 chomp(@lines = <>); # remove newlines
2296 $input = join(" ",@lines);
2299 # minimal handling of escape characters
2300 $input=~s/\\=/%3D/g;
2301 $input=~s/\\&/%26/g;
2303 @words = &shellwords($input);
2304 if ("@words"=~/=/) {
2305 $query_string = join('&',@words);
2307 $query_string = join('+',@words);
2309 return $query_string;
2314 # subroutine: read_multipart
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.
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;
2327 while (!$buffer->eof) {
2328 %header = $buffer->readHeader;
2330 # In beta1 it was "Content-disposition". In beta2 it's "Content-Disposition"
2332 my($key) = $header{'Content-disposition'} ? 'Content-disposition' : 'Content-Disposition';
2333 my($param)= $header{$key}=~/ name="([^\"]*)"/;
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="(.*)"$/;
2339 # add this parameter to our list
2340 $self->add_parameter($param);
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);
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;
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.
2360 while ($data = $buffer->read) {
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!)
2370 if ($filename=~/^[a-zA-Z_]/) {
2372 do { $cp = caller($frame++); } until !eval("'$cp'->isaCGI()");
2373 $filehandle = "$cp\:\:$filename";
2375 $filehandle = "\:\:$filename";
2378 open($filehandle,$tmp) || die "CGI open of $tmp: $!\n";
2379 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2381 push(@{$self->{$param}},$filename);
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}= {
2400 'tmpFileName' => <<'END_OF_FUNC',
2402 my($self,$filename) = self_or_default(@_);
2403 return $self->{'.tmpfiles'}->{$filename}->{name}->as_string;
2407 'uploadInfo' => <<'END_OF_FUNC'
2409 my($self,$filename) = self_or_default(@_);
2410 return $self->{'.tmpfiles'}->{$filename}->{info};
2418 # Globals and stubs for other packages that we use
2419 package MultipartBuffer;
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
2428 #reuse the autoload function
2429 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
2431 ###############################################################################
2432 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2433 ###############################################################################
2434 $AUTOLOADED_ROUTINES = ''; # prevent -w error
2435 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2438 'new' => <<'END_OF_FUNC',
2440 my($package,$interface,$boundary,$length,$filehandle) = @_;
2443 my($package) = caller;
2444 # force into caller's package if necessary
2445 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
2447 $IN = "main::STDIN" unless $IN;
2449 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
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.
2457 # Netscape seems to be a little bit unreliable
2458 # about providing boundary strings.
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
2466 $length -= $interface->read_from_client($IN,\$null,length($boundary)+2,0);
2468 } else { # otherwise we find it ourselves
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
2477 my $self = {LENGTH=>$length,
2478 BOUNDARY=>$boundary,
2480 INTERFACE=>$interface,
2484 $FILLUNIT = length($boundary)
2485 if length($boundary) > $FILLUNIT;
2487 return bless $self,ref $package || $package;
2491 'readHeader' => <<'END_OF_FUNC',
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;
2503 my($header) = substr($self->{BUFFER},0,$end+2);
2504 substr($self->{BUFFER},0,$end+4) = '';
2506 while ($header=~/^([\w-]+): (.*)$CRLF/mog) {
2513 # This reads and returns the body as a single scalar value.
2514 'readBody' => <<'END_OF_FUNC',
2519 while (defined($data = $self->read)) {
2520 $returnval .= $data;
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',
2531 my($self,$bytes) = @_;
2533 # default number of bytes to read
2534 $bytes = $bytes || $FILLUNIT;
2536 # Fill up our internal buffer in such a way that the boundary
2537 # is never split between reads.
2538 $self->fillBuffer($bytes);
2540 # Find the boundary in the buffer (it may not be there).
2541 my $start = index($self->{BUFFER},$self->{BOUNDARY});
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.
2548 # clear us out completely if we've hit the last boundary.
2549 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
2555 # just remove the boundary.
2556 substr($self->{BUFFER},0,length($self->{BOUNDARY})+2)='';
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
2567 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
2570 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
2571 substr($self->{BUFFER},0,$bytesToReturn)='';
2573 # If we hit the boundary, remove the CRLF from the end.
2574 return ($start > 0) ? substr($returnval,0,-2) : $returnval;
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',
2583 my($self,$bytes) = @_;
2584 return unless $self->{LENGTH};
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;
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},
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);
2606 $self->{ZERO_LOOP_COUNTER}=0;
2609 $self->{LENGTH} -= $bytesRead;
2614 # Return true when we've finished reading
2615 'eof' => <<'END_OF_FUNC'
2618 return 1 if (length($self->{BUFFER}) == 0)
2619 && ($self->{LENGTH} <= 0);
2627 ####################################################################################
2628 ################################## TEMPORARY FILES #################################
2629 ####################################################################################
2633 unless ($TMPDIRECTORY) {
2634 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp","${SL}tmp","${SL}temp","${SL}Temporary Items");
2636 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
2640 $TMPDIRECTORY = "." unless $TMPDIRECTORY;
2641 $SEQUENCE="CGItemp${$}0000";
2643 # cute feature, but overload implementation broke it
2644 # %OVERLOAD = ('""'=>'as_string');
2645 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
2647 ###############################################################################
2648 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2649 ###############################################################################
2650 $AUTOLOADED_ROUTINES = ''; # prevent -w error
2651 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2654 'new' => <<'END_OF_FUNC',
2658 my $directory = "${TMPDIRECTORY}${SL}${SEQUENCE}";
2659 return bless \$directory;
2663 'DESTROY' => <<'END_OF_FUNC',
2666 unlink $$self; # get rid of the file
2670 'as_string' => <<'END_OF_FUNC'
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.
2689 $MultipartBuffer::SPIN_LOOP_MAX;
2690 $MultipartBuffer::CRLF;
2691 $MultipartBuffer::TIMEOUT;
2692 $MultipartBuffer::FILLUNIT;
2693 $TempFile::SEQUENCE;
2704 CGI - Simple Common Gateway Interface Class
2709 # the rest is too complicated for a synopsis; keep reading
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
2722 The current version of CGI.pm is available at
2724 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
2725 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
2727 =head1 INSTALLATION:
2729 To install this package, just change to the directory in which this
2730 file is found and type the following:
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:
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
2748 use lib '/home/davis/lib';
2751 If you are using a version of perl earlier than 5.002 (such as NT perl), use
2755 unshift(@INC,'/home/davis/lib');
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.
2770 =head2 CREATING A NEW QUERY OBJECT:
2774 This will parse the input (from both POST and GET methods) and store
2775 it into a perl5 object called $query.
2777 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
2779 $query = new CGI(INPUTFILE);
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.
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:
2792 $query = new CGI(\*STDIN);
2794 You can also initialize the query object from an associative array
2797 $query = new CGI( {'dinosaur'=>'barney',
2798 'song'=>'I love you',
2799 'friends'=>[qw/Jessica George Nancy/]}
2802 or from a properly formatted, URL-escaped query string:
2804 $query = new CGI('dinosaur=barney&color=purple');
2806 To create an empty query, initialize it from an empty string or hash:
2808 $empty_query = new CGI("");
2810 $empty_query = new CGI({});
2812 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
2814 @keywords = $query->keywords
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.
2819 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
2821 @names = $query->param
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'.
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).
2835 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
2837 @values = $query->param('foo');
2841 $value = $query->param('foo');
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.
2848 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
2850 $query->param('foo','an','array','of','values');
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
2858 param() also recognizes a named parameter style of calling described
2859 in more detail later:
2861 $query->param(-name=>'foo',-values=>['an','array','of','values']);
2865 $query->param(-name=>'foo',-value=>'the value');
2867 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
2869 $query->append(-name=>;'foo',-values=>['yet','more','values']);
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.
2876 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
2878 $query->import_names('R');
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
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.
2890 =head2 DELETING A PARAMETER COMPLETELY:
2892 $query->delete('foo');
2894 This completely clears a parameter. It sometimes useful for
2895 resetting parameters that you don't want passed down between
2898 =head2 DELETING ALL PARAMETERS:
2900 $query->delete_all();
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.
2905 =head2 SAVING THE STATE OF THE FORM TO A FILE:
2907 $query->save(FILEHANDLE)
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,
2914 The format of the saved file is:
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:
2932 open (OUT,">>test.out") || die;
2934 foreach (0..$records) {
2936 $q->param(-name=>'counter',-value=>$_);
2941 # reopen for reading
2942 open (IN,"test.out") || die;
2944 my $q = new CGI(IN);
2945 print $q->param('counter'),"\n";
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
2952 http://www.genome.wi.mit.edu/genome_software/other/boulder.html
2954 for further details.
2956 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
2958 $myself = $query->self_url;
2959 print "<A HREF=$myself>I'm talking to myself.</A>";
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.
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>";
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:
2975 $myself = $query->url;
2976 print "<A HREF=$myself>No query string in this baby!</A>\n";
2978 You can also retrieve the unprocessed query string with query_string():
2980 $the_string = $query->query_string;
2982 =head2 COMPATIBILITY WITH CGI-LIB.PL
2984 To make it easier to port existing programs that use cgi-lib.pl
2985 the compatibility routine "ReadParse" is provided. Porting is
2989 require "cgi-lib.pl";
2991 print "The value of the antique is $in{antique}.\n";
2996 print "The value of the antique is $in{antique}.\n";
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.
3004 Once you use ReadParse, you can retrieve the query object itself
3008 print $q->textfield(-name=>'wow',
3009 -value=>'does this really work?');
3011 This allows you to start using the more interesting features
3012 of CGI.pm without rewriting your old scripts from scratch.
3014 =head2 CALLING CGI FUNCTIONS THAT TAKE MULTIPLE ARGUMENTS
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:
3022 $field = $query->radio_group(-name=>'OS',
3023 -values=>[Unix,Windows,Macintosh],
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:
3035 $field = $query->textfield(-name=>'State',
3036 -default=>'gaseous',
3037 -justification=>'RIGHT');
3039 This will result in an HTML tag that looks like this:
3041 <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
3042 JUSTIFICATION="RIGHT">
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:
3051 $query->use_named_parameters(1);
3052 $field = $query->radio_group('name'=>'OS',
3053 'values'=>['Unix','Windows','Macintosh'],
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.
3064 =head2 CREATING THE HTTP HEADER:
3066 print $query->header;
3070 print $query->header('image/gif');
3074 print $query->header('text/html','204 No response');
3078 print $query->header(-type=>'image/gif',
3080 -status=>'402 Payment required',
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:
3092 print $query->header('text/html','200 OK','Content-Length: 3002');
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.
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
3108 +30s 30 seconds from now
3109 +10m ten minutes from now
3110 +1h one hour from now
3111 -1d yesterday (i.e. "ASAP!")
3114 +10y in ten years time
3115 Thursday, 25-Apr-96 00:40:33 GMT at the indicated time & date
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
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
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.
3132 =head2 GENERATING A REDIRECTION INSTRUCTION
3134 print $query->redirect('http://somewhere.else/in/movie/land');
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.
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.
3147 You can use named parameters:
3149 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
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.
3158 =head2 CREATING THE HTML HEADER:
3160 print $query->start_html(-title=>'Secrets of the Pyramids',
3161 -author=>'fred@capricorn.org',
3164 -meta=>{'keywords'=>'pharaoh secret mummy',
3165 'copyright'=>'copyright 1996 King Tut'},
3170 print $query->start_html('Secrets of the Pyramids',
3171 'fred@capricorn.org','true',
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.
3180 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
3181 different from the current location, as in
3183 -xbase=>"http://home.mcom.com/"
3185 All relative links will be interpreted relative to this tag.
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.
3191 -target=>"answer_window"
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:
3199 <META NAME="keywords" CONTENT="pharaoh secret mummy">
3200 <META NAME="description" CONTENT="copyright 1996 King Tut">
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()>
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.
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
3224 print $query->header;
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?");
3233 // Get a silly answer
3234 function response(answer) {
3235 if (answer == "man")
3236 alert("Right you are!");
3238 alert("Wrong! Guess again.");
3241 print $query->start_html(-title=>'The Riddle of the Sphinx',
3246 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
3248 for more information about JavaScript.
3250 The old-style positional parameters are as follows:
3254 =item B<Parameters:>
3262 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
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!
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.
3277 =head2 ENDING THE HTML DOCUMENT:
3279 print $query->end_html
3281 This ends an HTML document by printing the </BODY></HTML> tags.
3283 =head1 CREATING FORMS:
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.
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.
3296 If you want to change the value of a field from its previous value, you have two
3299 (1) call the param() method to set it.
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:
3304 print $query->textfield(-name=>'field_name',
3305 -default=>'starting value',
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 Á,
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:
3318 $query->autoEscape(undef);
3321 =head2 CREATING AN ISINDEX TAG
3323 print $query->isindex(-action=>$action);
3327 print $query->isindex($action);
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.
3333 =head2 STARTING AND ENDING A FORM
3335 print $query->startform(-method=>$method,
3337 -encoding=>$encoding);
3338 <... various form stuff ...>
3339 print $query->endform;
3343 print $query->startform($method,$action,$encoding);
3344 <... various form stuff ...>
3345 print $query->endform;
3347 startform() will return a <FORM> tag with the optional method,
3348 action and form encoding that you specify. The defaults are:
3352 encoding: application/x-www-form-urlencoded
3354 endform() returns the closing </FORM> tag.
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:
3362 =item B<application/x-www-form-urlencoded>
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>.
3370 =item B<multipart/form-data>
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>
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
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
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.
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.
3404 =head2 CREATING A TEXT FIELD
3406 print $query->textfield(-name=>'field_name',
3407 -default=>'starting value',
3412 print $query->textfield('field_name','starting value',50,80);
3414 textfield() will return a text input field.
3422 The first parameter is the required name for the field (-name).
3426 The optional second parameter is the default starting value for the field
3427 contents (-default).
3431 The optional third parameter is the size of the field in
3436 The optional fourth parameter is the maximum number of characters the
3437 field will accept (-maxlength).
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
3446 $value = $query->param('foo');
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:
3451 $query->param('foo',"I'm taking over this value!");
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)
3457 print $query->textfield(-name=>'field_name',
3458 -default=>'starting value',
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.
3471 =head2 CREATING A BIG TEXT FIELD
3473 print $query->textarea(-name=>'foo',
3474 -default=>'starting value',
3480 print $query->textarea('foo','starting value',10,50);
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
3487 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3488 and B<-onSelect> parameters are recognized. See textfield().
3490 =head2 CREATING A PASSWORD FIELD
3492 print $query->password_field(-name=>'secret',
3493 -value=>'starting value',
3498 print $query->password_field('secret','starting value',50,80);
3500 password_field() is identical to textfield(), except that its contents
3501 will be starred out on the web page.
3503 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3504 and B<-onSelect> parameters are recognized. See textfield().
3506 =head2 CREATING A FILE UPLOAD FIELD
3508 print $query->filefield(-name=>'uploaded_file',
3509 -default=>'starting value',
3514 print $query->filefield('uploaded_file','starting value',50,80);
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()>.
3529 The first parameter is the required name for the field (-name).
3533 The optional second parameter is the starting value for the field contents
3534 to be used as the default file name (-default).
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
3545 The optional third parameter is the size of the field in
3550 The optional fourth parameter is the maximum number of characters the
3551 field will accept (-maxlength).
3555 When the form is processed, you can retrieve the entered filename
3558 $filename = $query->param('uploaded_file');
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:
3566 On an MS-DOS/Windows and OS/2 machines, the filename will follow DOS conventions:
3568 C:\PATH\TO\THE\FILE.MSW
3570 On a Macintosh machine, the filename will follow Mac conventions:
3572 HD 40:Desktop Folder:Sort Through:Reminders
3574 The filename returned is also a file handle. You can read the contents
3575 of the file using standard Perl file reading calls:
3577 # Read a text file and print it out
3578 while (<$filename>) {
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;
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.
3595 $filename = $query->param('uploaded_file');
3596 $type = $query->uploadInfo($filename)->{'Content-Type'};
3597 unless ($type eq 'text/html') {
3598 die "HTML FILES ONLY!";
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.
3605 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>
3606 and B<-onSelect> parameters are recognized. See textfield()
3609 =head2 CREATING A POPUP MENU
3611 print $query->popup_menu('menu_name',
3612 ['eenie','meenie','minie'],
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'],
3624 -or (named parameter style)-
3626 print $query->popup_menu(-name=>'menu_name',
3627 -values=>['eenie','meenie','minie'],
3631 popup_menu() creates a menu.
3637 The required first argument is the menu's name (-name).
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".
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.
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).
3663 When the form is processed, the selected value of the popup menu can
3666 $popup_menu_value = $query->param('menu_name');
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.
3672 =head2 CREATING A SCROLLING LIST
3674 print $query->scrolling_list('list_name',
3675 ['eenie','meenie','minie','moe'],
3676 ['eenie','moe'],5,'true');
3679 print $query->scrolling_list('list_name',
3680 ['eenie','meenie','minie','moe'],
3681 ['eenie','moe'],5,'true',
3686 print $query->scrolling_list(-name=>'list_name',
3687 -values=>['eenie','meenie','minie','moe'],
3688 -default=>['eenie','moe'],
3693 scrolling_list() creates a scrolling list.
3697 =item B<Parameters:>
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
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
3716 The optional fourth argument is the size of the list (-size).
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.
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.
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:
3734 @selected = $query->param('list_name');
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.
3742 =head2 CREATING A GROUP OF RELATED CHECKBOXES
3744 print $query->checkbox_group(-name=>'group_name',
3745 -values=>['eenie','meenie','minie','moe'],
3746 -default=>['eenie','moe'],
3750 print $query->checkbox_group('group_name',
3751 ['eenie','meenie','minie','moe'],
3752 ['eenie','moe'],'true',\%labels);
3754 HTML3-COMPATIBLE BROWSERS ONLY:
3756 print $query->checkbox_group(-name=>'group_name',
3757 -values=>['eenie','meenie','minie','moe'],
3758 -rows=2,-columns=>2);
3761 checkbox_group() creates a list of checkboxes that are related
3766 =item B<Parameters:>
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.
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.
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.
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.
3798 B<HTML3-compatible browsers> (such as Netscape) can take advantage
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
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
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:
3820 @turned_on = $query->param('group_name');
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:
3826 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
3827 &use_in_creative_way(@h);
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.
3835 =head2 CREATING A STANDALONE CHECKBOX
3837 print $query->checkbox(-name=>'checkbox_name',
3838 -checked=>'checked',
3840 -label=>'CLICK ME');
3844 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
3846 checkbox() is used to create an isolated checkbox that isn't logically
3847 related to any others.
3851 =item B<Parameters:>
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
3861 The optional second parameter (-checked) specifies that the checkbox
3862 is turned on by default. Synonyms are -selected and -on.
3866 The optional third parameter (-value) specifies the value of the
3867 checkbox when it is checked. If not provided, the word "on" is
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
3878 The value of the checkbox can be retrieved using:
3880 $turned_on = $query->param('checkbox_name');
3882 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
3883 parameter. See checkbox_group() for further details.
3885 =head2 CREATING A RADIO BUTTON GROUP
3887 print $query->radio_group(-name=>'group_name',
3888 -values=>['eenie','meenie','minie'],
3895 print $query->radio_group('group_name',['eenie','meenie','minie'],
3896 'meenie','true',\%labels);
3899 HTML3-COMPATIBLE BROWSERS ONLY:
3901 print $query->radio_group(-name=>'group_name',
3902 -values=>['eenie','meenie','minie','moe'],
3903 -rows=2,-columns=>2);
3905 radio_group() creates a set of logically-related radio buttons
3906 (turning one member of the group on turns the others off)
3910 =item B<Parameters:>
3914 The first argument is the name of the group and is required (-name).
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
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.
3933 The optional fourth parameter (-linebreak) can be set to 'true' to put
3934 line breaks between the buttons, creating a vertical list.
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
3945 B<HTML3-compatible browsers> (such as Netscape) can take advantage
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
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
3963 When the form is processed, the selected radio button can
3966 $which_radio_button = $query->param('group_name');
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:
3972 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
3973 &use_in_creative_way(@h);
3975 =head2 CREATING A SUBMIT BUTTON
3977 print $query->submit(-name=>'button_name',
3982 print $query->submit('button_name','value');
3984 submit() will create the query submission button. Every form
3985 should have one of these.
3989 =item B<Parameters:>
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.
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.
4006 You can figure out which button was pressed by using different
4007 values for each one:
4009 $which_one = $query->param('button_name');
4011 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
4012 parameter. See checkbox_group() for further details.
4014 =head2 CREATING A RESET BUTTON
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.
4022 =head2 CREATING A DEFAULT BUTTON
4024 print $query->defaults('button_label')
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.
4030 =head2 CREATING A HIDDEN FIELD
4032 print $query->hidden(-name=>'hidden_name',
4033 -default=>['value1','value2'...]);
4037 print $query->hidden('hidden_name','value1','value2'...);
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.
4045 =item B<Parameters:>
4049 The first argument is required and specifies the name of this
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
4060 Fetch the value of a hidden field this way:
4062 $hidden_value = $query->param('hidden_name');
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
4069 $query->param('hidden_name','new','values','here');
4071 =head2 CREATING A CLICKABLE IMAGE BUTTON
4073 print $query->image_button(-name=>'button_name',
4074 -src=>'/source/URL',
4079 print $query->image_button('button_name','/source/URL','MIDDLE');
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
4086 JAVASCRIPTING: image_button() recognizes the B<-onClick>
4087 parameter. See checkbox_group() for further details.
4091 =item B<Parameters:>
4095 The first argument (-name) is required and specifies the name of this
4100 The second argument (-src) is also required and specifies the URL
4103 The third option (-align, optional) is an alignment type, and may be
4104 TOP, BOTTOM or MIDDLE
4108 Fetch the value of the button this way:
4109 $x = $query->param('button_name.x');
4110 $y = $query->param('button_name.y');
4112 =head2 CREATING A JAVASCRIPT ACTION BUTTON
4114 print $query->button(-name=>'button_name',
4115 -value=>'user visible label',
4116 -onClick=>"do_something()");
4120 print $query->button('button_name',"do_something()");
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
4128 =head1 NETSCAPE COOKIES
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.
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.
4140 In addition to the required name=value pair, each cookie has several
4141 optional attributes:
4145 =item 1. an expiration time
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.
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.
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.
4176 =item 4. a "secure" flag
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.
4183 The interface to Netscape cookies is the B<cookie()> method:
4185 $cookie = $query->cookie(-name=>'sessionID',
4188 -path=>'/cgi-bin/database',
4189 -domain=>'.capricorn.org',
4191 print $query->header(-cookie=>$cookie);
4193 B<cookie()> creates a new cookie. Its parameters include:
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.
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:
4210 $cookie=$query->cookie(-name=>'family information',
4211 -value=>\%childrens_ages);
4215 The optional partial path for which this cookie will be valid, as described
4220 The optional partial domain for which this cookie will be valid, as described
4225 The optional expiration date for this cookie. The format is as described
4226 in the section on the B<header()> method:
4228 "+1h" one hour from now
4232 If set to true, this cookie will only be used within a secure
4237 The cookie created by cookie() must be incorporated into the HTTP
4238 header within the string returned by the header() method:
4240 print $query->header(-cookie=>$my_cookie);
4242 To create multiple cookies, give header() an array reference:
4244 $cookie1 = $query->cookie(-name=>'riddle_name',
4245 -value=>"The Sphynx's Question");
4246 $cookie2 = $query->cookie(-name=>'answers',
4248 print $query->header(-cookie=>[$cookie1,$cookie2]);
4250 To retrieve a cookie, request it by name by calling cookie()
4251 method without the B<-value> parameter:
4255 %answers = $query->cookie(-name=>'answers');
4256 # $query->cookie('answers') will work too!
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:
4263 # turn a CGI parameter into a cookie
4264 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
4266 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
4268 See the B<cookie.cgi> example script for some ideas on how to use
4269 cookies effectively.
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.
4279 =head1 WORKING WITH NETSCAPE FRAMES
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:
4287 =item 1. Create a <Frameset> document
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.
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
4298 http://home.netscape.com/assist/net_sites/frames.html
4300 =item 2. Specify the destination for the document in the HTTP header
4302 You may provide a B<-target> parameter to the header() method:
4304 print $q->header(-target=>'ResultsWindow');
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.
4313 =item 3. Specify the destination for the document in the <FORM> tag
4315 You can specify the frame to load in the FORM tag itself. With
4316 CGI.pm it looks like this:
4318 print $q->startform(-target=>'ResultsWindow');
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.
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.
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:
4339 your_script.pl keyword1 keyword2 keyword3
4343 your_script.pl keyword1+keyword2+keyword3
4347 your_script.pl name1=value1 name2=value2
4351 your_script.pl name1=value1&name2=value2
4353 or even as newline-delimited parameters on standard input.
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
4360 your_script.pl "name1='I am a long value'" "name2=two\ words"
4362 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
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:
4371 Produces something that looks like:
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.
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
4394 print "<H2>Current Values</H2> $query\n";
4396 =head1 FETCHING ENVIRONMENT VARIABLES
4398 Some of the more useful environment variables can be fetched
4399 through this interface. The methods are as follows:
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.
4414 =item B<raw_cookie()>
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
4423 =item B<user_agent()>
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);
4430 =item B<path_info()>
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
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.
4446 =item B<path_translated()>
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".
4452 The Microsoft IIS is broken with respect to the translated
4455 =item B<remote_host()>
4457 Returns either the remote host name or IP address.
4458 if the former is unavailable.
4460 =item B<script_name()>
4461 Return the script name as a partial URL, for self-refering
4466 Return the URL of the page the browser was viewing
4467 prior to fetching your script. Not available for all
4470 =item B<auth_type ()>
4472 Return the authorization/verification method in use for this
4475 =item B<server_name ()>
4477 Returns the name of the server, usually the machine's host
4480 =item B<virtual_host ()>
4482 When using virtual hosts, returns the name of the host that
4483 the browser attempted to contact
4485 =item B<server_software ()>
4487 Returns the server software and version number.
4489 =item B<remote_user ()>
4491 Return the authorization/verification name used for user
4492 verification, if this script is protected.
4494 =item B<user_name ()>
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
4501 =item B<request_method()>
4503 Returns the method used to access your script, usually
4504 one of 'POST', 'GET' or 'HEAD'.
4508 =head1 CREATING HTML ELEMENTS:
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.
4515 This example shows how to use the HTML methods:
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."),
4526 This results in the following HTML code (extra newlines have been
4527 added for readability):
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>
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):
4540 use CGI shortcuts; # IMPORT HTML SHORTCUTS
4542 "Many years ago on the island of",
4543 a({href=>"http://crete.org/"},"Crete"),
4544 "there lived a minotaur named",
4549 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4551 The HTML methods will accept zero, one or multiple arguments. If you
4552 provide no arguments, you get a single tag:
4557 If you provide one or more string arguments, they are concatenated
4558 together with spaces and placed between opening and closing tags:
4560 print h1("Chapter","1");
4561 # gives "<h1>Chapter 1</h1>"
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:
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>
4570 You are free to use CGI.pm-style dashes in front of the attribute
4571 names if you prefer:
4573 print img {-src=>'fred.gif',-align=>'LEFT'};
4574 # gives <img ALIGN="LEFT" SRC="fred.gif">
4576 =head2 Generating new HTML tags
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:
4583 use CGI shortcuts,winkin,blinkin,nod;
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:
4588 print blinkin {color=>'blue',rate=>'fast'},"Yahoo!";
4589 # <blinkin COLOR="blue" RATE="fast">Yahoo!</blinkin>
4591 =head1 IMPORTING CGI METHOD CALLS INTO YOUR NAME SPACE
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:
4596 use CGI <list of methods>;
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:
4603 use CGI param,header;
4604 print header('text/plain');
4605 $zipcode = param('zipcode');
4607 You can import groups of methods by referring to a number of special
4614 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4619 Import all fill-out form generating methods, such as B<textfield()>.
4623 Import all methods that generate HTML 2.0 standard elements.
4627 Import all methods that generate HTML 3.0 proposed elements (such as
4628 <table>, <super> and <sub>).
4632 Import all methods that generate Netscape-specific HTML extensions.
4636 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4641 Import "standard" features, 'html2', 'form' and 'cgi'.
4645 Import all the available methods. For the full list, see the CGI.pm
4646 code, where the variable %TAGS is defined.
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.
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:
4662 use CGI standard,html2;
4665 start_html('Simple Script'),
4666 h1('Simple Script'),
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,
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";
4688 =head1 USING NPH SCRIPTS
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.
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.
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
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.
4713 There are a number of ways to put CGI.pm into NPH mode:
4717 =item In the B<use> statement
4718 Simply add ":nph" to the list of symbols to be imported into your script:
4720 use CGI qw(:standard :nph)
4722 =item By calling the B<nph()> method:
4724 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
4728 =item By using B<-nph> parameters in the B<header()> and B<redirect()> statements:
4730 print $q->header(-nph=>1);
4734 =head1 AUTHOR INFORMATION
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.
4742 Address bug reports and comments to:
4743 lstein@genome.wi.mit.edu
4747 Thanks very much to:
4751 =item Matt Heffron (heffron@falstaff.css.beckman.com)
4753 =item James Taylor (james.taylor@srs.gov)
4755 =item Scott Anguish <sanguish@digifix.com>
4757 =item Mike Jewell (mlj3u@virginia.edu)
4759 =item Timothy Shimmin (tes@kbs.citri.edu.au)
4761 =item Joergen Haegg (jh@axis.se)
4763 =item Laurent Delfosse (delfosse@csgrad1.cs.wvu.edu)
4765 =item Richard Resnick (applepi1@aol.com)
4767 =item Craig Bishop (csb@barwonwater.vic.gov.au)
4769 =item Tony Curtis (tc@vcpc.univie.ac.at)
4771 =item Tim Bunce (Tim.Bunce@ig.co.uk)
4773 =item Tom Christiansen (tchrist@convex.com)
4775 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
4777 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
4779 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
4781 =item Stephen Dahmen (joyfire@inxpress.net)
4783 =item Ed Jordan (ed@fidalgo.net)
4785 =item David Alan Pisoni (david@cnation.com)
4787 =item ...and many many more...
4789 for suggestions and bug fixes.
4793 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
4796 #!/usr/local/bin/perl
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);
4808 print $query->end_html;
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');
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],
4823 -defaults=>[England,Asia]);
4825 print "<P><EM>How far can they fly?</EM><BR>",
4826 $query->radio_group(
4828 -values=>['10 ft','1 mile','10 miles','real far'],
4829 -default=>'1 mile');
4831 print "<P><EM>What's your favorite color?</EM> ";
4832 print $query->popup_menu(-name=>'Color',
4833 -values=>['black','brown','red','yellow'],
4836 print $query->hidden('Reference','Monty Python and the Holy Grail');
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'],
4846 print "<P><EM>Any parting comments?</EM><BR>";
4847 print $query->textarea(-name=>'Comments',
4851 print "<P>",$query->reset;
4852 print $query->submit('Action','Shout');
4853 print $query->submit('Action','Scream');
4854 print $query->endform;
4862 print "<H2>Here are the current settings in this form</H2>";
4864 foreach $key ($query->param) {
4865 print "<STRONG>$key</STRONG> -> ";
4866 @values = $query->param($key);
4867 print join(", ",@values),"<BR>\n";
4874 <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
4875 <A HREF="/">Home Page</A>
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.
4886 Note that the code is truly contorted in order to avoid spurious
4887 warnings when programs are run with the B<-w> switch.
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>