Work around MinGW mangling of "host:/path"
[msysgit/historical-msysgit.git] / lib / perl5 / 5.6.1 / CGI.pm
blob1c9d2d466121ac16dd9129b11fa1fa3c06baed7e
1 package CGI;
2 require 5.004;
3 use Carp 'croak';
5 # See the bottom of this file for the POD documentation. Search for the
6 # string '=head'.
8 # You can run this file through either pod2man or pod2html to produce pretty
9 # documentation in manual or html file format (these utilities are part of the
10 # Perl 5 distribution).
12 # Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
13 # It may be used and modified freely, but I do request that this copyright
14 # notice remain attached to the file. You may modify this module as you
15 # wish, but if you redistribute a modified version, please attach a note
16 # listing the modifications you have made.
18 # The most recent version and complete docs are available at:
19 # http://stein.cshl.org/WWW/software/CGI/
21 $CGI::revision = '$Id: CGI.pm,v 1.49 2001/02/04 23:08:39 lstein Exp $';
22 $CGI::VERSION='2.752';
24 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
26 # $TempFile::TMPDIRECTORY = '/usr/tmp';
27 use CGI::Util qw(rearrange make_attributes unescape escape expires);
29 use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
32 # >>>>> Here are some globals that you might want to adjust <<<<<<
33 sub initialize_globals {
34 # Set this to 1 to enable copious autoloader debugging messages
35 $AUTOLOAD_DEBUG = 0;
37 # Set this to 1 to generate XTML-compatible output
38 $XHTML = 1;
40 # Change this to the preferred DTD to print in start_html()
41 # or use default_dtd('text of DTD to use');
42 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
43 'http://www.w3.org/TR/html4/loose.dtd' ] ;
45 # Set this to 1 to enable NOSTICKY scripts
46 # or:
47 # 1) use CGI qw(-nosticky)
48 # 2) $CGI::nosticky(1)
49 $NOSTICKY = 0;
51 # Set this to 1 to enable NPH scripts
52 # or:
53 # 1) use CGI qw(-nph)
54 # 2) CGI::nph(1)
55 # 3) print header(-nph=>1)
56 $NPH = 0;
58 # Set this to 1 to enable debugging from @ARGV
59 # Set to 2 to enable debugging from STDIN
60 $DEBUG = 1;
62 # Set this to 1 to make the temporary files created
63 # during file uploads safe from prying eyes
64 # or do...
65 # 1) use CGI qw(:private_tempfiles)
66 # 2) CGI::private_tempfiles(1);
67 $PRIVATE_TEMPFILES = 0;
69 # Set this to a positive value to limit the size of a POSTing
70 # to a certain number of bytes:
71 $POST_MAX = -1;
73 # Change this to 1 to disable uploads entirely:
74 $DISABLE_UPLOADS = 0;
76 # Automatically determined -- don't change
77 $EBCDIC = 0;
79 # Change this to 1 to suppress redundant HTTP headers
80 $HEADERS_ONCE = 0;
82 # separate the name=value pairs by semicolons rather than ampersands
83 $USE_PARAM_SEMICOLONS = 1;
85 # Other globals that you shouldn't worry about.
86 undef $Q;
87 $BEEN_THERE = 0;
88 undef @QUERY_PARAM;
89 undef %EXPORT;
90 undef $QUERY_CHARSET;
91 undef %QUERY_FIELDNAMES;
93 # prevent complaints by mod_perl
97 # ------------------ START OF THE LIBRARY ------------
99 # make mod_perlhappy
100 initialize_globals();
102 # FIGURE OUT THE OS WE'RE RUNNING UNDER
103 # Some systems support the $^O variable. If not
104 # available then require() the Config library
105 unless ($OS) {
106 unless ($OS = $^O) {
107 require Config;
108 $OS = $Config::Config{'osname'};
111 if ($OS =~ /^MSWin/i) {
112 $OS = 'WINDOWS';
113 } elsif ($OS =~ /^VMS/i) {
114 $OS = 'VMS';
115 } elsif ($OS =~ /^dos/i) {
116 $OS = 'DOS';
117 } elsif ($OS =~ /^MacOS/i) {
118 $OS = 'MACINTOSH';
119 } elsif ($OS =~ /^os2/i) {
120 $OS = 'OS2';
121 } elsif ($OS =~ /^epoc/i) {
122 $OS = 'EPOC';
123 } else {
124 $OS = 'UNIX';
127 # Some OS logic. Binary mode enabled on DOS, NT and VMS
128 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin)/;
130 # This is the default class for the CGI object to use when all else fails.
131 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
133 # This is where to look for autoloaded routines.
134 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
136 # The path separator is a slash, backslash or semicolon, depending
137 # on the paltform.
138 $SL = {
139 UNIX=>'/', OS2=>'\\', EPOC=>'/',
140 WINDOWS=>'\\', DOS=>'\\', MACINTOSH=>':', VMS=>'/'
141 }->{$OS};
143 # This no longer seems to be necessary
144 # Turn on NPH scripts by default when running under IIS server!
145 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
146 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
148 # Turn on special checking for Doug MacEachern's modperl
149 if (exists $ENV{'GATEWAY_INTERFACE'}
151 ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
153 $| = 1;
154 require Apache;
156 # Turn on special checking for ActiveState's PerlEx
157 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
159 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
160 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
161 # and sometimes CR). The most popular VMS web server
162 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
163 # use ASCII, so \015\012 means something different. I find this all
164 # really annoying.
165 $EBCDIC = "\t" ne "\011";
166 if ($OS eq 'VMS') {
167 $CRLF = "\n";
168 } elsif ($EBCDIC) {
169 $CRLF= "\r\n";
170 } else {
171 $CRLF = "\015\012";
174 if ($needs_binmode) {
175 $CGI::DefaultClass->binmode(main::STDOUT);
176 $CGI::DefaultClass->binmode(main::STDIN);
177 $CGI::DefaultClass->binmode(main::STDERR);
180 %EXPORT_TAGS = (
181 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
182 tt u i b blockquote pre img a address cite samp dfn html head
183 base body Link nextid title meta kbd start_html end_html
184 input Select option comment charset escapeHTML/],
185 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
186 embed basefont style span layer ilayer font frameset frame script small big/],
187 ':netscape'=>[qw/blink fontsize center/],
188 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
189 submit reset defaults radio_group popup_menu button autoEscape
190 scrolling_list image_button start_form end_form startform endform
191 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
192 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
193 raw_cookie request_method query_string Accept user_agent remote_host content_type
194 remote_addr referer server_name server_software server_port server_protocol
195 virtual_host remote_ident auth_type http
196 save_parameters restore_parameters param_fetch
197 remote_user user_name header redirect import_names put
198 Delete Delete_all url_param cgi_error/],
199 ':ssl' => [qw/https/],
200 ':imagemap' => [qw/Area Map/],
201 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
202 ':html' => [qw/:html2 :html3 :netscape/],
203 ':standard' => [qw/:html2 :html3 :form :cgi/],
204 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
205 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal/]
208 # to import symbols into caller
209 sub import {
210 my $self = shift;
212 # This causes modules to clash.
213 # undef %EXPORT_OK;
214 # undef %EXPORT;
216 $self->_setup_symbols(@_);
217 my ($callpack, $callfile, $callline) = caller;
219 # To allow overriding, search through the packages
220 # Till we find one in which the correct subroutine is defined.
221 my @packages = ($self,@{"$self\:\:ISA"});
222 foreach $sym (keys %EXPORT) {
223 my $pck;
224 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
225 foreach $pck (@packages) {
226 if (defined(&{"$pck\:\:$sym"})) {
227 $def = $pck;
228 last;
231 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
235 sub compile {
236 my $pack = shift;
237 $pack->_setup_symbols('-compile',@_);
240 sub expand_tags {
241 my($tag) = @_;
242 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
243 my(@r);
244 return ($tag) unless $EXPORT_TAGS{$tag};
245 foreach (@{$EXPORT_TAGS{$tag}}) {
246 push(@r,&expand_tags($_));
248 return @r;
251 #### Method: new
252 # The new routine. This will check the current environment
253 # for an existing query string, and initialize itself, if so.
254 ####
255 sub new {
256 my($class,$initializer) = @_;
257 my $self = {};
258 bless $self,ref $class || $class || $DefaultClass;
259 if ($MOD_PERL && defined Apache->request) {
260 Apache->request->register_cleanup(\&CGI::_reset_globals);
261 undef $NPH;
263 $self->_reset_globals if $PERLEX;
264 $self->init($initializer);
265 return $self;
268 # We provide a DESTROY method so that the autoloader
269 # doesn't bother trying to find it.
270 sub DESTROY { }
272 #### Method: param
273 # Returns the value(s)of a named parameter.
274 # If invoked in a list context, returns the
275 # entire list. Otherwise returns the first
276 # member of the list.
277 # If name is not provided, return a list of all
278 # the known parameters names available.
279 # If more than one argument is provided, the
280 # second and subsequent arguments are used to
281 # set the value of the parameter.
282 ####
283 sub param {
284 my($self,@p) = self_or_default(@_);
285 return $self->all_parameters unless @p;
286 my($name,$value,@other);
288 # For compatibility between old calling style and use_named_parameters() style,
289 # we have to special case for a single parameter present.
290 if (@p > 1) {
291 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
292 my(@values);
294 if (substr($p[0],0,1) eq '-') {
295 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
296 } else {
297 foreach ($value,@other) {
298 push(@values,$_) if defined($_);
301 # If values is provided, then we set it.
302 if (@values) {
303 $self->add_parameter($name);
304 $self->{$name}=[@values];
306 } else {
307 $name = $p[0];
310 return unless defined($name) && $self->{$name};
311 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
314 sub self_or_default {
315 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
316 unless (defined($_[0]) &&
317 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
319 $Q = $CGI::DefaultClass->new unless defined($Q);
320 unshift(@_,$Q);
322 return wantarray ? @_ : $Q;
325 sub self_or_CGI {
326 local $^W=0; # prevent a warning
327 if (defined($_[0]) &&
328 (substr(ref($_[0]),0,3) eq 'CGI'
329 || UNIVERSAL::isa($_[0],'CGI'))) {
330 return @_;
331 } else {
332 return ($DefaultClass,@_);
336 ########################################
337 # THESE METHODS ARE MORE OR LESS PRIVATE
338 # GO TO THE __DATA__ SECTION TO SEE MORE
339 # PUBLIC METHODS
340 ########################################
342 # Initialize the query object from the environment.
343 # If a parameter list is found, this object will be set
344 # to an associative array in which parameter names are keys
345 # and the values are stored as lists
346 # If a keyword list is found, this method creates a bogus
347 # parameter list with the single parameter 'keywords'.
349 sub init {
350 my($self,$initializer) = @_;
351 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
352 local($/) = "\n";
354 # if we get called more than once, we want to initialize
355 # ourselves from the original query (which may be gone
356 # if it was read from STDIN originally.)
357 if (defined(@QUERY_PARAM) && !defined($initializer)) {
358 foreach (@QUERY_PARAM) {
359 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
361 $self->charset($QUERY_CHARSET);
362 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
363 return;
366 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
367 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
369 $fh = to_filehandle($initializer) if $initializer;
371 # set charset to the safe ISO-8859-1
372 $self->charset('ISO-8859-1');
374 METHOD: {
376 # avoid unreasonably large postings
377 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
378 $self->cgi_error("413 Request entity too large");
379 last METHOD;
382 # Process multipart postings, but only if the initializer is
383 # not defined.
384 if ($meth eq 'POST'
385 && defined($ENV{'CONTENT_TYPE'})
386 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
387 && !defined($initializer)
389 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
390 $self->read_multipart($boundary,$content_length);
391 last METHOD;
394 # If initializer is defined, then read parameters
395 # from it.
396 if (defined($initializer)) {
397 if (UNIVERSAL::isa($initializer,'CGI')) {
398 $query_string = $initializer->query_string;
399 last METHOD;
401 if (ref($initializer) && ref($initializer) eq 'HASH') {
402 foreach (keys %$initializer) {
403 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
405 last METHOD;
408 if (defined($fh) && ($fh ne '')) {
409 while (<$fh>) {
410 chomp;
411 last if /^=/;
412 push(@lines,$_);
414 # massage back into standard format
415 if ("@lines" =~ /=/) {
416 $query_string=join("&",@lines);
417 } else {
418 $query_string=join("+",@lines);
420 last METHOD;
423 # last chance -- treat it as a string
424 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
425 $query_string = $initializer;
427 last METHOD;
430 # If method is GET or HEAD, fetch the query from
431 # the environment.
432 if ($meth=~/^(GET|HEAD)$/) {
433 if ($MOD_PERL) {
434 $query_string = Apache->request->args;
435 } else {
436 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
437 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
439 last METHOD;
442 if ($meth eq 'POST') {
443 $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
444 if $content_length > 0;
445 # Some people want to have their cake and eat it too!
446 # Uncomment this line to have the contents of the query string
447 # APPENDED to the POST data.
448 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
449 last METHOD;
452 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
453 # Check the command line and then the standard input for data.
454 # We use the shellwords package in order to behave the way that
455 # UN*X programmers expect.
456 $query_string = read_from_cmdline() if $DEBUG;
459 # We now have the query string in hand. We do slightly
460 # different things for keyword lists and parameter lists.
461 if (defined $query_string && length $query_string) {
462 if ($query_string =~ /[&=;]/) {
463 $self->parse_params($query_string);
464 } else {
465 $self->add_parameter('keywords');
466 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
470 # Special case. Erase everything if there is a field named
471 # .defaults.
472 if ($self->param('.defaults')) {
473 undef %{$self};
476 # Associative array containing our defined fieldnames
477 $self->{'.fieldnames'} = {};
478 foreach ($self->param('.cgifields')) {
479 $self->{'.fieldnames'}->{$_}++;
482 # Clear out our default submission button flag if present
483 $self->delete('.submit');
484 $self->delete('.cgifields');
486 $self->save_request unless $initializer;
489 # FUNCTIONS TO OVERRIDE:
490 # Turn a string into a filehandle
491 sub to_filehandle {
492 my $thingy = shift;
493 return undef unless $thingy;
494 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
495 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
496 if (!ref($thingy)) {
497 my $caller = 1;
498 while (my $package = caller($caller++)) {
499 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
500 return $tmp if defined(fileno($tmp));
503 return undef;
506 # send output to the browser
507 sub put {
508 my($self,@p) = self_or_default(@_);
509 $self->print(@p);
512 # print to standard output (for overriding in mod_perl)
513 sub print {
514 shift;
515 CORE::print(@_);
518 # get/set last cgi_error
519 sub cgi_error {
520 my ($self,$err) = self_or_default(@_);
521 $self->{'.cgi_error'} = $err if defined $err;
522 return $self->{'.cgi_error'};
525 sub save_request {
526 my($self) = @_;
527 # We're going to play with the package globals now so that if we get called
528 # again, we initialize ourselves in exactly the same way. This allows
529 # us to have several of these objects.
530 @QUERY_PARAM = $self->param; # save list of parameters
531 foreach (@QUERY_PARAM) {
532 next unless defined $_;
533 $QUERY_PARAM{$_}=$self->{$_};
535 $QUERY_CHARSET = $self->charset;
536 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
539 sub parse_params {
540 my($self,$tosplit) = @_;
541 my(@pairs) = split(/[&;]/,$tosplit);
542 my($param,$value);
543 foreach (@pairs) {
544 ($param,$value) = split('=',$_,2);
545 $value = '' unless defined $value;
546 $param = unescape($param);
547 $value = unescape($value);
548 $self->add_parameter($param);
549 push (@{$self->{$param}},$value);
553 sub add_parameter {
554 my($self,$param)=@_;
555 return unless defined $param;
556 push (@{$self->{'.parameters'}},$param)
557 unless defined($self->{$param});
560 sub all_parameters {
561 my $self = shift;
562 return () unless defined($self) && $self->{'.parameters'};
563 return () unless @{$self->{'.parameters'}};
564 return @{$self->{'.parameters'}};
567 # put a filehandle into binary mode (DOS)
568 sub binmode {
569 CORE::binmode($_[1]);
572 sub _make_tag_func {
573 my ($self,$tagname) = @_;
574 my $func = qq(
575 sub $tagname {
576 shift if \$_[0] &&
577 (ref(\$_[0]) &&
578 (substr(ref(\$_[0]),0,3) eq 'CGI' ||
579 UNIVERSAL::isa(\$_[0],'CGI')));
580 my(\$attr) = '';
581 if (ref(\$_[0]) && ref(\$_[0]) eq 'HASH') {
582 my(\@attr) = make_attributes(shift()||undef,1);
583 \$attr = " \@attr" if \@attr;
586 if ($tagname=~/start_(\w+)/i) {
587 $func .= qq! return "<\L$1\E\$attr>";} !;
588 } elsif ($tagname=~/end_(\w+)/i) {
589 $func .= qq! return "<\L/$1\E>"; } !;
590 } else {
591 $func .= qq#
592 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@_;
593 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
594 my \@result = map { "\$tag\$_\$untag" }
595 (ref(\$_[0]) eq 'ARRAY') ? \@{\$_[0]} : "\@_";
596 return "\@result";
599 return $func;
602 sub AUTOLOAD {
603 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
604 my $func = &_compile;
605 goto &$func;
608 sub _compile {
609 my($func) = $AUTOLOAD;
610 my($pack,$func_name);
612 local($1,$2); # this fixes an obscure variable suicide problem.
613 $func=~/(.+)::([^:]+)$/;
614 ($pack,$func_name) = ($1,$2);
615 $pack=~s/::SUPER$//; # fix another obscure problem
616 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
617 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
619 my($sub) = \%{"$pack\:\:SUBS"};
620 unless (%$sub) {
621 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
622 eval "package $pack; $$auto";
623 croak("$AUTOLOAD: $@") if $@;
624 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
626 my($code) = $sub->{$func_name};
628 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
629 if (!$code) {
630 (my $base = $func_name) =~ s/^(start_|end_)//i;
631 if ($EXPORT{':any'} ||
632 $EXPORT{'-any'} ||
633 $EXPORT{$base} ||
634 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
635 && $EXPORT_OK{$base}) {
636 $code = $CGI::DefaultClass->_make_tag_func($func_name);
639 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
640 eval "package $pack; $code";
641 if ($@) {
642 $@ =~ s/ at .*\n//;
643 croak("$AUTOLOAD: $@");
646 CORE::delete($sub->{$func_name}); #free storage
647 return "$pack\:\:$func_name";
650 sub _reset_globals { initialize_globals(); }
652 sub _setup_symbols {
653 my $self = shift;
654 my $compile = 0;
655 foreach (@_) {
656 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
657 $NPH++, next if /^[:-]nph$/;
658 $NOSTICKY++, next if /^[:-]nosticky$/;
659 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
660 $DEBUG=2, next if /^[:-][Dd]ebug$/;
661 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
662 $XHTML++, next if /^[:-]xhtml$/;
663 $XHTML=0, next if /^[:-]no_?xhtml$/;
664 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
665 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
666 $EXPORT{$_}++, next if /^[:-]any$/;
667 $compile++, next if /^[:-]compile$/;
669 # This is probably extremely evil code -- to be deleted some day.
670 if (/^[-]autoload$/) {
671 my($pkg) = caller(1);
672 *{"${pkg}::AUTOLOAD"} = sub {
673 my($routine) = $AUTOLOAD;
674 $routine =~ s/^.*::/CGI::/;
675 &$routine;
677 next;
680 foreach (&expand_tags($_)) {
681 tr/a-zA-Z0-9_//cd; # don't allow weird function names
682 $EXPORT{$_}++;
685 _compile_all(keys %EXPORT) if $compile;
688 sub charset {
689 my ($self,$charset) = self_or_default(@_);
690 $self->{'.charset'} = $charset if defined $charset;
691 $self->{'.charset'};
694 ###############################################################################
695 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
696 ###############################################################################
697 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
698 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
700 %SUBS = (
702 'URL_ENCODED'=> <<'END_OF_FUNC',
703 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
704 END_OF_FUNC
706 'MULTIPART' => <<'END_OF_FUNC',
707 sub MULTIPART { 'multipart/form-data'; }
708 END_OF_FUNC
710 'SERVER_PUSH' => <<'END_OF_FUNC',
711 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
712 END_OF_FUNC
714 'new_MultipartBuffer' => <<'END_OF_FUNC',
715 # Create a new multipart buffer
716 sub new_MultipartBuffer {
717 my($self,$boundary,$length,$filehandle) = @_;
718 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
720 END_OF_FUNC
722 'read_from_client' => <<'END_OF_FUNC',
723 # Read data from a file handle
724 sub read_from_client {
725 my($self, $fh, $buff, $len, $offset) = @_;
726 local $^W=0; # prevent a warning
727 return undef unless defined($fh);
728 return read($fh, $$buff, $len, $offset);
730 END_OF_FUNC
732 'delete' => <<'END_OF_FUNC',
733 #### Method: delete
734 # Deletes the named parameter entirely.
735 ####
736 sub delete {
737 my($self,@p) = self_or_default(@_);
738 my($name) = rearrange([NAME],@p);
739 CORE::delete $self->{$name};
740 CORE::delete $self->{'.fieldnames'}->{$name};
741 @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
742 return wantarray ? () : undef;
744 END_OF_FUNC
746 #### Method: import_names
747 # Import all parameters into the given namespace.
748 # Assumes namespace 'Q' if not specified
749 ####
750 'import_names' => <<'END_OF_FUNC',
751 sub import_names {
752 my($self,$namespace,$delete) = self_or_default(@_);
753 $namespace = 'Q' unless defined($namespace);
754 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
755 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
756 # can anyone find an easier way to do this?
757 foreach (keys %{"${namespace}::"}) {
758 local *symbol = "${namespace}::${_}";
759 undef $symbol;
760 undef @symbol;
761 undef %symbol;
764 my($param,@value,$var);
765 foreach $param ($self->param) {
766 # protect against silly names
767 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
768 $var =~ s/^(?=\d)/_/;
769 local *symbol = "${namespace}::$var";
770 @value = $self->param($param);
771 @symbol = @value;
772 $symbol = $value[0];
775 END_OF_FUNC
777 #### Method: keywords
778 # Keywords acts a bit differently. Calling it in a list context
779 # returns the list of keywords.
780 # Calling it in a scalar context gives you the size of the list.
781 ####
782 'keywords' => <<'END_OF_FUNC',
783 sub keywords {
784 my($self,@values) = self_or_default(@_);
785 # If values is provided, then we set it.
786 $self->{'keywords'}=[@values] if @values;
787 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
788 @result;
790 END_OF_FUNC
792 # These are some tie() interfaces for compatibility
793 # with Steve Brenner's cgi-lib.pl routines
794 'Vars' => <<'END_OF_FUNC',
795 sub Vars {
796 my $q = shift;
797 my %in;
798 tie(%in,CGI,$q);
799 return %in if wantarray;
800 return \%in;
802 END_OF_FUNC
804 # These are some tie() interfaces for compatibility
805 # with Steve Brenner's cgi-lib.pl routines
806 'ReadParse' => <<'END_OF_FUNC',
807 sub ReadParse {
808 local(*in);
809 if (@_) {
810 *in = $_[0];
811 } else {
812 my $pkg = caller();
813 *in=*{"${pkg}::in"};
815 tie(%in,CGI);
816 return scalar(keys %in);
818 END_OF_FUNC
820 'PrintHeader' => <<'END_OF_FUNC',
821 sub PrintHeader {
822 my($self) = self_or_default(@_);
823 return $self->header();
825 END_OF_FUNC
827 'HtmlTop' => <<'END_OF_FUNC',
828 sub HtmlTop {
829 my($self,@p) = self_or_default(@_);
830 return $self->start_html(@p);
832 END_OF_FUNC
834 'HtmlBot' => <<'END_OF_FUNC',
835 sub HtmlBot {
836 my($self,@p) = self_or_default(@_);
837 return $self->end_html(@p);
839 END_OF_FUNC
841 'SplitParam' => <<'END_OF_FUNC',
842 sub SplitParam {
843 my ($param) = @_;
844 my (@params) = split ("\0", $param);
845 return (wantarray ? @params : $params[0]);
847 END_OF_FUNC
849 'MethGet' => <<'END_OF_FUNC',
850 sub MethGet {
851 return request_method() eq 'GET';
853 END_OF_FUNC
855 'MethPost' => <<'END_OF_FUNC',
856 sub MethPost {
857 return request_method() eq 'POST';
859 END_OF_FUNC
861 'TIEHASH' => <<'END_OF_FUNC',
862 sub TIEHASH {
863 return $_[1] if defined $_[1];
864 return $Q ||= new shift;
866 END_OF_FUNC
868 'STORE' => <<'END_OF_FUNC',
869 sub STORE {
870 my $self = shift;
871 my $tag = shift;
872 my $vals = shift;
873 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
874 $self->param(-name=>$tag,-value=>\@vals);
876 END_OF_FUNC
878 'FETCH' => <<'END_OF_FUNC',
879 sub FETCH {
880 return $_[0] if $_[1] eq 'CGI';
881 return undef unless defined $_[0]->param($_[1]);
882 return join("\0",$_[0]->param($_[1]));
884 END_OF_FUNC
886 'FIRSTKEY' => <<'END_OF_FUNC',
887 sub FIRSTKEY {
888 $_[0]->{'.iterator'}=0;
889 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
891 END_OF_FUNC
893 'NEXTKEY' => <<'END_OF_FUNC',
894 sub NEXTKEY {
895 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
897 END_OF_FUNC
899 'EXISTS' => <<'END_OF_FUNC',
900 sub EXISTS {
901 exists $_[0]->{$_[1]};
903 END_OF_FUNC
905 'DELETE' => <<'END_OF_FUNC',
906 sub DELETE {
907 $_[0]->delete($_[1]);
909 END_OF_FUNC
911 'CLEAR' => <<'END_OF_FUNC',
912 sub CLEAR {
913 %{$_[0]}=();
915 ####
916 END_OF_FUNC
918 ####
919 # Append a new value to an existing query
920 ####
921 'append' => <<'EOF',
922 sub append {
923 my($self,@p) = @_;
924 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
925 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
926 if (@values) {
927 $self->add_parameter($name);
928 push(@{$self->{$name}},@values);
930 return $self->param($name);
934 #### Method: delete_all
935 # Delete all parameters
936 ####
937 'delete_all' => <<'EOF',
938 sub delete_all {
939 my($self) = self_or_default(@_);
940 undef %{$self};
944 'Delete' => <<'EOF',
945 sub Delete {
946 my($self,@p) = self_or_default(@_);
947 $self->delete(@p);
951 'Delete_all' => <<'EOF',
952 sub Delete_all {
953 my($self,@p) = self_or_default(@_);
954 $self->delete_all(@p);
958 #### Method: autoescape
959 # If you want to turn off the autoescaping features,
960 # call this method with undef as the argument
961 'autoEscape' => <<'END_OF_FUNC',
962 sub autoEscape {
963 my($self,$escape) = self_or_default(@_);
964 $self->{'dontescape'}=!$escape;
966 END_OF_FUNC
969 #### Method: version
970 # Return the current version
971 ####
972 'version' => <<'END_OF_FUNC',
973 sub version {
974 return $VERSION;
976 END_OF_FUNC
978 #### Method: url_param
979 # Return a parameter in the QUERY_STRING, regardless of
980 # whether this was a POST or a GET
981 ####
982 'url_param' => <<'END_OF_FUNC',
983 sub url_param {
984 my ($self,@p) = self_or_default(@_);
985 my $name = shift(@p);
986 return undef unless exists($ENV{QUERY_STRING});
987 unless (exists($self->{'.url_param'})) {
988 $self->{'.url_param'}={}; # empty hash
989 if ($ENV{QUERY_STRING} =~ /=/) {
990 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
991 my($param,$value);
992 foreach (@pairs) {
993 ($param,$value) = split('=',$_,2);
994 $param = unescape($param);
995 $value = unescape($value);
996 push(@{$self->{'.url_param'}->{$param}},$value);
998 } else {
999 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1002 return keys %{$self->{'.url_param'}} unless defined($name);
1003 return () unless $self->{'.url_param'}->{$name};
1004 return wantarray ? @{$self->{'.url_param'}->{$name}}
1005 : $self->{'.url_param'}->{$name}->[0];
1007 END_OF_FUNC
1009 #### Method: Dump
1010 # Returns a string in which all the known parameter/value
1011 # pairs are represented as nested lists, mainly for the purposes
1012 # of debugging.
1013 ####
1014 'Dump' => <<'END_OF_FUNC',
1015 sub Dump {
1016 my($self) = self_or_default(@_);
1017 my($param,$value,@result);
1018 return '<UL></UL>' unless $self->param;
1019 push(@result,"<UL>");
1020 foreach $param ($self->param) {
1021 my($name)=$self->escapeHTML($param);
1022 push(@result,"<LI><STRONG>$param</STRONG>");
1023 push(@result,"<UL>");
1024 foreach $value ($self->param($param)) {
1025 $value = $self->escapeHTML($value);
1026 $value =~ s/\n/<BR>\n/g;
1027 push(@result,"<LI>$value");
1029 push(@result,"</UL>");
1031 push(@result,"</UL>\n");
1032 return join("\n",@result);
1034 END_OF_FUNC
1036 #### Method as_string
1038 # synonym for "dump"
1039 ####
1040 'as_string' => <<'END_OF_FUNC',
1041 sub as_string {
1042 &Dump(@_);
1044 END_OF_FUNC
1046 #### Method: save
1047 # Write values out to a filehandle in such a way that they can
1048 # be reinitialized by the filehandle form of the new() method
1049 ####
1050 'save' => <<'END_OF_FUNC',
1051 sub save {
1052 my($self,$filehandle) = self_or_default(@_);
1053 $filehandle = to_filehandle($filehandle);
1054 my($param);
1055 local($,) = ''; # set print field separator back to a sane value
1056 local($\) = ''; # set output line separator to a sane value
1057 foreach $param ($self->param) {
1058 my($escaped_param) = escape($param);
1059 my($value);
1060 foreach $value ($self->param($param)) {
1061 print $filehandle "$escaped_param=",escape("$value"),"\n";
1064 foreach (keys %{$self->{'.fieldnames'}}) {
1065 print $filehandle ".cgifields=",escape("$_"),"\n";
1067 print $filehandle "=\n"; # end of record
1069 END_OF_FUNC
1072 #### Method: save_parameters
1073 # An alias for save() that is a better name for exportation.
1074 # Only intended to be used with the function (non-OO) interface.
1075 ####
1076 'save_parameters' => <<'END_OF_FUNC',
1077 sub save_parameters {
1078 my $fh = shift;
1079 return save(to_filehandle($fh));
1081 END_OF_FUNC
1083 #### Method: restore_parameters
1084 # A way to restore CGI parameters from an initializer.
1085 # Only intended to be used with the function (non-OO) interface.
1086 ####
1087 'restore_parameters' => <<'END_OF_FUNC',
1088 sub restore_parameters {
1089 $Q = $CGI::DefaultClass->new(@_);
1091 END_OF_FUNC
1093 #### Method: multipart_init
1094 # Return a Content-Type: style header for server-push
1095 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1097 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1098 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1099 ####
1100 'multipart_init' => <<'END_OF_FUNC',
1101 sub multipart_init {
1102 my($self,@p) = self_or_default(@_);
1103 my($boundary,@other) = rearrange([BOUNDARY],@p);
1104 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1105 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1106 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1107 $type = SERVER_PUSH($boundary);
1108 return $self->header(
1109 -nph => 1,
1110 -type => $type,
1111 (map { split "=", $_, 2 } @other),
1112 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1114 END_OF_FUNC
1117 #### Method: multipart_start
1118 # Return a Content-Type: style header for server-push, start of section
1120 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1121 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1122 ####
1123 'multipart_start' => <<'END_OF_FUNC',
1124 sub multipart_start {
1125 my(@header);
1126 my($self,@p) = self_or_default(@_);
1127 my($type,@other) = rearrange([TYPE],@p);
1128 $type = $type || 'text/html';
1129 push(@header,"Content-Type: $type");
1131 # rearrange() was designed for the HTML portion, so we
1132 # need to fix it up a little.
1133 foreach (@other) {
1134 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1135 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1137 push(@header,@other);
1138 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1139 return $header;
1141 END_OF_FUNC
1144 #### Method: multipart_end
1145 # Return a MIME boundary separator for server-push, end of section
1147 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1148 # contribution
1149 ####
1150 'multipart_end' => <<'END_OF_FUNC',
1151 sub multipart_end {
1152 my($self,@p) = self_or_default(@_);
1153 return $self->{'separator'};
1155 END_OF_FUNC
1158 #### Method: multipart_final
1159 # Return a MIME boundary separator for server-push, end of all sections
1161 # Contributed by Andrew Benham (adsb@bigfoot.com)
1162 ####
1163 'multipart_final' => <<'END_OF_FUNC',
1164 sub multipart_final {
1165 my($self,@p) = self_or_default(@_);
1166 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1168 END_OF_FUNC
1171 #### Method: header
1172 # Return a Content-Type: style header
1174 ####
1175 'header' => <<'END_OF_FUNC',
1176 sub header {
1177 my($self,@p) = self_or_default(@_);
1178 my(@header);
1180 return undef if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1182 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,@other) =
1183 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1184 'STATUS',['COOKIE','COOKIES'],'TARGET',
1185 'EXPIRES','NPH','CHARSET',
1186 'ATTACHMENT'],@p);
1188 $nph ||= $NPH;
1189 if (defined $charset) {
1190 $self->charset($charset);
1191 } else {
1192 $charset = $self->charset;
1195 # rearrange() was designed for the HTML portion, so we
1196 # need to fix it up a little.
1197 foreach (@other) {
1198 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1199 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1202 $type ||= 'text/html' unless defined($type);
1203 $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/;
1205 # Maybe future compatibility. Maybe not.
1206 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1207 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1208 push(@header,"Server: " . &server_software()) if $nph;
1210 push(@header,"Status: $status") if $status;
1211 push(@header,"Window-Target: $target") if $target;
1212 # push all the cookies -- there may be several
1213 if ($cookie) {
1214 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1215 foreach (@cookie) {
1216 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1217 push(@header,"Set-Cookie: $cs") if $cs ne '';
1220 # if the user indicates an expiration time, then we need
1221 # both an Expires and a Date header (so that the browser is
1222 # uses OUR clock)
1223 push(@header,"Expires: " . expires($expires,'http'))
1224 if $expires;
1225 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1226 push(@header,"Pragma: no-cache") if $self->cache();
1227 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1228 push(@header,@other);
1229 push(@header,"Content-Type: $type") if $type ne '';
1231 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1232 if ($MOD_PERL and not $nph) {
1233 my $r = Apache->request;
1234 $r->send_cgi_header($header);
1235 return '';
1237 return $header;
1239 END_OF_FUNC
1242 #### Method: cache
1243 # Control whether header() will produce the no-cache
1244 # Pragma directive.
1245 ####
1246 'cache' => <<'END_OF_FUNC',
1247 sub cache {
1248 my($self,$new_value) = self_or_default(@_);
1249 $new_value = '' unless $new_value;
1250 if ($new_value ne '') {
1251 $self->{'cache'} = $new_value;
1253 return $self->{'cache'};
1255 END_OF_FUNC
1258 #### Method: redirect
1259 # Return a Location: style header
1261 ####
1262 'redirect' => <<'END_OF_FUNC',
1263 sub redirect {
1264 my($self,@p) = self_or_default(@_);
1265 my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,COOKIE,NPH],@p);
1266 $url ||= $self->self_url;
1267 my(@o);
1268 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1269 unshift(@o,
1270 '-Status'=>'302 Moved',
1271 '-Location'=>$url,
1272 '-nph'=>$nph);
1273 unshift(@o,'-Target'=>$target) if $target;
1274 unshift(@o,'-Cookie'=>$cookie) if $cookie;
1275 unshift(@o,'-Type'=>'');
1276 return $self->header(@o);
1278 END_OF_FUNC
1281 #### Method: start_html
1282 # Canned HTML header
1284 # Parameters:
1285 # $title -> (optional) The title for this HTML document (-title)
1286 # $author -> (optional) e-mail address of the author (-author)
1287 # $base -> (optional) if set to true, will enter the BASE address of this document
1288 # for resolving relative references (-base)
1289 # $xbase -> (optional) alternative base at some remote location (-xbase)
1290 # $target -> (optional) target window to load all links into (-target)
1291 # $script -> (option) Javascript code (-script)
1292 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1293 # $meta -> (optional) Meta information tags
1294 # $head -> (optional) any other elements you'd like to incorporate into the <HEAD> tag
1295 # (a scalar or array ref)
1296 # $style -> (optional) reference to an external style sheet
1297 # @other -> (optional) any other named parameters you'd like to incorporate into
1298 # the <BODY> tag.
1299 ####
1300 'start_html' => <<'END_OF_FUNC',
1301 sub start_html {
1302 my($self,@p) = &self_or_default(@_);
1303 my($title,$author,$base,$xbase,$script,$noscript,$target,$meta,$head,$style,$dtd,$lang,@other) =
1304 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG],@p);
1306 # strangely enough, the title needs to be escaped as HTML
1307 # while the author needs to be escaped as a URL
1308 $title = $self->escapeHTML($title || 'Untitled Document');
1309 $author = $self->escape($author);
1310 $lang ||= 'en-US';
1311 my(@result,$xml_dtd);
1312 if ($dtd) {
1313 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1314 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1315 } else {
1316 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1318 } else {
1319 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1322 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1323 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1324 push @result,q(<?xml version="1.0" encoding="utf-8"?>) if $xml_dtd;
1326 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1327 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t"$dtd->[1]">));
1328 } else {
1329 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1331 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang"><head><title>$title</title>)
1332 : qq(<html lang="$lang"><head><title>$title</title>));
1333 if (defined $author) {
1334 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1335 : "<link rev=\"made\" href=\"mailto:$author\">");
1338 if ($base || $xbase || $target) {
1339 my $href = $xbase || $self->url('-path'=>1);
1340 my $t = $target ? qq/ target="$target"/ : '';
1341 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1344 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1345 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1346 : qq(<meta name="$_" content="$meta->{$_}">)); }
1349 push(@result,ref($head) ? @$head : $head) if $head;
1351 # handle the infrequently-used -style and -script parameters
1352 push(@result,$self->_style($style)) if defined $style;
1353 push(@result,$self->_script($script)) if defined $script;
1355 # handle -noscript parameter
1356 push(@result,<<END) if $noscript;
1357 <noscript>
1358 $noscript
1359 </noscript>
1362 my($other) = @other ? " @other" : '';
1363 push(@result,"</head><body$other>");
1364 return join("\n",@result);
1366 END_OF_FUNC
1368 ### Method: _style
1369 # internal method for generating a CSS style section
1370 ####
1371 '_style' => <<'END_OF_FUNC',
1372 sub _style {
1373 my ($self,$style) = @_;
1374 my (@result);
1375 my $type = 'text/css';
1377 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1378 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1380 if (ref($style)) {
1381 my($src,$code,$stype,@other) =
1382 rearrange([SRC,CODE,TYPE],
1383 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1384 ref($style) eq 'ARRAY' ? @$style : %$style);
1385 $type = $stype if $stype;
1386 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1387 { # If it is, push a LINK tag for each one.
1388 foreach $src (@$src)
1390 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1391 : qq(<link rel="stylesheet" type="$type" href="$src">/)) if $src;
1394 else
1395 { # Otherwise, push the single -src, if it exists.
1396 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1397 : qq(<link rel="stylesheet" type="$type" href="$src">)
1398 ) if $src;
1400 push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
1401 } else {
1402 push(@result,style({'type'=>$type},"$cdata_start\n$style\n$cdata_end"));
1404 @result;
1406 END_OF_FUNC
1408 '_script' => <<'END_OF_FUNC',
1409 sub _script {
1410 my ($self,$script) = @_;
1411 my (@result);
1413 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1414 foreach $script (@scripts) {
1415 my($src,$code,$language);
1416 if (ref($script)) { # script is a hash
1417 ($src,$code,$language, $type) =
1418 rearrange([SRC,CODE,LANGUAGE,TYPE],
1419 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1420 ref($script) eq 'ARRAY' ? @$script : %$script);
1421 # User may not have specified language
1422 $language ||= 'JavaScript';
1423 unless (defined $type) {
1424 $type = lc $language;
1425 # strip '1.2' from 'javascript1.2'
1426 $type =~ s/^(\D+).*$/text\/$1/;
1428 } else {
1429 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1432 my $comment = '//'; # javascript by default
1433 $comment = '#' if $type=~/perl|tcl/i;
1434 $comment = "'" if $type=~/vbscript/i;
1436 my $cdata_start = "\n<!-- Hide script\n";
1437 $cdata_start .= "$comment<![CDATA[\n" if $XHTML;
1438 my $cdata_end = $XHTML ? "\n$comment]]>" : $comment;
1439 $cdata_end .= " End script hiding -->\n";
1441 my(@satts);
1442 push(@satts,'src'=>$src) if $src;
1443 push(@satts,'language'=>$language);
1444 push(@satts,'type'=>$type);
1445 $code = "$cdata_start$code$cdata_end" if defined $code;
1446 push(@result,script({@satts},$code || ''));
1448 @result;
1450 END_OF_FUNC
1452 #### Method: end_html
1453 # End an HTML document.
1454 # Trivial method for completeness. Just returns "</BODY>"
1455 ####
1456 'end_html' => <<'END_OF_FUNC',
1457 sub end_html {
1458 return "</body></html>";
1460 END_OF_FUNC
1463 ################################
1464 # METHODS USED IN BUILDING FORMS
1465 ################################
1467 #### Method: isindex
1468 # Just prints out the isindex tag.
1469 # Parameters:
1470 # $action -> optional URL of script to run
1471 # Returns:
1472 # A string containing a <ISINDEX> tag
1473 'isindex' => <<'END_OF_FUNC',
1474 sub isindex {
1475 my($self,@p) = self_or_default(@_);
1476 my($action,@other) = rearrange([ACTION],@p);
1477 $action = qq/action="$action"/ if $action;
1478 my($other) = @other ? " @other" : '';
1479 return $XHTML ? "<isindex $action$other />" : "<isindex $action$other>";
1481 END_OF_FUNC
1484 #### Method: startform
1485 # Start a form
1486 # Parameters:
1487 # $method -> optional submission method to use (GET or POST)
1488 # $action -> optional URL of script to run
1489 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1490 'startform' => <<'END_OF_FUNC',
1491 sub startform {
1492 my($self,@p) = self_or_default(@_);
1494 my($method,$action,$enctype,@other) =
1495 rearrange([METHOD,ACTION,ENCTYPE],@p);
1497 $method = lc($method) || 'post';
1498 $enctype = $enctype || &URL_ENCODED;
1499 unless (defined $action) {
1500 $action = $self->url(-absolute=>1,-path=>1);
1501 $action .= "?$ENV{QUERY_STRING}" if $ENV{QUERY_STRING};
1503 $action = qq(action="$action");
1504 my($other) = @other ? " @other" : '';
1505 $self->{'.parametersToAdd'}={};
1506 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1508 END_OF_FUNC
1511 #### Method: start_form
1512 # synonym for startform
1513 'start_form' => <<'END_OF_FUNC',
1514 sub start_form {
1515 &startform;
1517 END_OF_FUNC
1519 'end_multipart_form' => <<'END_OF_FUNC',
1520 sub end_multipart_form {
1521 &endform;
1523 END_OF_FUNC
1525 #### Method: start_multipart_form
1526 # synonym for startform
1527 'start_multipart_form' => <<'END_OF_FUNC',
1528 sub start_multipart_form {
1529 my($self,@p) = self_or_default(@_);
1530 if (defined($param[0]) && substr($param[0],0,1) eq '-') {
1531 my(%p) = @p;
1532 $p{'-enctype'}=&MULTIPART;
1533 return $self->startform(%p);
1534 } else {
1535 my($method,$action,@other) =
1536 rearrange([METHOD,ACTION],@p);
1537 return $self->startform($method,$action,&MULTIPART,@other);
1540 END_OF_FUNC
1543 #### Method: endform
1544 # End a form
1545 'endform' => <<'END_OF_FUNC',
1546 sub endform {
1547 my($self,@p) = self_or_default(@_);
1548 if ( $NOSTICKY ) {
1549 return wantarray ? ("</form>") : "\n</form>";
1550 } else {
1551 return wantarray ? ($self->get_fields,"</form>") :
1552 $self->get_fields ."\n</form>";
1555 END_OF_FUNC
1558 #### Method: end_form
1559 # synonym for endform
1560 'end_form' => <<'END_OF_FUNC',
1561 sub end_form {
1562 &endform;
1564 END_OF_FUNC
1567 '_textfield' => <<'END_OF_FUNC',
1568 sub _textfield {
1569 my($self,$tag,@p) = self_or_default(@_);
1570 my($name,$default,$size,$maxlength,$override,@other) =
1571 rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1573 my $current = $override ? $default :
1574 (defined($self->param($name)) ? $self->param($name) : $default);
1576 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1577 $name = defined($name) ? $self->escapeHTML($name) : '';
1578 my($s) = defined($size) ? qq/ size="$size"/ : '';
1579 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1580 my($other) = @other ? " @other" : '';
1581 # this entered at cristy's request to fix problems with file upload fields
1582 # and WebTV -- not sure it won't break stuff
1583 my($value) = $current ne '' ? qq(value="$current") : '';
1584 return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />)
1585 : qq/<input type="$tag" name="$name" $value$s$m$other>/;
1587 END_OF_FUNC
1589 #### Method: textfield
1590 # Parameters:
1591 # $name -> Name of the text field
1592 # $default -> Optional default value of the field if not
1593 # already defined.
1594 # $size -> Optional width of field in characaters.
1595 # $maxlength -> Optional maximum number of characters.
1596 # Returns:
1597 # A string containing a <INPUT TYPE="text"> field
1599 'textfield' => <<'END_OF_FUNC',
1600 sub textfield {
1601 my($self,@p) = self_or_default(@_);
1602 $self->_textfield('text',@p);
1604 END_OF_FUNC
1607 #### Method: filefield
1608 # Parameters:
1609 # $name -> Name of the file upload field
1610 # $size -> Optional width of field in characaters.
1611 # $maxlength -> Optional maximum number of characters.
1612 # Returns:
1613 # A string containing a <INPUT TYPE="text"> field
1615 'filefield' => <<'END_OF_FUNC',
1616 sub filefield {
1617 my($self,@p) = self_or_default(@_);
1618 $self->_textfield('file',@p);
1620 END_OF_FUNC
1623 #### Method: password
1624 # Create a "secret password" entry field
1625 # Parameters:
1626 # $name -> Name of the field
1627 # $default -> Optional default value of the field if not
1628 # already defined.
1629 # $size -> Optional width of field in characters.
1630 # $maxlength -> Optional maximum characters that can be entered.
1631 # Returns:
1632 # A string containing a <INPUT TYPE="password"> field
1634 'password_field' => <<'END_OF_FUNC',
1635 sub password_field {
1636 my ($self,@p) = self_or_default(@_);
1637 $self->_textfield('password',@p);
1639 END_OF_FUNC
1641 #### Method: textarea
1642 # Parameters:
1643 # $name -> Name of the text field
1644 # $default -> Optional default value of the field if not
1645 # already defined.
1646 # $rows -> Optional number of rows in text area
1647 # $columns -> Optional number of columns in text area
1648 # Returns:
1649 # A string containing a <TEXTAREA></TEXTAREA> tag
1651 'textarea' => <<'END_OF_FUNC',
1652 sub textarea {
1653 my($self,@p) = self_or_default(@_);
1655 my($name,$default,$rows,$cols,$override,@other) =
1656 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1658 my($current)= $override ? $default :
1659 (defined($self->param($name)) ? $self->param($name) : $default);
1661 $name = defined($name) ? $self->escapeHTML($name) : '';
1662 $current = defined($current) ? $self->escapeHTML($current) : '';
1663 my($r) = $rows ? " rows=$rows" : '';
1664 my($c) = $cols ? " cols=$cols" : '';
1665 my($other) = @other ? " @other" : '';
1666 return qq{<textarea name="$name"$r$c$other>$current</textarea>};
1668 END_OF_FUNC
1671 #### Method: button
1672 # Create a javascript button.
1673 # Parameters:
1674 # $name -> (optional) Name for the button. (-name)
1675 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1676 # $onclick -> (optional) Text of the JavaScript to run when the button is
1677 # clicked.
1678 # Returns:
1679 # A string containing a <INPUT TYPE="button"> tag
1680 ####
1681 'button' => <<'END_OF_FUNC',
1682 sub button {
1683 my($self,@p) = self_or_default(@_);
1685 my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
1686 [ONCLICK,SCRIPT]],@p);
1688 $label=$self->escapeHTML($label);
1689 $value=$self->escapeHTML($value,1);
1690 $script=$self->escapeHTML($script);
1692 my($name) = '';
1693 $name = qq/ name="$label"/ if $label;
1694 $value = $value || $label;
1695 my($val) = '';
1696 $val = qq/ value="$value"/ if $value;
1697 $script = qq/ onclick="$script"/ if $script;
1698 my($other) = @other ? " @other" : '';
1699 return $XHTML ? qq(<input type="button"$name$val$script$other />)
1700 : qq/<input type="button"$name$val$script$other>/;
1702 END_OF_FUNC
1705 #### Method: submit
1706 # Create a "submit query" button.
1707 # Parameters:
1708 # $name -> (optional) Name for the button.
1709 # $value -> (optional) Value of the button when selected (also doubles as label).
1710 # $label -> (optional) Label printed on the button(also doubles as the value).
1711 # Returns:
1712 # A string containing a <INPUT TYPE="submit"> tag
1713 ####
1714 'submit' => <<'END_OF_FUNC',
1715 sub submit {
1716 my($self,@p) = self_or_default(@_);
1718 my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
1720 $label=$self->escapeHTML($label);
1721 $value=$self->escapeHTML($value,1);
1723 my($name) = ' name=".submit"' unless $NOSTICKY;
1724 $name = qq/ name="$label"/ if defined($label);
1725 $value = defined($value) ? $value : $label;
1726 my($val) = '';
1727 $val = qq/ value="$value"/ if defined($value);
1728 my($other) = @other ? " @other" : '';
1729 return $XHTML ? qq(<input type="submit"$name$val$other />)
1730 : qq/<input type="submit"$name$val$other>/;
1732 END_OF_FUNC
1735 #### Method: reset
1736 # Create a "reset" button.
1737 # Parameters:
1738 # $name -> (optional) Name for the button.
1739 # Returns:
1740 # A string containing a <INPUT TYPE="reset"> tag
1741 ####
1742 'reset' => <<'END_OF_FUNC',
1743 sub reset {
1744 my($self,@p) = self_or_default(@_);
1745 my($label,@other) = rearrange([NAME],@p);
1746 $label=$self->escapeHTML($label);
1747 my($value) = defined($label) ? qq/ value="$label"/ : '';
1748 my($other) = @other ? " @other" : '';
1749 return $XHTML ? qq(<input type="reset"$value$other />)
1750 : qq/<input type="reset"$value$other>/;
1752 END_OF_FUNC
1755 #### Method: defaults
1756 # Create a "defaults" button.
1757 # Parameters:
1758 # $name -> (optional) Name for the button.
1759 # Returns:
1760 # A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
1762 # Note: this button has a special meaning to the initialization script,
1763 # and tells it to ERASE the current query string so that your defaults
1764 # are used again!
1765 ####
1766 'defaults' => <<'END_OF_FUNC',
1767 sub defaults {
1768 my($self,@p) = self_or_default(@_);
1770 my($label,@other) = rearrange([[NAME,VALUE]],@p);
1772 $label=$self->escapeHTML($label,1);
1773 $label = $label || "Defaults";
1774 my($value) = qq/ value="$label"/;
1775 my($other) = @other ? " @other" : '';
1776 return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
1777 : qq/<input type="submit" NAME=".defaults"$value$other>/;
1779 END_OF_FUNC
1782 #### Method: comment
1783 # Create an HTML <!-- comment -->
1784 # Parameters: a string
1785 'comment' => <<'END_OF_FUNC',
1786 sub comment {
1787 my($self,@p) = self_or_CGI(@_);
1788 return "<!-- @p -->";
1790 END_OF_FUNC
1792 #### Method: checkbox
1793 # Create a checkbox that is not logically linked to any others.
1794 # The field value is "on" when the button is checked.
1795 # Parameters:
1796 # $name -> Name of the checkbox
1797 # $checked -> (optional) turned on by default if true
1798 # $value -> (optional) value of the checkbox, 'on' by default
1799 # $label -> (optional) a user-readable label printed next to the box.
1800 # Otherwise the checkbox name is used.
1801 # Returns:
1802 # A string containing a <INPUT TYPE="checkbox"> field
1803 ####
1804 'checkbox' => <<'END_OF_FUNC',
1805 sub checkbox {
1806 my($self,@p) = self_or_default(@_);
1808 my($name,$checked,$value,$label,$override,@other) =
1809 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1811 $value = defined $value ? $value : 'on';
1813 if (!$override && ($self->{'.fieldnames'}->{$name} ||
1814 defined $self->param($name))) {
1815 $checked = grep($_ eq $value,$self->param($name)) ? ' checked' : '';
1816 } else {
1817 $checked = $checked ? qq/ checked/ : '';
1819 my($the_label) = defined $label ? $label : $name;
1820 $name = $self->escapeHTML($name);
1821 $value = $self->escapeHTML($value,1);
1822 $the_label = $self->escapeHTML($the_label);
1823 my($other) = @other ? " @other" : '';
1824 $self->register_parameter($name);
1825 return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
1826 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
1828 END_OF_FUNC
1831 #### Method: checkbox_group
1832 # Create a list of logically-linked checkboxes.
1833 # Parameters:
1834 # $name -> Common name for all the check boxes
1835 # $values -> A pointer to a regular array containing the
1836 # values for each checkbox in the group.
1837 # $defaults -> (optional)
1838 # 1. If a pointer to a regular array of checkbox values,
1839 # then this will be used to decide which
1840 # checkboxes to turn on by default.
1841 # 2. If a scalar, will be assumed to hold the
1842 # value of a single checkbox in the group to turn on.
1843 # $linebreak -> (optional) Set to true to place linebreaks
1844 # between the buttons.
1845 # $labels -> (optional)
1846 # A pointer to an associative array of labels to print next to each checkbox
1847 # in the form $label{'value'}="Long explanatory label".
1848 # Otherwise the provided values are used as the labels.
1849 # Returns:
1850 # An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1851 ####
1852 'checkbox_group' => <<'END_OF_FUNC',
1853 sub checkbox_group {
1854 my($self,@p) = self_or_default(@_);
1856 my($name,$values,$defaults,$linebreak,$labels,$rows,$columns,
1857 $rowheaders,$colheaders,$override,$nolabels,@other) =
1858 rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1859 LINEBREAK,LABELS,ROWS,[COLUMNS,COLS],
1860 ROWHEADERS,COLHEADERS,
1861 [OVERRIDE,FORCE],NOLABELS],@p);
1863 my($checked,$break,$result,$label);
1865 my(%checked) = $self->previous_or_default($name,$defaults,$override);
1867 if ($linebreak) {
1868 $break = $XHTML ? "<br />" : "<br>";
1870 else {
1871 $break = '';
1873 $name=$self->escapeHTML($name);
1875 # Create the elements
1876 my(@elements,@values);
1878 @values = $self->_set_values_and_labels($values,\$labels,$name);
1880 my($other) = @other ? " @other" : '';
1881 foreach (@values) {
1882 $checked = $checked{$_} ? qq/ checked/ : '';
1883 $label = '';
1884 unless (defined($nolabels) && $nolabels) {
1885 $label = $_;
1886 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1887 $label = $self->escapeHTML($label);
1889 $_ = $self->escapeHTML($_,1);
1890 push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other />${label}${break})
1891 : qq/<input type="checkbox" name="$name" value="$_"$checked$other>${label}${break}/);
1893 $self->register_parameter($name);
1894 return wantarray ? @elements : join(' ',@elements)
1895 unless defined($columns) || defined($rows);
1896 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1898 END_OF_FUNC
1900 # Escape HTML -- used internally
1901 'escapeHTML' => <<'END_OF_FUNC',
1902 sub escapeHTML {
1903 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
1904 return undef unless defined($toencode);
1905 return $toencode if ref($self) && $self->{'dontescape'};
1906 $toencode =~ s{&}{&amp;}gso;
1907 $toencode =~ s{<}{&lt;}gso;
1908 $toencode =~ s{>}{&gt;}gso;
1909 $toencode =~ s{"}{&quot;}gso;
1910 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
1911 uc $self->{'.charset'} eq 'WINDOWS-1252';
1912 if ($latin) { # bug in some browsers
1913 $toencode =~ s{'}{&#39;}gso;
1914 $toencode =~ s{\x8b}{&#139;}gso;
1915 $toencode =~ s{\x9b}{&#155;}gso;
1916 if (defined $newlinestoo && $newlinestoo) {
1917 $toencode =~ s{\012}{&#10;}gso;
1918 $toencode =~ s{\015}{&#13;}gso;
1921 return $toencode;
1923 END_OF_FUNC
1925 # unescape HTML -- used internally
1926 'unescapeHTML' => <<'END_OF_FUNC',
1927 sub unescapeHTML {
1928 my ($self,$string) = CGI::self_or_default(@_);
1929 return undef unless defined($string);
1930 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
1931 : 1;
1932 # thanks to Randal Schwartz for the correct solution to this one
1933 $string=~ s[&(.*?);]{
1934 local $_ = $1;
1935 /^amp$/i ? "&" :
1936 /^quot$/i ? '"' :
1937 /^gt$/i ? ">" :
1938 /^lt$/i ? "<" :
1939 /^#(\d+)$/ && $latin ? chr($1) :
1940 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
1942 }gex;
1943 return $string;
1945 END_OF_FUNC
1947 # Internal procedure - don't use
1948 '_tableize' => <<'END_OF_FUNC',
1949 sub _tableize {
1950 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1951 $rowheaders = [] unless defined $rowheaders;
1952 $colheaders = [] unless defined $colheaders;
1953 my($result);
1955 if (defined($columns)) {
1956 $rows = int(0.99 + @elements/$columns) unless defined($rows);
1958 if (defined($rows)) {
1959 $columns = int(0.99 + @elements/$rows) unless defined($columns);
1962 # rearrange into a pretty table
1963 $result = "<table>";
1964 my($row,$column);
1965 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
1966 $result .= "<tr>" if @{$colheaders};
1967 foreach (@{$colheaders}) {
1968 $result .= "<th>$_</th>";
1970 for ($row=0;$row<$rows;$row++) {
1971 $result .= "<tr>";
1972 $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
1973 for ($column=0;$column<$columns;$column++) {
1974 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
1975 if defined($elements[$column*$rows + $row]);
1977 $result .= "</tr>";
1979 $result .= "</table>";
1980 return $result;
1982 END_OF_FUNC
1985 #### Method: radio_group
1986 # Create a list of logically-linked radio buttons.
1987 # Parameters:
1988 # $name -> Common name for all the buttons.
1989 # $values -> A pointer to a regular array containing the
1990 # values for each button in the group.
1991 # $default -> (optional) Value of the button to turn on by default. Pass '-'
1992 # to turn _nothing_ on.
1993 # $linebreak -> (optional) Set to true to place linebreaks
1994 # between the buttons.
1995 # $labels -> (optional)
1996 # A pointer to an associative array of labels to print next to each checkbox
1997 # in the form $label{'value'}="Long explanatory label".
1998 # Otherwise the provided values are used as the labels.
1999 # Returns:
2000 # An ARRAY containing a series of <INPUT TYPE="radio"> fields
2001 ####
2002 'radio_group' => <<'END_OF_FUNC',
2003 sub radio_group {
2004 my($self,@p) = self_or_default(@_);
2006 my($name,$values,$default,$linebreak,$labels,
2007 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
2008 rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,
2009 ROWS,[COLUMNS,COLS],
2010 ROWHEADERS,COLHEADERS,
2011 [OVERRIDE,FORCE],NOLABELS],@p);
2012 my($result,$checked);
2014 if (!$override && defined($self->param($name))) {
2015 $checked = $self->param($name);
2016 } else {
2017 $checked = $default;
2019 my(@elements,@values);
2020 @values = $self->_set_values_and_labels($values,\$labels,$name);
2022 # If no check array is specified, check the first by default
2023 $checked = $values[0] unless defined($checked) && $checked ne '';
2024 $name=$self->escapeHTML($name);
2026 my($other) = @other ? " @other" : '';
2027 foreach (@values) {
2028 my($checkit) = $checked eq $_ ? qq/ checked/ : '';
2029 my($break);
2030 if ($linebreak) {
2031 $break = $XHTML ? "<br />" : "<br>";
2033 else {
2034 $break = '';
2036 my($label)='';
2037 unless (defined($nolabels) && $nolabels) {
2038 $label = $_;
2039 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2040 $label = $self->escapeHTML($label,1);
2042 $_=$self->escapeHTML($_);
2043 push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other />${label}${break})
2044 : qq/<input type="radio" name="$name" value="$_"$checkit$other>${label}${break}/);
2046 $self->register_parameter($name);
2047 return wantarray ? @elements : join(' ',@elements)
2048 unless defined($columns) || defined($rows);
2049 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2051 END_OF_FUNC
2054 #### Method: popup_menu
2055 # Create a popup menu.
2056 # Parameters:
2057 # $name -> Name for all the menu
2058 # $values -> A pointer to a regular array containing the
2059 # text of each menu item.
2060 # $default -> (optional) Default item to display
2061 # $labels -> (optional)
2062 # A pointer to an associative array of labels to print next to each checkbox
2063 # in the form $label{'value'}="Long explanatory label".
2064 # Otherwise the provided values are used as the labels.
2065 # Returns:
2066 # A string containing the definition of a popup menu.
2067 ####
2068 'popup_menu' => <<'END_OF_FUNC',
2069 sub popup_menu {
2070 my($self,@p) = self_or_default(@_);
2072 my($name,$values,$default,$labels,$override,@other) =
2073 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
2074 my($result,$selected);
2076 if (!$override && defined($self->param($name))) {
2077 $selected = $self->param($name);
2078 } else {
2079 $selected = $default;
2081 $name=$self->escapeHTML($name);
2082 my($other) = @other ? " @other" : '';
2084 my(@values);
2085 @values = $self->_set_values_and_labels($values,\$labels,$name);
2087 $result = qq/<select name="$name"$other>\n/;
2088 foreach (@values) {
2089 my($selectit) = defined($selected) ? ($selected eq $_ ? qq/selected/ : '' ) : '';
2090 my($label) = $_;
2091 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2092 my($value) = $self->escapeHTML($_);
2093 $label=$self->escapeHTML($label,1);
2094 $result .= "<option $selectit value=\"$value\">$label</option>\n";
2097 $result .= "</select>\n";
2098 return $result;
2100 END_OF_FUNC
2103 #### Method: scrolling_list
2104 # Create a scrolling list.
2105 # Parameters:
2106 # $name -> name for the list
2107 # $values -> A pointer to a regular array containing the
2108 # values for each option line in the list.
2109 # $defaults -> (optional)
2110 # 1. If a pointer to a regular array of options,
2111 # then this will be used to decide which
2112 # lines to turn on by default.
2113 # 2. Otherwise holds the value of the single line to turn on.
2114 # $size -> (optional) Size of the list.
2115 # $multiple -> (optional) If set, allow multiple selections.
2116 # $labels -> (optional)
2117 # A pointer to an associative array of labels to print next to each checkbox
2118 # in the form $label{'value'}="Long explanatory label".
2119 # Otherwise the provided values are used as the labels.
2120 # Returns:
2121 # A string containing the definition of a scrolling list.
2122 ####
2123 'scrolling_list' => <<'END_OF_FUNC',
2124 sub scrolling_list {
2125 my($self,@p) = self_or_default(@_);
2126 my($name,$values,$defaults,$size,$multiple,$labels,$override,@other)
2127 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2128 SIZE,MULTIPLE,LABELS,[OVERRIDE,FORCE]],@p);
2130 my($result,@values);
2131 @values = $self->_set_values_and_labels($values,\$labels,$name);
2133 $size = $size || scalar(@values);
2135 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2136 my($is_multiple) = $multiple ? qq/ multiple/ : '';
2137 my($has_size) = $size ? qq/ size="$size"/: '';
2138 my($other) = @other ? " @other" : '';
2140 $name=$self->escapeHTML($name);
2141 $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
2142 foreach (@values) {
2143 my($selectit) = $selected{$_} ? qq/selected/ : '';
2144 my($label) = $_;
2145 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2146 $label=$self->escapeHTML($label);
2147 my($value)=$self->escapeHTML($_,1);
2148 $result .= "<option $selectit value=\"$value\">$label</option>\n";
2150 $result .= "</select>\n";
2151 $self->register_parameter($name);
2152 return $result;
2154 END_OF_FUNC
2157 #### Method: hidden
2158 # Parameters:
2159 # $name -> Name of the hidden field
2160 # @default -> (optional) Initial values of field (may be an array)
2161 # or
2162 # $default->[initial values of field]
2163 # Returns:
2164 # A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
2165 ####
2166 'hidden' => <<'END_OF_FUNC',
2167 sub hidden {
2168 my($self,@p) = self_or_default(@_);
2170 # this is the one place where we departed from our standard
2171 # calling scheme, so we have to special-case (darn)
2172 my(@result,@value);
2173 my($name,$default,$override,@other) =
2174 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2176 my $do_override = 0;
2177 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2178 @value = ref($default) ? @{$default} : $default;
2179 $do_override = $override;
2180 } else {
2181 foreach ($default,$override,@other) {
2182 push(@value,$_) if defined($_);
2186 # use previous values if override is not set
2187 my @prev = $self->param($name);
2188 @value = @prev if !$do_override && @prev;
2190 $name=$self->escapeHTML($name);
2191 foreach (@value) {
2192 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2193 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
2194 : qq(<input type="hidden" name="$name" value="$_">);
2196 return wantarray ? @result : join('',@result);
2198 END_OF_FUNC
2201 #### Method: image_button
2202 # Parameters:
2203 # $name -> Name of the button
2204 # $src -> URL of the image source
2205 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2206 # Returns:
2207 # A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
2208 ####
2209 'image_button' => <<'END_OF_FUNC',
2210 sub image_button {
2211 my($self,@p) = self_or_default(@_);
2213 my($name,$src,$alignment,@other) =
2214 rearrange([NAME,SRC,ALIGN],@p);
2216 my($align) = $alignment ? " align=\U$alignment" : '';
2217 my($other) = @other ? " @other" : '';
2218 $name=$self->escapeHTML($name);
2219 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2220 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2222 END_OF_FUNC
2225 #### Method: self_url
2226 # Returns a URL containing the current script and all its
2227 # param/value pairs arranged as a query. You can use this
2228 # to create a link that, when selected, will reinvoke the
2229 # script with all its state information preserved.
2230 ####
2231 'self_url' => <<'END_OF_FUNC',
2232 sub self_url {
2233 my($self,@p) = self_or_default(@_);
2234 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2236 END_OF_FUNC
2239 # This is provided as a synonym to self_url() for people unfortunate
2240 # enough to have incorporated it into their programs already!
2241 'state' => <<'END_OF_FUNC',
2242 sub state {
2243 &self_url;
2245 END_OF_FUNC
2248 #### Method: url
2249 # Like self_url, but doesn't return the query string part of
2250 # the URL.
2251 ####
2252 'url' => <<'END_OF_FUNC',
2253 sub url {
2254 my($self,@p) = self_or_default(@_);
2255 my ($relative,$absolute,$full,$path_info,$query,$base) =
2256 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
2257 my $url;
2258 $full++ if $base || !($relative || $absolute);
2260 my $path = $self->path_info;
2261 my $script_name = $self->script_name;
2263 # If anybody knows why I ever wrote this please tell me!
2264 # if (exists($ENV{REQUEST_URI})) {
2265 # my $index;
2266 # $script_name = $ENV{REQUEST_URI};
2267 # # strip query string
2268 # substr($script_name,$index) = '' if ($index = index($script_name,'?')) >= 0;
2269 # # and path
2270 # if (exists($ENV{PATH_INFO})) {
2271 # (my $encoded_path = $ENV{PATH_INFO}) =~ s!([^a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;;
2272 # substr($script_name,$index) = '' if ($index = rindex($script_name,$encoded_path)) >= 0;
2274 # } else {
2275 # $script_name = $self->script_name;
2278 if ($full) {
2279 my $protocol = $self->protocol();
2280 $url = "$protocol://";
2281 my $vh = http('host');
2282 if ($vh) {
2283 $url .= $vh;
2284 } else {
2285 $url .= server_name();
2286 my $port = $self->server_port;
2287 $url .= ":" . $port
2288 unless (lc($protocol) eq 'http' && $port == 80)
2289 || (lc($protocol) eq 'https' && $port == 443);
2291 return $url if $base;
2292 $url .= $script_name;
2293 } elsif ($relative) {
2294 ($url) = $script_name =~ m!([^/]+)$!;
2295 } elsif ($absolute) {
2296 $url = $script_name;
2299 $url .= $path if $path_info and defined $path;
2300 $url .= "?" . $self->query_string if $query and $self->query_string;
2301 $url = '' unless defined $url;
2302 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/uc sprintf("%%%02x",ord($1))/eg;
2303 return $url;
2306 END_OF_FUNC
2308 #### Method: cookie
2309 # Set or read a cookie from the specified name.
2310 # Cookie can then be passed to header().
2311 # Usual rules apply to the stickiness of -value.
2312 # Parameters:
2313 # -name -> name for this cookie (optional)
2314 # -value -> value of this cookie (scalar, array or hash)
2315 # -path -> paths for which this cookie is valid (optional)
2316 # -domain -> internet domain in which this cookie is valid (optional)
2317 # -secure -> if true, cookie only passed through secure channel (optional)
2318 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2319 ####
2320 'cookie' => <<'END_OF_FUNC',
2321 sub cookie {
2322 my($self,@p) = self_or_default(@_);
2323 my($name,$value,$path,$domain,$secure,$expires) =
2324 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2326 require CGI::Cookie;
2328 # if no value is supplied, then we retrieve the
2329 # value of the cookie, if any. For efficiency, we cache the parsed
2330 # cookies in our state variables.
2331 unless ( defined($value) ) {
2332 $self->{'.cookies'} = CGI::Cookie->fetch
2333 unless $self->{'.cookies'};
2335 # If no name is supplied, then retrieve the names of all our cookies.
2336 return () unless $self->{'.cookies'};
2337 return keys %{$self->{'.cookies'}} unless $name;
2338 return () unless $self->{'.cookies'}->{$name};
2339 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2342 # If we get here, we're creating a new cookie
2343 return undef unless defined($name) && $name ne ''; # this is an error
2345 my @param;
2346 push(@param,'-name'=>$name);
2347 push(@param,'-value'=>$value);
2348 push(@param,'-domain'=>$domain) if $domain;
2349 push(@param,'-path'=>$path) if $path;
2350 push(@param,'-expires'=>$expires) if $expires;
2351 push(@param,'-secure'=>$secure) if $secure;
2353 return new CGI::Cookie(@param);
2355 END_OF_FUNC
2357 'parse_keywordlist' => <<'END_OF_FUNC',
2358 sub parse_keywordlist {
2359 my($self,$tosplit) = @_;
2360 $tosplit = unescape($tosplit); # unescape the keywords
2361 $tosplit=~tr/+/ /; # pluses to spaces
2362 my(@keywords) = split(/\s+/,$tosplit);
2363 return @keywords;
2365 END_OF_FUNC
2367 'param_fetch' => <<'END_OF_FUNC',
2368 sub param_fetch {
2369 my($self,@p) = self_or_default(@_);
2370 my($name) = rearrange([NAME],@p);
2371 unless (exists($self->{$name})) {
2372 $self->add_parameter($name);
2373 $self->{$name} = [];
2376 return $self->{$name};
2378 END_OF_FUNC
2380 ###############################################
2381 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2382 ###############################################
2384 #### Method: path_info
2385 # Return the extra virtual path information provided
2386 # after the URL (if any)
2387 ####
2388 'path_info' => <<'END_OF_FUNC',
2389 sub path_info {
2390 my ($self,$info) = self_or_default(@_);
2391 if (defined($info)) {
2392 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2393 $self->{'.path_info'} = $info;
2394 } elsif (! defined($self->{'.path_info'}) ) {
2395 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2396 $ENV{'PATH_INFO'} : '';
2398 # hack to fix broken path info in IIS
2399 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2402 return $self->{'.path_info'};
2404 END_OF_FUNC
2407 #### Method: request_method
2408 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2409 ####
2410 'request_method' => <<'END_OF_FUNC',
2411 sub request_method {
2412 return $ENV{'REQUEST_METHOD'};
2414 END_OF_FUNC
2416 #### Method: content_type
2417 # Returns the content_type string
2418 ####
2419 'content_type' => <<'END_OF_FUNC',
2420 sub content_type {
2421 return $ENV{'CONTENT_TYPE'};
2423 END_OF_FUNC
2425 #### Method: path_translated
2426 # Return the physical path information provided
2427 # by the URL (if any)
2428 ####
2429 'path_translated' => <<'END_OF_FUNC',
2430 sub path_translated {
2431 return $ENV{'PATH_TRANSLATED'};
2433 END_OF_FUNC
2436 #### Method: query_string
2437 # Synthesize a query string from our current
2438 # parameters
2439 ####
2440 'query_string' => <<'END_OF_FUNC',
2441 sub query_string {
2442 my($self) = self_or_default(@_);
2443 my($param,$value,@pairs);
2444 foreach $param ($self->param) {
2445 my($eparam) = escape($param);
2446 foreach $value ($self->param($param)) {
2447 $value = escape($value);
2448 next unless defined $value;
2449 push(@pairs,"$eparam=$value");
2452 foreach (keys %{$self->{'.fieldnames'}}) {
2453 push(@pairs,".cgifields=".escape("$_"));
2455 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2457 END_OF_FUNC
2460 #### Method: accept
2461 # Without parameters, returns an array of the
2462 # MIME types the browser accepts.
2463 # With a single parameter equal to a MIME
2464 # type, will return undef if the browser won't
2465 # accept it, 1 if the browser accepts it but
2466 # doesn't give a preference, or a floating point
2467 # value between 0.0 and 1.0 if the browser
2468 # declares a quantitative score for it.
2469 # This handles MIME type globs correctly.
2470 ####
2471 'Accept' => <<'END_OF_FUNC',
2472 sub Accept {
2473 my($self,$search) = self_or_CGI(@_);
2474 my(%prefs,$type,$pref,$pat);
2476 my(@accept) = split(',',$self->http('accept'));
2478 foreach (@accept) {
2479 ($pref) = /q=(\d\.\d+|\d+)/;
2480 ($type) = m#(\S+/[^;]+)#;
2481 next unless $type;
2482 $prefs{$type}=$pref || 1;
2485 return keys %prefs unless $search;
2487 # if a search type is provided, we may need to
2488 # perform a pattern matching operation.
2489 # The MIME types use a glob mechanism, which
2490 # is easily translated into a perl pattern match
2492 # First return the preference for directly supported
2493 # types:
2494 return $prefs{$search} if $prefs{$search};
2496 # Didn't get it, so try pattern matching.
2497 foreach (keys %prefs) {
2498 next unless /\*/; # not a pattern match
2499 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2500 $pat =~ s/\*/.*/g; # turn it into a pattern
2501 return $prefs{$_} if $search=~/$pat/;
2504 END_OF_FUNC
2507 #### Method: user_agent
2508 # If called with no parameters, returns the user agent.
2509 # If called with one parameter, does a pattern match (case
2510 # insensitive) on the user agent.
2511 ####
2512 'user_agent' => <<'END_OF_FUNC',
2513 sub user_agent {
2514 my($self,$match)=self_or_CGI(@_);
2515 return $self->http('user_agent') unless $match;
2516 return $self->http('user_agent') =~ /$match/i;
2518 END_OF_FUNC
2521 #### Method: raw_cookie
2522 # Returns the magic cookies for the session.
2523 # The cookies are not parsed or altered in any way, i.e.
2524 # cookies are returned exactly as given in the HTTP
2525 # headers. If a cookie name is given, only that cookie's
2526 # value is returned, otherwise the entire raw cookie
2527 # is returned.
2528 ####
2529 'raw_cookie' => <<'END_OF_FUNC',
2530 sub raw_cookie {
2531 my($self,$key) = self_or_CGI(@_);
2533 require CGI::Cookie;
2535 if (defined($key)) {
2536 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2537 unless $self->{'.raw_cookies'};
2539 return () unless $self->{'.raw_cookies'};
2540 return () unless $self->{'.raw_cookies'}->{$key};
2541 return $self->{'.raw_cookies'}->{$key};
2543 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2545 END_OF_FUNC
2547 #### Method: virtual_host
2548 # Return the name of the virtual_host, which
2549 # is not always the same as the server
2550 ######
2551 'virtual_host' => <<'END_OF_FUNC',
2552 sub virtual_host {
2553 my $vh = http('host') || server_name();
2554 $vh =~ s/:\d+$//; # get rid of port number
2555 return $vh;
2557 END_OF_FUNC
2559 #### Method: remote_host
2560 # Return the name of the remote host, or its IP
2561 # address if unavailable. If this variable isn't
2562 # defined, it returns "localhost" for debugging
2563 # purposes.
2564 ####
2565 'remote_host' => <<'END_OF_FUNC',
2566 sub remote_host {
2567 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2568 || 'localhost';
2570 END_OF_FUNC
2573 #### Method: remote_addr
2574 # Return the IP addr of the remote host.
2575 ####
2576 'remote_addr' => <<'END_OF_FUNC',
2577 sub remote_addr {
2578 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2580 END_OF_FUNC
2583 #### Method: script_name
2584 # Return the partial URL to this script for
2585 # self-referencing scripts. Also see
2586 # self_url(), which returns a URL with all state information
2587 # preserved.
2588 ####
2589 'script_name' => <<'END_OF_FUNC',
2590 sub script_name {
2591 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2592 # These are for debugging
2593 return "/$0" unless $0=~/^\//;
2594 return $0;
2596 END_OF_FUNC
2599 #### Method: referer
2600 # Return the HTTP_REFERER: useful for generating
2601 # a GO BACK button.
2602 ####
2603 'referer' => <<'END_OF_FUNC',
2604 sub referer {
2605 my($self) = self_or_CGI(@_);
2606 return $self->http('referer');
2608 END_OF_FUNC
2611 #### Method: server_name
2612 # Return the name of the server
2613 ####
2614 'server_name' => <<'END_OF_FUNC',
2615 sub server_name {
2616 return $ENV{'SERVER_NAME'} || 'localhost';
2618 END_OF_FUNC
2620 #### Method: server_software
2621 # Return the name of the server software
2622 ####
2623 'server_software' => <<'END_OF_FUNC',
2624 sub server_software {
2625 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2627 END_OF_FUNC
2629 #### Method: server_port
2630 # Return the tcp/ip port the server is running on
2631 ####
2632 'server_port' => <<'END_OF_FUNC',
2633 sub server_port {
2634 return $ENV{'SERVER_PORT'} || 80; # for debugging
2636 END_OF_FUNC
2638 #### Method: server_protocol
2639 # Return the protocol (usually HTTP/1.0)
2640 ####
2641 'server_protocol' => <<'END_OF_FUNC',
2642 sub server_protocol {
2643 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2645 END_OF_FUNC
2647 #### Method: http
2648 # Return the value of an HTTP variable, or
2649 # the list of variables if none provided
2650 ####
2651 'http' => <<'END_OF_FUNC',
2652 sub http {
2653 my ($self,$parameter) = self_or_CGI(@_);
2654 return $ENV{$parameter} if $parameter=~/^HTTP/;
2655 $parameter =~ tr/-/_/;
2656 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2657 my(@p);
2658 foreach (keys %ENV) {
2659 push(@p,$_) if /^HTTP/;
2661 return @p;
2663 END_OF_FUNC
2665 #### Method: https
2666 # Return the value of HTTPS
2667 ####
2668 'https' => <<'END_OF_FUNC',
2669 sub https {
2670 local($^W)=0;
2671 my ($self,$parameter) = self_or_CGI(@_);
2672 return $ENV{HTTPS} unless $parameter;
2673 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2674 $parameter =~ tr/-/_/;
2675 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2676 my(@p);
2677 foreach (keys %ENV) {
2678 push(@p,$_) if /^HTTPS/;
2680 return @p;
2682 END_OF_FUNC
2684 #### Method: protocol
2685 # Return the protocol (http or https currently)
2686 ####
2687 'protocol' => <<'END_OF_FUNC',
2688 sub protocol {
2689 local($^W)=0;
2690 my $self = shift;
2691 return 'https' if uc($self->https()) eq 'ON';
2692 return 'https' if $self->server_port == 443;
2693 my $prot = $self->server_protocol;
2694 my($protocol,$version) = split('/',$prot);
2695 return "\L$protocol\E";
2697 END_OF_FUNC
2699 #### Method: remote_ident
2700 # Return the identity of the remote user
2701 # (but only if his host is running identd)
2702 ####
2703 'remote_ident' => <<'END_OF_FUNC',
2704 sub remote_ident {
2705 return $ENV{'REMOTE_IDENT'};
2707 END_OF_FUNC
2710 #### Method: auth_type
2711 # Return the type of use verification/authorization in use, if any.
2712 ####
2713 'auth_type' => <<'END_OF_FUNC',
2714 sub auth_type {
2715 return $ENV{'AUTH_TYPE'};
2717 END_OF_FUNC
2720 #### Method: remote_user
2721 # Return the authorization name used for user
2722 # verification.
2723 ####
2724 'remote_user' => <<'END_OF_FUNC',
2725 sub remote_user {
2726 return $ENV{'REMOTE_USER'};
2728 END_OF_FUNC
2731 #### Method: user_name
2732 # Try to return the remote user's name by hook or by
2733 # crook
2734 ####
2735 'user_name' => <<'END_OF_FUNC',
2736 sub user_name {
2737 my ($self) = self_or_CGI(@_);
2738 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2740 END_OF_FUNC
2742 #### Method: nosticky
2743 # Set or return the NOSTICKY global flag
2744 ####
2745 'nosticky' => <<'END_OF_FUNC',
2746 sub nosticky {
2747 my ($self,$param) = self_or_CGI(@_);
2748 $CGI::NOSTICKY = $param if defined($param);
2749 return $CGI::NOSTICKY;
2751 END_OF_FUNC
2753 #### Method: nph
2754 # Set or return the NPH global flag
2755 ####
2756 'nph' => <<'END_OF_FUNC',
2757 sub nph {
2758 my ($self,$param) = self_or_CGI(@_);
2759 $CGI::NPH = $param if defined($param);
2760 return $CGI::NPH;
2762 END_OF_FUNC
2764 #### Method: private_tempfiles
2765 # Set or return the private_tempfiles global flag
2766 ####
2767 'private_tempfiles' => <<'END_OF_FUNC',
2768 sub private_tempfiles {
2769 my ($self,$param) = self_or_CGI(@_);
2770 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2771 return $CGI::PRIVATE_TEMPFILES;
2773 END_OF_FUNC
2775 #### Method: default_dtd
2776 # Set or return the default_dtd global
2777 ####
2778 'default_dtd' => <<'END_OF_FUNC',
2779 sub default_dtd {
2780 my ($self,$param,$param2) = self_or_CGI(@_);
2781 if (defined $param2 && defined $param) {
2782 $CGI::DEFAULT_DTD = [ $param, $param2 ];
2783 } elsif (defined $param) {
2784 $CGI::DEFAULT_DTD = $param;
2786 return $CGI::DEFAULT_DTD;
2788 END_OF_FUNC
2790 # -------------- really private subroutines -----------------
2791 'previous_or_default' => <<'END_OF_FUNC',
2792 sub previous_or_default {
2793 my($self,$name,$defaults,$override) = @_;
2794 my(%selected);
2796 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2797 defined($self->param($name)) ) ) {
2798 grep($selected{$_}++,$self->param($name));
2799 } elsif (defined($defaults) && ref($defaults) &&
2800 (ref($defaults) eq 'ARRAY')) {
2801 grep($selected{$_}++,@{$defaults});
2802 } else {
2803 $selected{$defaults}++ if defined($defaults);
2806 return %selected;
2808 END_OF_FUNC
2810 'register_parameter' => <<'END_OF_FUNC',
2811 sub register_parameter {
2812 my($self,$param) = @_;
2813 $self->{'.parametersToAdd'}->{$param}++;
2815 END_OF_FUNC
2817 'get_fields' => <<'END_OF_FUNC',
2818 sub get_fields {
2819 my($self) = @_;
2820 return $self->CGI::hidden('-name'=>'.cgifields',
2821 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2822 '-override'=>1);
2824 END_OF_FUNC
2826 'read_from_cmdline' => <<'END_OF_FUNC',
2827 sub read_from_cmdline {
2828 my($input,@words);
2829 my($query_string);
2830 if ($DEBUG && @ARGV) {
2831 @words = @ARGV;
2832 } elsif ($DEBUG > 1) {
2833 require "shellwords.pl";
2834 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2835 chomp(@lines = <STDIN>); # remove newlines
2836 $input = join(" ",@lines);
2837 @words = &shellwords($input);
2839 foreach (@words) {
2840 s/\\=/%3D/g;
2841 s/\\&/%26/g;
2844 if ("@words"=~/=/) {
2845 $query_string = join('&',@words);
2846 } else {
2847 $query_string = join('+',@words);
2849 return $query_string;
2851 END_OF_FUNC
2853 #####
2854 # subroutine: read_multipart
2856 # Read multipart data and store it into our parameters.
2857 # An interesting feature is that if any of the parts is a file, we
2858 # create a temporary file and open up a filehandle on it so that the
2859 # caller can read from it if necessary.
2860 #####
2861 'read_multipart' => <<'END_OF_FUNC',
2862 sub read_multipart {
2863 my($self,$boundary,$length,$filehandle) = @_;
2864 my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
2865 return unless $buffer;
2866 my(%header,$body);
2867 my $filenumber = 0;
2868 while (!$buffer->eof) {
2869 %header = $buffer->readHeader;
2871 unless (%header) {
2872 $self->cgi_error("400 Bad request (malformed multipart POST)");
2873 return;
2876 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
2878 # Bug: Netscape doesn't escape quotation marks in file names!!!
2879 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
2881 # add this parameter to our list
2882 $self->add_parameter($param);
2884 # If no filename specified, then just read the data and assign it
2885 # to our parameter list.
2886 if ( !defined($filename) || $filename eq '' ) {
2887 my($value) = $buffer->readBody;
2888 push(@{$self->{$param}},$value);
2889 next;
2892 my ($tmpfile,$tmp,$filehandle);
2893 UPLOADS: {
2894 # If we get here, then we are dealing with a potentially large
2895 # uploaded form. Save the data to a temporary file, then open
2896 # the file for reading.
2898 # skip the file if uploads disabled
2899 if ($DISABLE_UPLOADS) {
2900 while (defined($data = $buffer->read)) { }
2901 last UPLOADS;
2904 # choose a relatively unpredictable tmpfile sequence number
2905 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
2906 for (my $cnt=10;$cnt>0;$cnt--) {
2907 next unless $tmpfile = new TempFile($seqno);
2908 $tmp = $tmpfile->as_string;
2909 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
2910 $seqno += int rand(100);
2912 die "CGI open of tmpfile: $!\n" unless $filehandle;
2913 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2915 my ($data);
2916 local($\) = '';
2917 while (defined($data = $buffer->read)) {
2918 print $filehandle $data;
2921 # back up to beginning of file
2922 seek($filehandle,0,0);
2923 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2925 # Save some information about the uploaded file where we can get
2926 # at it later.
2927 $self->{'.tmpfiles'}->{fileno($filehandle)}= {
2928 name => $tmpfile,
2929 info => {%header},
2931 push(@{$self->{$param}},$filehandle);
2935 END_OF_FUNC
2937 'upload' =><<'END_OF_FUNC',
2938 sub upload {
2939 my($self,$param_name) = self_or_default(@_);
2940 my $param = $self->param($param_name);
2941 return unless $param;
2942 return unless ref($param) && fileno($param);
2943 return $param;
2945 END_OF_FUNC
2947 'tmpFileName' => <<'END_OF_FUNC',
2948 sub tmpFileName {
2949 my($self,$filename) = self_or_default(@_);
2950 return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
2951 $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
2952 : '';
2954 END_OF_FUNC
2956 'uploadInfo' => <<'END_OF_FUNC',
2957 sub uploadInfo {
2958 my($self,$filename) = self_or_default(@_);
2959 return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
2961 END_OF_FUNC
2963 # internal routine, don't use
2964 '_set_values_and_labels' => <<'END_OF_FUNC',
2965 sub _set_values_and_labels {
2966 my $self = shift;
2967 my ($v,$l,$n) = @_;
2968 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
2969 return $self->param($n) if !defined($v);
2970 return $v if !ref($v);
2971 return ref($v) eq 'HASH' ? keys %$v : @$v;
2973 END_OF_FUNC
2975 '_compile_all' => <<'END_OF_FUNC',
2976 sub _compile_all {
2977 foreach (@_) {
2978 next if defined(&$_);
2979 $AUTOLOAD = "CGI::$_";
2980 _compile();
2983 END_OF_FUNC
2986 END_OF_AUTOLOAD
2989 #########################################################
2990 # Globals and stubs for other packages that we use.
2991 #########################################################
2993 ################### Fh -- lightweight filehandle ###############
2994 package Fh;
2995 use overload
2996 '""' => \&asString,
2997 'cmp' => \&compare,
2998 'fallback'=>1;
3000 $FH='fh00000';
3002 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3004 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3005 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3006 %SUBS = (
3007 'asString' => <<'END_OF_FUNC',
3008 sub asString {
3009 my $self = shift;
3010 # get rid of package name
3011 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3012 $i =~ s/%(..)/ chr(hex($1)) /eg;
3013 return $i;
3014 # BEGIN DEAD CODE
3015 # This was an extremely clever patch that allowed "use strict refs".
3016 # Unfortunately it relied on another bug that caused leaky file descriptors.
3017 # The underlying bug has been fixed, so this no longer works. However
3018 # "strict refs" still works for some reason.
3019 # my $self = shift;
3020 # return ${*{$self}{SCALAR}};
3021 # END DEAD CODE
3023 END_OF_FUNC
3025 'compare' => <<'END_OF_FUNC',
3026 sub compare {
3027 my $self = shift;
3028 my $value = shift;
3029 return "$self" cmp $value;
3031 END_OF_FUNC
3033 'new' => <<'END_OF_FUNC',
3034 sub new {
3035 my($pack,$name,$file,$delete) = @_;
3036 require Fcntl unless defined &Fcntl::O_RDWR;
3037 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3038 my $fv = ++$FH . $safename;
3039 my $ref = \*{"Fh::$fv"};
3040 sysopen($ref,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3041 unlink($file) if $delete;
3042 CORE::delete $Fh::{$fv};
3043 return bless $ref,$pack;
3045 END_OF_FUNC
3047 'DESTROY' => <<'END_OF_FUNC',
3048 sub DESTROY {
3049 my $self = shift;
3050 close $self;
3052 END_OF_FUNC
3055 END_OF_AUTOLOAD
3057 ######################## MultipartBuffer ####################
3058 package MultipartBuffer;
3060 # how many bytes to read at a time. We use
3061 # a 4K buffer by default.
3062 $INITIAL_FILLUNIT = 1024 * 4;
3063 $TIMEOUT = 240*60; # 4 hour timeout for big files
3064 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3065 $CRLF=$CGI::CRLF;
3067 #reuse the autoload function
3068 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3070 # avoid autoloader warnings
3071 sub DESTROY {}
3073 ###############################################################################
3074 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3075 ###############################################################################
3076 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3077 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3078 %SUBS = (
3080 'new' => <<'END_OF_FUNC',
3081 sub new {
3082 my($package,$interface,$boundary,$length,$filehandle) = @_;
3083 $FILLUNIT = $INITIAL_FILLUNIT;
3084 my $IN;
3085 if ($filehandle) {
3086 my($package) = caller;
3087 # force into caller's package if necessary
3088 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
3090 $IN = "main::STDIN" unless $IN;
3092 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
3094 # If the user types garbage into the file upload field,
3095 # then Netscape passes NOTHING to the server (not good).
3096 # We may hang on this read in that case. So we implement
3097 # a read timeout. If nothing is ready to read
3098 # by then, we return.
3100 # Netscape seems to be a little bit unreliable
3101 # about providing boundary strings.
3102 my $boundary_read = 0;
3103 if ($boundary) {
3105 # Under the MIME spec, the boundary consists of the
3106 # characters "--" PLUS the Boundary string
3108 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3109 # the two extra hyphens. We do a special case here on the user-agent!!!!
3110 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac');
3112 } else { # otherwise we find it ourselves
3113 my($old);
3114 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3115 $boundary = <$IN>; # BUG: This won't work correctly under mod_perl
3116 $length -= length($boundary);
3117 chomp($boundary); # remove the CRLF
3118 $/ = $old; # restore old line separator
3119 $boundary_read++;
3122 my $self = {LENGTH=>$length,
3123 BOUNDARY=>$boundary,
3124 IN=>$IN,
3125 INTERFACE=>$interface,
3126 BUFFER=>'',
3129 $FILLUNIT = length($boundary)
3130 if length($boundary) > $FILLUNIT;
3132 my $retval = bless $self,ref $package || $package;
3134 # Read the preamble and the topmost (boundary) line plus the CRLF.
3135 unless ($boundary_read) {
3136 while ($self->read(0)) { }
3138 die "Malformed multipart POST\n" if $self->eof;
3140 return $retval;
3142 END_OF_FUNC
3144 'readHeader' => <<'END_OF_FUNC',
3145 sub readHeader {
3146 my($self) = @_;
3147 my($end);
3148 my($ok) = 0;
3149 my($bad) = 0;
3151 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3153 do {
3154 $self->fillBuffer($FILLUNIT);
3155 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3156 $ok++ if $self->{BUFFER} eq '';
3157 $bad++ if !$ok && $self->{LENGTH} <= 0;
3158 # this was a bad idea
3159 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3160 } until $ok || $bad;
3161 return () if $bad;
3163 my($header) = substr($self->{BUFFER},0,$end+2);
3164 substr($self->{BUFFER},0,$end+4) = '';
3165 my %return;
3168 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3169 # (Folding Long Header Fields), 3.4.3 (Comments)
3170 # and 3.4.5 (Quoted-Strings).
3172 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3173 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3174 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3175 my ($field_name,$field_value) = ($1,$2); # avoid taintedness
3176 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3177 $return{$field_name}=$field_value;
3179 return %return;
3181 END_OF_FUNC
3183 # This reads and returns the body as a single scalar value.
3184 'readBody' => <<'END_OF_FUNC',
3185 sub readBody {
3186 my($self) = @_;
3187 my($data);
3188 my($returnval)='';
3189 while (defined($data = $self->read)) {
3190 $returnval .= $data;
3192 return $returnval;
3194 END_OF_FUNC
3196 # This will read $bytes or until the boundary is hit, whichever happens
3197 # first. After the boundary is hit, we return undef. The next read will
3198 # skip over the boundary and begin reading again;
3199 'read' => <<'END_OF_FUNC',
3200 sub read {
3201 my($self,$bytes) = @_;
3203 # default number of bytes to read
3204 $bytes = $bytes || $FILLUNIT;
3206 # Fill up our internal buffer in such a way that the boundary
3207 # is never split between reads.
3208 $self->fillBuffer($bytes);
3210 # Find the boundary in the buffer (it may not be there).
3211 my $start = index($self->{BUFFER},$self->{BOUNDARY});
3212 # protect against malformed multipart POST operations
3213 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3215 # If the boundary begins the data, then skip past it
3216 # and return undef.
3217 if ($start == 0) {
3219 # clear us out completely if we've hit the last boundary.
3220 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3221 $self->{BUFFER}='';
3222 $self->{LENGTH}=0;
3223 return undef;
3226 # just remove the boundary.
3227 substr($self->{BUFFER},0,length($self->{BOUNDARY}))='';
3228 $self->{BUFFER} =~ s/^\012\015?//;
3229 return undef;
3232 my $bytesToReturn;
3233 if ($start > 0) { # read up to the boundary
3234 $bytesToReturn = $start > $bytes ? $bytes : $start;
3235 } else { # read the requested number of bytes
3236 # leave enough bytes in the buffer to allow us to read
3237 # the boundary. Thanks to Kevin Hendrick for finding
3238 # this one.
3239 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3242 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3243 substr($self->{BUFFER},0,$bytesToReturn)='';
3245 # If we hit the boundary, remove the CRLF from the end.
3246 return ($start > 0) ? substr($returnval,0,-2) : $returnval;
3248 END_OF_FUNC
3251 # This fills up our internal buffer in such a way that the
3252 # boundary is never split between reads
3253 'fillBuffer' => <<'END_OF_FUNC',
3254 sub fillBuffer {
3255 my($self,$bytes) = @_;
3256 return unless $self->{LENGTH};
3258 my($boundaryLength) = length($self->{BOUNDARY});
3259 my($bufferLength) = length($self->{BUFFER});
3260 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3261 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3263 # Try to read some data. We may hang here if the browser is screwed up.
3264 my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3265 \$self->{BUFFER},
3266 $bytesToRead,
3267 $bufferLength);
3268 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3270 # An apparent bug in the Apache server causes the read()
3271 # to return zero bytes repeatedly without blocking if the
3272 # remote user aborts during a file transfer. I don't know how
3273 # they manage this, but the workaround is to abort if we get
3274 # more than SPIN_LOOP_MAX consecutive zero reads.
3275 if ($bytesRead == 0) {
3276 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3277 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3278 } else {
3279 $self->{ZERO_LOOP_COUNTER}=0;
3282 $self->{LENGTH} -= $bytesRead;
3284 END_OF_FUNC
3287 # Return true when we've finished reading
3288 'eof' => <<'END_OF_FUNC'
3289 sub eof {
3290 my($self) = @_;
3291 return 1 if (length($self->{BUFFER}) == 0)
3292 && ($self->{LENGTH} <= 0);
3293 undef;
3295 END_OF_FUNC
3298 END_OF_AUTOLOAD
3300 ####################################################################################
3301 ################################## TEMPORARY FILES #################################
3302 ####################################################################################
3303 package TempFile;
3305 $SL = $CGI::SL;
3306 $MAC = $CGI::OS eq 'MACINTOSH';
3307 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3308 unless ($TMPDIRECTORY) {
3309 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3310 "C:${SL}temp","${SL}tmp","${SL}temp",
3311 "${vol}${SL}Temporary Items",
3312 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3313 "C:${SL}system${SL}temp");
3314 unshift(@TEMP,$ENV{'TMPDIR'}) if exists $ENV{'TMPDIR'};
3316 # this feature was supposed to provide per-user tmpfiles, but
3317 # it is problematic.
3318 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3319 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3320 # : can generate a 'getpwuid() not implemented' exception, even though
3321 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3322 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3323 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3325 foreach (@TEMP) {
3326 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3330 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3331 $MAXTRIES = 5000;
3333 # cute feature, but overload implementation broke it
3334 # %OVERLOAD = ('""'=>'as_string');
3335 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3337 ###############################################################################
3338 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3339 ###############################################################################
3340 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3341 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3342 %SUBS = (
3344 'new' => <<'END_OF_FUNC',
3345 sub new {
3346 my($package,$sequence) = @_;
3347 my $filename;
3348 for (my $i = 0; $i < $MAXTRIES; $i++) {
3349 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3351 # untaint the darn thing
3352 return unless $filename =~ m!^([a-zA-Z0-9_ '":/.\$\\-]+)$!;
3353 $filename = $1;
3354 return bless \$filename;
3356 END_OF_FUNC
3358 'DESTROY' => <<'END_OF_FUNC',
3359 sub DESTROY {
3360 my($self) = @_;
3361 unlink $$self; # get rid of the file
3363 END_OF_FUNC
3365 'as_string' => <<'END_OF_FUNC'
3366 sub as_string {
3367 my($self) = @_;
3368 return $$self;
3370 END_OF_FUNC
3373 END_OF_AUTOLOAD
3375 package CGI;
3377 # We get a whole bunch of warnings about "possibly uninitialized variables"
3378 # when running with the -w switch. Touch them all once to get rid of the
3379 # warnings. This is ugly and I hate it.
3380 if ($^W) {
3381 $CGI::CGI = '';
3382 $CGI::CGI=<<EOF;
3383 $CGI::VERSION;
3384 $MultipartBuffer::SPIN_LOOP_MAX;
3385 $MultipartBuffer::CRLF;
3386 $MultipartBuffer::TIMEOUT;
3387 $MultipartBuffer::INITIAL_FILLUNIT;
3394 __END__
3396 =head1 NAME
3398 CGI - Simple Common Gateway Interface Class
3400 =head1 SYNOPSIS
3402 # CGI script that creates a fill-out form
3403 # and echoes back its values.
3405 use CGI qw/:standard/;
3406 print header,
3407 start_html('A Simple Example'),
3408 h1('A Simple Example'),
3409 start_form,
3410 "What's your name? ",textfield('name'),p,
3411 "What's the combination?", p,
3412 checkbox_group(-name=>'words',
3413 -values=>['eenie','meenie','minie','moe'],
3414 -defaults=>['eenie','minie']), p,
3415 "What's your favorite color? ",
3416 popup_menu(-name=>'color',
3417 -values=>['red','green','blue','chartreuse']),p,
3418 submit,
3419 end_form,
3422 if (param()) {
3423 print "Your name is",em(param('name')),p,
3424 "The keywords are: ",em(join(", ",param('words'))),p,
3425 "Your favorite color is ",em(param('color')),
3429 =head1 ABSTRACT
3431 This perl library uses perl5 objects to make it easy to create Web
3432 fill-out forms and parse their contents. This package defines CGI
3433 objects, entities that contain the values of the current query string
3434 and other state variables. Using a CGI object's methods, you can
3435 examine keywords and parameters passed to your script, and create
3436 forms whose initial values are taken from the current query (thereby
3437 preserving state information). The module provides shortcut functions
3438 that produce boilerplate HTML, reducing typing and coding errors. It
3439 also provides functionality for some of the more advanced features of
3440 CGI scripting, including support for file uploads, cookies, cascading
3441 style sheets, server push, and frames.
3443 CGI.pm also provides a simple function-oriented programming style for
3444 those who don't need its object-oriented features.
3446 The current version of CGI.pm is available at
3448 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3449 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3451 =head1 DESCRIPTION
3453 =head2 PROGRAMMING STYLE
3455 There are two styles of programming with CGI.pm, an object-oriented
3456 style and a function-oriented style. In the object-oriented style you
3457 create one or more CGI objects and then use object methods to create
3458 the various elements of the page. Each CGI object starts out with the
3459 list of named parameters that were passed to your CGI script by the
3460 server. You can modify the objects, save them to a file or database
3461 and recreate them. Because each object corresponds to the "state" of
3462 the CGI script, and because each object's parameter list is
3463 independent of the others, this allows you to save the state of the
3464 script and restore it later.
3466 For example, using the object oriented style, here is how you create
3467 a simple "Hello World" HTML page:
3469 #!/usr/local/bin/perl -w
3470 use CGI; # load CGI routines
3471 $q = new CGI; # create new CGI object
3472 print $q->header, # create the HTTP header
3473 $q->start_html('hello world'), # start the HTML
3474 $q->h1('hello world'), # level 1 header
3475 $q->end_html; # end the HTML
3477 In the function-oriented style, there is one default CGI object that
3478 you rarely deal with directly. Instead you just call functions to
3479 retrieve CGI parameters, create HTML tags, manage cookies, and so
3480 on. This provides you with a cleaner programming interface, but
3481 limits you to using one CGI object at a time. The following example
3482 prints the same page, but uses the function-oriented interface.
3483 The main differences are that we now need to import a set of functions
3484 into our name space (usually the "standard" functions), and we don't
3485 need to create the CGI object.
3487 #!/usr/local/bin/perl
3488 use CGI qw/:standard/; # load standard CGI routines
3489 print header, # create the HTTP header
3490 start_html('hello world'), # start the HTML
3491 h1('hello world'), # level 1 header
3492 end_html; # end the HTML
3494 The examples in this document mainly use the object-oriented style.
3495 See HOW TO IMPORT FUNCTIONS for important information on
3496 function-oriented programming in CGI.pm
3498 =head2 CALLING CGI.PM ROUTINES
3500 Most CGI.pm routines accept several arguments, sometimes as many as 20
3501 optional ones! To simplify this interface, all routines use a named
3502 argument calling style that looks like this:
3504 print $q->header(-type=>'image/gif',-expires=>'+3d');
3506 Each argument name is preceded by a dash. Neither case nor order
3507 matters in the argument list. -type, -Type, and -TYPE are all
3508 acceptable. In fact, only the first argument needs to begin with a
3509 dash. If a dash is present in the first argument, CGI.pm assumes
3510 dashes for the subsequent ones.
3512 Several routines are commonly called with just one argument. In the
3513 case of these routines you can provide the single argument without an
3514 argument name. header() happens to be one of these routines. In this
3515 case, the single argument is the document type.
3517 print $q->header('text/html');
3519 Other such routines are documented below.
3521 Sometimes named arguments expect a scalar, sometimes a reference to an
3522 array, and sometimes a reference to a hash. Often, you can pass any
3523 type of argument and the routine will do whatever is most appropriate.
3524 For example, the param() routine is used to set a CGI parameter to a
3525 single or a multi-valued value. The two cases are shown below:
3527 $q->param(-name=>'veggie',-value=>'tomato');
3528 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3530 A large number of routines in CGI.pm actually aren't specifically
3531 defined in the module, but are generated automatically as needed.
3532 These are the "HTML shortcuts," routines that generate HTML tags for
3533 use in dynamically-generated pages. HTML tags have both attributes
3534 (the attribute="value" pairs within the tag itself) and contents (the
3535 part between the opening and closing pairs.) To distinguish between
3536 attributes and contents, CGI.pm uses the convention of passing HTML
3537 attributes as a hash reference as the first argument, and the
3538 contents, if any, as any subsequent arguments. It works out like
3539 this:
3541 Code Generated HTML
3542 ---- --------------
3543 h1() <H1>
3544 h1('some','contents'); <H1>some contents</H1>
3545 h1({-align=>left}); <H1 ALIGN="LEFT">
3546 h1({-align=>left},'contents'); <H1 ALIGN="LEFT">contents</H1>
3548 HTML tags are described in more detail later.
3550 Many newcomers to CGI.pm are puzzled by the difference between the
3551 calling conventions for the HTML shortcuts, which require curly braces
3552 around the HTML tag attributes, and the calling conventions for other
3553 routines, which manage to generate attributes without the curly
3554 brackets. Don't be confused. As a convenience the curly braces are
3555 optional in all but the HTML shortcuts. If you like, you can use
3556 curly braces when calling any routine that takes named arguments. For
3557 example:
3559 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3561 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3562 names conflict with built-in Perl functions. The most frequent of
3563 these is the -values argument, used to create multi-valued menus,
3564 radio button clusters and the like. To get around this warning, you
3565 have several choices:
3567 =over 4
3569 =item 1.
3571 Use another name for the argument, if one is available.
3572 For example, -value is an alias for -values.
3574 =item 2.
3576 Change the capitalization, e.g. -Values
3578 =item 3.
3580 Put quotes around the argument name, e.g. '-values'
3582 =back
3584 Many routines will do something useful with a named argument that it
3585 doesn't recognize. For example, you can produce non-standard HTTP
3586 header fields by providing them as named arguments:
3588 print $q->header(-type => 'text/html',
3589 -cost => 'Three smackers',
3590 -annoyance_level => 'high',
3591 -complaints_to => 'bit bucket');
3593 This will produce the following nonstandard HTTP header:
3595 HTTP/1.0 200 OK
3596 Cost: Three smackers
3597 Annoyance-level: high
3598 Complaints-to: bit bucket
3599 Content-type: text/html
3601 Notice the way that underscores are translated automatically into
3602 hyphens. HTML-generating routines perform a different type of
3603 translation.
3605 This feature allows you to keep up with the rapidly changing HTTP and
3606 HTML "standards".
3608 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3610 $query = new CGI;
3612 This will parse the input (from both POST and GET methods) and store
3613 it into a perl5 object called $query.
3615 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3617 $query = new CGI(INPUTFILE);
3619 If you provide a file handle to the new() method, it will read
3620 parameters from the file (or STDIN, or whatever). The file can be in
3621 any of the forms describing below under debugging (i.e. a series of
3622 newline delimited TAG=VALUE pairs will work). Conveniently, this type
3623 of file is created by the save() method (see below). Multiple records
3624 can be saved and restored.
3626 Perl purists will be pleased to know that this syntax accepts
3627 references to file handles, or even references to filehandle globs,
3628 which is the "official" way to pass a filehandle:
3630 $query = new CGI(\*STDIN);
3632 You can also initialize the CGI object with a FileHandle or IO::File
3633 object.
3635 If you are using the function-oriented interface and want to
3636 initialize CGI state from a file handle, the way to do this is with
3637 B<restore_parameters()>. This will (re)initialize the
3638 default CGI object from the indicated file handle.
3640 open (IN,"test.in") || die;
3641 restore_parameters(IN);
3642 close IN;
3644 You can also initialize the query object from an associative array
3645 reference:
3647 $query = new CGI( {'dinosaur'=>'barney',
3648 'song'=>'I love you',
3649 'friends'=>[qw/Jessica George Nancy/]}
3652 or from a properly formatted, URL-escaped query string:
3654 $query = new CGI('dinosaur=barney&color=purple');
3656 or from a previously existing CGI object (currently this clones the
3657 parameter list, but none of the other object-specific fields, such as
3658 autoescaping):
3660 $old_query = new CGI;
3661 $new_query = new CGI($old_query);
3663 To create an empty query, initialize it from an empty string or hash:
3665 $empty_query = new CGI("");
3667 -or-
3669 $empty_query = new CGI({});
3671 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3673 @keywords = $query->keywords
3675 If the script was invoked as the result of an <ISINDEX> search, the
3676 parsed keywords can be obtained as an array using the keywords() method.
3678 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3680 @names = $query->param
3682 If the script was invoked with a parameter list
3683 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
3684 will return the parameter names as a list. If the script was invoked
3685 as an <ISINDEX> script and contains a string without ampersands
3686 (e.g. "value1+value2+value3") , there will be a single parameter named
3687 "keywords" containing the "+"-delimited keywords.
3689 NOTE: As of version 1.5, the array of parameter names returned will
3690 be in the same order as they were submitted by the browser.
3691 Usually this order is the same as the order in which the
3692 parameters are defined in the form (however, this isn't part
3693 of the spec, and so isn't guaranteed).
3695 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3697 @values = $query->param('foo');
3699 -or-
3701 $value = $query->param('foo');
3703 Pass the param() method a single argument to fetch the value of the
3704 named parameter. If the parameter is multivalued (e.g. from multiple
3705 selections in a scrolling list), you can ask to receive an array. Otherwise
3706 the method will return a single value.
3708 If a value is not given in the query string, as in the queries
3709 "name1=&name2=" or "name1&name2", it will be returned as an empty
3710 string. This feature is new in 2.63.
3712 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3714 $query->param('foo','an','array','of','values');
3716 This sets the value for the named parameter 'foo' to an array of
3717 values. This is one way to change the value of a field AFTER
3718 the script has been invoked once before. (Another way is with
3719 the -override parameter accepted by all methods that generate
3720 form elements.)
3722 param() also recognizes a named parameter style of calling described
3723 in more detail later:
3725 $query->param(-name=>'foo',-values=>['an','array','of','values']);
3727 -or-
3729 $query->param(-name=>'foo',-value=>'the value');
3731 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
3733 $query->append(-name=>'foo',-values=>['yet','more','values']);
3735 This adds a value or list of values to the named parameter. The
3736 values are appended to the end of the parameter if it already exists.
3737 Otherwise the parameter is created. Note that this method only
3738 recognizes the named argument calling syntax.
3740 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
3742 $query->import_names('R');
3744 This creates a series of variables in the 'R' namespace. For example,
3745 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
3746 If no namespace is given, this method will assume 'Q'.
3747 WARNING: don't import anything into 'main'; this is a major security
3748 risk!!!!
3750 In older versions, this method was called B<import()>. As of version 2.20,
3751 this name has been removed completely to avoid conflict with the built-in
3752 Perl module B<import> operator.
3754 =head2 DELETING A PARAMETER COMPLETELY:
3756 $query->delete('foo');
3758 This completely clears a parameter. It sometimes useful for
3759 resetting parameters that you don't want passed down between
3760 script invocations.
3762 If you are using the function call interface, use "Delete()" instead
3763 to avoid conflicts with Perl's built-in delete operator.
3765 =head2 DELETING ALL PARAMETERS:
3767 $query->delete_all();
3769 This clears the CGI object completely. It might be useful to ensure
3770 that all the defaults are taken when you create a fill-out form.
3772 Use Delete_all() instead if you are using the function call interface.
3774 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
3776 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
3777 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
3779 If you need access to the parameter list in a way that isn't covered
3780 by the methods above, you can obtain a direct reference to it by
3781 calling the B<param_fetch()> method with the name of the . This
3782 will return an array reference to the named parameters, which you then
3783 can manipulate in any way you like.
3785 You can also use a named argument style using the B<-name> argument.
3787 =head2 FETCHING THE PARAMETER LIST AS A HASH:
3789 $params = $q->Vars;
3790 print $params->{'address'};
3791 @foo = split("\0",$params->{'foo'});
3792 %params = $q->Vars;
3794 use CGI ':cgi-lib';
3795 $params = Vars;
3797 Many people want to fetch the entire parameter list as a hash in which
3798 the keys are the names of the CGI parameters, and the values are the
3799 parameters' values. The Vars() method does this. Called in a scalar
3800 context, it returns the parameter list as a tied hash reference.
3801 Changing a key changes the value of the parameter in the underlying
3802 CGI parameter list. Called in a list context, it returns the
3803 parameter list as an ordinary hash. This allows you to read the
3804 contents of the parameter list, but not to change it.
3806 When using this, the thing you must watch out for are multivalued CGI
3807 parameters. Because a hash cannot distinguish between scalar and
3808 list context, multivalued parameters will be returned as a packed
3809 string, separated by the "\0" (null) character. You must split this
3810 packed string in order to get at the individual values. This is the
3811 convention introduced long ago by Steve Brenner in his cgi-lib.pl
3812 module for Perl version 4.
3814 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
3815 function calls (also see the section on CGI-LIB compatibility).
3817 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
3819 $query->save(FILEHANDLE)
3821 This will write the current state of the form to the provided
3822 filehandle. You can read it back in by providing a filehandle
3823 to the new() method. Note that the filehandle can be a file, a pipe,
3824 or whatever!
3826 The format of the saved file is:
3828 NAME1=VALUE1
3829 NAME1=VALUE1'
3830 NAME2=VALUE2
3831 NAME3=VALUE3
3834 Both name and value are URL escaped. Multi-valued CGI parameters are
3835 represented as repeated names. A session record is delimited by a
3836 single = symbol. You can write out multiple records and read them
3837 back in with several calls to B<new>. You can do this across several
3838 sessions by opening the file in append mode, allowing you to create
3839 primitive guest books, or to keep a history of users' queries. Here's
3840 a short example of creating multiple session records:
3842 use CGI;
3844 open (OUT,">>test.out") || die;
3845 $records = 5;
3846 foreach (0..$records) {
3847 my $q = new CGI;
3848 $q->param(-name=>'counter',-value=>$_);
3849 $q->save(OUT);
3851 close OUT;
3853 # reopen for reading
3854 open (IN,"test.out") || die;
3855 while (!eof(IN)) {
3856 my $q = new CGI(IN);
3857 print $q->param('counter'),"\n";
3860 The file format used for save/restore is identical to that used by the
3861 Whitehead Genome Center's data exchange format "Boulderio", and can be
3862 manipulated and even databased using Boulderio utilities. See
3864 http://stein.cshl.org/boulder/
3866 for further details.
3868 If you wish to use this method from the function-oriented (non-OO)
3869 interface, the exported name for this method is B<save_parameters()>.
3871 =head2 RETRIEVING CGI ERRORS
3873 Errors can occur while processing user input, particularly when
3874 processing uploaded files. When these errors occur, CGI will stop
3875 processing and return an empty parameter list. You can test for
3876 the existence and nature of errors using the I<cgi_error()> function.
3877 The error messages are formatted as HTTP status codes. You can either
3878 incorporate the error text into an HTML page, or use it as the value
3879 of the HTTP status:
3881 my $error = $q->cgi_error;
3882 if ($error) {
3883 print $q->header(-status=>$error),
3884 $q->start_html('Problems'),
3885 $q->h2('Request not processed'),
3886 $q->strong($error);
3887 exit 0;
3890 When using the function-oriented interface (see the next section),
3891 errors may only occur the first time you call I<param()>. Be ready
3892 for this!
3894 =head2 USING THE FUNCTION-ORIENTED INTERFACE
3896 To use the function-oriented interface, you must specify which CGI.pm
3897 routines or sets of routines to import into your script's namespace.
3898 There is a small overhead associated with this importation, but it
3899 isn't much.
3901 use CGI <list of methods>;
3903 The listed methods will be imported into the current package; you can
3904 call them directly without creating a CGI object first. This example
3905 shows how to import the B<param()> and B<header()>
3906 methods, and then use them directly:
3908 use CGI 'param','header';
3909 print header('text/plain');
3910 $zipcode = param('zipcode');
3912 More frequently, you'll import common sets of functions by referring
3913 to the groups by name. All function sets are preceded with a ":"
3914 character as in ":html3" (for tags defined in the HTML 3 standard).
3916 Here is a list of the function sets you can import:
3918 =over 4
3920 =item B<:cgi>
3922 Import all CGI-handling methods, such as B<param()>, B<path_info()>
3923 and the like.
3925 =item B<:form>
3927 Import all fill-out form generating methods, such as B<textfield()>.
3929 =item B<:html2>
3931 Import all methods that generate HTML 2.0 standard elements.
3933 =item B<:html3>
3935 Import all methods that generate HTML 3.0 proposed elements (such as
3936 <table>, <super> and <sub>).
3938 =item B<:netscape>
3940 Import all methods that generate Netscape-specific HTML extensions.
3942 =item B<:html>
3944 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
3945 'netscape')...
3947 =item B<:standard>
3949 Import "standard" features, 'html2', 'html3', 'form' and 'cgi'.
3951 =item B<:all>
3953 Import all the available methods. For the full list, see the CGI.pm
3954 code, where the variable %EXPORT_TAGS is defined.
3956 =back
3958 If you import a function name that is not part of CGI.pm, the module
3959 will treat it as a new HTML tag and generate the appropriate
3960 subroutine. You can then use it like any other HTML tag. This is to
3961 provide for the rapidly-evolving HTML "standard." For example, say
3962 Microsoft comes out with a new tag called <GRADIENT> (which causes the
3963 user's desktop to be flooded with a rotating gradient fill until his
3964 machine reboots). You don't need to wait for a new version of CGI.pm
3965 to start using it immediately:
3967 use CGI qw/:standard :html3 gradient/;
3968 print gradient({-start=>'red',-end=>'blue'});
3970 Note that in the interests of execution speed CGI.pm does B<not> use
3971 the standard L<Exporter> syntax for specifying load symbols. This may
3972 change in the future.
3974 If you import any of the state-maintaining CGI or form-generating
3975 methods, a default CGI object will be created and initialized
3976 automatically the first time you use any of the methods that require
3977 one to be present. This includes B<param()>, B<textfield()>,
3978 B<submit()> and the like. (If you need direct access to the CGI
3979 object, you can find it in the global variable B<$CGI::Q>). By
3980 importing CGI.pm methods, you can create visually elegant scripts:
3982 use CGI qw/:standard/;
3983 print
3984 header,
3985 start_html('Simple Script'),
3986 h1('Simple Script'),
3987 start_form,
3988 "What's your name? ",textfield('name'),p,
3989 "What's the combination?",
3990 checkbox_group(-name=>'words',
3991 -values=>['eenie','meenie','minie','moe'],
3992 -defaults=>['eenie','moe']),p,
3993 "What's your favorite color?",
3994 popup_menu(-name=>'color',
3995 -values=>['red','green','blue','chartreuse']),p,
3996 submit,
3997 end_form,
3998 hr,"\n";
4000 if (param) {
4001 print
4002 "Your name is ",em(param('name')),p,
4003 "The keywords are: ",em(join(", ",param('words'))),p,
4004 "Your favorite color is ",em(param('color')),".\n";
4006 print end_html;
4008 =head2 PRAGMAS
4010 In addition to the function sets, there are a number of pragmas that
4011 you can import. Pragmas, which are always preceded by a hyphen,
4012 change the way that CGI.pm functions in various ways. Pragmas,
4013 function sets, and individual functions can all be imported in the
4014 same use() line. For example, the following use statement imports the
4015 standard set of functions and enables debugging mode (pragma
4016 -debug):
4018 use CGI qw/:standard -debug/;
4020 The current list of pragmas is as follows:
4022 =over 4
4024 =item -any
4026 When you I<use CGI -any>, then any method that the query object
4027 doesn't recognize will be interpreted as a new HTML tag. This allows
4028 you to support the next I<ad hoc> Netscape or Microsoft HTML
4029 extension. This lets you go wild with new and unsupported tags:
4031 use CGI qw(-any);
4032 $q=new CGI;
4033 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4035 Since using <cite>any</cite> causes any mistyped method name
4036 to be interpreted as an HTML tag, use it with care or not at
4037 all.
4039 =item -compile
4041 This causes the indicated autoloaded methods to be compiled up front,
4042 rather than deferred to later. This is useful for scripts that run
4043 for an extended period of time under FastCGI or mod_perl, and for
4044 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4045 it in conjunction with the methods or method families you plan to use.
4047 use CGI qw(-compile :standard :html3);
4049 or even
4051 use CGI qw(-compile :all);
4053 Note that using the -compile pragma in this way will always have
4054 the effect of importing the compiled functions into the current
4055 namespace. If you want to compile without importing use the
4056 compile() method instead (see below).
4058 =item -nosticky
4060 This makes CGI.pm not generating the hidden fields .submit
4061 and .cgifields. It is very useful if you don't want to
4062 have the hidden fields appear in the querystring in a GET method.
4063 For example, a search script generated this way will have
4064 a very nice url with search parameters for bookmarking.
4066 =item -no_xhtml
4068 By default, CGI.pm versions 2.69 and higher emit XHTML
4069 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4070 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4071 feature.
4073 =item -nph
4075 This makes CGI.pm produce a header appropriate for an NPH (no
4076 parsed header) script. You may need to do other things as well
4077 to tell the server that the script is NPH. See the discussion
4078 of NPH scripts below.
4080 =item -newstyle_urls
4082 Separate the name=value pairs in CGI parameter query strings with
4083 semicolons rather than ampersands. For example:
4085 ?name=fred;age=24;favorite_color=3
4087 Semicolon-delimited query strings are always accepted, but will not be
4088 emitted by self_url() and query_string() unless the -newstyle_urls
4089 pragma is specified.
4091 This became the default in version 2.64.
4093 =item -oldstyle_urls
4095 Separate the name=value pairs in CGI parameter query strings with
4096 ampersands rather than semicolons. This is no longer the default.
4098 =item -autoload
4100 This overrides the autoloader so that any function in your program
4101 that is not recognized is referred to CGI.pm for possible evaluation.
4102 This allows you to use all the CGI.pm functions without adding them to
4103 your symbol table, which is of concern for mod_perl users who are
4104 worried about memory consumption. I<Warning:> when
4105 I<-autoload> is in effect, you cannot use "poetry mode"
4106 (functions without the parenthesis). Use I<hr()> rather
4107 than I<hr>, or add something like I<use subs qw/hr p header/>
4108 to the top of your script.
4110 =item -no_debug
4112 This turns off the command-line processing features. If you want to
4113 run a CGI.pm script from the command line to produce HTML, and you
4114 don't want it to read CGI parameters from the command line or STDIN,
4115 then use this pragma:
4117 use CGI qw(-no_debug :standard);
4119 =item -debug
4121 This turns on full debugging. In addition to reading CGI arguments
4122 from the command-line processing, CGI.pm will pause and try to read
4123 arguments from STDIN, producing the message "(offline mode: enter
4124 name=value pairs on standard input)" features.
4126 See the section on debugging for more details.
4128 =item -private_tempfiles
4130 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4131 file to a temporary directory, then deletes the file when done.
4132 However, this opens the risk of eavesdropping as described in the file
4133 upload section. Another CGI script author could peek at this data
4134 during the upload, even if it is confidential information. On Unix
4135 systems, the -private_tempfiles pragma will cause the temporary file
4136 to be unlinked as soon as it is opened and before any data is written
4137 into it, reducing, but not eliminating the risk of eavesdropping
4138 (there is still a potential race condition). To make life harder for
4139 the attacker, the program chooses tempfile names by calculating a 32
4140 bit checksum of the incoming HTTP headers.
4142 To ensure that the temporary file cannot be read by other CGI scripts,
4143 use suEXEC or a CGI wrapper program to run your script. The temporary
4144 file is created with mode 0600 (neither world nor group readable).
4146 The temporary directory is selected using the following algorithm:
4148 1. if the current user (e.g. "nobody") has a directory named
4149 "tmp" in its home directory, use that (Unix systems only).
4151 2. if the environment variable TMPDIR exists, use the location
4152 indicated.
4154 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4155 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4157 Each of these locations is checked that it is a directory and is
4158 writable. If not, the algorithm tries the next choice.
4160 =back
4162 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4164 Many of the methods generate HTML tags. As described below, tag
4165 functions automatically generate both the opening and closing tags.
4166 For example:
4168 print h1('Level 1 Header');
4170 produces
4172 <H1>Level 1 Header</H1>
4174 There will be some times when you want to produce the start and end
4175 tags yourself. In this case, you can use the form start_I<tag_name>
4176 and end_I<tag_name>, as in:
4178 print start_h1,'Level 1 Header',end_h1;
4180 With a few exceptions (described below), start_I<tag_name> and
4181 end_I<tag_name> functions are not generated automatically when you
4182 I<use CGI>. However, you can specify the tags you want to generate
4183 I<start/end> functions for by putting an asterisk in front of their
4184 name, or, alternatively, requesting either "start_I<tag_name>" or
4185 "end_I<tag_name>" in the import list.
4187 Example:
4189 use CGI qw/:standard *table start_ul/;
4191 In this example, the following functions are generated in addition to
4192 the standard ones:
4194 =over 4
4196 =item 1. start_table() (generates a <TABLE> tag)
4198 =item 2. end_table() (generates a </TABLE> tag)
4200 =item 3. start_ul() (generates a <UL> tag)
4202 =item 4. end_ul() (generates a </UL> tag)
4204 =back
4206 =head1 GENERATING DYNAMIC DOCUMENTS
4208 Most of CGI.pm's functions deal with creating documents on the fly.
4209 Generally you will produce the HTTP header first, followed by the
4210 document itself. CGI.pm provides functions for generating HTTP
4211 headers of various types as well as for generating HTML. For creating
4212 GIF images, see the GD.pm module.
4214 Each of these functions produces a fragment of HTML or HTTP which you
4215 can print out directly so that it displays in the browser window,
4216 append to a string, or save to a file for later use.
4218 =head2 CREATING A STANDARD HTTP HEADER:
4220 Normally the first thing you will do in any CGI script is print out an
4221 HTTP header. This tells the browser what type of document to expect,
4222 and gives other optional information, such as the language, expiration
4223 date, and whether to cache the document. The header can also be
4224 manipulated for special purposes, such as server push and pay per view
4225 pages.
4227 print $query->header;
4229 -or-
4231 print $query->header('image/gif');
4233 -or-
4235 print $query->header('text/html','204 No response');
4237 -or-
4239 print $query->header(-type=>'image/gif',
4240 -nph=>1,
4241 -status=>'402 Payment required',
4242 -expires=>'+3d',
4243 -cookie=>$cookie,
4244 -charset=>'utf-7',
4245 -attachment=>'foo.gif',
4246 -Cost=>'$2.00');
4248 header() returns the Content-type: header. You can provide your own
4249 MIME type if you choose, otherwise it defaults to text/html. An
4250 optional second parameter specifies the status code and a human-readable
4251 message. For example, you can specify 204, "No response" to create a
4252 script that tells the browser to do nothing at all.
4254 The last example shows the named argument style for passing arguments
4255 to the CGI methods using named parameters. Recognized parameters are
4256 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4257 parameters will be stripped of their initial hyphens and turned into
4258 header fields, allowing you to specify any HTTP header you desire.
4259 Internal underscores will be turned into hyphens:
4261 print $query->header(-Content_length=>3002);
4263 Most browsers will not cache the output from CGI scripts. Every time
4264 the browser reloads the page, the script is invoked anew. You can
4265 change this behavior with the B<-expires> parameter. When you specify
4266 an absolute or relative expiration interval with this parameter, some
4267 browsers and proxy servers will cache the script's output until the
4268 indicated expiration date. The following forms are all valid for the
4269 -expires field:
4271 +30s 30 seconds from now
4272 +10m ten minutes from now
4273 +1h one hour from now
4274 -1d yesterday (i.e. "ASAP!")
4275 now immediately
4276 +3M in three months
4277 +10y in ten years time
4278 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4280 The B<-cookie> parameter generates a header that tells the browser to provide
4281 a "magic cookie" during all subsequent transactions with your script.
4282 Netscape cookies have a special format that includes interesting attributes
4283 such as expiration time. Use the cookie() method to create and retrieve
4284 session cookies.
4286 The B<-nph> parameter, if set to a true value, will issue the correct
4287 headers to work with a NPH (no-parse-header) script. This is important
4288 to use with certain servers that expect all their scripts to be NPH.
4290 The B<-charset> parameter can be used to control the character set
4291 sent to the browser. If not provided, defaults to ISO-8859-1. As a
4292 side effect, this sets the charset() method as well.
4294 The B<-attachment> parameter can be used to turn the page into an
4295 attachment. Instead of displaying the page, some browsers will prompt
4296 the user to save it to disk. The value of the argument is the
4297 suggested name for the saved file. In order for this to work, you may
4298 have to set the B<-type> to "application/octet-stream".
4300 =head2 GENERATING A REDIRECTION HEADER
4302 print $query->redirect('http://somewhere.else/in/movie/land');
4304 Sometimes you don't want to produce a document yourself, but simply
4305 redirect the browser elsewhere, perhaps choosing a URL based on the
4306 time of day or the identity of the user.
4308 The redirect() function redirects the browser to a different URL. If
4309 you use redirection like this, you should B<not> print out a header as
4310 well.
4312 One hint I can offer is that relative links may not work correctly
4313 when you generate a redirection to another document on your site.
4314 This is due to a well-intentioned optimization that some servers use.
4315 The solution to this is to use the full URL (including the http: part)
4316 of the document you are redirecting to.
4318 You can also use named arguments:
4320 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4321 -nph=>1);
4323 The B<-nph> parameter, if set to a true value, will issue the correct
4324 headers to work with a NPH (no-parse-header) script. This is important
4325 to use with certain servers, such as Microsoft Internet Explorer, which
4326 expect all their scripts to be NPH.
4328 =head2 CREATING THE HTML DOCUMENT HEADER
4330 print $query->start_html(-title=>'Secrets of the Pyramids',
4331 -author=>'fred@capricorn.org',
4332 -base=>'true',
4333 -target=>'_blank',
4334 -meta=>{'keywords'=>'pharaoh secret mummy',
4335 'copyright'=>'copyright 1996 King Tut'},
4336 -style=>{'src'=>'/styles/style1.css'},
4337 -BGCOLOR=>'blue');
4339 After creating the HTTP header, most CGI scripts will start writing
4340 out an HTML document. The start_html() routine creates the top of the
4341 page, along with a lot of optional information that controls the
4342 page's appearance and behavior.
4344 This method returns a canned HTML header and the opening <BODY> tag.
4345 All parameters are optional. In the named parameter form, recognized
4346 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4347 (see below for the explanation). Any additional parameters you
4348 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4349 to the <BODY> tag. Additional parameters must be proceeded by a
4350 hyphen.
4352 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
4353 different from the current location, as in
4355 -xbase=>"http://home.mcom.com/"
4357 All relative links will be interpreted relative to this tag.
4359 The argument B<-target> allows you to provide a default target frame
4360 for all the links and fill-out forms on the page. B<This is a
4361 non-standard HTTP feature which only works with Netscape browsers!>
4362 See the Netscape documentation on frames for details of how to
4363 manipulate this.
4365 -target=>"answer_window"
4367 All relative links will be interpreted relative to this tag.
4368 You add arbitrary meta information to the header with the B<-meta>
4369 argument. This argument expects a reference to an associative array
4370 containing name/value pairs of meta information. These will be turned
4371 into a series of header <META> tags that look something like this:
4373 <META NAME="keywords" CONTENT="pharaoh secret mummy">
4374 <META NAME="description" CONTENT="copyright 1996 King Tut">
4376 To create an HTTP-EQUIV type of <META> tag, use B<-head>, described
4377 below.
4379 The B<-style> argument is used to incorporate cascading stylesheets
4380 into your code. See the section on CASCADING STYLESHEETS for more
4381 information.
4383 The B<-lang> argument is used to incorporate a language attribute into
4384 the <HTML> tag. The default if not specified is "en-US" for US
4385 English. For example:
4387 print $q->start_html(-lang=>'fr-CA');
4389 You can place other arbitrary HTML elements to the <HEAD> section with the
4390 B<-head> tag. For example, to place the rarely-used <LINK> element in the
4391 head section, use this:
4393 print start_html(-head=>Link({-rel=>'next',
4394 -href=>'http://www.capricorn.com/s2.html'}));
4396 To incorporate multiple HTML elements into the <HEAD> section, just pass an
4397 array reference:
4399 print start_html(-head=>[
4400 Link({-rel=>'next',
4401 -href=>'http://www.capricorn.com/s2.html'}),
4402 Link({-rel=>'previous',
4403 -href=>'http://www.capricorn.com/s1.html'})
4407 And here's how to create an HTTP-EQUIV <META> tag:
4409 print start_html(-head=>meta({-http_equiv => 'Content-Type',
4410 -content => 'text/html'}))
4413 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4414 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4415 to add Netscape JavaScript calls to your pages. B<-script> should
4416 point to a block of text containing JavaScript function definitions.
4417 This block will be placed within a <SCRIPT> block inside the HTML (not
4418 HTTP) header. The block is placed in the header in order to give your
4419 page a fighting chance of having all its JavaScript functions in place
4420 even if the user presses the stop button before the page has loaded
4421 completely. CGI.pm attempts to format the script in such a way that
4422 JavaScript-naive browsers will not choke on the code: unfortunately
4423 there are some browsers, such as Chimera for Unix, that get confused
4424 by it nevertheless.
4426 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4427 code to execute when the page is respectively opened and closed by the
4428 browser. Usually these parameters are calls to functions defined in the
4429 B<-script> field:
4431 $query = new CGI;
4432 print $query->header;
4433 $JSCRIPT=<<END;
4434 // Ask a silly question
4435 function riddle_me_this() {
4436 var r = prompt("What walks on four legs in the morning, " +
4437 "two legs in the afternoon, " +
4438 "and three legs in the evening?");
4439 response(r);
4441 // Get a silly answer
4442 function response(answer) {
4443 if (answer == "man")
4444 alert("Right you are!");
4445 else
4446 alert("Wrong! Guess again.");
4449 print $query->start_html(-title=>'The Riddle of the Sphinx',
4450 -script=>$JSCRIPT);
4452 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4453 browsers that do not have JavaScript (or browsers where JavaScript is turned
4454 off).
4456 Netscape 3.0 recognizes several attributes of the <SCRIPT> tag,
4457 including LANGUAGE and SRC. The latter is particularly interesting,
4458 as it allows you to keep the JavaScript code in a file or CGI script
4459 rather than cluttering up each page with the source. To use these
4460 attributes pass a HASH reference in the B<-script> parameter containing
4461 one or more of -language, -src, or -code:
4463 print $q->start_html(-title=>'The Riddle of the Sphinx',
4464 -script=>{-language=>'JAVASCRIPT',
4465 -src=>'/javascript/sphinx.js'}
4468 print $q->(-title=>'The Riddle of the Sphinx',
4469 -script=>{-language=>'PERLSCRIPT',
4470 -code=>'print "hello world!\n;"'}
4474 A final feature allows you to incorporate multiple <SCRIPT> sections into the
4475 header. Just pass the list of script sections as an array reference.
4476 this allows you to specify different source files for different dialects
4477 of JavaScript. Example:
4479 print $q->start_html(-title=>'The Riddle of the Sphinx',
4480 -script=>[
4481 { -language => 'JavaScript1.0',
4482 -src => '/javascript/utilities10.js'
4484 { -language => 'JavaScript1.1',
4485 -src => '/javascript/utilities11.js'
4487 { -language => 'JavaScript1.2',
4488 -src => '/javascript/utilities12.js'
4490 { -language => 'JavaScript28.2',
4491 -src => '/javascript/utilities219.js'
4495 </pre>
4497 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4501 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4503 for more information about JavaScript.
4505 The old-style positional parameters are as follows:
4507 =over 4
4509 =item B<Parameters:>
4511 =item 1.
4513 The title
4515 =item 2.
4517 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
4519 =item 3.
4521 A 'true' flag if you want to include a <BASE> tag in the header. This
4522 helps resolve relative addresses to absolute ones when the document is moved,
4523 but makes the document hierarchy non-portable. Use with care!
4525 =item 4, 5, 6...
4527 Any other parameters you want to include in the <BODY> tag. This is a good
4528 place to put Netscape extensions, such as colors and wallpaper patterns.
4530 =back
4532 =head2 ENDING THE HTML DOCUMENT:
4534 print $query->end_html
4536 This ends an HTML document by printing the </BODY></HTML> tags.
4538 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4540 $myself = $query->self_url;
4541 print q(<A HREF="$myself">I'm talking to myself.</A>);
4543 self_url() will return a URL, that, when selected, will reinvoke
4544 this script with all its state information intact. This is most
4545 useful when you want to jump around within the document using
4546 internal anchors but you don't want to disrupt the current contents
4547 of the form(s). Something like this will do the trick.
4549 $myself = $query->self_url;
4550 print "<A HREF=$myself#table1>See table 1</A>";
4551 print "<A HREF=$myself#table2>See table 2</A>";
4552 print "<A HREF=$myself#yourself>See for yourself</A>";
4554 If you want more control over what's returned, using the B<url()>
4555 method instead.
4557 You can also retrieve the unprocessed query string with query_string():
4559 $the_string = $query->query_string;
4561 =head2 OBTAINING THE SCRIPT'S URL
4563 $full_url = $query->url();
4564 $full_url = $query->url(-full=>1); #alternative syntax
4565 $relative_url = $query->url(-relative=>1);
4566 $absolute_url = $query->url(-absolute=>1);
4567 $url_with_path = $query->url(-path_info=>1);
4568 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4569 $netloc = $query->url(-base => 1);
4571 B<url()> returns the script's URL in a variety of formats. Called
4572 without any arguments, it returns the full form of the URL, including
4573 host name and port number
4575 http://your.host.com/path/to/script.cgi
4577 You can modify this format with the following named arguments:
4579 =over 4
4581 =item B<-absolute>
4583 If true, produce an absolute URL, e.g.
4585 /path/to/script.cgi
4587 =item B<-relative>
4589 Produce a relative URL. This is useful if you want to reinvoke your
4590 script with different parameters. For example:
4592 script.cgi
4594 =item B<-full>
4596 Produce the full URL, exactly as if called without any arguments.
4597 This overrides the -relative and -absolute arguments.
4599 =item B<-path> (B<-path_info>)
4601 Append the additional path information to the URL. This can be
4602 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
4603 is provided as a synonym.
4605 =item B<-query> (B<-query_string>)
4607 Append the query string to the URL. This can be combined with
4608 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
4609 as a synonym.
4611 =item B<-base>
4613 Generate just the protocol and net location, as in http://www.foo.com:8000
4615 =back
4617 =head2 MIXING POST AND URL PARAMETERS
4619 $color = $query-&gt;url_param('color');
4621 It is possible for a script to receive CGI parameters in the URL as
4622 well as in the fill-out form by creating a form that POSTs to a URL
4623 containing a query string (a "?" mark followed by arguments). The
4624 B<param()> method will always return the contents of the POSTed
4625 fill-out form, ignoring the URL's query string. To retrieve URL
4626 parameters, call the B<url_param()> method. Use it in the same way as
4627 B<param()>. The main difference is that it allows you to read the
4628 parameters, but not set them.
4631 Under no circumstances will the contents of the URL query string
4632 interfere with similarly-named CGI parameters in POSTed forms. If you
4633 try to mix a URL query string with a form submitted with the GET
4634 method, the results will not be what you expect.
4636 =head1 CREATING STANDARD HTML ELEMENTS:
4638 CGI.pm defines general HTML shortcut methods for most, if not all of
4639 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
4640 HTML element and return a fragment of HTML text that you can then
4641 print or manipulate as you like. Each shortcut returns a fragment of
4642 HTML code that you can append to a string, save to a file, or, most
4643 commonly, print out so that it displays in the browser window.
4645 This example shows how to use the HTML methods:
4647 $q = new CGI;
4648 print $q->blockquote(
4649 "Many years ago on the island of",
4650 $q->a({href=>"http://crete.org/"},"Crete"),
4651 "there lived a Minotaur named",
4652 $q->strong("Fred."),
4654 $q->hr;
4656 This results in the following HTML code (extra newlines have been
4657 added for readability):
4659 <blockquote>
4660 Many years ago on the island of
4661 <a HREF="http://crete.org/">Crete</a> there lived
4662 a minotaur named <strong>Fred.</strong>
4663 </blockquote>
4664 <hr>
4666 If you find the syntax for calling the HTML shortcuts awkward, you can
4667 import them into your namespace and dispense with the object syntax
4668 completely (see the next section for more details):
4670 use CGI ':standard';
4671 print blockquote(
4672 "Many years ago on the island of",
4673 a({href=>"http://crete.org/"},"Crete"),
4674 "there lived a minotaur named",
4675 strong("Fred."),
4679 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4681 The HTML methods will accept zero, one or multiple arguments. If you
4682 provide no arguments, you get a single tag:
4684 print hr; # <HR>
4686 If you provide one or more string arguments, they are concatenated
4687 together with spaces and placed between opening and closing tags:
4689 print h1("Chapter","1"); # <H1>Chapter 1</H1>"
4691 If the first argument is an associative array reference, then the keys
4692 and values of the associative array become the HTML tag's attributes:
4694 print a({-href=>'fred.html',-target=>'_new'},
4695 "Open a new frame");
4697 <A HREF="fred.html",TARGET="_new">Open a new frame</A>
4699 You may dispense with the dashes in front of the attribute names if
4700 you prefer:
4702 print img {src=>'fred.gif',align=>'LEFT'};
4704 <IMG ALIGN="LEFT" SRC="fred.gif">
4706 Sometimes an HTML tag attribute has no argument. For example, ordered
4707 lists can be marked as COMPACT. The syntax for this is an argument that
4708 that points to an undef string:
4710 print ol({compact=>undef},li('one'),li('two'),li('three'));
4712 Prior to CGI.pm version 2.41, providing an empty ('') string as an
4713 attribute argument was the same as providing undef. However, this has
4714 changed in order to accommodate those who want to create tags of the form
4715 <IMG ALT="">. The difference is shown in these two pieces of code:
4717 CODE RESULT
4718 img({alt=>undef}) <IMG ALT>
4719 img({alt=>''}) <IMT ALT="">
4721 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
4723 One of the cool features of the HTML shortcuts is that they are
4724 distributive. If you give them an argument consisting of a
4725 B<reference> to a list, the tag will be distributed across each
4726 element of the list. For example, here's one way to make an ordered
4727 list:
4729 print ul(
4730 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
4733 This example will result in HTML output that looks like this:
4735 <UL>
4736 <LI TYPE="disc">Sneezy</LI>
4737 <LI TYPE="disc">Doc</LI>
4738 <LI TYPE="disc">Sleepy</LI>
4739 <LI TYPE="disc">Happy</LI>
4740 </UL>
4742 This is extremely useful for creating tables. For example:
4744 print table({-border=>undef},
4745 caption('When Should You Eat Your Vegetables?'),
4746 Tr({-align=>CENTER,-valign=>TOP},
4748 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
4749 td(['Tomatoes' , 'no', 'yes', 'yes']),
4750 td(['Broccoli' , 'no', 'no', 'yes']),
4751 td(['Onions' , 'yes','yes', 'yes'])
4756 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
4758 Consider this bit of code:
4760 print blockquote(em('Hi'),'mom!'));
4762 It will ordinarily return the string that you probably expect, namely:
4764 <BLOCKQUOTE><EM>Hi</EM> mom!</BLOCKQUOTE>
4766 Note the space between the element "Hi" and the element "mom!".
4767 CGI.pm puts the extra space there using array interpolation, which is
4768 controlled by the magic $" variable. Sometimes this extra space is
4769 not what you want, for example, when you are trying to align a series
4770 of images. In this case, you can simply change the value of $" to an
4771 empty string.
4774 local($") = '';
4775 print blockquote(em('Hi'),'mom!'));
4778 I suggest you put the code in a block as shown here. Otherwise the
4779 change to $" will affect all subsequent code until you explicitly
4780 reset it.
4782 =head2 NON-STANDARD HTML SHORTCUTS
4784 A few HTML tags don't follow the standard pattern for various
4785 reasons.
4787 B<comment()> generates an HTML comment (<!-- comment -->). Call it
4788 like
4790 print comment('here is my comment');
4792 Because of conflicts with built-in Perl functions, the following functions
4793 begin with initial caps:
4795 Select
4797 Link
4798 Delete
4799 Accept
4802 In addition, start_html(), end_html(), start_form(), end_form(),
4803 start_multipart_form() and all the fill-out form tags are special.
4804 See their respective sections.
4806 =head2 AUTOESCAPING HTML
4808 By default, all HTML that is emitted by the form-generating functions
4809 is passed through a function called escapeHTML():
4811 =over 4
4813 =item $escaped_string = escapeHTML("unescaped string");
4815 Escape HTML formatting characters in a string.
4817 =back
4819 Provided that you have specified a character set of ISO-8859-1 (the
4820 default), the standard HTML escaping rules will be used. The "<"
4821 character becomes "&lt;", ">" becomes "&gt;", "&" becomes "&amp;", and
4822 the quote character becomes "&quot;". In addition, the hexadecimal
4823 0x8b and 0x9b characters, which many windows-based browsers interpret
4824 as the left and right angle-bracket characters, are replaced by their
4825 numeric HTML entities ("&#139" and "&#155;"). If you manually change
4826 the charset, either by calling the charset() method explicitly or by
4827 passing a -charset argument to header(), then B<all> characters will
4828 be replaced by their numeric entities, since CGI.pm has no lookup
4829 table for all the possible encodings.
4831 The automatic escaping does not apply to other shortcuts, such as
4832 h1(). You should call escapeHTML() yourself on untrusted data in
4833 order to protect your pages against nasty tricks that people may enter
4834 into guestbooks, etc.. To change the character set, use charset().
4835 To turn autoescaping off completely, use autoescape():
4837 =over 4
4839 =item $charset = charset([$charset]);
4841 Get or set the current character set.
4843 =item $flag = autoEscape([$flag]);
4845 Get or set the value of the autoescape flag.
4847 =back
4849 =head2 PRETTY-PRINTING HTML
4851 By default, all the HTML produced by these functions comes out as one
4852 long line without carriage returns or indentation. This is yuck, but
4853 it does reduce the size of the documents by 10-20%. To get
4854 pretty-printed output, please use L<CGI::Pretty>, a subclass
4855 contributed by Brian Paulsen.
4857 =head1 CREATING FILL-OUT FORMS:
4859 I<General note> The various form-creating methods all return strings
4860 to the caller, containing the tag or tags that will create the requested
4861 form element. You are responsible for actually printing out these strings.
4862 It's set up this way so that you can place formatting tags
4863 around the form elements.
4865 I<Another note> The default values that you specify for the forms are only
4866 used the B<first> time the script is invoked (when there is no query
4867 string). On subsequent invocations of the script (when there is a query
4868 string), the former values are used even if they are blank.
4870 If you want to change the value of a field from its previous value, you have two
4871 choices:
4873 (1) call the param() method to set it.
4875 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
4876 This forces the default value to be used, regardless of the previous value:
4878 print $query->textfield(-name=>'field_name',
4879 -default=>'starting value',
4880 -override=>1,
4881 -size=>50,
4882 -maxlength=>80);
4884 I<Yet another note> By default, the text and labels of form elements are
4885 escaped according to HTML rules. This means that you can safely use
4886 "<CLICK ME>" as the label for a button. However, it also interferes with
4887 your ability to incorporate special HTML character sequences, such as &Aacute;,
4888 into your fields. If you wish to turn off automatic escaping, call the
4889 autoEscape() method with a false value immediately after creating the CGI object:
4891 $query = new CGI;
4892 $query->autoEscape(undef);
4894 =head2 CREATING AN ISINDEX TAG
4896 print $query->isindex(-action=>$action);
4898 -or-
4900 print $query->isindex($action);
4902 Prints out an <ISINDEX> tag. Not very exciting. The parameter
4903 -action specifies the URL of the script to process the query. The
4904 default is to process the query with the current script.
4906 =head2 STARTING AND ENDING A FORM
4908 print $query->start_form(-method=>$method,
4909 -action=>$action,
4910 -enctype=>$encoding);
4911 <... various form stuff ...>
4912 print $query->endform;
4914 -or-
4916 print $query->start_form($method,$action,$encoding);
4917 <... various form stuff ...>
4918 print $query->endform;
4920 start_form() will return a <FORM> tag with the optional method,
4921 action and form encoding that you specify. The defaults are:
4923 method: POST
4924 action: this script
4925 enctype: application/x-www-form-urlencoded
4927 endform() returns the closing </FORM> tag.
4929 Start_form()'s enctype argument tells the browser how to package the various
4930 fields of the form before sending the form to the server. Two
4931 values are possible:
4933 B<Note:> This method was previously named startform(), and startform()
4934 is still recognized as an alias.
4936 =over 4
4938 =item B<application/x-www-form-urlencoded>
4940 This is the older type of encoding used by all browsers prior to
4941 Netscape 2.0. It is compatible with many CGI scripts and is
4942 suitable for short fields containing text data. For your
4943 convenience, CGI.pm stores the name of this encoding
4944 type in B<&CGI::URL_ENCODED>.
4946 =item B<multipart/form-data>
4948 This is the newer type of encoding introduced by Netscape 2.0.
4949 It is suitable for forms that contain very large fields or that
4950 are intended for transferring binary data. Most importantly,
4951 it enables the "file upload" feature of Netscape 2.0 forms. For
4952 your convenience, CGI.pm stores the name of this encoding type
4953 in B<&CGI::MULTIPART>
4955 Forms that use this type of encoding are not easily interpreted
4956 by CGI scripts unless they use CGI.pm or another library designed
4957 to handle them.
4959 =back
4961 For compatibility, the start_form() method uses the older form of
4962 encoding by default. If you want to use the newer form of encoding
4963 by default, you can call B<start_multipart_form()> instead of
4964 B<start_form()>.
4966 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
4967 for use with JavaScript. The -name parameter gives the
4968 form a name so that it can be identified and manipulated by
4969 JavaScript functions. -onSubmit should point to a JavaScript
4970 function that will be executed just before the form is submitted to your
4971 server. You can use this opportunity to check the contents of the form
4972 for consistency and completeness. If you find something wrong, you
4973 can put up an alert box or maybe fix things up yourself. You can
4974 abort the submission by returning false from this function.
4976 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
4977 block in the HTML header and -onSubmit points to one of these function
4978 call. See start_html() for details.
4980 =head2 CREATING A TEXT FIELD
4982 print $query->textfield(-name=>'field_name',
4983 -default=>'starting value',
4984 -size=>50,
4985 -maxlength=>80);
4986 -or-
4988 print $query->textfield('field_name','starting value',50,80);
4990 textfield() will return a text input field.
4992 =over 4
4994 =item B<Parameters>
4996 =item 1.
4998 The first parameter is the required name for the field (-name).
5000 =item 2.
5002 The optional second parameter is the default starting value for the field
5003 contents (-default).
5005 =item 3.
5007 The optional third parameter is the size of the field in
5008 characters (-size).
5010 =item 4.
5012 The optional fourth parameter is the maximum number of characters the
5013 field will accept (-maxlength).
5015 =back
5017 As with all these methods, the field will be initialized with its
5018 previous contents from earlier invocations of the script.
5019 When the form is processed, the value of the text field can be
5020 retrieved with:
5022 $value = $query->param('foo');
5024 If you want to reset it from its initial value after the script has been
5025 called once, you can do so like this:
5027 $query->param('foo',"I'm taking over this value!");
5029 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5030 value, you can force its current value by using the -override (alias -force)
5031 parameter:
5033 print $query->textfield(-name=>'field_name',
5034 -default=>'starting value',
5035 -override=>1,
5036 -size=>50,
5037 -maxlength=>80);
5039 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5040 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5041 parameters to register JavaScript event handlers. The onChange
5042 handler will be called whenever the user changes the contents of the
5043 text field. You can do text validation if you like. onFocus and
5044 onBlur are called respectively when the insertion point moves into and
5045 out of the text field. onSelect is called when the user changes the
5046 portion of the text that is selected.
5048 =head2 CREATING A BIG TEXT FIELD
5050 print $query->textarea(-name=>'foo',
5051 -default=>'starting value',
5052 -rows=>10,
5053 -columns=>50);
5057 print $query->textarea('foo','starting value',10,50);
5059 textarea() is just like textfield, but it allows you to specify
5060 rows and columns for a multiline text entry box. You can provide
5061 a starting value for the field, which can be long and contain
5062 multiple lines.
5064 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5065 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5066 recognized. See textfield().
5068 =head2 CREATING A PASSWORD FIELD
5070 print $query->password_field(-name=>'secret',
5071 -value=>'starting value',
5072 -size=>50,
5073 -maxlength=>80);
5074 -or-
5076 print $query->password_field('secret','starting value',50,80);
5078 password_field() is identical to textfield(), except that its contents
5079 will be starred out on the web page.
5081 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5082 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5083 recognized. See textfield().
5085 =head2 CREATING A FILE UPLOAD FIELD
5087 print $query->filefield(-name=>'uploaded_file',
5088 -default=>'starting value',
5089 -size=>50,
5090 -maxlength=>80);
5091 -or-
5093 print $query->filefield('uploaded_file','starting value',50,80);
5095 filefield() will return a file upload field for Netscape 2.0 browsers.
5096 In order to take full advantage of this I<you must use the new
5097 multipart encoding scheme> for the form. You can do this either
5098 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5099 or by calling the new method B<start_multipart_form()> instead of
5100 vanilla B<start_form()>.
5102 =over 4
5104 =item B<Parameters>
5106 =item 1.
5108 The first parameter is the required name for the field (-name).
5110 =item 2.
5112 The optional second parameter is the starting value for the field contents
5113 to be used as the default file name (-default).
5115 For security reasons, browsers don't pay any attention to this field,
5116 and so the starting value will always be blank. Worse, the field
5117 loses its "sticky" behavior and forgets its previous contents. The
5118 starting value field is called for in the HTML specification, however,
5119 and possibly some browser will eventually provide support for it.
5121 =item 3.
5123 The optional third parameter is the size of the field in
5124 characters (-size).
5126 =item 4.
5128 The optional fourth parameter is the maximum number of characters the
5129 field will accept (-maxlength).
5131 =back
5133 When the form is processed, you can retrieve the entered filename
5134 by calling param():
5136 $filename = $query->param('uploaded_file');
5138 Different browsers will return slightly different things for the
5139 name. Some browsers return the filename only. Others return the full
5140 path to the file, using the path conventions of the user's machine.
5141 Regardless, the name returned is always the name of the file on the
5142 I<user's> machine, and is unrelated to the name of the temporary file
5143 that CGI.pm creates during upload spooling (see below).
5145 The filename returned is also a file handle. You can read the contents
5146 of the file using standard Perl file reading calls:
5148 # Read a text file and print it out
5149 while (<$filename>) {
5150 print;
5153 # Copy a binary file to somewhere safe
5154 open (OUTFILE,">>/usr/local/web/users/feedback");
5155 while ($bytesread=read($filename,$buffer,1024)) {
5156 print OUTFILE $buffer;
5159 However, there are problems with the dual nature of the upload fields.
5160 If you C<use strict>, then Perl will complain when you try to use a
5161 string as a filehandle. You can get around this by placing the file
5162 reading code in a block containing the C<no strict> pragma. More
5163 seriously, it is possible for the remote user to type garbage into the
5164 upload field, in which case what you get from param() is not a
5165 filehandle at all, but a string.
5167 To be safe, use the I<upload()> function (new in version 2.47). When
5168 called with the name of an upload field, I<upload()> returns a
5169 filehandle, or undef if the parameter is not a valid filehandle.
5171 $fh = $query->upload('uploaded_file');
5172 while (<$fh>) {
5173 print;
5176 This is the recommended idiom.
5178 When a file is uploaded the browser usually sends along some
5179 information along with it in the format of headers. The information
5180 usually includes the MIME content type. Future browsers may send
5181 other information as well (such as modification date and size). To
5182 retrieve this information, call uploadInfo(). It returns a reference to
5183 an associative array containing all the document headers.
5185 $filename = $query->param('uploaded_file');
5186 $type = $query->uploadInfo($filename)->{'Content-Type'};
5187 unless ($type eq 'text/html') {
5188 die "HTML FILES ONLY!";
5191 If you are using a machine that recognizes "text" and "binary" data
5192 modes, be sure to understand when and how to use them (see the Camel book).
5193 Otherwise you may find that binary files are corrupted during file
5194 uploads.
5196 There are occasionally problems involving parsing the uploaded file.
5197 This usually happens when the user presses "Stop" before the upload is
5198 finished. In this case, CGI.pm will return undef for the name of the
5199 uploaded file and set I<cgi_error()> to the string "400 Bad request
5200 (malformed multipart POST)". This error message is designed so that
5201 you can incorporate it into a status code to be sent to the browser.
5202 Example:
5204 $file = $query->upload('uploaded_file');
5205 if (!$file && $query->cgi_error) {
5206 print $query->header(-status=>$query->cgi_error);
5207 exit 0;
5210 You are free to create a custom HTML page to complain about the error,
5211 if you wish.
5213 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5214 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5215 recognized. See textfield() for details.
5217 =head2 CREATING A POPUP MENU
5219 print $query->popup_menu('menu_name',
5220 ['eenie','meenie','minie'],
5221 'meenie');
5223 -or-
5225 %labels = ('eenie'=>'your first choice',
5226 'meenie'=>'your second choice',
5227 'minie'=>'your third choice');
5228 print $query->popup_menu('menu_name',
5229 ['eenie','meenie','minie'],
5230 'meenie',\%labels);
5232 -or (named parameter style)-
5234 print $query->popup_menu(-name=>'menu_name',
5235 -values=>['eenie','meenie','minie'],
5236 -default=>'meenie',
5237 -labels=>\%labels);
5239 popup_menu() creates a menu.
5241 =over 4
5243 =item 1.
5245 The required first argument is the menu's name (-name).
5247 =item 2.
5249 The required second argument (-values) is an array B<reference>
5250 containing the list of menu items in the menu. You can pass the
5251 method an anonymous array, as shown in the example, or a reference to
5252 a named array, such as "\@foo".
5254 =item 3.
5256 The optional third parameter (-default) is the name of the default
5257 menu choice. If not specified, the first item will be the default.
5258 The values of the previous choice will be maintained across queries.
5260 =item 4.
5262 The optional fourth parameter (-labels) is provided for people who
5263 want to use different values for the user-visible label inside the
5264 popup menu nd the value returned to your script. It's a pointer to an
5265 associative array relating menu values to user-visible labels. If you
5266 leave this parameter blank, the menu values will be displayed by
5267 default. (You can also leave a label undefined if you want to).
5269 =back
5271 When the form is processed, the selected value of the popup menu can
5272 be retrieved using:
5274 $popup_menu_value = $query->param('menu_name');
5276 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5277 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5278 B<-onBlur>. See the textfield() section for details on when these
5279 handlers are called.
5281 =head2 CREATING A SCROLLING LIST
5283 print $query->scrolling_list('list_name',
5284 ['eenie','meenie','minie','moe'],
5285 ['eenie','moe'],5,'true');
5286 -or-
5288 print $query->scrolling_list('list_name',
5289 ['eenie','meenie','minie','moe'],
5290 ['eenie','moe'],5,'true',
5291 \%labels);
5293 -or-
5295 print $query->scrolling_list(-name=>'list_name',
5296 -values=>['eenie','meenie','minie','moe'],
5297 -default=>['eenie','moe'],
5298 -size=>5,
5299 -multiple=>'true',
5300 -labels=>\%labels);
5302 scrolling_list() creates a scrolling list.
5304 =over 4
5306 =item B<Parameters:>
5308 =item 1.
5310 The first and second arguments are the list name (-name) and values
5311 (-values). As in the popup menu, the second argument should be an
5312 array reference.
5314 =item 2.
5316 The optional third argument (-default) can be either a reference to a
5317 list containing the values to be selected by default, or can be a
5318 single value to select. If this argument is missing or undefined,
5319 then nothing is selected when the list first appears. In the named
5320 parameter version, you can use the synonym "-defaults" for this
5321 parameter.
5323 =item 3.
5325 The optional fourth argument is the size of the list (-size).
5327 =item 4.
5329 The optional fifth argument can be set to true to allow multiple
5330 simultaneous selections (-multiple). Otherwise only one selection
5331 will be allowed at a time.
5333 =item 5.
5335 The optional sixth argument is a pointer to an associative array
5336 containing long user-visible labels for the list items (-labels).
5337 If not provided, the values will be displayed.
5339 When this form is processed, all selected list items will be returned as
5340 a list under the parameter name 'list_name'. The values of the
5341 selected items can be retrieved with:
5343 @selected = $query->param('list_name');
5345 =back
5347 JAVASCRIPTING: scrolling_list() recognizes the following event
5348 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5349 and B<-onBlur>. See textfield() for the description of when these
5350 handlers are called.
5352 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5354 print $query->checkbox_group(-name=>'group_name',
5355 -values=>['eenie','meenie','minie','moe'],
5356 -default=>['eenie','moe'],
5357 -linebreak=>'true',
5358 -labels=>\%labels);
5360 print $query->checkbox_group('group_name',
5361 ['eenie','meenie','minie','moe'],
5362 ['eenie','moe'],'true',\%labels);
5364 HTML3-COMPATIBLE BROWSERS ONLY:
5366 print $query->checkbox_group(-name=>'group_name',
5367 -values=>['eenie','meenie','minie','moe'],
5368 -rows=2,-columns=>2);
5371 checkbox_group() creates a list of checkboxes that are related
5372 by the same name.
5374 =over 4
5376 =item B<Parameters:>
5378 =item 1.
5380 The first and second arguments are the checkbox name and values,
5381 respectively (-name and -values). As in the popup menu, the second
5382 argument should be an array reference. These values are used for the
5383 user-readable labels printed next to the checkboxes as well as for the
5384 values passed to your script in the query string.
5386 =item 2.
5388 The optional third argument (-default) can be either a reference to a
5389 list containing the values to be checked by default, or can be a
5390 single value to checked. If this argument is missing or undefined,
5391 then nothing is selected when the list first appears.
5393 =item 3.
5395 The optional fourth argument (-linebreak) can be set to true to place
5396 line breaks between the checkboxes so that they appear as a vertical
5397 list. Otherwise, they will be strung together on a horizontal line.
5399 =item 4.
5401 The optional fifth argument is a pointer to an associative array
5402 relating the checkbox values to the user-visible labels that will
5403 be printed next to them (-labels). If not provided, the values will
5404 be used as the default.
5406 =item 5.
5408 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5409 the optional parameters B<-rows>, and B<-columns>. These parameters
5410 cause checkbox_group() to return an HTML3 compatible table containing
5411 the checkbox group formatted with the specified number of rows and
5412 columns. You can provide just the -columns parameter if you wish;
5413 checkbox_group will calculate the correct number of rows for you.
5415 To include row and column headings in the returned table, you
5416 can use the B<-rowheaders> and B<-colheaders> parameters. Both
5417 of these accept a pointer to an array of headings to use.
5418 The headings are just decorative. They don't reorganize the
5419 interpretation of the checkboxes -- they're still a single named
5420 unit.
5422 =back
5424 When the form is processed, all checked boxes will be returned as
5425 a list under the parameter name 'group_name'. The values of the
5426 "on" checkboxes can be retrieved with:
5428 @turned_on = $query->param('group_name');
5430 The value returned by checkbox_group() is actually an array of button
5431 elements. You can capture them and use them within tables, lists,
5432 or in other creative ways:
5434 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
5435 &use_in_creative_way(@h);
5437 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
5438 parameter. This specifies a JavaScript code fragment or
5439 function call to be executed every time the user clicks on
5440 any of the buttons in the group. You can retrieve the identity
5441 of the particular button clicked on using the "this" variable.
5443 =head2 CREATING A STANDALONE CHECKBOX
5445 print $query->checkbox(-name=>'checkbox_name',
5446 -checked=>'checked',
5447 -value=>'ON',
5448 -label=>'CLICK ME');
5450 -or-
5452 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
5454 checkbox() is used to create an isolated checkbox that isn't logically
5455 related to any others.
5457 =over 4
5459 =item B<Parameters:>
5461 =item 1.
5463 The first parameter is the required name for the checkbox (-name). It
5464 will also be used for the user-readable label printed next to the
5465 checkbox.
5467 =item 2.
5469 The optional second parameter (-checked) specifies that the checkbox
5470 is turned on by default. Synonyms are -selected and -on.
5472 =item 3.
5474 The optional third parameter (-value) specifies the value of the
5475 checkbox when it is checked. If not provided, the word "on" is
5476 assumed.
5478 =item 4.
5480 The optional fourth parameter (-label) is the user-readable label to
5481 be attached to the checkbox. If not provided, the checkbox name is
5482 used.
5484 =back
5486 The value of the checkbox can be retrieved using:
5488 $turned_on = $query->param('checkbox_name');
5490 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5491 parameter. See checkbox_group() for further details.
5493 =head2 CREATING A RADIO BUTTON GROUP
5495 print $query->radio_group(-name=>'group_name',
5496 -values=>['eenie','meenie','minie'],
5497 -default=>'meenie',
5498 -linebreak=>'true',
5499 -labels=>\%labels);
5501 -or-
5503 print $query->radio_group('group_name',['eenie','meenie','minie'],
5504 'meenie','true',\%labels);
5507 HTML3-COMPATIBLE BROWSERS ONLY:
5509 print $query->radio_group(-name=>'group_name',
5510 -values=>['eenie','meenie','minie','moe'],
5511 -rows=2,-columns=>2);
5513 radio_group() creates a set of logically-related radio buttons
5514 (turning one member of the group on turns the others off)
5516 =over 4
5518 =item B<Parameters:>
5520 =item 1.
5522 The first argument is the name of the group and is required (-name).
5524 =item 2.
5526 The second argument (-values) is the list of values for the radio
5527 buttons. The values and the labels that appear on the page are
5528 identical. Pass an array I<reference> in the second argument, either
5529 using an anonymous array, as shown, or by referencing a named array as
5530 in "\@foo".
5532 =item 3.
5534 The optional third parameter (-default) is the name of the default
5535 button to turn on. If not specified, the first item will be the
5536 default. You can provide a nonexistent button name, such as "-" to
5537 start up with no buttons selected.
5539 =item 4.
5541 The optional fourth parameter (-linebreak) can be set to 'true' to put
5542 line breaks between the buttons, creating a vertical list.
5544 =item 5.
5546 The optional fifth parameter (-labels) is a pointer to an associative
5547 array relating the radio button values to user-visible labels to be
5548 used in the display. If not provided, the values themselves are
5549 displayed.
5551 =item 6.
5553 B<HTML3-compatible browsers> (such as Netscape) can take advantage
5554 of the optional
5555 parameters B<-rows>, and B<-columns>. These parameters cause
5556 radio_group() to return an HTML3 compatible table containing
5557 the radio group formatted with the specified number of rows
5558 and columns. You can provide just the -columns parameter if you
5559 wish; radio_group will calculate the correct number of rows
5560 for you.
5562 To include row and column headings in the returned table, you
5563 can use the B<-rowheader> and B<-colheader> parameters. Both
5564 of these accept a pointer to an array of headings to use.
5565 The headings are just decorative. They don't reorganize the
5566 interpretation of the radio buttons -- they're still a single named
5567 unit.
5569 =back
5571 When the form is processed, the selected radio button can
5572 be retrieved using:
5574 $which_radio_button = $query->param('group_name');
5576 The value returned by radio_group() is actually an array of button
5577 elements. You can capture them and use them within tables, lists,
5578 or in other creative ways:
5580 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
5581 &use_in_creative_way(@h);
5583 =head2 CREATING A SUBMIT BUTTON
5585 print $query->submit(-name=>'button_name',
5586 -value=>'value');
5588 -or-
5590 print $query->submit('button_name','value');
5592 submit() will create the query submission button. Every form
5593 should have one of these.
5595 =over 4
5597 =item B<Parameters:>
5599 =item 1.
5601 The first argument (-name) is optional. You can give the button a
5602 name if you have several submission buttons in your form and you want
5603 to distinguish between them. The name will also be used as the
5604 user-visible label. Be aware that a few older browsers don't deal with this correctly and
5605 B<never> send back a value from a button.
5607 =item 2.
5609 The second argument (-value) is also optional. This gives the button
5610 a value that will be passed to your script in the query string.
5612 =back
5614 You can figure out which button was pressed by using different
5615 values for each one:
5617 $which_one = $query->param('button_name');
5619 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
5620 parameter. See checkbox_group() for further details.
5622 =head2 CREATING A RESET BUTTON
5624 print $query->reset
5626 reset() creates the "reset" button. Note that it restores the
5627 form to its value from the last time the script was called,
5628 NOT necessarily to the defaults.
5630 Note that this conflicts with the Perl reset() built-in. Use
5631 CORE::reset() to get the original reset function.
5633 =head2 CREATING A DEFAULT BUTTON
5635 print $query->defaults('button_label')
5637 defaults() creates a button that, when invoked, will cause the
5638 form to be completely reset to its defaults, wiping out all the
5639 changes the user ever made.
5641 =head2 CREATING A HIDDEN FIELD
5643 print $query->hidden(-name=>'hidden_name',
5644 -default=>['value1','value2'...]);
5646 -or-
5648 print $query->hidden('hidden_name','value1','value2'...);
5650 hidden() produces a text field that can't be seen by the user. It
5651 is useful for passing state variable information from one invocation
5652 of the script to the next.
5654 =over 4
5656 =item B<Parameters:>
5658 =item 1.
5660 The first argument is required and specifies the name of this
5661 field (-name).
5663 =item 2.
5665 The second argument is also required and specifies its value
5666 (-default). In the named parameter style of calling, you can provide
5667 a single value here or a reference to a whole list
5669 =back
5671 Fetch the value of a hidden field this way:
5673 $hidden_value = $query->param('hidden_name');
5675 Note, that just like all the other form elements, the value of a
5676 hidden field is "sticky". If you want to replace a hidden field with
5677 some other values after the script has been called once you'll have to
5678 do it manually:
5680 $query->param('hidden_name','new','values','here');
5682 =head2 CREATING A CLICKABLE IMAGE BUTTON
5684 print $query->image_button(-name=>'button_name',
5685 -src=>'/source/URL',
5686 -align=>'MIDDLE');
5688 -or-
5690 print $query->image_button('button_name','/source/URL','MIDDLE');
5692 image_button() produces a clickable image. When it's clicked on the
5693 position of the click is returned to your script as "button_name.x"
5694 and "button_name.y", where "button_name" is the name you've assigned
5695 to it.
5697 JAVASCRIPTING: image_button() recognizes the B<-onClick>
5698 parameter. See checkbox_group() for further details.
5700 =over 4
5702 =item B<Parameters:>
5704 =item 1.
5706 The first argument (-name) is required and specifies the name of this
5707 field.
5709 =item 2.
5711 The second argument (-src) is also required and specifies the URL
5713 =item 3.
5715 The third option (-align, optional) is an alignment type, and may be
5716 TOP, BOTTOM or MIDDLE
5718 =back
5720 Fetch the value of the button this way:
5721 $x = $query->param('button_name.x');
5722 $y = $query->param('button_name.y');
5724 =head2 CREATING A JAVASCRIPT ACTION BUTTON
5726 print $query->button(-name=>'button_name',
5727 -value=>'user visible label',
5728 -onClick=>"do_something()");
5730 -or-
5732 print $query->button('button_name',"do_something()");
5734 button() produces a button that is compatible with Netscape 2.0's
5735 JavaScript. When it's pressed the fragment of JavaScript code
5736 pointed to by the B<-onClick> parameter will be executed. On
5737 non-Netscape browsers this form element will probably not even
5738 display.
5740 =head1 HTTP COOKIES
5742 Netscape browsers versions 1.1 and higher, and all versions of
5743 Internet Explorer, support a so-called "cookie" designed to help
5744 maintain state within a browser session. CGI.pm has several methods
5745 that support cookies.
5747 A cookie is a name=value pair much like the named parameters in a CGI
5748 query string. CGI scripts create one or more cookies and send
5749 them to the browser in the HTTP header. The browser maintains a list
5750 of cookies that belong to a particular Web server, and returns them
5751 to the CGI script during subsequent interactions.
5753 In addition to the required name=value pair, each cookie has several
5754 optional attributes:
5756 =over 4
5758 =item 1. an expiration time
5760 This is a time/date string (in a special GMT format) that indicates
5761 when a cookie expires. The cookie will be saved and returned to your
5762 script until this expiration date is reached if the user exits
5763 the browser and restarts it. If an expiration date isn't specified, the cookie
5764 will remain active until the user quits the browser.
5766 =item 2. a domain
5768 This is a partial or complete domain name for which the cookie is
5769 valid. The browser will return the cookie to any host that matches
5770 the partial domain name. For example, if you specify a domain name
5771 of ".capricorn.com", then the browser will return the cookie to
5772 Web servers running on any of the machines "www.capricorn.com",
5773 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
5774 must contain at least two periods to prevent attempts to match
5775 on top level domains like ".edu". If no domain is specified, then
5776 the browser will only return the cookie to servers on the host the
5777 cookie originated from.
5779 =item 3. a path
5781 If you provide a cookie path attribute, the browser will check it
5782 against your script's URL before returning the cookie. For example,
5783 if you specify the path "/cgi-bin", then the cookie will be returned
5784 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
5785 and "/cgi-bin/customer_service/complain.pl", but not to the script
5786 "/cgi-private/site_admin.pl". By default, path is set to "/", which
5787 causes the cookie to be sent to any CGI script on your site.
5789 =item 4. a "secure" flag
5791 If the "secure" attribute is set, the cookie will only be sent to your
5792 script if the CGI request is occurring on a secure channel, such as SSL.
5794 =back
5796 The interface to HTTP cookies is the B<cookie()> method:
5798 $cookie = $query->cookie(-name=>'sessionID',
5799 -value=>'xyzzy',
5800 -expires=>'+1h',
5801 -path=>'/cgi-bin/database',
5802 -domain=>'.capricorn.org',
5803 -secure=>1);
5804 print $query->header(-cookie=>$cookie);
5806 B<cookie()> creates a new cookie. Its parameters include:
5808 =over 4
5810 =item B<-name>
5812 The name of the cookie (required). This can be any string at all.
5813 Although browsers limit their cookie names to non-whitespace
5814 alphanumeric characters, CGI.pm removes this restriction by escaping
5815 and unescaping cookies behind the scenes.
5817 =item B<-value>
5819 The value of the cookie. This can be any scalar value,
5820 array reference, or even associative array reference. For example,
5821 you can store an entire associative array into a cookie this way:
5823 $cookie=$query->cookie(-name=>'family information',
5824 -value=>\%childrens_ages);
5826 =item B<-path>
5828 The optional partial path for which this cookie will be valid, as described
5829 above.
5831 =item B<-domain>
5833 The optional partial domain for which this cookie will be valid, as described
5834 above.
5836 =item B<-expires>
5838 The optional expiration date for this cookie. The format is as described
5839 in the section on the B<header()> method:
5841 "+1h" one hour from now
5843 =item B<-secure>
5845 If set to true, this cookie will only be used within a secure
5846 SSL session.
5848 =back
5850 The cookie created by cookie() must be incorporated into the HTTP
5851 header within the string returned by the header() method:
5853 print $query->header(-cookie=>$my_cookie);
5855 To create multiple cookies, give header() an array reference:
5857 $cookie1 = $query->cookie(-name=>'riddle_name',
5858 -value=>"The Sphynx's Question");
5859 $cookie2 = $query->cookie(-name=>'answers',
5860 -value=>\%answers);
5861 print $query->header(-cookie=>[$cookie1,$cookie2]);
5863 To retrieve a cookie, request it by name by calling cookie() method
5864 without the B<-value> parameter:
5866 use CGI;
5867 $query = new CGI;
5868 $riddle = $query->cookie('riddle_name');
5869 %answers = $query->cookie('answers');
5871 Cookies created with a single scalar value, such as the "riddle_name"
5872 cookie, will be returned in that form. Cookies with array and hash
5873 values can also be retrieved.
5875 The cookie and CGI namespaces are separate. If you have a parameter
5876 named 'answers' and a cookie named 'answers', the values retrieved by
5877 param() and cookie() are independent of each other. However, it's
5878 simple to turn a CGI parameter into a cookie, and vice-versa:
5880 # turn a CGI parameter into a cookie
5881 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
5882 # vice-versa
5883 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
5885 See the B<cookie.cgi> example script for some ideas on how to use
5886 cookies effectively.
5888 =head1 WORKING WITH FRAMES
5890 It's possible for CGI.pm scripts to write into several browser panels
5891 and windows using the HTML 4 frame mechanism. There are three
5892 techniques for defining new frames programmatically:
5894 =over 4
5896 =item 1. Create a <Frameset> document
5898 After writing out the HTTP header, instead of creating a standard
5899 HTML document using the start_html() call, create a <FRAMESET>
5900 document that defines the frames on the page. Specify your script(s)
5901 (with appropriate parameters) as the SRC for each of the frames.
5903 There is no specific support for creating <FRAMESET> sections
5904 in CGI.pm, but the HTML is very simple to write. See the frame
5905 documentation in Netscape's home pages for details
5907 http://home.netscape.com/assist/net_sites/frames.html
5909 =item 2. Specify the destination for the document in the HTTP header
5911 You may provide a B<-target> parameter to the header() method:
5913 print $q->header(-target=>'ResultsWindow');
5915 This will tell the browser to load the output of your script into the
5916 frame named "ResultsWindow". If a frame of that name doesn't already
5917 exist, the browser will pop up a new window and load your script's
5918 document into that. There are a number of magic names that you can
5919 use for targets. See the frame documents on Netscape's home pages for
5920 details.
5922 =item 3. Specify the destination for the document in the <FORM> tag
5924 You can specify the frame to load in the FORM tag itself. With
5925 CGI.pm it looks like this:
5927 print $q->start_form(-target=>'ResultsWindow');
5929 When your script is reinvoked by the form, its output will be loaded
5930 into the frame named "ResultsWindow". If one doesn't already exist
5931 a new window will be created.
5933 =back
5935 The script "frameset.cgi" in the examples directory shows one way to
5936 create pages in which the fill-out form and the response live in
5937 side-by-side frames.
5939 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
5941 CGI.pm has limited support for HTML3's cascading style sheets (css).
5942 To incorporate a stylesheet into your document, pass the
5943 start_html() method a B<-style> parameter. The value of this
5944 parameter may be a scalar, in which case it is incorporated directly
5945 into a <STYLE> section, or it may be a hash reference. In the latter
5946 case you should provide the hash with one or more of B<-src> or
5947 B<-code>. B<-src> points to a URL where an externally-defined
5948 stylesheet can be found. B<-code> points to a scalar value to be
5949 incorporated into a <STYLE> section. Style definitions in B<-code>
5950 override similarly-named ones in B<-src>, hence the name "cascading."
5952 You may also specify the type of the stylesheet by adding the optional
5953 B<-type> parameter to the hash pointed to by B<-style>. If not
5954 specified, the style defaults to 'text/css'.
5956 To refer to a style within the body of your document, add the
5957 B<-class> parameter to any HTML element:
5959 print h1({-class=>'Fancy'},'Welcome to the Party');
5961 Or define styles on the fly with the B<-style> parameter:
5963 print h1({-style=>'Color: red;'},'Welcome to Hell');
5965 You may also use the new B<span()> element to apply a style to a
5966 section of text:
5968 print span({-style=>'Color: red;'},
5969 h1('Welcome to Hell'),
5970 "Where did that handbasket get to?"
5973 Note that you must import the ":html3" definitions to have the
5974 B<span()> method available. Here's a quick and dirty example of using
5975 CSS's. See the CSS specification at
5976 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
5978 use CGI qw/:standard :html3/;
5980 #here's a stylesheet incorporated directly into the page
5981 $newStyle=<<END;
5982 <!--
5983 P.Tip {
5984 margin-right: 50pt;
5985 margin-left: 50pt;
5986 color: red;
5988 P.Alert {
5989 font-size: 30pt;
5990 font-family: sans-serif;
5991 color: red;
5995 print header();
5996 print start_html( -title=>'CGI with Style',
5997 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
5998 -code=>$newStyle}
6000 print h1('CGI with Style'),
6001 p({-class=>'Tip'},
6002 "Better read the cascading style sheet spec before playing with this!"),
6003 span({-style=>'color: magenta'},
6004 "Look Mom, no hands!",
6005 p(),
6006 "Whooo wee!"
6008 print end_html;
6010 Pass an array reference to B<-style> in order to incorporate multiple
6011 stylesheets into your document.
6013 =head1 DEBUGGING
6015 If you are running the script from the command line or in the perl
6016 debugger, you can pass the script a list of keywords or
6017 parameter=value pairs on the command line or from standard input (you
6018 don't have to worry about tricking your script into reading from
6019 environment variables). You can pass keywords like this:
6021 your_script.pl keyword1 keyword2 keyword3
6023 or this:
6025 your_script.pl keyword1+keyword2+keyword3
6027 or this:
6029 your_script.pl name1=value1 name2=value2
6031 or this:
6033 your_script.pl name1=value1&name2=value2
6035 To turn off this feature, use the -no_debug pragma.
6037 To test the POST method, you may enable full debugging with the -debug
6038 pragma. This will allow you to feed newline-delimited name=value
6039 pairs to the script on standard input.
6041 When debugging, you can use quotes and backslashes to escape
6042 characters in the familiar shell manner, letting you place
6043 spaces and other funny characters in your parameter=value
6044 pairs:
6046 your_script.pl "name1='I am a long value'" "name2=two\ words"
6048 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6050 The Dump() method produces a string consisting of all the query's
6051 name/value pairs formatted nicely as a nested list. This is useful
6052 for debugging purposes:
6054 print $query->Dump
6057 Produces something that looks like:
6059 <UL>
6060 <LI>name1
6061 <UL>
6062 <LI>value1
6063 <LI>value2
6064 </UL>
6065 <LI>name2
6066 <UL>
6067 <LI>value1
6068 </UL>
6069 </UL>
6071 As a shortcut, you can interpolate the entire CGI object into a string
6072 and it will be replaced with the a nice HTML dump shown above:
6074 $query=new CGI;
6075 print "<H2>Current Values</H2> $query\n";
6077 =head1 FETCHING ENVIRONMENT VARIABLES
6079 Some of the more useful environment variables can be fetched
6080 through this interface. The methods are as follows:
6082 =over 4
6084 =item B<Accept()>
6086 Return a list of MIME types that the remote browser accepts. If you
6087 give this method a single argument corresponding to a MIME type, as in
6088 $query->Accept('text/html'), it will return a floating point value
6089 corresponding to the browser's preference for this type from 0.0
6090 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
6091 list are handled correctly.
6093 Note that the capitalization changed between version 2.43 and 2.44 in
6094 order to avoid conflict with Perl's accept() function.
6096 =item B<raw_cookie()>
6098 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
6099 Netscape browsers version 1.1 and higher, and all versions of Internet
6100 Explorer. Cookies have a special format, and this method call just
6101 returns the raw form (?cookie dough). See cookie() for ways of
6102 setting and retrieving cooked cookies.
6104 Called with no parameters, raw_cookie() returns the packed cookie
6105 structure. You can separate it into individual cookies by splitting
6106 on the character sequence "; ". Called with the name of a cookie,
6107 retrieves the B<unescaped> form of the cookie. You can use the
6108 regular cookie() method to get the names, or use the raw_fetch()
6109 method from the CGI::Cookie module.
6111 =item B<user_agent()>
6113 Returns the HTTP_USER_AGENT variable. If you give
6114 this method a single argument, it will attempt to
6115 pattern match on it, allowing you to do something
6116 like $query->user_agent(netscape);
6118 =item B<path_info()>
6120 Returns additional path information from the script URL.
6121 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6122 $query->path_info() returning "/additional/stuff".
6124 NOTE: The Microsoft Internet Information Server
6125 is broken with respect to additional path information. If
6126 you use the Perl DLL library, the IIS server will attempt to
6127 execute the additional path information as a Perl script.
6128 If you use the ordinary file associations mapping, the
6129 path information will be present in the environment,
6130 but incorrect. The best thing to do is to avoid using additional
6131 path information in CGI scripts destined for use with IIS.
6133 =item B<path_translated()>
6135 As per path_info() but returns the additional
6136 path information translated into a physical path, e.g.
6137 "/usr/local/etc/httpd/htdocs/additional/stuff".
6139 The Microsoft IIS is broken with respect to the translated
6140 path as well.
6142 =item B<remote_host()>
6144 Returns either the remote host name or IP address.
6145 if the former is unavailable.
6147 =item B<script_name()>
6149 Return the script name as a partial URL, for self-refering
6150 scripts.
6152 =item B<referer()>
6154 Return the URL of the page the browser was viewing
6155 prior to fetching your script. Not available for all
6156 browsers.
6158 =item B<auth_type ()>
6160 Return the authorization/verification method in use for this
6161 script, if any.
6163 =item B<server_name ()>
6165 Returns the name of the server, usually the machine's host
6166 name.
6168 =item B<virtual_host ()>
6170 When using virtual hosts, returns the name of the host that
6171 the browser attempted to contact
6173 =item B<server_port ()>
6175 Return the port that the server is listening on.
6177 =item B<server_software ()>
6179 Returns the server software and version number.
6181 =item B<remote_user ()>
6183 Return the authorization/verification name used for user
6184 verification, if this script is protected.
6186 =item B<user_name ()>
6188 Attempt to obtain the remote user's name, using a variety of different
6189 techniques. This only works with older browsers such as Mosaic.
6190 Newer browsers do not report the user name for privacy reasons!
6192 =item B<request_method()>
6194 Returns the method used to access your script, usually
6195 one of 'POST', 'GET' or 'HEAD'.
6197 =item B<content_type()>
6199 Returns the content_type of data submitted in a POST, generally
6200 multipart/form-data or application/x-www-form-urlencoded
6202 =item B<http()>
6204 Called with no arguments returns the list of HTTP environment
6205 variables, including such things as HTTP_USER_AGENT,
6206 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6207 like-named HTTP header fields in the request. Called with the name of
6208 an HTTP header field, returns its value. Capitalization and the use
6209 of hyphens versus underscores are not significant.
6211 For example, all three of these examples are equivalent:
6213 $requested_language = $q->http('Accept-language');
6214 $requested_language = $q->http('Accept_language');
6215 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6217 =item B<https()>
6219 The same as I<http()>, but operates on the HTTPS environment variables
6220 present when the SSL protocol is in effect. Can be used to determine
6221 whether SSL is turned on.
6223 =back
6225 =head1 USING NPH SCRIPTS
6227 NPH, or "no-parsed-header", scripts bypass the server completely by
6228 sending the complete HTTP header directly to the browser. This has
6229 slight performance benefits, but is of most use for taking advantage
6230 of HTTP extensions that are not directly supported by your server,
6231 such as server push and PICS headers.
6233 Servers use a variety of conventions for designating CGI scripts as
6234 NPH. Many Unix servers look at the beginning of the script's name for
6235 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6236 Internet Information Server, in contrast, try to decide whether a
6237 program is an NPH script by examining the first line of script output.
6240 CGI.pm supports NPH scripts with a special NPH mode. When in this
6241 mode, CGI.pm will output the necessary extra header information when
6242 the header() and redirect() methods are
6243 called.
6245 The Microsoft Internet Information Server requires NPH mode. As of version
6246 2.30, CGI.pm will automatically detect when the script is running under IIS
6247 and put itself into this mode. You do not need to do this manually, although
6248 it won't hurt anything if you do.
6250 There are a number of ways to put CGI.pm into NPH mode:
6252 =over 4
6254 =item In the B<use> statement
6256 Simply add the "-nph" pragmato the list of symbols to be imported into
6257 your script:
6259 use CGI qw(:standard -nph)
6261 =item By calling the B<nph()> method:
6263 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6265 CGI->nph(1)
6267 =item By using B<-nph> parameters
6269 in the B<header()> and B<redirect()> statements:
6271 print $q->header(-nph=>1);
6273 =back
6275 =head1 Server Push
6277 CGI.pm provides four simple functions for producing multipart
6278 documents of the type needed to implement server push. These
6279 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6280 import these into your namespace, you must import the ":push" set.
6281 You are also advised to put the script into NPH mode and to set $| to
6282 1 to avoid buffering problems.
6284 Here is a simple script that demonstrates server push:
6286 #!/usr/local/bin/perl
6287 use CGI qw/:push -nph/;
6288 $| = 1;
6289 print multipart_init(-boundary=>'----here we go!');
6290 foreach (0 .. 4) {
6291 print multipart_start(-type=>'text/plain'),
6292 "The current time is ",scalar(localtime),"\n";
6293 if ($_ < 4) {
6294 print multipart_end;
6295 } else {
6296 print multipart_final;
6298 sleep 1;
6301 This script initializes server push by calling B<multipart_init()>.
6302 It then enters a loop in which it begins a new multipart section by
6303 calling B<multipart_start()>, prints the current local time,
6304 and ends a multipart section with B<multipart_end()>. It then sleeps
6305 a second, and begins again. On the final iteration, it ends the
6306 multipart section with B<multipart_final()> rather than with
6307 B<multipart_end()>.
6309 =over 4
6311 =item multipart_init()
6313 multipart_init(-boundary=>$boundary);
6315 Initialize the multipart system. The -boundary argument specifies
6316 what MIME boundary string to use to separate parts of the document.
6317 If not provided, CGI.pm chooses a reasonable boundary for you.
6319 =item multipart_start()
6321 multipart_start(-type=>$type)
6323 Start a new part of the multipart document using the specified MIME
6324 type. If not specified, text/html is assumed.
6326 =item multipart_end()
6328 multipart_end()
6330 End a part. You must remember to call multipart_end() once for each
6331 multipart_start(), except at the end of the last part of the multipart
6332 document when multipart_final() should be called instead of multipart_end().
6334 =item multipart_final()
6336 multipart_final()
6338 End all parts. You should call multipart_final() rather than
6339 multipart_end() at the end of the last part of the multipart document.
6341 =back
6343 Users interested in server push applications should also have a look
6344 at the CGI::Push module.
6346 Only Netscape Navigator supports server push. Internet Explorer
6347 browsers do not.
6349 =head1 Avoiding Denial of Service Attacks
6351 A potential problem with CGI.pm is that, by default, it attempts to
6352 process form POSTings no matter how large they are. A wily hacker
6353 could attack your site by sending a CGI script a huge POST of many
6354 megabytes. CGI.pm will attempt to read the entire POST into a
6355 variable, growing hugely in size until it runs out of memory. While
6356 the script attempts to allocate the memory the system may slow down
6357 dramatically. This is a form of denial of service attack.
6359 Another possible attack is for the remote user to force CGI.pm to
6360 accept a huge file upload. CGI.pm will accept the upload and store it
6361 in a temporary directory even if your script doesn't expect to receive
6362 an uploaded file. CGI.pm will delete the file automatically when it
6363 terminates, but in the meantime the remote user may have filled up the
6364 server's disk space, causing problems for other programs.
6366 The best way to avoid denial of service attacks is to limit the amount
6367 of memory, CPU time and disk space that CGI scripts can use. Some Web
6368 servers come with built-in facilities to accomplish this. In other
6369 cases, you can use the shell I<limit> or I<ulimit>
6370 commands to put ceilings on CGI resource usage.
6373 CGI.pm also has some simple built-in protections against denial of
6374 service attacks, but you must activate them before you can use them.
6375 These take the form of two global variables in the CGI name space:
6377 =over 4
6379 =item B<$CGI::POST_MAX>
6381 If set to a non-negative integer, this variable puts a ceiling
6382 on the size of POSTings, in bytes. If CGI.pm detects a POST
6383 that is greater than the ceiling, it will immediately exit with an error
6384 message. This value will affect both ordinary POSTs and
6385 multipart POSTs, meaning that it limits the maximum size of file
6386 uploads as well. You should set this to a reasonably high
6387 value, such as 1 megabyte.
6389 =item B<$CGI::DISABLE_UPLOADS>
6391 If set to a non-zero value, this will disable file uploads
6392 completely. Other fill-out form values will work as usual.
6394 =back
6396 You can use these variables in either of two ways.
6398 =over 4
6400 =item B<1. On a script-by-script basis>
6402 Set the variable at the top of the script, right after the "use" statement:
6404 use CGI qw/:standard/;
6405 use CGI::Carp 'fatalsToBrowser';
6406 $CGI::POST_MAX=1024 * 100; # max 100K posts
6407 $CGI::DISABLE_UPLOADS = 1; # no uploads
6409 =item B<2. Globally for all scripts>
6411 Open up CGI.pm, find the definitions for $POST_MAX and
6412 $DISABLE_UPLOADS, and set them to the desired values. You'll
6413 find them towards the top of the file in a subroutine named
6414 initialize_globals().
6416 =back
6418 An attempt to send a POST larger than $POST_MAX bytes will cause
6419 I<param()> to return an empty CGI parameter list. You can test for
6420 this event by checking I<cgi_error()>, either after you create the CGI
6421 object or, if you are using the function-oriented interface, call
6422 <param()> for the first time. If the POST was intercepted, then
6423 cgi_error() will return the message "413 POST too large".
6425 This error message is actually defined by the HTTP protocol, and is
6426 designed to be returned to the browser as the CGI script's status
6427 code. For example:
6429 $uploaded_file = param('upload');
6430 if (!$uploaded_file && cgi_error()) {
6431 print header(-status=>cgi_error());
6432 exit 0;
6435 However it isn't clear that any browser currently knows what to do
6436 with this status code. It might be better just to create an
6437 HTML page that warns the user of the problem.
6439 =head1 COMPATIBILITY WITH CGI-LIB.PL
6441 To make it easier to port existing programs that use cgi-lib.pl the
6442 compatibility routine "ReadParse" is provided. Porting is simple:
6444 OLD VERSION
6445 require "cgi-lib.pl";
6446 &ReadParse;
6447 print "The value of the antique is $in{antique}.\n";
6449 NEW VERSION
6450 use CGI;
6451 CGI::ReadParse
6452 print "The value of the antique is $in{antique}.\n";
6454 CGI.pm's ReadParse() routine creates a tied variable named %in,
6455 which can be accessed to obtain the query variables. Like
6456 ReadParse, you can also provide your own variable. Infrequently
6457 used features of ReadParse, such as the creation of @in and $in
6458 variables, are not supported.
6460 Once you use ReadParse, you can retrieve the query object itself
6461 this way:
6463 $q = $in{CGI};
6464 print $q->textfield(-name=>'wow',
6465 -value=>'does this really work?');
6467 This allows you to start using the more interesting features
6468 of CGI.pm without rewriting your old scripts from scratch.
6470 =head1 AUTHOR INFORMATION
6472 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
6474 This library is free software; you can redistribute it and/or modify
6475 it under the same terms as Perl itself.
6477 Address bug reports and comments to: lstein@cshl.org. When sending
6478 bug reports, please provide the version of CGI.pm, the version of
6479 Perl, the name and version of your Web server, and the name and
6480 version of the operating system you are using. If the problem is even
6481 remotely browser dependent, please provide information about the
6482 affected browers as well.
6484 =head1 CREDITS
6486 Thanks very much to:
6488 =over 4
6490 =item Matt Heffron (heffron@falstaff.css.beckman.com)
6492 =item James Taylor (james.taylor@srs.gov)
6494 =item Scott Anguish <sanguish@digifix.com>
6496 =item Mike Jewell (mlj3u@virginia.edu)
6498 =item Timothy Shimmin (tes@kbs.citri.edu.au)
6500 =item Joergen Haegg (jh@axis.se)
6502 =item Laurent Delfosse (delfosse@delfosse.com)
6504 =item Richard Resnick (applepi1@aol.com)
6506 =item Craig Bishop (csb@barwonwater.vic.gov.au)
6508 =item Tony Curtis (tc@vcpc.univie.ac.at)
6510 =item Tim Bunce (Tim.Bunce@ig.co.uk)
6512 =item Tom Christiansen (tchrist@convex.com)
6514 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
6516 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
6518 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
6520 =item Stephen Dahmen (joyfire@inxpress.net)
6522 =item Ed Jordan (ed@fidalgo.net)
6524 =item David Alan Pisoni (david@cnation.com)
6526 =item Doug MacEachern (dougm@opengroup.org)
6528 =item Robin Houston (robin@oneworld.org)
6530 =item ...and many many more...
6532 for suggestions and bug fixes.
6534 =back
6536 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
6539 #!/usr/local/bin/perl
6541 use CGI;
6543 $query = new CGI;
6545 print $query->header;
6546 print $query->start_html("Example CGI.pm Form");
6547 print "<H1> Example CGI.pm Form</H1>\n";
6548 &print_prompt($query);
6549 &do_work($query);
6550 &print_tail;
6551 print $query->end_html;
6553 sub print_prompt {
6554 my($query) = @_;
6556 print $query->start_form;
6557 print "<EM>What's your name?</EM><BR>";
6558 print $query->textfield('name');
6559 print $query->checkbox('Not my real name');
6561 print "<P><EM>Where can you find English Sparrows?</EM><BR>";
6562 print $query->checkbox_group(
6563 -name=>'Sparrow locations',
6564 -values=>[England,France,Spain,Asia,Hoboken],
6565 -linebreak=>'yes',
6566 -defaults=>[England,Asia]);
6568 print "<P><EM>How far can they fly?</EM><BR>",
6569 $query->radio_group(
6570 -name=>'how far',
6571 -values=>['10 ft','1 mile','10 miles','real far'],
6572 -default=>'1 mile');
6574 print "<P><EM>What's your favorite color?</EM> ";
6575 print $query->popup_menu(-name=>'Color',
6576 -values=>['black','brown','red','yellow'],
6577 -default=>'red');
6579 print $query->hidden('Reference','Monty Python and the Holy Grail');
6581 print "<P><EM>What have you got there?</EM><BR>";
6582 print $query->scrolling_list(
6583 -name=>'possessions',
6584 -values=>['A Coconut','A Grail','An Icon',
6585 'A Sword','A Ticket'],
6586 -size=>5,
6587 -multiple=>'true');
6589 print "<P><EM>Any parting comments?</EM><BR>";
6590 print $query->textarea(-name=>'Comments',
6591 -rows=>10,
6592 -columns=>50);
6594 print "<P>",$query->reset;
6595 print $query->submit('Action','Shout');
6596 print $query->submit('Action','Scream');
6597 print $query->endform;
6598 print "<HR>\n";
6601 sub do_work {
6602 my($query) = @_;
6603 my(@values,$key);
6605 print "<H2>Here are the current settings in this form</H2>";
6607 foreach $key ($query->param) {
6608 print "<STRONG>$key</STRONG> -> ";
6609 @values = $query->param($key);
6610 print join(", ",@values),"<BR>\n";
6614 sub print_tail {
6615 print <<END;
6616 <HR>
6617 <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
6618 <A HREF="/">Home Page</A>
6622 =head1 BUGS
6624 This module has grown large and monolithic. Furthermore it's doing many
6625 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
6626 are also done in the LWP modules. It should be discarded in favor of
6627 the CGI::* modules, but somehow I continue to work on it.
6629 Note that the code is truly contorted in order to avoid spurious
6630 warnings when programs are run with the B<-w> switch.
6632 =head1 SEE ALSO
6634 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
6635 L<CGI::Base>, L<CGI::Form>, L<CGI::Push>, L<CGI::Fast>,
6636 L<CGI::Pretty>
6638 =cut