This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
make op/write.t work better under stdio by running the subtests
[perl5.git] / lib / CGI.pm
CommitLineData
54310121 1package CGI;
424ec8fa 2require 5.004;
ba056755 3use Carp 'croak';
54310121 4
5# See the bottom of this file for the POD documentation. Search for the
6# string '=head'.
7
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).
11
424ec8fa 12# Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
54310121 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.
17
18# The most recent version and complete docs are available at:
71f3e297 19# http://stein.cshl.org/WWW/software/CGI/
54310121 20
efc8e943 21$CGI::revision = '$Id: CGI.pm,v 1.151 2004/01/13 16:28:35 lstein Exp $';
e70cb7eb 22$CGI::VERSION=3.04;
54310121 23
24# HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25# UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
ac734d8b 26# $CGITempFile::TMPDIRECTORY = '/usr/tmp';
2ed511ec 27use CGI::Util qw(rearrange make_attributes unescape escape expires ebcdic2ascii ascii2ebcdic);
54310121 28
3acbd4f5
JH
29#use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30# 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
31
32use constant XHTML_DTD => ['-//W3C//DTD XHTML 1.0 Transitional//EN',
33 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'];
6b4ac661 34
8f3ccfa2
JH
35{
36 local $^W = 0;
37 $TAINTED = substr("$0$^X",0,0);
38}
188ba755
JH
39
40my @SAVED_SYMBOLS;
41
8f3ccfa2
JH
42$MOD_PERL = 0; # no mod_perl by default
43
424ec8fa
GS
44# >>>>> Here are some globals that you might want to adjust <<<<<<
45sub initialize_globals {
46 # Set this to 1 to enable copious autoloader debugging messages
47 $AUTOLOAD_DEBUG = 0;
2371fea9 48
6b4ac661
JH
49 # Set this to 1 to generate XTML-compatible output
50 $XHTML = 1;
424ec8fa
GS
51
52 # Change this to the preferred DTD to print in start_html()
53 # or use default_dtd('text of DTD to use');
3d1a2ec4
GS
54 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
55 'http://www.w3.org/TR/html4/loose.dtd' ] ;
56
57 # Set this to 1 to enable NOSTICKY scripts
58 # or:
59 # 1) use CGI qw(-nosticky)
60 # 2) $CGI::nosticky(1)
61 $NOSTICKY = 0;
424ec8fa
GS
62
63 # Set this to 1 to enable NPH scripts
64 # or:
65 # 1) use CGI qw(-nph)
3d1a2ec4 66 # 2) CGI::nph(1)
424ec8fa
GS
67 # 3) print header(-nph=>1)
68 $NPH = 0;
69
3d1a2ec4
GS
70 # Set this to 1 to enable debugging from @ARGV
71 # Set to 2 to enable debugging from STDIN
72 $DEBUG = 1;
424ec8fa
GS
73
74 # Set this to 1 to make the temporary files created
75 # during file uploads safe from prying eyes
76 # or do...
77 # 1) use CGI qw(:private_tempfiles)
3d1a2ec4 78 # 2) CGI::private_tempfiles(1);
424ec8fa
GS
79 $PRIVATE_TEMPFILES = 0;
80
8f3ccfa2
JH
81 # Set this to 1 to cause files uploaded in multipart documents
82 # to be closed, instead of caching the file handle
83 # or:
84 # 1) use CGI qw(:close_upload_files)
85 # 2) $CGI::close_upload_files(1);
86 # Uploads with many files run out of file handles.
87 # Also, for performance, since the file is already on disk,
88 # it can just be renamed, instead of read and written.
89 $CLOSE_UPLOAD_FILES = 0;
90
424ec8fa
GS
91 # Set this to a positive value to limit the size of a POSTing
92 # to a certain number of bytes:
93 $POST_MAX = -1;
94
95 # Change this to 1 to disable uploads entirely:
96 $DISABLE_UPLOADS = 0;
97
3538e1d5
GS
98 # Automatically determined -- don't change
99 $EBCDIC = 0;
100
71f3e297
JH
101 # Change this to 1 to suppress redundant HTTP headers
102 $HEADERS_ONCE = 0;
103
104 # separate the name=value pairs by semicolons rather than ampersands
3d1a2ec4 105 $USE_PARAM_SEMICOLONS = 1;
71f3e297 106
2371fea9
JH
107 # Do not include undefined params parsed from query string
108 # use CGI qw(-no_undef_params);
109 $NO_UNDEF_PARAMS = 0;
199d4a26 110
424ec8fa
GS
111 # Other globals that you shouldn't worry about.
112 undef $Q;
113 $BEEN_THERE = 0;
114 undef @QUERY_PARAM;
115 undef %EXPORT;
d45d855d
JH
116 undef $QUERY_CHARSET;
117 undef %QUERY_FIELDNAMES;
424ec8fa
GS
118
119 # prevent complaints by mod_perl
120 1;
121}
122
54310121 123# ------------------ START OF THE LIBRARY ------------
124
424ec8fa
GS
125# make mod_perlhappy
126initialize_globals();
127
54310121 128# FIGURE OUT THE OS WE'RE RUNNING UNDER
129# Some systems support the $^O variable. If not
130# available then require() the Config library
131unless ($OS) {
132 unless ($OS = $^O) {
133 require Config;
134 $OS = $Config::Config{'osname'};
135 }
136}
ac1855b3 137if ($OS =~ /^MSWin/i) {
3538e1d5 138 $OS = 'WINDOWS';
ac1855b3 139} elsif ($OS =~ /^VMS/i) {
3538e1d5 140 $OS = 'VMS';
ac1855b3 141} elsif ($OS =~ /^dos/i) {
3538e1d5 142 $OS = 'DOS';
ac1855b3 143} elsif ($OS =~ /^MacOS/i) {
54310121 144 $OS = 'MACINTOSH';
ac1855b3 145} elsif ($OS =~ /^os2/i) {
54310121 146 $OS = 'OS2';
ac1855b3 147} elsif ($OS =~ /^epoc/i) {
fa6a1c44 148 $OS = 'EPOC';
188ba755
JH
149} elsif ($OS =~ /^cygwin/i) {
150 $OS = 'CYGWIN';
54310121 151} else {
152 $OS = 'UNIX';
153}
154
155# Some OS logic. Binary mode enabled on DOS, NT and VMS
188ba755 156$needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin|CYGWIN)/;
54310121 157
158# This is the default class for the CGI object to use when all else fails.
159$DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
424ec8fa 160
54310121 161# This is where to look for autoloaded routines.
162$AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
163
164# The path separator is a slash, backslash or semicolon, depending
165# on the paltform.
166$SL = {
8f3ccfa2
JH
167 UNIX => '/', OS2 => '\\', EPOC => '/', CYGWIN => '/',
168 WINDOWS => '\\', DOS => '\\', MACINTOSH => ':', VMS => '/'
54310121 169 }->{$OS};
170
424ec8fa 171# This no longer seems to be necessary
54310121 172# Turn on NPH scripts by default when running under IIS server!
424ec8fa
GS
173# $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
174$IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
54310121 175
176# Turn on special checking for Doug MacEachern's modperl
8f3ccfa2
JH
177if (exists $ENV{MOD_PERL}) {
178 eval "require mod_perl";
179 # mod_perl handlers may run system() on scripts using CGI.pm;
180 # Make sure so we don't get fooled by inherited $ENV{MOD_PERL}
181 if (defined $mod_perl::VERSION) {
188ba755 182 if ($mod_perl::VERSION >= 1.99) {
8f3ccfa2 183 $MOD_PERL = 2;
efc8e943 184 require Apache::Response;
8f3ccfa2
JH
185 require Apache::RequestRec;
186 require Apache::RequestUtil;
187 require APR::Pool;
188ba755 188 } else {
8f3ccfa2 189 $MOD_PERL = 1;
188ba755
JH
190 require Apache;
191 }
192 }
8f3ccfa2 193}
188ba755 194
424ec8fa
GS
195# Turn on special checking for ActiveState's PerlEx
196$PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
197
198# Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
199# of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
200# and sometimes CR). The most popular VMS web server
201# doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
202# use ASCII, so \015\012 means something different. I find this all
203# really annoying.
204$EBCDIC = "\t" ne "\011";
205if ($OS eq 'VMS') {
3538e1d5 206 $CRLF = "\n";
424ec8fa 207} elsif ($EBCDIC) {
3538e1d5 208 $CRLF= "\r\n";
424ec8fa 209} else {
3538e1d5
GS
210 $CRLF = "\015\012";
211}
212
54310121 213if ($needs_binmode) {
2ed511ec
RGS
214 $CGI::DefaultClass->binmode(\*main::STDOUT);
215 $CGI::DefaultClass->binmode(\*main::STDIN);
216 $CGI::DefaultClass->binmode(\*main::STDERR);
54310121 217}
218
54310121 219%EXPORT_TAGS = (
424ec8fa
GS
220 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
221 tt u i b blockquote pre img a address cite samp dfn html head
222 base body Link nextid title meta kbd start_html end_html
3d1a2ec4 223 input Select option comment charset escapeHTML/],
71f3e297 224 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
1c87da1d 225 embed basefont style span layer ilayer font frameset frame script small big Area Map/],
3acbd4f5
JH
226 ':html4'=>[qw/abbr acronym bdo col colgroup del fieldset iframe
227 ins label legend noframes noscript object optgroup Q
228 thead tbody tfoot/],
424ec8fa
GS
229 ':netscape'=>[qw/blink fontsize center/],
230 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
231 submit reset defaults radio_group popup_menu button autoEscape
232 scrolling_list image_button start_form end_form startform endform
71f3e297 233 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
3538e1d5
GS
234 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
235 raw_cookie request_method query_string Accept user_agent remote_host content_type
2ed511ec
RGS
236 remote_addr referer server_name server_software server_port server_protocol virtual_port
237 virtual_host remote_ident auth_type http append
424ec8fa 238 save_parameters restore_parameters param_fetch
3538e1d5
GS
239 remote_user user_name header redirect import_names put
240 Delete Delete_all url_param cgi_error/],
424ec8fa 241 ':ssl' => [qw/https/],
3538e1d5 242 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
3acbd4f5
JH
243 ':html' => [qw/:html2 :html3 :html4 :netscape/],
244 ':standard' => [qw/:html2 :html3 :html4 :form :cgi/],
ba056755 245 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
3acbd4f5 246 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal :html4/]
424ec8fa 247 );
54310121 248
249# to import symbols into caller
250sub import {
251 my $self = shift;
424ec8fa 252
188ba755 253 # This causes modules to clash.
b2d0d414
JH
254 undef %EXPORT_OK;
255 undef %EXPORT;
424ec8fa
GS
256
257 $self->_setup_symbols(@_);
54310121 258 my ($callpack, $callfile, $callline) = caller;
424ec8fa 259
54310121 260 # To allow overriding, search through the packages
261 # Till we find one in which the correct subroutine is defined.
262 my @packages = ($self,@{"$self\:\:ISA"});
263 foreach $sym (keys %EXPORT) {
264 my $pck;
265 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
266 foreach $pck (@packages) {
267 if (defined(&{"$pck\:\:$sym"})) {
268 $def = $pck;
269 last;
270 }
271 }
272 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
273 }
274}
275
424ec8fa
GS
276sub compile {
277 my $pack = shift;
278 $pack->_setup_symbols('-compile',@_);
279}
280
54310121 281sub expand_tags {
282 my($tag) = @_;
71f3e297 283 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
54310121 284 my(@r);
285 return ($tag) unless $EXPORT_TAGS{$tag};
286 foreach (@{$EXPORT_TAGS{$tag}}) {
287 push(@r,&expand_tags($_));
288 }
289 return @r;
290}
291
292#### Method: new
293# The new routine. This will check the current environment
294# for an existing query string, and initialize itself, if so.
295####
296sub new {
8f3ccfa2
JH
297 my($class,@initializer) = @_;
298 my $self = {};
2ed511ec 299
8f3ccfa2
JH
300 bless $self,ref $class || $class || $DefaultClass;
301 if (ref($initializer[0])
302 && (UNIVERSAL::isa($initializer[0],'Apache')
303 ||
304 UNIVERSAL::isa($initializer[0],'Apache::RequestRec')
305 )) {
306 $self->r(shift @initializer);
307 }
efc8e943
NC
308 if (ref($initializer[0])
309 && (UNIVERSAL::isa($initializer[0],'CODE'))) {
310 $self->upload_hook(shift @initializer, shift @initializer);
311 }
8f3ccfa2
JH
312 if ($MOD_PERL) {
313 $self->r(Apache->request) unless $self->r;
314 my $r = $self->r;
315 if ($MOD_PERL == 1) {
316 $r->register_cleanup(\&CGI::_reset_globals);
317 }
318 else {
319 # XXX: once we have the new API
320 # will do a real PerlOptions -SetupEnv check
321 $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
322 $r->pool->cleanup_register(\&CGI::_reset_globals);
424ec8fa 323 }
8f3ccfa2
JH
324 undef $NPH;
325 }
326 $self->_reset_globals if $PERLEX;
327 $self->init(@initializer);
328 return $self;
54310121 329}
330
2ed511ec
RGS
331# We provide a DESTROY method so that we can ensure that
332# temporary files are closed (via Fh->DESTROY) before they
333# are unlinked (via CGITempFile->DESTROY) because it is not
334# possible to unlink an open file on Win32. We explicitly
335# call DESTROY on each, rather than just undefing them and
336# letting Perl DESTROY them by garbage collection, in case the
337# user is still holding any reference to them as well.
338sub DESTROY {
339 my $self = shift;
340 foreach my $href (values %{$self->{'.tmpfiles'}}) {
341 $href->{hndl}->DESTROY if defined $href->{hndl};
342 $href->{name}->DESTROY if defined $href->{name};
343 }
344}
54310121 345
8f3ccfa2
JH
346sub r {
347 my $self = shift;
348 my $r = $self->{'.r'};
349 $self->{'.r'} = shift if @_;
350 $r;
351}
352
2ed511ec
RGS
353sub upload_hook {
354 my ($self,$hook,$data) = self_or_default(@_);
355 $self->{'.upload_hook'} = $hook;
356 $self->{'.upload_data'} = $data;
357}
358
54310121 359#### Method: param
360# Returns the value(s)of a named parameter.
361# If invoked in a list context, returns the
362# entire list. Otherwise returns the first
363# member of the list.
364# If name is not provided, return a list of all
365# the known parameters names available.
366# If more than one argument is provided, the
367# second and subsequent arguments are used to
368# set the value of the parameter.
369####
370sub param {
371 my($self,@p) = self_or_default(@_);
372 return $self->all_parameters unless @p;
373 my($name,$value,@other);
374
375 # For compatibility between old calling style and use_named_parameters() style,
376 # we have to special case for a single parameter present.
377 if (@p > 1) {
3d1a2ec4 378 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
54310121 379 my(@values);
380
3d1a2ec4 381 if (substr($p[0],0,1) eq '-') {
54310121 382 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
383 } else {
384 foreach ($value,@other) {
385 push(@values,$_) if defined($_);
386 }
387 }
388 # If values is provided, then we set it.
389 if (@values) {
390 $self->add_parameter($name);
391 $self->{$name}=[@values];
392 }
393 } else {
394 $name = $p[0];
395 }
396
71f3e297 397 return unless defined($name) && $self->{$name};
54310121 398 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
399}
400
54310121 401sub self_or_default {
424ec8fa 402 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
54310121 403 unless (defined($_[0]) &&
424ec8fa
GS
404 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
405 ) {
54310121 406 $Q = $CGI::DefaultClass->new unless defined($Q);
407 unshift(@_,$Q);
408 }
3d1a2ec4 409 return wantarray ? @_ : $Q;
54310121 410}
411
54310121 412sub self_or_CGI {
413 local $^W=0; # prevent a warning
414 if (defined($_[0]) &&
415 (substr(ref($_[0]),0,3) eq 'CGI'
424ec8fa 416 || UNIVERSAL::isa($_[0],'CGI'))) {
54310121 417 return @_;
418 } else {
419 return ($DefaultClass,@_);
420 }
421}
422
54310121 423########################################
424# THESE METHODS ARE MORE OR LESS PRIVATE
425# GO TO THE __DATA__ SECTION TO SEE MORE
426# PUBLIC METHODS
427########################################
428
429# Initialize the query object from the environment.
430# If a parameter list is found, this object will be set
431# to an associative array in which parameter names are keys
432# and the values are stored as lists
433# If a keyword list is found, this method creates a bogus
434# parameter list with the single parameter 'keywords'.
435
436sub init {
8f3ccfa2
JH
437 my $self = shift;
438 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
439
440 my $initializer = shift; # for backward compatibility
441 local($/) = "\n";
442
443 # set autoescaping on by default
444 $self->{'escape'} = 1;
54310121 445
446 # if we get called more than once, we want to initialize
447 # ourselves from the original query (which may be gone
448 # if it was read from STDIN originally.)
d45d855d 449 if (defined(@QUERY_PARAM) && !defined($initializer)) {
54310121 450 foreach (@QUERY_PARAM) {
451 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
452 }
d45d855d
JH
453 $self->charset($QUERY_CHARSET);
454 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
54310121 455 return;
456 }
457
458 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
424ec8fa 459 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
3538e1d5 460
424ec8fa 461 $fh = to_filehandle($initializer) if $initializer;
54310121 462
a3b3a725
JH
463 # set charset to the safe ISO-8859-1
464 $self->charset('ISO-8859-1');
465
54310121 466 METHOD: {
54310121 467
3538e1d5
GS
468 # avoid unreasonably large postings
469 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
1c87da1d
JH
470 # quietly read and discard the post
471 my $buffer;
472 my $max = $content_length;
2ed511ec
RGS
473 while ($max > 0 &&
474 (my $bytes = $MOD_PERL
475 ? $self->r->read($buffer,$max < 10000 ? $max : 10000)
476 : read(STDIN,$buffer,$max < 10000 ? $max : 10000)
477 )) {
478 $self->cgi_error("413 Request entity too large");
479 last METHOD;
1c87da1d 480 }
2ed511ec 481 }
3538e1d5 482
424ec8fa
GS
483 # Process multipart postings, but only if the initializer is
484 # not defined.
485 if ($meth eq 'POST'
486 && defined($ENV{'CONTENT_TYPE'})
487 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
488 && !defined($initializer)
489 ) {
71f3e297 490 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
424ec8fa
GS
491 $self->read_multipart($boundary,$content_length);
492 last METHOD;
493 }
494
495 # If initializer is defined, then read parameters
496 # from it.
497 if (defined($initializer)) {
498 if (UNIVERSAL::isa($initializer,'CGI')) {
499 $query_string = $initializer->query_string;
500 last METHOD;
501 }
54310121 502 if (ref($initializer) && ref($initializer) eq 'HASH') {
503 foreach (keys %$initializer) {
504 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
505 }
506 last METHOD;
507 }
508
424ec8fa
GS
509 if (defined($fh) && ($fh ne '')) {
510 while (<$fh>) {
54310121 511 chomp;
512 last if /^=/;
513 push(@lines,$_);
514 }
515 # massage back into standard format
516 if ("@lines" =~ /=/) {
517 $query_string=join("&",@lines);
518 } else {
519 $query_string=join("+",@lines);
520 }
521 last METHOD;
522 }
424ec8fa 523
2ed511ec
RGS
524 if (defined($fh) && ($fh ne '')) {
525 while (<$fh>) {
526 chomp;
527 last if /^=/;
528 push(@lines,$_);
529 }
530 # massage back into standard format
531 if ("@lines" =~ /=/) {
532 $query_string=join("&",@lines);
533 } else {
534 $query_string=join("+",@lines);
535 }
536 last METHOD;
537 }
538
424ec8fa
GS
539 # last chance -- treat it as a string
540 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
54310121 541 $query_string = $initializer;
424ec8fa 542
54310121 543 last METHOD;
544 }
54310121 545
424ec8fa
GS
546 # If method is GET or HEAD, fetch the query from
547 # the environment.
548 if ($meth=~/^(GET|HEAD)$/) {
3538e1d5 549 if ($MOD_PERL) {
8f3ccfa2 550 $query_string = $self->r->args;
3538e1d5
GS
551 } else {
552 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
3d1a2ec4 553 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
3538e1d5 554 }
424ec8fa
GS
555 last METHOD;
556 }
54310121 557
424ec8fa 558 if ($meth eq 'POST') {
2ed511ec 559 $self->read_from_client(\$query_string,$content_length,0)
424ec8fa 560 if $content_length > 0;
54310121 561 # Some people want to have their cake and eat it too!
562 # Uncomment this line to have the contents of the query string
563 # APPENDED to the POST data.
424ec8fa 564 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
54310121 565 last METHOD;
566 }
424ec8fa
GS
567
568 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
54310121 569 # Check the command line and then the standard input for data.
570 # We use the shellwords package in order to behave the way that
571 # UN*X programmers expect.
2ed511ec
RGS
572 if ($DEBUG)
573 {
574 my $cmdline_ret = read_from_cmdline();
575 $query_string = $cmdline_ret->{'query_string'};
576 if (defined($cmdline_ret->{'subpath'}))
577 {
578 $self->path_info($cmdline_ret->{'subpath'});
579 }
580 }
54310121 581 }
424ec8fa 582
8f3ccfa2
JH
583# YL: Begin Change for XML handler 10/19/2001
584 if ($meth eq 'POST'
585 && defined($ENV{'CONTENT_TYPE'})
1c87da1d
JH
586 && $ENV{'CONTENT_TYPE'} !~ m|^application/x-www-form-urlencoded|
587 && $ENV{'CONTENT_TYPE'} !~ m|^multipart/form-data| ) {
8f3ccfa2
JH
588 my($param) = 'POSTDATA' ;
589 $self->add_parameter($param) ;
590 push (@{$self->{$param}},$query_string);
591 undef $query_string ;
592 }
593# YL: End Change for XML handler 10/19/2001
594
54310121 595 # We now have the query string in hand. We do slightly
596 # different things for keyword lists and parameter lists.
ba056755 597 if (defined $query_string && length $query_string) {
3d1a2ec4 598 if ($query_string =~ /[&=;]/) {
54310121 599 $self->parse_params($query_string);
600 } else {
601 $self->add_parameter('keywords');
602 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
603 }
604 }
605
606 # Special case. Erase everything if there is a field named
607 # .defaults.
608 if ($self->param('.defaults')) {
e70cb7eb 609 $self->delete_all();
54310121 610 }
611
612 # Associative array containing our defined fieldnames
613 $self->{'.fieldnames'} = {};
614 foreach ($self->param('.cgifields')) {
615 $self->{'.fieldnames'}->{$_}++;
616 }
617
618 # Clear out our default submission button flag if present
619 $self->delete('.submit');
620 $self->delete('.cgifields');
3d1a2ec4 621
8f3ccfa2 622 $self->save_request unless defined $initializer;
54310121 623}
624
54310121 625# FUNCTIONS TO OVERRIDE:
54310121 626# Turn a string into a filehandle
627sub to_filehandle {
424ec8fa
GS
628 my $thingy = shift;
629 return undef unless $thingy;
630 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
631 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
632 if (!ref($thingy)) {
633 my $caller = 1;
634 while (my $package = caller($caller++)) {
635 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
636 return $tmp if defined(fileno($tmp));
637 }
54310121 638 }
424ec8fa 639 return undef;
54310121 640}
641
642# send output to the browser
643sub put {
644 my($self,@p) = self_or_default(@_);
645 $self->print(@p);
646}
647
648# print to standard output (for overriding in mod_perl)
649sub print {
650 shift;
651 CORE::print(@_);
652}
653
3538e1d5
GS
654# get/set last cgi_error
655sub cgi_error {
656 my ($self,$err) = self_or_default(@_);
657 $self->{'.cgi_error'} = $err if defined $err;
658 return $self->{'.cgi_error'};
659}
660
54310121 661sub save_request {
662 my($self) = @_;
663 # We're going to play with the package globals now so that if we get called
664 # again, we initialize ourselves in exactly the same way. This allows
665 # us to have several of these objects.
666 @QUERY_PARAM = $self->param; # save list of parameters
667 foreach (@QUERY_PARAM) {
3d1a2ec4
GS
668 next unless defined $_;
669 $QUERY_PARAM{$_}=$self->{$_};
54310121 670 }
d45d855d
JH
671 $QUERY_CHARSET = $self->charset;
672 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
54310121 673}
674
54310121 675sub parse_params {
676 my($self,$tosplit) = @_;
71f3e297 677 my(@pairs) = split(/[&;]/,$tosplit);
54310121 678 my($param,$value);
679 foreach (@pairs) {
424ec8fa 680 ($param,$value) = split('=',$_,2);
b2d0d414 681 next unless defined $param;
69c89ae7 682 next if $NO_UNDEF_PARAMS and not defined $value;
3d1a2ec4 683 $value = '' unless defined $value;
424ec8fa
GS
684 $param = unescape($param);
685 $value = unescape($value);
54310121 686 $self->add_parameter($param);
687 push (@{$self->{$param}},$value);
688 }
689}
690
691sub add_parameter {
692 my($self,$param)=@_;
3d1a2ec4 693 return unless defined $param;
54310121 694 push (@{$self->{'.parameters'}},$param)
695 unless defined($self->{$param});
696}
697
698sub all_parameters {
699 my $self = shift;
700 return () unless defined($self) && $self->{'.parameters'};
701 return () unless @{$self->{'.parameters'}};
702 return @{$self->{'.parameters'}};
703}
704
424ec8fa
GS
705# put a filehandle into binary mode (DOS)
706sub binmode {
2ed511ec 707 return unless defined($_[1]) && defined fileno($_[1]);
424ec8fa
GS
708 CORE::binmode($_[1]);
709}
710
711sub _make_tag_func {
71f3e297 712 my ($self,$tagname) = @_;
3538e1d5 713 my $func = qq(
3d1a2ec4 714 sub $tagname {
8f3ccfa2
JH
715 my (\$q,\$a,\@rest) = self_or_default(\@_);
716 my(\$attr) = '';
717 if (ref(\$a) && ref(\$a) eq 'HASH') {
718 my(\@attr) = make_attributes(\$a,\$q->{'escape'});
719 \$attr = " \@attr" if \@attr;
720 } else {
1c87da1d 721 unshift \@rest,\$a if defined \$a;
8f3ccfa2 722 }
3538e1d5 723 );
71f3e297 724 if ($tagname=~/start_(\w+)/i) {
6b4ac661 725 $func .= qq! return "<\L$1\E\$attr>";} !;
71f3e297 726 } elsif ($tagname=~/end_(\w+)/i) {
6b4ac661 727 $func .= qq! return "<\L/$1\E>"; } !;
71f3e297
JH
728 } else {
729 $func .= qq#
1c87da1d 730 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@rest;
6b4ac661 731 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
3d1a2ec4 732 my \@result = map { "\$tag\$_\$untag" }
8f3ccfa2 733 (ref(\$rest[0]) eq 'ARRAY') ? \@{\$rest[0]} : "\@rest";
424ec8fa 734 return "\@result";
71f3e297
JH
735 }#;
736 }
737return $func;
54310121 738}
739
740sub AUTOLOAD {
741 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
424ec8fa
GS
742 my $func = &_compile;
743 goto &$func;
54310121 744}
745
424ec8fa
GS
746sub _compile {
747 my($func) = $AUTOLOAD;
748 my($pack,$func_name);
749 {
750 local($1,$2); # this fixes an obscure variable suicide problem.
751 $func=~/(.+)::([^:]+)$/;
752 ($pack,$func_name) = ($1,$2);
753 $pack=~s/::SUPER$//; # fix another obscure problem
754 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
755 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
756
757 my($sub) = \%{"$pack\:\:SUBS"};
758 unless (%$sub) {
759 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
760 eval "package $pack; $$auto";
ba056755 761 croak("$AUTOLOAD: $@") if $@;
424ec8fa
GS
762 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
763 }
764 my($code) = $sub->{$func_name};
765
766 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
767 if (!$code) {
71f3e297 768 (my $base = $func_name) =~ s/^(start_|end_)//i;
424ec8fa
GS
769 if ($EXPORT{':any'} ||
770 $EXPORT{'-any'} ||
71f3e297 771 $EXPORT{$base} ||
424ec8fa 772 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
71f3e297
JH
773 && $EXPORT_OK{$base}) {
774 $code = $CGI::DefaultClass->_make_tag_func($func_name);
424ec8fa
GS
775 }
776 }
ba056755 777 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
424ec8fa
GS
778 eval "package $pack; $code";
779 if ($@) {
780 $@ =~ s/ at .*\n//;
ba056755 781 croak("$AUTOLOAD: $@");
424ec8fa
GS
782 }
783 }
3538e1d5 784 CORE::delete($sub->{$func_name}); #free storage
424ec8fa
GS
785 return "$pack\:\:$func_name";
786}
787
3acbd4f5
JH
788sub _selected {
789 my $self = shift;
790 my $value = shift;
791 return '' unless $value;
2371fea9 792 return $XHTML ? qq( selected="selected") : qq( selected);
3acbd4f5
JH
793}
794
795sub _checked {
796 my $self = shift;
797 my $value = shift;
798 return '' unless $value;
2371fea9 799 return $XHTML ? qq( checked="checked") : qq( checked);
3acbd4f5
JH
800}
801
424ec8fa
GS
802sub _reset_globals { initialize_globals(); }
803
804sub _setup_symbols {
805 my $self = shift;
806 my $compile = 0;
b2d0d414
JH
807
808 # to avoid reexporting unwanted variables
809 undef %EXPORT;
810
424ec8fa 811 foreach (@_) {
71f3e297
JH
812 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
813 $NPH++, next if /^[:-]nph$/;
3d1a2ec4
GS
814 $NOSTICKY++, next if /^[:-]nosticky$/;
815 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
816 $DEBUG=2, next if /^[:-][Dd]ebug$/;
71f3e297 817 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
6b4ac661
JH
818 $XHTML++, next if /^[:-]xhtml$/;
819 $XHTML=0, next if /^[:-]no_?xhtml$/;
3d1a2ec4 820 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
71f3e297 821 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
8f3ccfa2 822 $CLOSE_UPLOAD_FILES++, next if /^[:-]close_upload_files$/;
71f3e297
JH
823 $EXPORT{$_}++, next if /^[:-]any$/;
824 $compile++, next if /^[:-]compile$/;
199d4a26 825 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
424ec8fa 826
71f3e297 827 # This is probably extremely evil code -- to be deleted some day.
424ec8fa
GS
828 if (/^[-]autoload$/) {
829 my($pkg) = caller(1);
830 *{"${pkg}::AUTOLOAD"} = sub {
831 my($routine) = $AUTOLOAD;
832 $routine =~ s/^.*::/CGI::/;
833 &$routine;
834 };
835 next;
836 }
837
838 foreach (&expand_tags($_)) {
839 tr/a-zA-Z0-9_//cd; # don't allow weird function names
840 $EXPORT{$_}++;
54310121 841 }
54310121 842 }
424ec8fa 843 _compile_all(keys %EXPORT) if $compile;
188ba755 844 @SAVED_SYMBOLS = @_;
54310121 845}
846
3d1a2ec4
GS
847sub charset {
848 my ($self,$charset) = self_or_default(@_);
849 $self->{'.charset'} = $charset if defined $charset;
850 $self->{'.charset'};
851}
852
54310121 853###############################################################################
854################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
855###############################################################################
856$AUTOLOADED_ROUTINES = ''; # get rid of -w warning
857$AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
858
859%SUBS = (
860
861'URL_ENCODED'=> <<'END_OF_FUNC',
862sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
863END_OF_FUNC
864
865'MULTIPART' => <<'END_OF_FUNC',
866sub MULTIPART { 'multipart/form-data'; }
867END_OF_FUNC
868
424ec8fa 869'SERVER_PUSH' => <<'END_OF_FUNC',
ba056755 870sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
424ec8fa
GS
871END_OF_FUNC
872
424ec8fa
GS
873'new_MultipartBuffer' => <<'END_OF_FUNC',
874# Create a new multipart buffer
875sub new_MultipartBuffer {
2ed511ec
RGS
876 my($self,$boundary,$length) = @_;
877 return MultipartBuffer->new($self,$boundary,$length);
424ec8fa
GS
878}
879END_OF_FUNC
880
881'read_from_client' => <<'END_OF_FUNC',
882# Read data from a file handle
883sub read_from_client {
2ed511ec 884 my($self, $buff, $len, $offset) = @_;
424ec8fa 885 local $^W=0; # prevent a warning
2ed511ec
RGS
886 return $MOD_PERL
887 ? $self->r->read($$buff, $len, $offset)
888 : read(\*STDIN, $$buff, $len, $offset);
424ec8fa
GS
889}
890END_OF_FUNC
891
892'delete' => <<'END_OF_FUNC',
893#### Method: delete
894# Deletes the named parameter entirely.
895####
896sub delete {
6b4ac661 897 my($self,@p) = self_or_default(@_);
1c87da1d
JH
898 my(@names) = rearrange([NAME],@p);
899 my @to_delete = ref($names[0]) eq 'ARRAY' ? @$names[0] : @names;
8f3ccfa2
JH
900 my %to_delete;
901 foreach my $name (@to_delete)
902 {
903 CORE::delete $self->{$name};
904 CORE::delete $self->{'.fieldnames'}->{$name};
905 $to_delete{$name}++;
188ba755 906 }
8f3ccfa2
JH
907 @{$self->{'.parameters'}}=grep { !exists($to_delete{$_}) } $self->param();
908 return wantarray ? () : undef;
424ec8fa
GS
909}
910END_OF_FUNC
911
912#### Method: import_names
913# Import all parameters into the given namespace.
914# Assumes namespace 'Q' if not specified
915####
916'import_names' => <<'END_OF_FUNC',
917sub import_names {
918 my($self,$namespace,$delete) = self_or_default(@_);
919 $namespace = 'Q' unless defined($namespace);
920 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
3538e1d5 921 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
424ec8fa
GS
922 # can anyone find an easier way to do this?
923 foreach (keys %{"${namespace}::"}) {
924 local *symbol = "${namespace}::${_}";
925 undef $symbol;
926 undef @symbol;
927 undef %symbol;
54310121 928 }
424ec8fa
GS
929 }
930 my($param,@value,$var);
931 foreach $param ($self->param) {
932 # protect against silly names
933 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
934 $var =~ s/^(?=\d)/_/;
935 local *symbol = "${namespace}::$var";
936 @value = $self->param($param);
937 @symbol = @value;
938 $symbol = $value[0];
54310121 939 }
940}
941END_OF_FUNC
942
943#### Method: keywords
944# Keywords acts a bit differently. Calling it in a list context
945# returns the list of keywords.
946# Calling it in a scalar context gives you the size of the list.
947####
948'keywords' => <<'END_OF_FUNC',
949sub keywords {
950 my($self,@values) = self_or_default(@_);
951 # If values is provided, then we set it.
475342a6 952 $self->{'keywords'}=[@values] if @values;
424ec8fa 953 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
54310121 954 @result;
955}
956END_OF_FUNC
957
958# These are some tie() interfaces for compatibility
959# with Steve Brenner's cgi-lib.pl routines
3538e1d5
GS
960'Vars' => <<'END_OF_FUNC',
961sub Vars {
ffd2dff2 962 my $q = shift;
3538e1d5 963 my %in;
ffd2dff2 964 tie(%in,CGI,$q);
3538e1d5
GS
965 return %in if wantarray;
966 return \%in;
967}
968END_OF_FUNC
969
970# These are some tie() interfaces for compatibility
971# with Steve Brenner's cgi-lib.pl routines
54310121 972'ReadParse' => <<'END_OF_FUNC',
973sub ReadParse {
974 local(*in);
975 if (@_) {
976 *in = $_[0];
977 } else {
978 my $pkg = caller();
979 *in=*{"${pkg}::in"};
980 }
981 tie(%in,CGI);
424ec8fa 982 return scalar(keys %in);
54310121 983}
984END_OF_FUNC
985
986'PrintHeader' => <<'END_OF_FUNC',
987sub PrintHeader {
988 my($self) = self_or_default(@_);
989 return $self->header();
990}
991END_OF_FUNC
992
993'HtmlTop' => <<'END_OF_FUNC',
994sub HtmlTop {
995 my($self,@p) = self_or_default(@_);
996 return $self->start_html(@p);
997}
998END_OF_FUNC
999
1000'HtmlBot' => <<'END_OF_FUNC',
1001sub HtmlBot {
1002 my($self,@p) = self_or_default(@_);
1003 return $self->end_html(@p);
1004}
1005END_OF_FUNC
1006
1007'SplitParam' => <<'END_OF_FUNC',
1008sub SplitParam {
1009 my ($param) = @_;
1010 my (@params) = split ("\0", $param);
1011 return (wantarray ? @params : $params[0]);
1012}
1013END_OF_FUNC
1014
1015'MethGet' => <<'END_OF_FUNC',
1016sub MethGet {
1017 return request_method() eq 'GET';
1018}
1019END_OF_FUNC
1020
1021'MethPost' => <<'END_OF_FUNC',
1022sub MethPost {
1023 return request_method() eq 'POST';
1024}
1025END_OF_FUNC
1026
1027'TIEHASH' => <<'END_OF_FUNC',
8f3ccfa2
JH
1028sub TIEHASH {
1029 my $class = shift;
1030 my $arg = $_[0];
1031 if (ref($arg) && UNIVERSAL::isa($arg,'CGI')) {
1032 return $arg;
1033 }
1034 return $Q ||= $class->new(@_);
54310121 1035}
1036END_OF_FUNC
1037
1038'STORE' => <<'END_OF_FUNC',
1039sub STORE {
3d1a2ec4
GS
1040 my $self = shift;
1041 my $tag = shift;
6b4ac661
JH
1042 my $vals = shift;
1043 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
3d1a2ec4 1044 $self->param(-name=>$tag,-value=>\@vals);
54310121 1045}
1046END_OF_FUNC
1047
1048'FETCH' => <<'END_OF_FUNC',
1049sub FETCH {
1050 return $_[0] if $_[1] eq 'CGI';
1051 return undef unless defined $_[0]->param($_[1]);
1052 return join("\0",$_[0]->param($_[1]));
1053}
1054END_OF_FUNC
1055
1056'FIRSTKEY' => <<'END_OF_FUNC',
1057sub FIRSTKEY {
1058 $_[0]->{'.iterator'}=0;
1059 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1060}
1061END_OF_FUNC
1062
1063'NEXTKEY' => <<'END_OF_FUNC',
1064sub NEXTKEY {
1065 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1066}
1067END_OF_FUNC
1068
1069'EXISTS' => <<'END_OF_FUNC',
1070sub EXISTS {
1071 exists $_[0]->{$_[1]};
1072}
1073END_OF_FUNC
1074
1075'DELETE' => <<'END_OF_FUNC',
1076sub DELETE {
1077 $_[0]->delete($_[1]);
1078}
1079END_OF_FUNC
1080
1081'CLEAR' => <<'END_OF_FUNC',
1082sub CLEAR {
1083 %{$_[0]}=();
1084}
1085####
1086END_OF_FUNC
1087
1088####
1089# Append a new value to an existing query
1090####
1091'append' => <<'EOF',
1092sub append {
1093 my($self,@p) = @_;
3d1a2ec4 1094 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
54310121 1095 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
1096 if (@values) {
1097 $self->add_parameter($name);
1098 push(@{$self->{$name}},@values);
1099 }
1100 return $self->param($name);
1101}
1102EOF
1103
1104#### Method: delete_all
1105# Delete all parameters
1106####
1107'delete_all' => <<'EOF',
1108sub delete_all {
1109 my($self) = self_or_default(@_);
1c87da1d 1110 my @param = $self->param();
8f3ccfa2 1111 $self->delete(@param);
54310121 1112}
1113EOF
1114
424ec8fa
GS
1115'Delete' => <<'EOF',
1116sub Delete {
1117 my($self,@p) = self_or_default(@_);
1118 $self->delete(@p);
1119}
1120EOF
1121
1122'Delete_all' => <<'EOF',
1123sub Delete_all {
1124 my($self,@p) = self_or_default(@_);
1125 $self->delete_all(@p);
1126}
1127EOF
1128
54310121 1129#### Method: autoescape
1130# If you want to turn off the autoescaping features,
1131# call this method with undef as the argument
1132'autoEscape' => <<'END_OF_FUNC',
1133sub autoEscape {
1134 my($self,$escape) = self_or_default(@_);
188ba755
JH
1135 my $d = $self->{'escape'};
1136 $self->{'escape'} = $escape;
1137 $d;
54310121 1138}
1139END_OF_FUNC
1140
1141
1142#### Method: version
1143# Return the current version
1144####
1145'version' => <<'END_OF_FUNC',
1146sub version {
1147 return $VERSION;
1148}
1149END_OF_FUNC
1150
424ec8fa
GS
1151#### Method: url_param
1152# Return a parameter in the QUERY_STRING, regardless of
1153# whether this was a POST or a GET
1154####
1155'url_param' => <<'END_OF_FUNC',
1156sub url_param {
1157 my ($self,@p) = self_or_default(@_);
1158 my $name = shift(@p);
1159 return undef unless exists($ENV{QUERY_STRING});
1160 unless (exists($self->{'.url_param'})) {
1161 $self->{'.url_param'}={}; # empty hash
1162 if ($ENV{QUERY_STRING} =~ /=/) {
71f3e297 1163 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
424ec8fa
GS
1164 my($param,$value);
1165 foreach (@pairs) {
1166 ($param,$value) = split('=',$_,2);
1167 $param = unescape($param);
1168 $value = unescape($value);
1169 push(@{$self->{'.url_param'}->{$param}},$value);
1170 }
1171 } else {
1172 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1173 }
1174 }
1175 return keys %{$self->{'.url_param'}} unless defined($name);
1176 return () unless $self->{'.url_param'}->{$name};
1177 return wantarray ? @{$self->{'.url_param'}->{$name}}
1178 : $self->{'.url_param'}->{$name}->[0];
1179}
1180END_OF_FUNC
1181
3d1a2ec4 1182#### Method: Dump
54310121 1183# Returns a string in which all the known parameter/value
1184# pairs are represented as nested lists, mainly for the purposes
1185# of debugging.
1186####
3d1a2ec4
GS
1187'Dump' => <<'END_OF_FUNC',
1188sub Dump {
54310121 1189 my($self) = self_or_default(@_);
1190 my($param,$value,@result);
3acbd4f5
JH
1191 return '<ul></ul>' unless $self->param;
1192 push(@result,"<ul>");
54310121 1193 foreach $param ($self->param) {
1194 my($name)=$self->escapeHTML($param);
1c87da1d 1195 push(@result,"<li><strong>$param</strong></li>");
3acbd4f5 1196 push(@result,"<ul>");
54310121 1197 foreach $value ($self->param($param)) {
1198 $value = $self->escapeHTML($value);
58129083 1199 $value =~ s/\n/<br \/>\n/g;
1c87da1d 1200 push(@result,"<li>$value</li>");
54310121 1201 }
3acbd4f5 1202 push(@result,"</ul>");
54310121 1203 }
3acbd4f5 1204 push(@result,"</ul>");
54310121 1205 return join("\n",@result);
1206}
1207END_OF_FUNC
1208
424ec8fa
GS
1209#### Method as_string
1210#
1211# synonym for "dump"
1212####
1213'as_string' => <<'END_OF_FUNC',
1214sub as_string {
3d1a2ec4 1215 &Dump(@_);
424ec8fa
GS
1216}
1217END_OF_FUNC
1218
1219#### Method: save
1220# Write values out to a filehandle in such a way that they can
1221# be reinitialized by the filehandle form of the new() method
54310121 1222####
1223'save' => <<'END_OF_FUNC',
1224sub save {
1225 my($self,$filehandle) = self_or_default(@_);
54310121 1226 $filehandle = to_filehandle($filehandle);
424ec8fa
GS
1227 my($param);
1228 local($,) = ''; # set print field separator back to a sane value
71f3e297 1229 local($\) = ''; # set output line separator to a sane value
54310121 1230 foreach $param ($self->param) {
424ec8fa 1231 my($escaped_param) = escape($param);
54310121 1232 my($value);
1233 foreach $value ($self->param($param)) {
3538e1d5 1234 print $filehandle "$escaped_param=",escape("$value"),"\n";
54310121 1235 }
1236 }
d45d855d
JH
1237 foreach (keys %{$self->{'.fieldnames'}}) {
1238 print $filehandle ".cgifields=",escape("$_"),"\n";
1239 }
54310121 1240 print $filehandle "=\n"; # end of record
1241}
1242END_OF_FUNC
1243
1244
424ec8fa
GS
1245#### Method: save_parameters
1246# An alias for save() that is a better name for exportation.
1247# Only intended to be used with the function (non-OO) interface.
1248####
1249'save_parameters' => <<'END_OF_FUNC',
1250sub save_parameters {
1251 my $fh = shift;
1252 return save(to_filehandle($fh));
1253}
1254END_OF_FUNC
1255
1256#### Method: restore_parameters
1257# A way to restore CGI parameters from an initializer.
1258# Only intended to be used with the function (non-OO) interface.
1259####
1260'restore_parameters' => <<'END_OF_FUNC',
1261sub restore_parameters {
1262 $Q = $CGI::DefaultClass->new(@_);
1263}
1264END_OF_FUNC
1265
1266#### Method: multipart_init
1267# Return a Content-Type: style header for server-push
ba056755 1268# This has to be NPH on most web servers, and it is advisable to set $| = 1
424ec8fa
GS
1269#
1270# Many thanks to Ed Jordan <ed@fidalgo.net> for this
ba056755 1271# contribution, updated by Andrew Benham (adsb@bigfoot.com)
424ec8fa
GS
1272####
1273'multipart_init' => <<'END_OF_FUNC',
1274sub multipart_init {
1275 my($self,@p) = self_or_default(@_);
3d1a2ec4 1276 my($boundary,@other) = rearrange([BOUNDARY],@p);
424ec8fa 1277 $boundary = $boundary || '------- =_aaaaaaaaaa0';
ba056755
JH
1278 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1279 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
424ec8fa
GS
1280 $type = SERVER_PUSH($boundary);
1281 return $self->header(
1282 -nph => 1,
1283 -type => $type,
1284 (map { split "=", $_, 2 } @other),
ba056755 1285 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
424ec8fa
GS
1286}
1287END_OF_FUNC
1288
1289
1290#### Method: multipart_start
1291# Return a Content-Type: style header for server-push, start of section
1292#
1293# Many thanks to Ed Jordan <ed@fidalgo.net> for this
ba056755 1294# contribution, updated by Andrew Benham (adsb@bigfoot.com)
424ec8fa
GS
1295####
1296'multipart_start' => <<'END_OF_FUNC',
1297sub multipart_start {
ba056755 1298 my(@header);
424ec8fa 1299 my($self,@p) = self_or_default(@_);
3d1a2ec4 1300 my($type,@other) = rearrange([TYPE],@p);
424ec8fa 1301 $type = $type || 'text/html';
ba056755
JH
1302 push(@header,"Content-Type: $type");
1303
1304 # rearrange() was designed for the HTML portion, so we
1305 # need to fix it up a little.
1306 foreach (@other) {
8f3ccfa2
JH
1307 # Don't use \s because of perl bug 21951
1308 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
ba056755
JH
1309 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1310 }
1311 push(@header,@other);
1312 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1313 return $header;
424ec8fa
GS
1314}
1315END_OF_FUNC
1316
1317
1318#### Method: multipart_end
ba056755 1319# Return a MIME boundary separator for server-push, end of section
424ec8fa
GS
1320#
1321# Many thanks to Ed Jordan <ed@fidalgo.net> for this
1322# contribution
1323####
1324'multipart_end' => <<'END_OF_FUNC',
1325sub multipart_end {
1326 my($self,@p) = self_or_default(@_);
1327 return $self->{'separator'};
1328}
1329END_OF_FUNC
1330
1331
ba056755
JH
1332#### Method: multipart_final
1333# Return a MIME boundary separator for server-push, end of all sections
1334#
1335# Contributed by Andrew Benham (adsb@bigfoot.com)
1336####
1337'multipart_final' => <<'END_OF_FUNC',
1338sub multipart_final {
1339 my($self,@p) = self_or_default(@_);
1340 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1341}
1342END_OF_FUNC
1343
1344
54310121 1345#### Method: header
1346# Return a Content-Type: style header
1347#
1348####
1349'header' => <<'END_OF_FUNC',
1350sub header {
1351 my($self,@p) = self_or_default(@_);
1352 my(@header);
1353
2ed511ec 1354 return "" if $self->{'.header_printed'}++ and $HEADERS_ONCE;
71f3e297 1355
8f3ccfa2 1356 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,$p3p,@other) =
3d1a2ec4
GS
1357 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1358 'STATUS',['COOKIE','COOKIES'],'TARGET',
6b4ac661 1359 'EXPIRES','NPH','CHARSET',
8f3ccfa2 1360 'ATTACHMENT','P3P'],@p);
3d1a2ec4
GS
1361
1362 $nph ||= $NPH;
1363 if (defined $charset) {
1364 $self->charset($charset);
1365 } else {
1366 $charset = $self->charset;
1367 }
54310121 1368
1369 # rearrange() was designed for the HTML portion, so we
1370 # need to fix it up a little.
1371 foreach (@other) {
8f3ccfa2
JH
1372 # Don't use \s because of perl bug 21951
1373 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1374 ($_ = $header) =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
54310121 1375 }
1376
71f3e297 1377 $type ||= 'text/html' unless defined($type);
8f3ccfa2 1378 $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/ and $charset ne '';
54310121 1379
424ec8fa
GS
1380 # Maybe future compatibility. Maybe not.
1381 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1382 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
ba056755 1383 push(@header,"Server: " . &server_software()) if $nph;
424ec8fa 1384
54310121 1385 push(@header,"Status: $status") if $status;
424ec8fa 1386 push(@header,"Window-Target: $target") if $target;
8f3ccfa2
JH
1387 if ($p3p) {
1388 $p3p = join ' ',@$p3p if ref($p3p) eq 'ARRAY';
1389 push(@header,qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p"));
1390 }
54310121 1391 # push all the cookies -- there may be several
1392 if ($cookie) {
424ec8fa 1393 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
54310121 1394 foreach (@cookie) {
71f3e297
JH
1395 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1396 push(@header,"Set-Cookie: $cs") if $cs ne '';
54310121 1397 }
1398 }
1399 # if the user indicates an expiration time, then we need
1400 # both an Expires and a Date header (so that the browser is
1401 # uses OUR clock)
424ec8fa 1402 push(@header,"Expires: " . expires($expires,'http'))
7d37aa8e 1403 if $expires;
ba056755 1404 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
54310121 1405 push(@header,"Pragma: no-cache") if $self->cache();
6b4ac661 1406 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
69c89ae7 1407 push(@header,map {ucfirst $_} @other);
71f3e297 1408 push(@header,"Content-Type: $type") if $type ne '';
424ec8fa
GS
1409 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1410 if ($MOD_PERL and not $nph) {
8f3ccfa2
JH
1411 $self->r->send_cgi_header($header);
1412 return '';
424ec8fa
GS
1413 }
1414 return $header;
54310121 1415}
1416END_OF_FUNC
1417
1418
1419#### Method: cache
1420# Control whether header() will produce the no-cache
1421# Pragma directive.
1422####
1423'cache' => <<'END_OF_FUNC',
1424sub cache {
1425 my($self,$new_value) = self_or_default(@_);
1426 $new_value = '' unless $new_value;
1427 if ($new_value ne '') {
1428 $self->{'cache'} = $new_value;
1429 }
1430 return $self->{'cache'};
1431}
1432END_OF_FUNC
1433
1434
1435#### Method: redirect
1436# Return a Location: style header
1437#
1438####
1439'redirect' => <<'END_OF_FUNC',
1440sub redirect {
1441 my($self,@p) = self_or_default(@_);
8f3ccfa2 1442 my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,['COOKIE','COOKIES'],NPH],@p);
6b4ac661 1443 $url ||= $self->self_url;
54310121 1444 my(@o);
424ec8fa
GS
1445 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1446 unshift(@o,
8f3ccfa2
JH
1447 '-Status' => '302 Moved',
1448 '-Location'=> $url,
1449 '-nph' => $nph);
424ec8fa 1450 unshift(@o,'-Target'=>$target) if $target;
71f3e297 1451 unshift(@o,'-Type'=>'');
8f3ccfa2
JH
1452 my @unescaped;
1453 unshift(@unescaped,'-Cookie'=>$cookie) if $cookie;
1454 return $self->header((map {$self->unescapeHTML($_)} @o),@unescaped);
54310121 1455}
1456END_OF_FUNC
1457
1458
1459#### Method: start_html
1460# Canned HTML header
1461#
1462# Parameters:
1463# $title -> (optional) The title for this HTML document (-title)
1464# $author -> (optional) e-mail address of the author (-author)
1465# $base -> (optional) if set to true, will enter the BASE address of this document
1466# for resolving relative references (-base)
1467# $xbase -> (optional) alternative base at some remote location (-xbase)
1468# $target -> (optional) target window to load all links into (-target)
1469# $script -> (option) Javascript code (-script)
47e3cabd 1470# $no_script -> (option) Javascript <noscript> tag (-noscript)
54310121 1471# $meta -> (optional) Meta information tags
3acbd4f5 1472# $head -> (optional) any other elements you'd like to incorporate into the <head> tag
7d37aa8e
LS
1473# (a scalar or array ref)
1474# $style -> (optional) reference to an external style sheet
54310121 1475# @other -> (optional) any other named parameters you'd like to incorporate into
3acbd4f5 1476# the <body> tag.
54310121 1477####
1478'start_html' => <<'END_OF_FUNC',
1479sub start_html {
1480 my($self,@p) = &self_or_default(@_);
ac734d8b
JH
1481 my($title,$author,$base,$xbase,$script,$noscript,
1482 $target,$meta,$head,$style,$dtd,$lang,$encoding,@other) =
1483 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG,ENCODING],@p);
1484
b2d0d414 1485 $encoding = 'iso-8859-1' unless defined $encoding;
54310121 1486
1487 # strangely enough, the title needs to be escaped as HTML
1488 # while the author needs to be escaped as a URL
1489 $title = $self->escapeHTML($title || 'Untitled Document');
424ec8fa 1490 $author = $self->escape($author);
8f3ccfa2 1491 $lang = 'en-US' unless defined $lang;
ba056755 1492 my(@result,$xml_dtd);
3d1a2ec4 1493 if ($dtd) {
6b4ac661 1494 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
3d1a2ec4
GS
1495 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1496 } else {
1497 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1498 }
1499 } else {
6b4ac661 1500 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
3d1a2ec4 1501 }
ba056755
JH
1502
1503 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1504 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
ac734d8b 1505 push @result,qq(<?xml version="1.0" encoding="$encoding"?>) if $xml_dtd;
ba056755 1506
3d1a2ec4 1507 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
b2d0d414 1508 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t "$dtd->[1]">));
3d1a2ec4 1509 } else {
03b9648d 1510 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
3d1a2ec4 1511 }
188ba755 1512 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang" xml:lang="$lang"><head><title>$title</title>)
8f3ccfa2
JH
1513 : ($lang ? qq(<html lang="$lang">) : "<html>")
1514 . "<head><title>$title</title>");
6b4ac661
JH
1515 if (defined $author) {
1516 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
03b9648d 1517 : "<link rev=\"made\" href=\"mailto:$author\">");
6b4ac661 1518 }
54310121 1519
1520 if ($base || $xbase || $target) {
424ec8fa 1521 my $href = $xbase || $self->url('-path'=>1);
6b4ac661
JH
1522 my $t = $target ? qq/ target="$target"/ : '';
1523 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
54310121 1524 }
1525
1526 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
6b4ac661
JH
1527 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1528 : qq(<meta name="$_" content="$meta->{$_}">)); }
54310121 1529 }
7d37aa8e
LS
1530
1531 push(@result,ref($head) ? @$head : $head) if $head;
1532
424ec8fa
GS
1533 # handle the infrequently-used -style and -script parameters
1534 push(@result,$self->_style($style)) if defined $style;
1535 push(@result,$self->_script($script)) if defined $script;
1536
1537 # handle -noscript parameter
1538 push(@result,<<END) if $noscript;
6b4ac661 1539<noscript>
424ec8fa 1540$noscript
6b4ac661 1541</noscript>
424ec8fa
GS
1542END
1543 ;
1544 my($other) = @other ? " @other" : '';
6b4ac661 1545 push(@result,"</head><body$other>");
424ec8fa
GS
1546 return join("\n",@result);
1547}
1548END_OF_FUNC
1549
1550### Method: _style
1551# internal method for generating a CSS style section
1552####
1553'_style' => <<'END_OF_FUNC',
1554sub _style {
1555 my ($self,$style) = @_;
1556 my (@result);
1557 my $type = 'text/css';
a3b3a725
JH
1558
1559 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1560 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1561
424ec8fa 1562 if (ref($style)) {
1c87da1d 1563 my($src,$code,$verbatim,$stype,$foo,@other) =
8f3ccfa2 1564 rearrange([SRC,CODE,VERBATIM,TYPE],
1c87da1d 1565 '-foo'=>'bar', # trick to allow dash to be omitted
6b4ac661 1566 ref($style) eq 'ARRAY' ? @$style : %$style);
1c87da1d
JH
1567 $type = $stype if $stype;
1568 my $other = @other ? join ' ',@other : '';
1569
6b4ac661 1570 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
8f3ccfa2
JH
1571 { # If it is, push a LINK tag for each one
1572 foreach $src (@$src)
6b4ac661 1573 {
1c87da1d
JH
1574 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1575 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)) if $src;
6b4ac661
JH
1576 }
1577 }
1578 else
1579 { # Otherwise, push the single -src, if it exists.
1c87da1d
JH
1580 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1581 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)
ba056755 1582 ) if $src;
6b4ac661 1583 }
2ed511ec 1584 if ($verbatim) {
8f3ccfa2 1585 push(@result, "<style type=\"text/css\">\n$verbatim\n</style>");
1c87da1d 1586 }
8f3ccfa2 1587 push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
424ec8fa 1588 } else {
1c87da1d
JH
1589 my $src = $style;
1590 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1591 : qq(<link rel="stylesheet" type="$type" href="$src"$other>));
7d37aa8e 1592 }
424ec8fa
GS
1593 @result;
1594}
1595END_OF_FUNC
1596
424ec8fa
GS
1597'_script' => <<'END_OF_FUNC',
1598sub _script {
1599 my ($self,$script) = @_;
1600 my (@result);
a3b3a725 1601
424ec8fa
GS
1602 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1603 foreach $script (@scripts) {
7d37aa8e
LS
1604 my($src,$code,$language);
1605 if (ref($script)) { # script is a hash
3d1a2ec4
GS
1606 ($src,$code,$language, $type) =
1607 rearrange([SRC,CODE,LANGUAGE,TYPE],
7d37aa8e 1608 '-foo'=>'bar', # a trick to allow the '-' to be omitted
3538e1d5 1609 ref($script) eq 'ARRAY' ? @$script : %$script);
3d1a2ec4
GS
1610 # User may not have specified language
1611 $language ||= 'JavaScript';
1612 unless (defined $type) {
1613 $type = lc $language;
1614 # strip '1.2' from 'javascript1.2'
1615 $type =~ s/^(\D+).*$/text\/$1/;
1616 }
7d37aa8e 1617 } else {
3d1a2ec4 1618 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
7d37aa8e 1619 }
a3b3a725
JH
1620
1621 my $comment = '//'; # javascript by default
1622 $comment = '#' if $type=~/perl|tcl/i;
1623 $comment = "'" if $type=~/vbscript/i;
1624
58129083
JH
1625 my ($cdata_start,$cdata_end);
1626 if ($XHTML) {
1627 $cdata_start = "$comment<![CDATA[\n";
1628 $cdata_end .= "\n$comment]]>";
1629 } else {
1630 $cdata_start = "\n<!-- Hide script\n";
1631 $cdata_end = $comment;
1632 $cdata_end .= " End script hiding -->\n";
1633 }
1634 my(@satts);
1635 push(@satts,'src'=>$src) if $src;
1636 push(@satts,'language'=>$language) unless defined $type;
1637 push(@satts,'type'=>$type);
1638 $code = "$cdata_start$code$cdata_end" if defined $code;
1639 push(@result,script({@satts},$code || ''));
7d37aa8e 1640 }
424ec8fa 1641 @result;
54310121 1642}
1643END_OF_FUNC
1644
54310121 1645#### Method: end_html
1646# End an HTML document.
3acbd4f5 1647# Trivial method for completeness. Just returns "</body>"
54310121 1648####
1649'end_html' => <<'END_OF_FUNC',
1650sub end_html {
6b4ac661 1651 return "</body></html>";
54310121 1652}
1653END_OF_FUNC
1654
1655
1656################################
1657# METHODS USED IN BUILDING FORMS
1658################################
1659
1660#### Method: isindex
1661# Just prints out the isindex tag.
1662# Parameters:
1663# $action -> optional URL of script to run
1664# Returns:
188ba755 1665# A string containing a <isindex> tag
54310121 1666'isindex' => <<'END_OF_FUNC',
1667sub isindex {
1668 my($self,@p) = self_or_default(@_);
3d1a2ec4 1669 my($action,@other) = rearrange([ACTION],@p);
188ba755 1670 $action = qq/ action="$action"/ if $action;
54310121 1671 my($other) = @other ? " @other" : '';
188ba755 1672 return $XHTML ? "<isindex$action$other />" : "<isindex$action$other>";
54310121 1673}
1674END_OF_FUNC
1675
1676
1677#### Method: startform
1678# Start a form
1679# Parameters:
1680# $method -> optional submission method to use (GET or POST)
1681# $action -> optional URL of script to run
1682# $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1683'startform' => <<'END_OF_FUNC',
1684sub startform {
1685 my($self,@p) = self_or_default(@_);
1686
1687 my($method,$action,$enctype,@other) =
3d1a2ec4 1688 rearrange([METHOD,ACTION,ENCTYPE],@p);
54310121 1689
03b9648d 1690 $method = lc($method) || 'post';
54310121 1691 $enctype = $enctype || &URL_ENCODED;
03b9648d 1692 unless (defined $action) {
2ed511ec 1693
cff99809 1694 $action = $self->escapeHTML($self->url(-absolute=>1,-path=>1));
188ba755 1695 if (length($ENV{QUERY_STRING})>0) {
cff99809 1696 $action .= "?".$self->escapeHTML($ENV{QUERY_STRING},1);
188ba755 1697 }
03b9648d
JH
1698 }
1699 $action = qq(action="$action");
54310121 1700 my($other) = @other ? " @other" : '';
1701 $self->{'.parametersToAdd'}={};
6b4ac661 1702 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
54310121 1703}
1704END_OF_FUNC
1705
1706
1707#### Method: start_form
1708# synonym for startform
1709'start_form' => <<'END_OF_FUNC',
1710sub start_form {
1711 &startform;
1712}
1713END_OF_FUNC
1714
71f3e297
JH
1715'end_multipart_form' => <<'END_OF_FUNC',
1716sub end_multipart_form {
1717 &endform;
1718}
1719END_OF_FUNC
54310121 1720
1721#### Method: start_multipart_form
1722# synonym for startform
1723'start_multipart_form' => <<'END_OF_FUNC',
1724sub start_multipart_form {
1725 my($self,@p) = self_or_default(@_);
3d1a2ec4 1726 if (defined($param[0]) && substr($param[0],0,1) eq '-') {
54310121 1727 my(%p) = @p;
1728 $p{'-enctype'}=&MULTIPART;
1729 return $self->startform(%p);
1730 } else {
1731 my($method,$action,@other) =
3d1a2ec4 1732 rearrange([METHOD,ACTION],@p);
54310121 1733 return $self->startform($method,$action,&MULTIPART,@other);
1734 }
1735}
1736END_OF_FUNC
1737
1738
1739#### Method: endform
1740# End a form
1741'endform' => <<'END_OF_FUNC',
1742sub endform {
1743 my($self,@p) = self_or_default(@_);
3d1a2ec4 1744 if ( $NOSTICKY ) {
6b4ac661 1745 return wantarray ? ("</form>") : "\n</form>";
3d1a2ec4 1746 } else {
8f3ccfa2
JH
1747 return wantarray ? ("<div>",$self->get_fields,"</div>","</form>") :
1748 "<div>".$self->get_fields ."</div>\n</form>";
3d1a2ec4 1749 }
54310121 1750}
1751END_OF_FUNC
1752
1753
1754#### Method: end_form
1755# synonym for endform
1756'end_form' => <<'END_OF_FUNC',
1757sub end_form {
1758 &endform;
1759}
1760END_OF_FUNC
1761
1762
424ec8fa
GS
1763'_textfield' => <<'END_OF_FUNC',
1764sub _textfield {
1765 my($self,$tag,@p) = self_or_default(@_);
1766 my($name,$default,$size,$maxlength,$override,@other) =
8f3ccfa2 1767 rearrange([NAME,[DEFAULT,VALUE,VALUES],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
424ec8fa
GS
1768
1769 my $current = $override ? $default :
1770 (defined($self->param($name)) ? $self->param($name) : $default);
1771
a3b3a725 1772 $current = defined($current) ? $self->escapeHTML($current,1) : '';
424ec8fa 1773 $name = defined($name) ? $self->escapeHTML($name) : '';
ba056755
JH
1774 my($s) = defined($size) ? qq/ size="$size"/ : '';
1775 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
71f3e297
JH
1776 my($other) = @other ? " @other" : '';
1777 # this entered at cristy's request to fix problems with file upload fields
1778 # and WebTV -- not sure it won't break stuff
6b4ac661
JH
1779 my($value) = $current ne '' ? qq(value="$current") : '';
1780 return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />)
b2d0d414 1781 : qq(<input type="$tag" name="$name" $value$s$m$other>);
424ec8fa
GS
1782}
1783END_OF_FUNC
1784
54310121 1785#### Method: textfield
1786# Parameters:
1787# $name -> Name of the text field
1788# $default -> Optional default value of the field if not
1789# already defined.
1790# $size -> Optional width of field in characaters.
1791# $maxlength -> Optional maximum number of characters.
1792# Returns:
188ba755 1793# A string containing a <input type="text"> field
54310121 1794#
1795'textfield' => <<'END_OF_FUNC',
1796sub textfield {
1797 my($self,@p) = self_or_default(@_);
424ec8fa 1798 $self->_textfield('text',@p);
54310121 1799}
1800END_OF_FUNC
1801
1802
1803#### Method: filefield
1804# Parameters:
1805# $name -> Name of the file upload field
1806# $size -> Optional width of field in characaters.
1807# $maxlength -> Optional maximum number of characters.
1808# Returns:
188ba755 1809# A string containing a <input type="file"> field
54310121 1810#
1811'filefield' => <<'END_OF_FUNC',
1812sub filefield {
1813 my($self,@p) = self_or_default(@_);
424ec8fa 1814 $self->_textfield('file',@p);
54310121 1815}
1816END_OF_FUNC
1817
1818
1819#### Method: password
1820# Create a "secret password" entry field
1821# Parameters:
1822# $name -> Name of the field
1823# $default -> Optional default value of the field if not
1824# already defined.
1825# $size -> Optional width of field in characters.
1826# $maxlength -> Optional maximum characters that can be entered.
1827# Returns:
188ba755 1828# A string containing a <input type="password"> field
54310121 1829#
1830'password_field' => <<'END_OF_FUNC',
1831sub password_field {
1832 my ($self,@p) = self_or_default(@_);
424ec8fa 1833 $self->_textfield('password',@p);
54310121 1834}
1835END_OF_FUNC
1836
54310121 1837#### Method: textarea
1838# Parameters:
1839# $name -> Name of the text field
1840# $default -> Optional default value of the field if not
1841# already defined.
1842# $rows -> Optional number of rows in text area
1843# $columns -> Optional number of columns in text area
1844# Returns:
3acbd4f5 1845# A string containing a <textarea></textarea> tag
54310121 1846#
1847'textarea' => <<'END_OF_FUNC',
1848sub textarea {
1849 my($self,@p) = self_or_default(@_);
1850
1851 my($name,$default,$rows,$cols,$override,@other) =
3d1a2ec4 1852 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
54310121 1853
1854 my($current)= $override ? $default :
1855 (defined($self->param($name)) ? $self->param($name) : $default);
1856
1857 $name = defined($name) ? $self->escapeHTML($name) : '';
1858 $current = defined($current) ? $self->escapeHTML($current) : '';
3acbd4f5
JH
1859 my($r) = $rows ? qq/ rows="$rows"/ : '';
1860 my($c) = $cols ? qq/ cols="$cols"/ : '';
54310121 1861 my($other) = @other ? " @other" : '';
6b4ac661 1862 return qq{<textarea name="$name"$r$c$other>$current</textarea>};
54310121 1863}
1864END_OF_FUNC
1865
1866
1867#### Method: button
1868# Create a javascript button.
1869# Parameters:
1870# $name -> (optional) Name for the button. (-name)
1871# $value -> (optional) Value of the button when selected (and visible name) (-value)
1872# $onclick -> (optional) Text of the JavaScript to run when the button is
1873# clicked.
1874# Returns:
188ba755 1875# A string containing a <input type="button"> tag
54310121 1876####
1877'button' => <<'END_OF_FUNC',
1878sub button {
1879 my($self,@p) = self_or_default(@_);
1880
3d1a2ec4 1881 my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
54310121 1882 [ONCLICK,SCRIPT]],@p);
1883
1884 $label=$self->escapeHTML($label);
a3b3a725 1885 $value=$self->escapeHTML($value,1);
54310121 1886 $script=$self->escapeHTML($script);
1887
1888 my($name) = '';
ba056755 1889 $name = qq/ name="$label"/ if $label;
54310121 1890 $value = $value || $label;
1891 my($val) = '';
6b4ac661
JH
1892 $val = qq/ value="$value"/ if $value;
1893 $script = qq/ onclick="$script"/ if $script;
54310121 1894 my($other) = @other ? " @other" : '';
6b4ac661 1895 return $XHTML ? qq(<input type="button"$name$val$script$other />)
b2d0d414 1896 : qq(<input type="button"$name$val$script$other>);
54310121 1897}
1898END_OF_FUNC
1899
1900
1901#### Method: submit
1902# Create a "submit query" button.
1903# Parameters:
1904# $name -> (optional) Name for the button.
1905# $value -> (optional) Value of the button when selected (also doubles as label).
1906# $label -> (optional) Label printed on the button(also doubles as the value).
1907# Returns:
188ba755 1908# A string containing a <input type="submit"> tag
54310121 1909####
1910'submit' => <<'END_OF_FUNC',
1911sub submit {
1912 my($self,@p) = self_or_default(@_);
1913
3d1a2ec4 1914 my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
54310121 1915
1916 $label=$self->escapeHTML($label);
a3b3a725 1917 $value=$self->escapeHTML($value,1);
54310121 1918
efc8e943 1919 my $name = $NOSTICKY ? '' : ' name=".submit"';
6b4ac661 1920 $name = qq/ name="$label"/ if defined($label);
424ec8fa 1921 $value = defined($value) ? $value : $label;
8f3ccfa2 1922 my $val = '';
6b4ac661 1923 $val = qq/ value="$value"/ if defined($value);
54310121 1924 my($other) = @other ? " @other" : '';
6b4ac661 1925 return $XHTML ? qq(<input type="submit"$name$val$other />)
b2d0d414 1926 : qq(<input type="submit"$name$val$other>);
54310121 1927}
1928END_OF_FUNC
1929
1930
1931#### Method: reset
1932# Create a "reset" button.
1933# Parameters:
1934# $name -> (optional) Name for the button.
1935# Returns:
188ba755 1936# A string containing a <input type="reset"> tag
54310121 1937####
1938'reset' => <<'END_OF_FUNC',
1939sub reset {
1940 my($self,@p) = self_or_default(@_);
8f3ccfa2 1941 my($label,$value,@other) = rearrange(['NAME',['VALUE','LABEL']],@p);
54310121 1942 $label=$self->escapeHTML($label);
8f3ccfa2
JH
1943 $value=$self->escapeHTML($value,1);
1944 my ($name) = ' name=".reset"';
1945 $name = qq/ name="$label"/ if defined($label);
1946 $value = defined($value) ? $value : $label;
1947 my($val) = '';
1948 $val = qq/ value="$value"/ if defined($value);
54310121 1949 my($other) = @other ? " @other" : '';
8f3ccfa2
JH
1950 return $XHTML ? qq(<input type="reset"$name$val$other />)
1951 : qq(<input type="reset"$name$val$other>);
54310121 1952}
1953END_OF_FUNC
1954
1955
1956#### Method: defaults
1957# Create a "defaults" button.
1958# Parameters:
1959# $name -> (optional) Name for the button.
1960# Returns:
188ba755 1961# A string containing a <input type="submit" name=".defaults"> tag
54310121 1962#
1963# Note: this button has a special meaning to the initialization script,
1964# and tells it to ERASE the current query string so that your defaults
1965# are used again!
1966####
1967'defaults' => <<'END_OF_FUNC',
1968sub defaults {
1969 my($self,@p) = self_or_default(@_);
1970
3d1a2ec4 1971 my($label,@other) = rearrange([[NAME,VALUE]],@p);
54310121 1972
a3b3a725 1973 $label=$self->escapeHTML($label,1);
54310121 1974 $label = $label || "Defaults";
6b4ac661 1975 my($value) = qq/ value="$label"/;
54310121 1976 my($other) = @other ? " @other" : '';
d45d855d 1977 return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
6b4ac661 1978 : qq/<input type="submit" NAME=".defaults"$value$other>/;
54310121 1979}
1980END_OF_FUNC
1981
1982
424ec8fa
GS
1983#### Method: comment
1984# Create an HTML <!-- comment -->
1985# Parameters: a string
1986'comment' => <<'END_OF_FUNC',
1987sub comment {
1988 my($self,@p) = self_or_CGI(@_);
1989 return "<!-- @p -->";
1990}
1991END_OF_FUNC
1992
54310121 1993#### Method: checkbox
1994# Create a checkbox that is not logically linked to any others.
1995# The field value is "on" when the button is checked.
1996# Parameters:
1997# $name -> Name of the checkbox
1998# $checked -> (optional) turned on by default if true
1999# $value -> (optional) value of the checkbox, 'on' by default
2000# $label -> (optional) a user-readable label printed next to the box.
2001# Otherwise the checkbox name is used.
2002# Returns:
188ba755 2003# A string containing a <input type="checkbox"> field
54310121 2004####
2005'checkbox' => <<'END_OF_FUNC',
2006sub checkbox {
2007 my($self,@p) = self_or_default(@_);
2008
2009 my($name,$checked,$value,$label,$override,@other) =
3d1a2ec4 2010 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
54310121 2011
424ec8fa
GS
2012 $value = defined $value ? $value : 'on';
2013
2014 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2015 defined $self->param($name))) {
3acbd4f5 2016 $checked = grep($_ eq $value,$self->param($name)) ? $self->_checked(1) : '';
54310121 2017 } else {
3acbd4f5 2018 $checked = $self->_checked($checked);
54310121 2019 }
2020 my($the_label) = defined $label ? $label : $name;
2021 $name = $self->escapeHTML($name);
a3b3a725 2022 $value = $self->escapeHTML($value,1);
54310121 2023 $the_label = $self->escapeHTML($the_label);
2024 my($other) = @other ? " @other" : '';
2025 $self->register_parameter($name);
6b4ac661
JH
2026 return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
2027 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
54310121 2028}
2029END_OF_FUNC
2030
2031
2032#### Method: checkbox_group
2033# Create a list of logically-linked checkboxes.
2034# Parameters:
2035# $name -> Common name for all the check boxes
2036# $values -> A pointer to a regular array containing the
2037# values for each checkbox in the group.
2038# $defaults -> (optional)
2039# 1. If a pointer to a regular array of checkbox values,
2040# then this will be used to decide which
2041# checkboxes to turn on by default.
2042# 2. If a scalar, will be assumed to hold the
2043# value of a single checkbox in the group to turn on.
2044# $linebreak -> (optional) Set to true to place linebreaks
2045# between the buttons.
2046# $labels -> (optional)
2047# A pointer to an associative array of labels to print next to each checkbox
2048# in the form $label{'value'}="Long explanatory label".
2049# Otherwise the provided values are used as the labels.
2050# Returns:
188ba755 2051# An ARRAY containing a series of <input type="checkbox"> fields
54310121 2052####
2053'checkbox_group' => <<'END_OF_FUNC',
2054sub checkbox_group {
2055 my($self,@p) = self_or_default(@_);
2056
188ba755 2057 my($name,$values,$defaults,$linebreak,$labels,$attributes,$rows,$columns,
54310121 2058 $rowheaders,$colheaders,$override,$nolabels,@other) =
3d1a2ec4 2059 rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
188ba755 2060 LINEBREAK,LABELS,ATTRIBUTES,ROWS,[COLUMNS,COLS],
54310121 2061 ROWHEADERS,COLHEADERS,
2062 [OVERRIDE,FORCE],NOLABELS],@p);
2063
2064 my($checked,$break,$result,$label);
2065
2066 my(%checked) = $self->previous_or_default($name,$defaults,$override);
2067
6b4ac661
JH
2068 if ($linebreak) {
2069 $break = $XHTML ? "<br />" : "<br>";
2070 }
2071 else {
2072 $break = '';
2073 }
54310121 2074 $name=$self->escapeHTML($name);
2075
2076 # Create the elements
424ec8fa
GS
2077 my(@elements,@values);
2078
2079 @values = $self->_set_values_and_labels($values,\$labels,$name);
2080
54310121 2081 my($other) = @other ? " @other" : '';
2082 foreach (@values) {
3acbd4f5 2083 $checked = $self->_checked($checked{$_});
54310121 2084 $label = '';
2085 unless (defined($nolabels) && $nolabels) {
2086 $label = $_;
424ec8fa 2087 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
54310121 2088 $label = $self->escapeHTML($label);
2089 }
188ba755 2090 my $attribs = $self->_set_attributes($_, $attributes);
a3b3a725 2091 $_ = $self->escapeHTML($_,1);
188ba755
JH
2092 push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other$attribs />${label}${break})
2093 : qq/<input type="checkbox" name="$name" value="$_"$checked$other$attribs>${label}${break}/);
54310121 2094 }
2095 $self->register_parameter($name);
424ec8fa
GS
2096 return wantarray ? @elements : join(' ',@elements)
2097 unless defined($columns) || defined($rows);
8f3ccfa2
JH
2098 $rows = 1 if $rows && $rows < 1;
2099 $cols = 1 if $cols && $cols < 1;
54310121 2100 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2101}
2102END_OF_FUNC
2103
54310121 2104# Escape HTML -- used internally
2105'escapeHTML' => <<'END_OF_FUNC',
2106sub escapeHTML {
ac734d8b
JH
2107 # hack to work around earlier hacks
2108 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
a3b3a725 2109 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
6b4ac661 2110 return undef unless defined($toencode);
188ba755 2111 return $toencode if ref($self) && !$self->{'escape'};
6b4ac661
JH
2112 $toencode =~ s{&}{&amp;}gso;
2113 $toencode =~ s{<}{&lt;}gso;
2114 $toencode =~ s{>}{&gt;}gso;
2115 $toencode =~ s{"}{&quot;}gso;
a3b3a725
JH
2116 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
2117 uc $self->{'.charset'} eq 'WINDOWS-1252';
2118 if ($latin) { # bug in some browsers
ba056755 2119 $toencode =~ s{'}{&#39;}gso;
188ba755
JH
2120 $toencode =~ s{\x8b}{&#8249;}gso;
2121 $toencode =~ s{\x9b}{&#8250;}gso;
a3b3a725
JH
2122 if (defined $newlinestoo && $newlinestoo) {
2123 $toencode =~ s{\012}{&#10;}gso;
2124 $toencode =~ s{\015}{&#13;}gso;
2125 }
2126 }
6b4ac661 2127 return $toencode;
54310121 2128}
2129END_OF_FUNC
2130
424ec8fa
GS
2131# unescape HTML -- used internally
2132'unescapeHTML' => <<'END_OF_FUNC',
2133sub unescapeHTML {
efc8e943
NC
2134 # hack to work around earlier hacks
2135 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
6b4ac661 2136 my ($self,$string) = CGI::self_or_default(@_);
424ec8fa 2137 return undef unless defined($string);
a3b3a725
JH
2138 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
2139 : 1;
71f3e297
JH
2140 # thanks to Randal Schwartz for the correct solution to this one
2141 $string=~ s[&(.*?);]{
2142 local $_ = $1;
2143 /^amp$/i ? "&" :
2144 /^quot$/i ? '"' :
2145 /^gt$/i ? ">" :
2146 /^lt$/i ? "<" :
6b4ac661
JH
2147 /^#(\d+)$/ && $latin ? chr($1) :
2148 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
71f3e297
JH
2149 $_
2150 }gex;
424ec8fa
GS
2151 return $string;
2152}
2153END_OF_FUNC
54310121 2154
2155# Internal procedure - don't use
2156'_tableize' => <<'END_OF_FUNC',
2157sub _tableize {
2158 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
6b4ac661
JH
2159 $rowheaders = [] unless defined $rowheaders;
2160 $colheaders = [] unless defined $colheaders;
54310121 2161 my($result);
2162
424ec8fa
GS
2163 if (defined($columns)) {
2164 $rows = int(0.99 + @elements/$columns) unless defined($rows);
2165 }
2166 if (defined($rows)) {
2167 $columns = int(0.99 + @elements/$rows) unless defined($columns);
2168 }
2169
54310121 2170 # rearrange into a pretty table
6b4ac661 2171 $result = "<table>";
54310121 2172 my($row,$column);
475342a6 2173 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
6b4ac661 2174 $result .= "<tr>" if @{$colheaders};
54310121 2175 foreach (@{$colheaders}) {
6b4ac661 2176 $result .= "<th>$_</th>";
54310121 2177 }
2178 for ($row=0;$row<$rows;$row++) {
6b4ac661
JH
2179 $result .= "<tr>";
2180 $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
54310121 2181 for ($column=0;$column<$columns;$column++) {
6b4ac661 2182 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
424ec8fa 2183 if defined($elements[$column*$rows + $row]);
54310121 2184 }
6b4ac661 2185 $result .= "</tr>";
54310121 2186 }
6b4ac661 2187 $result .= "</table>";
54310121 2188 return $result;
2189}
2190END_OF_FUNC
2191
2192
2193#### Method: radio_group
2194# Create a list of logically-linked radio buttons.
2195# Parameters:
2196# $name -> Common name for all the buttons.
2197# $values -> A pointer to a regular array containing the
2198# values for each button in the group.
2199# $default -> (optional) Value of the button to turn on by default. Pass '-'
2200# to turn _nothing_ on.
2201# $linebreak -> (optional) Set to true to place linebreaks
2202# between the buttons.
2203# $labels -> (optional)
2204# A pointer to an associative array of labels to print next to each checkbox
2205# in the form $label{'value'}="Long explanatory label".
2206# Otherwise the provided values are used as the labels.
2207# Returns:
188ba755 2208# An ARRAY containing a series of <input type="radio"> fields
54310121 2209####
2210'radio_group' => <<'END_OF_FUNC',
2211sub radio_group {
2212 my($self,@p) = self_or_default(@_);
2213
188ba755 2214 my($name,$values,$default,$linebreak,$labels,$attributes,
54310121 2215 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
188ba755 2216 rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,ATTRIBUTES,
54310121 2217 ROWS,[COLUMNS,COLS],
2218 ROWHEADERS,COLHEADERS,
2219 [OVERRIDE,FORCE],NOLABELS],@p);
2220 my($result,$checked);
2221
2222 if (!$override && defined($self->param($name))) {
2223 $checked = $self->param($name);
2224 } else {
2225 $checked = $default;
2226 }
424ec8fa 2227 my(@elements,@values);
424ec8fa
GS
2228 @values = $self->_set_values_and_labels($values,\$labels,$name);
2229
71f3e297
JH
2230 # If no check array is specified, check the first by default
2231 $checked = $values[0] unless defined($checked) && $checked ne '';
2232 $name=$self->escapeHTML($name);
2233
54310121 2234 my($other) = @other ? " @other" : '';
2235 foreach (@values) {
2371fea9 2236 my($checkit) = $checked eq $_ ? qq/ checked="checked"/ : '';
6b4ac661
JH
2237 my($break);
2238 if ($linebreak) {
ba056755 2239 $break = $XHTML ? "<br />" : "<br>";
6b4ac661
JH
2240 }
2241 else {
ba056755 2242 $break = '';
6b4ac661 2243 }
54310121 2244 my($label)='';
2245 unless (defined($nolabels) && $nolabels) {
2246 $label = $_;
424ec8fa 2247 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
a3b3a725 2248 $label = $self->escapeHTML($label,1);
54310121 2249 }
188ba755 2250 my $attribs = $self->_set_attributes($_, $attributes);
54310121 2251 $_=$self->escapeHTML($_);
188ba755
JH
2252 push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other$attribs />${label}${break})
2253 : qq/<input type="radio" name="$name" value="$_"$checkit$other$attribs>${label}${break}/);
54310121 2254 }
2255 $self->register_parameter($name);
424ec8fa
GS
2256 return wantarray ? @elements : join(' ',@elements)
2257 unless defined($columns) || defined($rows);
54310121 2258 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2259}
2260END_OF_FUNC
2261
2262
2263#### Method: popup_menu
2264# Create a popup menu.
2265# Parameters:
2266# $name -> Name for all the menu
2267# $values -> A pointer to a regular array containing the
2268# text of each menu item.
2269# $default -> (optional) Default item to display
2270# $labels -> (optional)
2271# A pointer to an associative array of labels to print next to each checkbox
2272# in the form $label{'value'}="Long explanatory label".
2273# Otherwise the provided values are used as the labels.
2274# Returns:
2275# A string containing the definition of a popup menu.
2276####
2277'popup_menu' => <<'END_OF_FUNC',
2278sub popup_menu {
2279 my($self,@p) = self_or_default(@_);
2280
188ba755
JH
2281 my($name,$values,$default,$labels,$attributes,$override,@other) =
2282 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,
2283 ATTRIBUTES,[OVERRIDE,FORCE]],@p);
54310121 2284 my($result,$selected);
2285
2286 if (!$override && defined($self->param($name))) {
2287 $selected = $self->param($name);
2288 } else {
2289 $selected = $default;
2290 }
2291 $name=$self->escapeHTML($name);
2292 my($other) = @other ? " @other" : '';
2293
424ec8fa
GS
2294 my(@values);
2295 @values = $self->_set_values_and_labels($values,\$labels,$name);
2296
6b4ac661 2297 $result = qq/<select name="$name"$other>\n/;
54310121 2298 foreach (@values) {
188ba755
JH
2299 if (/<optgroup/) {
2300 foreach (split(/\n/)) {
2301 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2302 s/(value="$selected")/$selectit $1/ if defined $selected;
2303 $result .= "$_\n";
2304 }
2305 }
2306 else {
2307 my $attribs = $self->_set_attributes($_, $attributes);
3acbd4f5 2308 my($selectit) = defined($selected) ? $self->_selected($selected eq $_) : '';
54310121 2309 my($label) = $_;
424ec8fa 2310 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
54310121 2311 my($value) = $self->escapeHTML($_);
a3b3a725 2312 $label=$self->escapeHTML($label,1);
188ba755
JH
2313 $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2314 }
54310121 2315 }
2316
69c89ae7 2317 $result .= "</select>";
54310121 2318 return $result;
2319}
2320END_OF_FUNC
2321
2322
188ba755
JH
2323#### Method: optgroup
2324# Create a optgroup.
2325# Parameters:
2326# $name -> Label for the group
2327# $values -> A pointer to a regular array containing the
2328# values for each option line in the group.
2329# $labels -> (optional)
2330# A pointer to an associative array of labels to print next to each item
2331# in the form $label{'value'}="Long explanatory label".
2332# Otherwise the provided values are used as the labels.
2333# $labeled -> (optional)
2334# A true value indicates the value should be used as the label attribute
2335# in the option elements.
2336# The label attribute specifies the option label presented to the user.
2337# This defaults to the content of the <option> element, but the label
2338# attribute allows authors to more easily use optgroup without sacrificing
2339# compatibility with browsers that do not support option groups.
2340# $novals -> (optional)
2341# A true value indicates to suppress the val attribute in the option elements
2342# Returns:
2343# A string containing the definition of an option group.
2344####
2345'optgroup' => <<'END_OF_FUNC',
2346sub optgroup {
2347 my($self,@p) = self_or_default(@_);
2348 my($name,$values,$attributes,$labeled,$noval,$labels,@other)
2349 = rearrange([NAME,[VALUES,VALUE],ATTRIBUTES,LABELED,NOVALS,LABELS],@p);
2350
2351 my($result,@values);
2352 @values = $self->_set_values_and_labels($values,\$labels,$name,$labeled,$novals);
2353 my($other) = @other ? " @other" : '';
2354
2355 $name=$self->escapeHTML($name);
2356 $result = qq/<optgroup label="$name"$other>\n/;
2357 foreach (@values) {
2358 if (/<optgroup/) {
2359 foreach (split(/\n/)) {
2360 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2361 s/(value="$selected")/$selectit $1/ if defined $selected;
2362 $result .= "$_\n";
2363 }
2364 }
2365 else {
2366 my $attribs = $self->_set_attributes($_, $attributes);
2367 my($label) = $_;
2368 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2369 $label=$self->escapeHTML($label);
2370 my($value)=$self->escapeHTML($_,1);
2371 $result .= $labeled ? $novals ? "<option$attribs label=\"$value\">$label</option>\n"
2372 : "<option$attribs label=\"$value\" value=\"$value\">$label</option>\n"
2373 : $novals ? "<option$attribs>$label</option>\n"
2374 : "<option$attribs value=\"$value\">$label</option>\n";
2375 }
2376 }
2377 $result .= "</optgroup>";
2378 return $result;
2379}
2380END_OF_FUNC
2381
2382
54310121 2383#### Method: scrolling_list
2384# Create a scrolling list.
2385# Parameters:
2386# $name -> name for the list
2387# $values -> A pointer to a regular array containing the
2388# values for each option line in the list.
2389# $defaults -> (optional)
2390# 1. If a pointer to a regular array of options,
2391# then this will be used to decide which
2392# lines to turn on by default.
2393# 2. Otherwise holds the value of the single line to turn on.
2394# $size -> (optional) Size of the list.
2395# $multiple -> (optional) If set, allow multiple selections.
2396# $labels -> (optional)
2397# A pointer to an associative array of labels to print next to each checkbox
2398# in the form $label{'value'}="Long explanatory label".
2399# Otherwise the provided values are used as the labels.
2400# Returns:
2401# A string containing the definition of a scrolling list.
2402####
2403'scrolling_list' => <<'END_OF_FUNC',
2404sub scrolling_list {
2405 my($self,@p) = self_or_default(@_);
188ba755 2406 my($name,$values,$defaults,$size,$multiple,$labels,$attributes,$override,@other)
3d1a2ec4 2407 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
188ba755 2408 SIZE,MULTIPLE,LABELS,ATTRIBUTES,[OVERRIDE,FORCE]],@p);
54310121 2409
424ec8fa
GS
2410 my($result,@values);
2411 @values = $self->_set_values_and_labels($values,\$labels,$name);
2412
54310121 2413 $size = $size || scalar(@values);
2414
2415 my(%selected) = $self->previous_or_default($name,$defaults,$override);
ac734d8b 2416 my($is_multiple) = $multiple ? qq/ multiple="multiple"/ : '';
6b4ac661 2417 my($has_size) = $size ? qq/ size="$size"/: '';
54310121 2418 my($other) = @other ? " @other" : '';
2419
2420 $name=$self->escapeHTML($name);
6b4ac661 2421 $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
54310121 2422 foreach (@values) {
3acbd4f5 2423 my($selectit) = $self->_selected($selected{$_});
54310121 2424 my($label) = $_;
424ec8fa 2425 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
54310121 2426 $label=$self->escapeHTML($label);
a3b3a725 2427 my($value)=$self->escapeHTML($_,1);
188ba755
JH
2428 my $attribs = $self->_set_attributes($_, $attributes);
2429 $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
54310121 2430 }
69c89ae7 2431 $result .= "</select>";
54310121 2432 $self->register_parameter($name);
2433 return $result;
2434}
2435END_OF_FUNC
2436
2437
2438#### Method: hidden
2439# Parameters:
2440# $name -> Name of the hidden field
2441# @default -> (optional) Initial values of field (may be an array)
2442# or
2443# $default->[initial values of field]
2444# Returns:
188ba755 2445# A string containing a <input type="hidden" name="name" value="value">
54310121 2446####
2447'hidden' => <<'END_OF_FUNC',
2448sub hidden {
2449 my($self,@p) = self_or_default(@_);
2450
2451 # this is the one place where we departed from our standard
2452 # calling scheme, so we have to special-case (darn)
2453 my(@result,@value);
2454 my($name,$default,$override,@other) =
3d1a2ec4 2455 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
54310121 2456
2457 my $do_override = 0;
3d1a2ec4 2458 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
54310121 2459 @value = ref($default) ? @{$default} : $default;
2460 $do_override = $override;
2461 } else {
2462 foreach ($default,$override,@other) {
2463 push(@value,$_) if defined($_);
2464 }
2465 }
2466
2467 # use previous values if override is not set
2468 my @prev = $self->param($name);
2469 @value = @prev if !$do_override && @prev;
2470
2471 $name=$self->escapeHTML($name);
2472 foreach (@value) {
a3b3a725 2473 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
ba056755 2474 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
03b9648d 2475 : qq(<input type="hidden" name="$name" value="$_">);
54310121 2476 }
2477 return wantarray ? @result : join('',@result);
2478}
2479END_OF_FUNC
2480
2481
2482#### Method: image_button
2483# Parameters:
2484# $name -> Name of the button
2485# $src -> URL of the image source
2486# $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2487# Returns:
188ba755 2488# A string containing a <input type="image" name="name" src="url" align="alignment">
54310121 2489####
2490'image_button' => <<'END_OF_FUNC',
2491sub image_button {
2492 my($self,@p) = self_or_default(@_);
2493
2494 my($name,$src,$alignment,@other) =
3d1a2ec4 2495 rearrange([NAME,SRC,ALIGN],@p);
54310121 2496
ac734d8b 2497 my($align) = $alignment ? " align=\U\"$alignment\"" : '';
54310121 2498 my($other) = @other ? " @other" : '';
2499 $name=$self->escapeHTML($name);
6b4ac661
JH
2500 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2501 : qq/<input type="image" name="$name" src="$src"$align$other>/;
54310121 2502}
2503END_OF_FUNC
2504
2505
2506#### Method: self_url
2507# Returns a URL containing the current script and all its
2508# param/value pairs arranged as a query. You can use this
2509# to create a link that, when selected, will reinvoke the
2510# script with all its state information preserved.
2511####
2512'self_url' => <<'END_OF_FUNC',
2513sub self_url {
424ec8fa
GS
2514 my($self,@p) = self_or_default(@_);
2515 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
54310121 2516}
2517END_OF_FUNC
2518
2519
2520# This is provided as a synonym to self_url() for people unfortunate
2521# enough to have incorporated it into their programs already!
2522'state' => <<'END_OF_FUNC',
2523sub state {
2524 &self_url;
2525}
2526END_OF_FUNC
2527
2528
2529#### Method: url
2530# Like self_url, but doesn't return the query string part of
2531# the URL.
2532####
2533'url' => <<'END_OF_FUNC',
2534sub url {
424ec8fa 2535 my($self,@p) = self_or_default(@_);
03b9648d
JH
2536 my ($relative,$absolute,$full,$path_info,$query,$base) =
2537 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
424ec8fa 2538 my $url;
2371fea9 2539 $full++ if $base || !($relative || $absolute);
424ec8fa 2540
3538e1d5 2541 my $path = $self->path_info;
d45d855d
JH
2542 my $script_name = $self->script_name;
2543
2371fea9
JH
2544 # for compatibility with Apache's MultiViews
2545 if (exists($ENV{REQUEST_URI})) {
2546 my $index;
8f3ccfa2 2547 $script_name = unescape($ENV{REQUEST_URI});
2371fea9
JH
2548 $script_name =~ s/\?.+$//; # strip query string
2549 # and path
2550 if (exists($ENV{PATH_INFO})) {
efc8e943
NC
2551 my $encoded_path = unescape($ENV{PATH_INFO});
2552 $script_name =~ s/\Q$encoded_path\E$//i;
2371fea9
JH
2553 }
2554 }
3538e1d5 2555
424ec8fa
GS
2556 if ($full) {
2557 my $protocol = $self->protocol();
2558 $url = "$protocol://";
2559 my $vh = http('host');
2560 if ($vh) {
2561 $url .= $vh;
2562 } else {
2563 $url .= server_name();
2564 my $port = $self->server_port;
2565 $url .= ":" . $port
2ed511ec 2566 unless (lc($protocol) eq 'http' && $port == 80)
424ec8fa
GS
2567 || (lc($protocol) eq 'https' && $port == 443);
2568 }
03b9648d 2569 return $url if $base;
3538e1d5 2570 $url .= $script_name;
424ec8fa 2571 } elsif ($relative) {
3538e1d5 2572 ($url) = $script_name =~ m!([^/]+)$!;
424ec8fa 2573 } elsif ($absolute) {
3538e1d5 2574 $url = $script_name;
424ec8fa 2575 }
03b9648d 2576
3538e1d5 2577 $url .= $path if $path_info and defined $path;
424ec8fa 2578 $url .= "?" . $self->query_string if $query and $self->query_string;
3d1a2ec4 2579 $url = '' unless defined $url;
2371fea9 2580 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
424ec8fa 2581 return $url;
54310121 2582}
2583
2584END_OF_FUNC
2585
2586#### Method: cookie
2587# Set or read a cookie from the specified name.
2588# Cookie can then be passed to header().
2589# Usual rules apply to the stickiness of -value.
2590# Parameters:
2591# -name -> name for this cookie (optional)
2592# -value -> value of this cookie (scalar, array or hash)
2593# -path -> paths for which this cookie is valid (optional)
2594# -domain -> internet domain in which this cookie is valid (optional)
2595# -secure -> if true, cookie only passed through secure channel (optional)
7d37aa8e 2596# -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
54310121 2597####
2598'cookie' => <<'END_OF_FUNC',
54310121 2599sub cookie {
2600 my($self,@p) = self_or_default(@_);
2601 my($name,$value,$path,$domain,$secure,$expires) =
3d1a2ec4 2602 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
54310121 2603
424ec8fa 2604 require CGI::Cookie;
54310121 2605
2606 # if no value is supplied, then we retrieve the
2607 # value of the cookie, if any. For efficiency, we cache the parsed
424ec8fa
GS
2608 # cookies in our state variables.
2609 unless ( defined($value) ) {
2610 $self->{'.cookies'} = CGI::Cookie->fetch
2611 unless $self->{'.cookies'};
54310121 2612
2613 # If no name is supplied, then retrieve the names of all our cookies.
2614 return () unless $self->{'.cookies'};
424ec8fa
GS
2615 return keys %{$self->{'.cookies'}} unless $name;
2616 return () unless $self->{'.cookies'}->{$name};
2617 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
54310121 2618 }
54310121 2619
424ec8fa 2620 # If we get here, we're creating a new cookie
ba056755 2621 return undef unless defined($name) && $name ne ''; # this is an error
54310121 2622
424ec8fa
GS
2623 my @param;
2624 push(@param,'-name'=>$name);
2625 push(@param,'-value'=>$value);
2626 push(@param,'-domain'=>$domain) if $domain;
2627 push(@param,'-path'=>$path) if $path;
2628 push(@param,'-expires'=>$expires) if $expires;
2629 push(@param,'-secure'=>$secure) if $secure;
54310121 2630
6b4ac661 2631 return new CGI::Cookie(@param);
54310121 2632}
2633END_OF_FUNC
2634
424ec8fa
GS
2635'parse_keywordlist' => <<'END_OF_FUNC',
2636sub parse_keywordlist {
2637 my($self,$tosplit) = @_;
2638 $tosplit = unescape($tosplit); # unescape the keywords
2639 $tosplit=~tr/+/ /; # pluses to spaces
2640 my(@keywords) = split(/\s+/,$tosplit);
2641 return @keywords;
2642}
2643END_OF_FUNC
2644
2645'param_fetch' => <<'END_OF_FUNC',
2646sub param_fetch {
2647 my($self,@p) = self_or_default(@_);
3d1a2ec4 2648 my($name) = rearrange([NAME],@p);
424ec8fa
GS
2649 unless (exists($self->{$name})) {
2650 $self->add_parameter($name);
2651 $self->{$name} = [];
2652 }
2653
2654 return $self->{$name};
2655}
2656END_OF_FUNC
2657
54310121 2658###############################################
2659# OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2660###############################################
2661
2662#### Method: path_info
2663# Return the extra virtual path information provided
2664# after the URL (if any)
2665####
2666'path_info' => <<'END_OF_FUNC',
2667sub path_info {
424ec8fa
GS
2668 my ($self,$info) = self_or_default(@_);
2669 if (defined($info)) {
2670 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2671 $self->{'.path_info'} = $info;
2672 } elsif (! defined($self->{'.path_info'}) ) {
2673 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2674 $ENV{'PATH_INFO'} : '';
2675
2676 # hack to fix broken path info in IIS
2677 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2678
2679 }
2680 return $self->{'.path_info'};
54310121 2681}
2682END_OF_FUNC
2683
2684
2685#### Method: request_method
2686# Returns 'POST', 'GET', 'PUT' or 'HEAD'
2687####
2688'request_method' => <<'END_OF_FUNC',
2689sub request_method {
2690 return $ENV{'REQUEST_METHOD'};
2691}
2692END_OF_FUNC
2693
3538e1d5
GS
2694#### Method: content_type
2695# Returns the content_type string
2696####
2697'content_type' => <<'END_OF_FUNC',
2698sub content_type {
2699 return $ENV{'CONTENT_TYPE'};
2700}
2701END_OF_FUNC
2702
54310121 2703#### Method: path_translated
2704# Return the physical path information provided
2705# by the URL (if any)
2706####
2707'path_translated' => <<'END_OF_FUNC',
2708sub path_translated {
2709 return $ENV{'PATH_TRANSLATED'};
2710}
2711END_OF_FUNC
2712
2713
2714#### Method: query_string
2715# Synthesize a query string from our current
2716# parameters
2717####
2718'query_string' => <<'END_OF_FUNC',
2719sub query_string {
2720 my($self) = self_or_default(@_);
2721 my($param,$value,@pairs);
2722 foreach $param ($self->param) {
424ec8fa 2723 my($eparam) = escape($param);
54310121 2724 foreach $value ($self->param($param)) {
424ec8fa 2725 $value = escape($value);
3538e1d5 2726 next unless defined $value;
54310121 2727 push(@pairs,"$eparam=$value");
2728 }
2729 }
d45d855d
JH
2730 foreach (keys %{$self->{'.fieldnames'}}) {
2731 push(@pairs,".cgifields=".escape("$_"));
2732 }
71f3e297 2733 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
54310121 2734}
2735END_OF_FUNC
2736
2737
2738#### Method: accept
2739# Without parameters, returns an array of the
2740# MIME types the browser accepts.
2741# With a single parameter equal to a MIME
2742# type, will return undef if the browser won't
2743# accept it, 1 if the browser accepts it but
2744# doesn't give a preference, or a floating point
2745# value between 0.0 and 1.0 if the browser
2746# declares a quantitative score for it.
2747# This handles MIME type globs correctly.
2748####
71f3e297
JH
2749'Accept' => <<'END_OF_FUNC',
2750sub Accept {
54310121 2751 my($self,$search) = self_or_CGI(@_);
2752 my(%prefs,$type,$pref,$pat);
2753
2754 my(@accept) = split(',',$self->http('accept'));
2755
2756 foreach (@accept) {
2757 ($pref) = /q=(\d\.\d+|\d+)/;
2758 ($type) = m#(\S+/[^;]+)#;
2759 next unless $type;
2760 $prefs{$type}=$pref || 1;
2761 }
2762
2763 return keys %prefs unless $search;
2764
2765 # if a search type is provided, we may need to
2766 # perform a pattern matching operation.
2767 # The MIME types use a glob mechanism, which
2768 # is easily translated into a perl pattern match
2769
2770 # First return the preference for directly supported
2771 # types:
2772 return $prefs{$search} if $prefs{$search};
2773
2774 # Didn't get it, so try pattern matching.
2775 foreach (keys %prefs) {
2776 next unless /\*/; # not a pattern match
2777 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2778 $pat =~ s/\*/.*/g; # turn it into a pattern
2779 return $prefs{$_} if $search=~/$pat/;
2780 }
2781}
2782END_OF_FUNC
2783
2784
2785#### Method: user_agent
2786# If called with no parameters, returns the user agent.
2787# If called with one parameter, does a pattern match (case
2788# insensitive) on the user agent.
2789####
2790'user_agent' => <<'END_OF_FUNC',
2791sub user_agent {
2792 my($self,$match)=self_or_CGI(@_);
2793 return $self->http('user_agent') unless $match;
2794 return $self->http('user_agent') =~ /$match/i;
2795}
2796END_OF_FUNC
2797
2798
424ec8fa
GS
2799#### Method: raw_cookie
2800# Returns the magic cookies for the session.
2801# The cookies are not parsed or altered in any way, i.e.
2802# cookies are returned exactly as given in the HTTP
2803# headers. If a cookie name is given, only that cookie's
2804# value is returned, otherwise the entire raw cookie
2805# is returned.
54310121 2806####
2807'raw_cookie' => <<'END_OF_FUNC',
2808sub raw_cookie {
424ec8fa
GS
2809 my($self,$key) = self_or_CGI(@_);
2810
2811 require CGI::Cookie;
2812
2813 if (defined($key)) {
2814 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2815 unless $self->{'.raw_cookies'};
2816
2817 return () unless $self->{'.raw_cookies'};
2818 return () unless $self->{'.raw_cookies'}->{$key};
2819 return $self->{'.raw_cookies'}->{$key};
2820 }
54310121 2821 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2822}
2823END_OF_FUNC
2824
2825#### Method: virtual_host
2826# Return the name of the virtual_host, which
2827# is not always the same as the server
2828######
2829'virtual_host' => <<'END_OF_FUNC',
2830sub virtual_host {
424ec8fa
GS
2831 my $vh = http('host') || server_name();
2832 $vh =~ s/:\d+$//; # get rid of port number
2833 return $vh;
54310121 2834}
2835END_OF_FUNC
2836
2837#### Method: remote_host
2838# Return the name of the remote host, or its IP
2839# address if unavailable. If this variable isn't
2840# defined, it returns "localhost" for debugging
2841# purposes.
2842####
2843'remote_host' => <<'END_OF_FUNC',
2844sub remote_host {
2845 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2846 || 'localhost';
2847}
2848END_OF_FUNC
2849
2850
2851#### Method: remote_addr
2852# Return the IP addr of the remote host.
2853####
2854'remote_addr' => <<'END_OF_FUNC',
2855sub remote_addr {
2856 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2857}
2858END_OF_FUNC
2859
2860
2861#### Method: script_name
2862# Return the partial URL to this script for
2863# self-referencing scripts. Also see
2864# self_url(), which returns a URL with all state information
2865# preserved.
2866####
2867'script_name' => <<'END_OF_FUNC',
2868sub script_name {
424ec8fa 2869 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
54310121 2870 # These are for debugging
2871 return "/$0" unless $0=~/^\//;
2872 return $0;
2873}
2874END_OF_FUNC
2875
2876
2877#### Method: referer
2878# Return the HTTP_REFERER: useful for generating
2879# a GO BACK button.
2880####
2881'referer' => <<'END_OF_FUNC',
2882sub referer {
2883 my($self) = self_or_CGI(@_);
2884 return $self->http('referer');
2885}
2886END_OF_FUNC
2887
2888
2889#### Method: server_name
2890# Return the name of the server
2891####
2892'server_name' => <<'END_OF_FUNC',
2893sub server_name {
2894 return $ENV{'SERVER_NAME'} || 'localhost';
2895}
2896END_OF_FUNC
2897
2898#### Method: server_software
2899# Return the name of the server software
2900####
2901'server_software' => <<'END_OF_FUNC',
2902sub server_software {
2903 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2904}
2905END_OF_FUNC
2906
2ed511ec
RGS
2907#### Method: virtual_port
2908# Return the server port, taking virtual hosts into account
2909####
2910'virtual_port' => <<'END_OF_FUNC',
2911sub virtual_port {
2912 my($self) = self_or_default(@_);
2913 my $vh = $self->http('host');
2914 if ($vh) {
2915 return ($vh =~ /:(\d+)$/)[0] || '80';
2916 } else {
2917 return $self->server_port();
2918 }
2919}
2920END_OF_FUNC
2921
54310121 2922#### Method: server_port
2923# Return the tcp/ip port the server is running on
2924####
2925'server_port' => <<'END_OF_FUNC',
2926sub server_port {
2927 return $ENV{'SERVER_PORT'} || 80; # for debugging
2928}
2929END_OF_FUNC
2930
2931#### Method: server_protocol
2932# Return the protocol (usually HTTP/1.0)
2933####
2934'server_protocol' => <<'END_OF_FUNC',
2935sub server_protocol {
2936 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2937}
2938END_OF_FUNC
2939
2940#### Method: http
2941# Return the value of an HTTP variable, or
2942# the list of variables if none provided
2943####
2944'http' => <<'END_OF_FUNC',
2945sub http {
2946 my ($self,$parameter) = self_or_CGI(@_);
2947 return $ENV{$parameter} if $parameter=~/^HTTP/;
3538e1d5 2948 $parameter =~ tr/-/_/;
54310121 2949 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2950 my(@p);
2951 foreach (keys %ENV) {
2952 push(@p,$_) if /^HTTP/;
2953 }
2954 return @p;
2955}
2956END_OF_FUNC
2957
2958#### Method: https
2959# Return the value of HTTPS
2960####
2961'https' => <<'END_OF_FUNC',
2962sub https {
2963 local($^W)=0;
2964 my ($self,$parameter) = self_or_CGI(@_);
2965 return $ENV{HTTPS} unless $parameter;
2966 return $ENV{$parameter} if $parameter=~/^HTTPS/;
3538e1d5 2967 $parameter =~ tr/-/_/;
54310121 2968 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2969 my(@p);
2970 foreach (keys %ENV) {
2971 push(@p,$_) if /^HTTPS/;
2972 }
2973 return @p;
2974}
2975END_OF_FUNC
2976
2977#### Method: protocol
2978# Return the protocol (http or https currently)
2979####
2980'protocol' => <<'END_OF_FUNC',
2981sub protocol {
2982 local($^W)=0;
2983 my $self = shift;
424ec8fa 2984 return 'https' if uc($self->https()) eq 'ON';
54310121 2985 return 'https' if $self->server_port == 443;
2986 my $prot = $self->server_protocol;
2987 my($protocol,$version) = split('/',$prot);
2988 return "\L$protocol\E";
2989}
2990END_OF_FUNC
2991
2992#### Method: remote_ident
2993# Return the identity of the remote user
2994# (but only if his host is running identd)
2995####
2996'remote_ident' => <<'END_OF_FUNC',
2997sub remote_ident {
2998 return $ENV{'REMOTE_IDENT'};
2999}
3000END_OF_FUNC
3001
3002
3003#### Method: auth_type
3004# Return the type of use verification/authorization in use, if any.
3005####
3006'auth_type' => <<'END_OF_FUNC',
3007sub auth_type {
3008 return $ENV{'AUTH_TYPE'};
3009}
3010END_OF_FUNC
3011
3012
3013#### Method: remote_user
3014# Return the authorization name used for user
3015# verification.
3016####
3017'remote_user' => <<'END_OF_FUNC',
3018sub remote_user {
3019 return $ENV{'REMOTE_USER'};
3020}
3021END_OF_FUNC
3022
3023
3024#### Method: user_name
3025# Try to return the remote user's name by hook or by
3026# crook
3027####
3028'user_name' => <<'END_OF_FUNC',
3029sub user_name {
3030 my ($self) = self_or_CGI(@_);
3031 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
3032}
3033END_OF_FUNC
3034
3d1a2ec4
GS
3035#### Method: nosticky
3036# Set or return the NOSTICKY global flag
3037####
3038'nosticky' => <<'END_OF_FUNC',
3039sub nosticky {
3040 my ($self,$param) = self_or_CGI(@_);
3041 $CGI::NOSTICKY = $param if defined($param);
3042 return $CGI::NOSTICKY;
3043}
3044END_OF_FUNC
3045
54310121 3046#### Method: nph
3047# Set or return the NPH global flag
3048####
3049'nph' => <<'END_OF_FUNC',
3050sub nph {
3051 my ($self,$param) = self_or_CGI(@_);
7d37aa8e
LS
3052 $CGI::NPH = $param if defined($param);
3053 return $CGI::NPH;
3054}
3055END_OF_FUNC
3056
3057#### Method: private_tempfiles
3058# Set or return the private_tempfiles global flag
3059####
3060'private_tempfiles' => <<'END_OF_FUNC',
3061sub private_tempfiles {
3062 my ($self,$param) = self_or_CGI(@_);
424ec8fa 3063 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
7d37aa8e 3064 return $CGI::PRIVATE_TEMPFILES;
54310121 3065}
3066END_OF_FUNC
8f3ccfa2
JH
3067#### Method: close_upload_files
3068# Set or return the close_upload_files global flag
3069####
3070'close_upload_files' => <<'END_OF_FUNC',
3071sub close_upload_files {
3072 my ($self,$param) = self_or_CGI(@_);
3073 $CGI::CLOSE_UPLOAD_FILES = $param if defined($param);
3074 return $CGI::CLOSE_UPLOAD_FILES;
3075}
3076END_OF_FUNC
3077
54310121 3078
424ec8fa
GS
3079#### Method: default_dtd
3080# Set or return the default_dtd global
3081####
3082'default_dtd' => <<'END_OF_FUNC',
3083sub default_dtd {
3d1a2ec4
GS
3084 my ($self,$param,$param2) = self_or_CGI(@_);
3085 if (defined $param2 && defined $param) {
3086 $CGI::DEFAULT_DTD = [ $param, $param2 ];
3087 } elsif (defined $param) {
3088 $CGI::DEFAULT_DTD = $param;
3089 }
424ec8fa
GS
3090 return $CGI::DEFAULT_DTD;
3091}
3092END_OF_FUNC
3093
54310121 3094# -------------- really private subroutines -----------------
3095'previous_or_default' => <<'END_OF_FUNC',
3096sub previous_or_default {
3097 my($self,$name,$defaults,$override) = @_;
3098 my(%selected);
3099
3100 if (!$override && ($self->{'.fieldnames'}->{$name} ||
3101 defined($self->param($name)) ) ) {
3102 grep($selected{$_}++,$self->param($name));
3103 } elsif (defined($defaults) && ref($defaults) &&
3104 (ref($defaults) eq 'ARRAY')) {
3105 grep($selected{$_}++,@{$defaults});
3106 } else {
3107 $selected{$defaults}++ if defined($defaults);
3108 }
3109
3110 return %selected;
3111}
3112END_OF_FUNC
3113
3114'register_parameter' => <<'END_OF_FUNC',
3115sub register_parameter {
3116 my($self,$param) = @_;
3117 $self->{'.parametersToAdd'}->{$param}++;
3118}
3119END_OF_FUNC
3120
3121'get_fields' => <<'END_OF_FUNC',
3122sub get_fields {
3123 my($self) = @_;
424ec8fa
GS
3124 return $self->CGI::hidden('-name'=>'.cgifields',
3125 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
3126 '-override'=>1);
54310121 3127}
3128END_OF_FUNC
3129
3130'read_from_cmdline' => <<'END_OF_FUNC',
3131sub read_from_cmdline {
54310121 3132 my($input,@words);
3133 my($query_string);
2ed511ec 3134 my($subpath);
3d1a2ec4 3135 if ($DEBUG && @ARGV) {
424ec8fa 3136 @words = @ARGV;
3d1a2ec4 3137 } elsif ($DEBUG > 1) {
424ec8fa 3138 require "shellwords.pl";
2ed511ec 3139 print STDERR "(offline mode: enter name=value pairs on standard input; press ^D or ^Z when done)\n";
424ec8fa 3140 chomp(@lines = <STDIN>); # remove newlines
54310121 3141 $input = join(" ",@lines);
424ec8fa
GS
3142 @words = &shellwords($input);
3143 }
3144 foreach (@words) {
3145 s/\\=/%3D/g;
3146 s/\\&/%26/g;
54310121 3147 }
3148
54310121 3149 if ("@words"=~/=/) {
3150 $query_string = join('&',@words);
3151 } else {
3152 $query_string = join('+',@words);
3153 }
2ed511ec
RGS
3154 if ($query_string =~ /^(.*?)\?(.*)$/)
3155 {
3156 $query_string = $2;
3157 $subpath = $1;
3158 }
3159 return { 'query_string' => $query_string, 'subpath' => $subpath };
54310121 3160}
3161END_OF_FUNC
3162
3163#####
3164# subroutine: read_multipart
3165#
3166# Read multipart data and store it into our parameters.
3167# An interesting feature is that if any of the parts is a file, we
3168# create a temporary file and open up a filehandle on it so that the
3169# caller can read from it if necessary.
3170#####
3171'read_multipart' => <<'END_OF_FUNC',
3172sub read_multipart {
2ed511ec
RGS
3173 my($self,$boundary,$length) = @_;
3174 my($buffer) = $self->new_MultipartBuffer($boundary,$length);
54310121 3175 return unless $buffer;
3176 my(%header,$body);
424ec8fa 3177 my $filenumber = 0;
54310121 3178 while (!$buffer->eof) {
3179 %header = $buffer->readHeader;
3538e1d5
GS
3180
3181 unless (%header) {
3182 $self->cgi_error("400 Bad request (malformed multipart POST)");
3183 return;
3184 }
54310121 3185
424ec8fa 3186 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
188ba755 3187 $param .= $TAINTED;
54310121 3188
424ec8fa 3189 # Bug: Netscape doesn't escape quotation marks in file names!!!
6b4ac661 3190 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
8f3ccfa2
JH
3191 # Test for Opera's multiple upload feature
3192 my($multipart) = ( defined( $header{'Content-Type'} ) &&
3193 $header{'Content-Type'} =~ /multipart\/mixed/ ) ?
3194 1 : 0;
54310121 3195
3196 # add this parameter to our list
3197 $self->add_parameter($param);
3198
3199 # If no filename specified, then just read the data and assign it
3200 # to our parameter list.
8f3ccfa2 3201 if ( ( !defined($filename) || $filename eq '' ) && !$multipart ) {
54310121 3202 my($value) = $buffer->readBody;
188ba755 3203 $value .= $TAINTED;
54310121 3204 push(@{$self->{$param}},$value);
3205 next;
3206 }
3207
424ec8fa
GS
3208 my ($tmpfile,$tmp,$filehandle);
3209 UPLOADS: {
3210 # If we get here, then we are dealing with a potentially large
3211 # uploaded form. Save the data to a temporary file, then open
3212 # the file for reading.
54310121 3213
424ec8fa
GS
3214 # skip the file if uploads disabled
3215 if ($DISABLE_UPLOADS) {
3216 while (defined($data = $buffer->read)) { }
3217 last UPLOADS;
3218 }
7d37aa8e 3219
8f3ccfa2
JH
3220 # set the filename to some recognizable value
3221 if ( ( !defined($filename) || $filename eq '' ) && $multipart ) {
3222 $filename = "multipart/mixed";
3223 }
3224
3538e1d5
GS
3225 # choose a relatively unpredictable tmpfile sequence number
3226 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
3227 for (my $cnt=10;$cnt>0;$cnt--) {
ac734d8b 3228 next unless $tmpfile = new CGITempFile($seqno);
3538e1d5 3229 $tmp = $tmpfile->as_string;
ffd2dff2 3230 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
3538e1d5
GS
3231 $seqno += int rand(100);
3232 }
69c89ae7 3233 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
2ed511ec
RGS
3234 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode
3235 && defined fileno($filehandle);
424ec8fa 3236
8f3ccfa2 3237 # if this is an multipart/mixed attachment, save the header
2ed511ec 3238 # together with the body for later parsing with an external
8f3ccfa2
JH
3239 # MIME parser module
3240 if ( $multipart ) {
3241 foreach ( keys %header ) {
3242 print $filehandle "$_: $header{$_}${CRLF}";
3243 }
3244 print $filehandle "${CRLF}";
3245 }
3246
424ec8fa 3247 my ($data);
71f3e297 3248 local($\) = '';
2ed511ec
RGS
3249 my $totalbytes;
3250 while (defined($data = $buffer->read)) {
3251 if (defined $self->{'.upload_hook'})
3252 {
3253 $totalbytes += length($data);
3254 &{$self->{'.upload_hook'}}($filename ,$data, $totalbytes, $self->{'.upload_data'});
3255 }
424ec8fa 3256 print $filehandle $data;
2ed511ec 3257 }
424ec8fa
GS
3258
3259 # back up to beginning of file
3260 seek($filehandle,0,0);
8f3ccfa2
JH
3261
3262 ## Close the filehandle if requested this allows a multipart MIME
3263 ## upload to contain many files, and we won't die due to too many
3264 ## open file handles. The user can access the files using the hash
3265 ## below.
3266 close $filehandle if $CLOSE_UPLOAD_FILES;
424ec8fa
GS
3267 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3268
3269 # Save some information about the uploaded file where we can get
3270 # at it later.
ffd2dff2 3271 $self->{'.tmpfiles'}->{fileno($filehandle)}= {
2ed511ec 3272 hndl => $filehandle,
424ec8fa
GS
3273 name => $tmpfile,
3274 info => {%header},
3275 };
3276 push(@{$self->{$param}},$filehandle);
3277 }
54310121 3278 }
3279}
3280END_OF_FUNC
3281
3538e1d5
GS
3282'upload' =><<'END_OF_FUNC',
3283sub upload {
3284 my($self,$param_name) = self_or_default(@_);
199d4a26
JH
3285 my @param = grep(ref && fileno($_), $self->param($param_name));
3286 return unless @param;
3287 return wantarray ? @param : $param[0];
3538e1d5
GS
3288}
3289END_OF_FUNC
3290
54310121 3291'tmpFileName' => <<'END_OF_FUNC',
3292sub tmpFileName {
3293 my($self,$filename) = self_or_default(@_);
ffd2dff2
GS
3294 return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
3295 $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
7d37aa8e 3296 : '';
54310121 3297}
3298END_OF_FUNC
3299
424ec8fa 3300'uploadInfo' => <<'END_OF_FUNC',
54310121 3301sub uploadInfo {
3302 my($self,$filename) = self_or_default(@_);
ffd2dff2 3303 return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
54310121 3304}
3305END_OF_FUNC
3306
424ec8fa
GS
3307# internal routine, don't use
3308'_set_values_and_labels' => <<'END_OF_FUNC',
3309sub _set_values_and_labels {
3310 my $self = shift;
3311 my ($v,$l,$n) = @_;
3312 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
3313 return $self->param($n) if !defined($v);
3314 return $v if !ref($v);
3315 return ref($v) eq 'HASH' ? keys %$v : @$v;
3316}
3317END_OF_FUNC
3318
188ba755
JH
3319# internal routine, don't use
3320'_set_attributes' => <<'END_OF_FUNC',
3321sub _set_attributes {
3322 my $self = shift;
3323 my($element, $attributes) = @_;
3324 return '' unless defined($attributes->{$element});
3325 $attribs = ' ';
3326 foreach my $attrib (keys %{$attributes->{$element}}) {
3327 $attrib =~ s/^-//;
3328 $attribs .= "@{[lc($attrib)]}=\"$attributes->{$element}{$attrib}\" ";
3329 }
3330 $attribs =~ s/ $//;
3331 return $attribs;
3332}
3333END_OF_FUNC
3334
424ec8fa
GS
3335'_compile_all' => <<'END_OF_FUNC',
3336sub _compile_all {
3337 foreach (@_) {
3338 next if defined(&$_);
3339 $AUTOLOAD = "CGI::$_";
3340 _compile();
3341 }
3342}
3343END_OF_FUNC
3344
54310121 3345);
3346END_OF_AUTOLOAD
3347;
3348
424ec8fa
GS
3349#########################################################
3350# Globals and stubs for other packages that we use.
3351#########################################################
3352
3353################### Fh -- lightweight filehandle ###############
3354package Fh;
3355use overload
3356 '""' => \&asString,
3357 'cmp' => \&compare,
3358 'fallback'=>1;
3359
3360$FH='fh00000';
3361
3362*Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3363
3364$AUTOLOADED_ROUTINES = ''; # prevent -w error
3365$AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3366%SUBS = (
3367'asString' => <<'END_OF_FUNC',
3368sub asString {
3369 my $self = shift;
71f3e297 3370 # get rid of package name
ffd2dff2 3371 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
ba056755 3372 $i =~ s/%(..)/ chr(hex($1)) /eg;
188ba755 3373 return $i.$CGI::TAINTED;
71f3e297
JH
3374# BEGIN DEAD CODE
3375# This was an extremely clever patch that allowed "use strict refs".
3376# Unfortunately it relied on another bug that caused leaky file descriptors.
3377# The underlying bug has been fixed, so this no longer works. However
3378# "strict refs" still works for some reason.
3379# my $self = shift;
3380# return ${*{$self}{SCALAR}};
3381# END DEAD CODE
424ec8fa
GS
3382}
3383END_OF_FUNC
3384
3385'compare' => <<'END_OF_FUNC',
3386sub compare {
3387 my $self = shift;
3388 my $value = shift;
3389 return "$self" cmp $value;
3390}
3391END_OF_FUNC
3392
3393'new' => <<'END_OF_FUNC',
3394sub new {
3395 my($pack,$name,$file,$delete) = @_;
188ba755 3396 _setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
424ec8fa 3397 require Fcntl unless defined &Fcntl::O_RDWR;
ba056755
JH
3398 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3399 my $fv = ++$FH . $safename;
6b4ac661 3400 my $ref = \*{"Fh::$fv"};
188ba755
JH
3401 $file =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3402 my $safe = $1;
3403 sysopen($ref,$safe,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3404 unlink($safe) if $delete;
6b4ac661 3405 CORE::delete $Fh::{$fv};
71f3e297 3406 return bless $ref,$pack;
424ec8fa
GS
3407}
3408END_OF_FUNC
3409
3410'DESTROY' => <<'END_OF_FUNC',
3411sub DESTROY {
3412 my $self = shift;
3413 close $self;
3414}
3415END_OF_FUNC
3416
3417);
3418END_OF_AUTOLOAD
3419
3420######################## MultipartBuffer ####################
54310121 3421package MultipartBuffer;
3422
2ed511ec
RGS
3423use constant DEBUG => 0;
3424
54310121 3425# how many bytes to read at a time. We use
71f3e297
JH
3426# a 4K buffer by default.
3427$INITIAL_FILLUNIT = 1024 * 4;
3428$TIMEOUT = 240*60; # 4 hour timeout for big files
3429$SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
54310121 3430$CRLF=$CGI::CRLF;
3431
3432#reuse the autoload function
3433*MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3434
424ec8fa
GS
3435# avoid autoloader warnings
3436sub DESTROY {}
3437
54310121 3438###############################################################################
3439################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3440###############################################################################
3441$AUTOLOADED_ROUTINES = ''; # prevent -w error
3442$AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3443%SUBS = (
3444
3445'new' => <<'END_OF_FUNC',
3446sub new {
2ed511ec 3447 my($package,$interface,$boundary,$length) = @_;
424ec8fa 3448 $FILLUNIT = $INITIAL_FILLUNIT;
2ed511ec 3449 $CGI::DefaultClass->binmode($IN); # if $CGI::needs_binmode; # just do it always
54310121 3450
3451 # If the user types garbage into the file upload field,
3452 # then Netscape passes NOTHING to the server (not good).
3453 # We may hang on this read in that case. So we implement
3454 # a read timeout. If nothing is ready to read
3455 # by then, we return.
3456
3457 # Netscape seems to be a little bit unreliable
3458 # about providing boundary strings.
3d1a2ec4 3459 my $boundary_read = 0;
54310121 3460 if ($boundary) {
3461
3462 # Under the MIME spec, the boundary consists of the
3463 # characters "--" PLUS the Boundary string
424ec8fa
GS
3464
3465 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
71f3e297 3466 # the two extra hyphens. We do a special case here on the user-agent!!!!
69c89ae7 3467 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
424ec8fa 3468
54310121 3469 } else { # otherwise we find it ourselves
3470 my($old);
3471 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
2ed511ec 3472 $boundary = <STDIN>; # BUG: This won't work correctly under mod_perl
54310121 3473 $length -= length($boundary);
3474 chomp($boundary); # remove the CRLF
3475 $/ = $old; # restore old line separator
3d1a2ec4 3476 $boundary_read++;
54310121 3477 }
3478
3479 my $self = {LENGTH=>$length,
3480 BOUNDARY=>$boundary,
54310121 3481 INTERFACE=>$interface,
3482 BUFFER=>'',
3483 };
3484
3485 $FILLUNIT = length($boundary)
3486 if length($boundary) > $FILLUNIT;
3487
424ec8fa
GS
3488 my $retval = bless $self,ref $package || $package;
3489
3490 # Read the preamble and the topmost (boundary) line plus the CRLF.
3d1a2ec4
GS
3491 unless ($boundary_read) {
3492 while ($self->read(0)) { }
3493 }
2ed511ec 3494 die "Malformed multipart POST: data truncated\n" if $self->eof;
424ec8fa
GS
3495
3496 return $retval;
54310121 3497}
3498END_OF_FUNC
3499
3500'readHeader' => <<'END_OF_FUNC',
3501sub readHeader {
3502 my($self) = @_;
3503 my($end);
3504 my($ok) = 0;
47e3cabd 3505 my($bad) = 0;
424ec8fa 3506
2ed511ec 3507 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS' || $CGI::EBCDIC;
424ec8fa 3508
54310121 3509 do {
3510 $self->fillBuffer($FILLUNIT);
3511 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3512 $ok++ if $self->{BUFFER} eq '';
47e3cabd 3513 $bad++ if !$ok && $self->{LENGTH} <= 0;
424ec8fa
GS
3514 # this was a bad idea
3515 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
47e3cabd
LS
3516 } until $ok || $bad;
3517 return () if $bad;
54310121 3518
2ed511ec
RGS
3519 #EBCDIC NOTE: translate header into EBCDIC, but watch out for continuation lines!
3520
54310121 3521 my($header) = substr($self->{BUFFER},0,$end+2);
3522 substr($self->{BUFFER},0,$end+4) = '';
3523 my %return;
424ec8fa 3524
2ed511ec
RGS
3525 if ($CGI::EBCDIC) {
3526 warn "untranslated header=$header\n" if DEBUG;
3527 $header = CGI::Util::ascii2ebcdic($header);
3528 warn "translated header=$header\n" if DEBUG;
3529 }
3530
424ec8fa
GS
3531 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3532 # (Folding Long Header Fields), 3.4.3 (Comments)
3533 # and 3.4.5 (Quoted-Strings).
3534
3535 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3536 $header=~s/$CRLF\s+/ /og; # merge continuation lines
188ba755 3537
424ec8fa 3538 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
188ba755 3539 my ($field_name,$field_value) = ($1,$2);
424ec8fa
GS
3540 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3541 $return{$field_name}=$field_value;
54310121 3542 }
3543 return %return;
3544}
3545END_OF_FUNC
3546
3547# This reads and returns the body as a single scalar value.
3548'readBody' => <<'END_OF_FUNC',
3549sub readBody {
3550 my($self) = @_;
3551 my($data);
3552 my($returnval)='';
2ed511ec
RGS
3553
3554 #EBCDIC NOTE: want to translate returnval into EBCDIC HERE
3555
54310121 3556 while (defined($data = $self->read)) {
3557 $returnval .= $data;
3558 }
2ed511ec
RGS
3559
3560 if ($CGI::EBCDIC) {
3561 warn "untranslated body=$returnval\n" if DEBUG;
3562 $returnval = CGI::Util::ascii2ebcdic($returnval);
3563 warn "translated body=$returnval\n" if DEBUG;
3564 }
54310121 3565 return $returnval;
3566}
3567END_OF_FUNC
3568
3569# This will read $bytes or until the boundary is hit, whichever happens
3570# first. After the boundary is hit, we return undef. The next read will
3571# skip over the boundary and begin reading again;
3572'read' => <<'END_OF_FUNC',
3573sub read {
3574 my($self,$bytes) = @_;
3575
3576 # default number of bytes to read
2ed511ec 3577 $bytes = $bytes || $FILLUNIT;
54310121 3578
3579 # Fill up our internal buffer in such a way that the boundary
3580 # is never split between reads.
3581 $self->fillBuffer($bytes);
3582
2ed511ec
RGS
3583 my $boundary_start = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}) : $self->{BOUNDARY};
3584 my $boundary_end = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}.'--') : $self->{BOUNDARY}.'--';
3585
54310121 3586 # Find the boundary in the buffer (it may not be there).
2ed511ec
RGS
3587 my $start = index($self->{BUFFER},$boundary_start);
3588
3589 warn "boundary=$self->{BOUNDARY} length=$self->{LENGTH} start=$start\n" if DEBUG;
47e3cabd
LS
3590 # protect against malformed multipart POST operations
3591 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
54310121 3592
2ed511ec
RGS
3593
3594 #EBCDIC NOTE: want to translate boundary search into ASCII here.
3595
54310121 3596 # If the boundary begins the data, then skip past it
03b9648d 3597 # and return undef.
54310121 3598 if ($start == 0) {
3599
3600 # clear us out completely if we've hit the last boundary.
2ed511ec 3601 if (index($self->{BUFFER},$boundary_end)==0) {
54310121 3602 $self->{BUFFER}='';
3603 $self->{LENGTH}=0;
3604 return undef;
3605 }
3606
3607 # just remove the boundary.
2ed511ec 3608 substr($self->{BUFFER},0,length($boundary_start))='';
03b9648d 3609 $self->{BUFFER} =~ s/^\012\015?//;
54310121 3610 return undef;
3611 }
3612
8f3ccfa2 3613 my $bytesToReturn;
54310121 3614 if ($start > 0) { # read up to the boundary
8f3ccfa2 3615 $bytesToReturn = $start-2 > $bytes ? $bytes : $start;
54310121 3616 } else { # read the requested number of bytes
3617 # leave enough bytes in the buffer to allow us to read
3618 # the boundary. Thanks to Kevin Hendrick for finding
3619 # this one.
2ed511ec 3620 $bytesToReturn = $bytes - (length($boundary_start)+1);
54310121 3621 }
3622
3623 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3624 substr($self->{BUFFER},0,$bytesToReturn)='';
3625
3626 # If we hit the boundary, remove the CRLF from the end.
8f3ccfa2 3627 return ($bytesToReturn==$start)
ac734d8b 3628 ? substr($returnval,0,-2) : $returnval;
54310121 3629}
3630END_OF_FUNC
3631
3632
3633# This fills up our internal buffer in such a way that the
3634# boundary is never split between reads
3635'fillBuffer' => <<'END_OF_FUNC',
3636sub fillBuffer {
3637 my($self,$bytes) = @_;
3638 return unless $self->{LENGTH};
3639
3640 my($boundaryLength) = length($self->{BOUNDARY});
3641 my($bufferLength) = length($self->{BUFFER});
3642 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3643 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3644
2ed511ec
RGS
3645 # Try to read some data. We may hang here if the browser is screwed up.
3646 my $bytesRead = $self->{INTERFACE}->read_from_client(\$self->{BUFFER},
54310121 3647 $bytesToRead,
3648 $bufferLength);
2ed511ec 3649 warn "bytesToRead=$bytesToRead, bufferLength=$bufferLength, buffer=$self->{BUFFER}\n" if DEBUG;
71f3e297 3650 $self->{BUFFER} = '' unless defined $self->{BUFFER};
54310121 3651
47e3cabd 3652 # An apparent bug in the Apache server causes the read()
54310121 3653 # to return zero bytes repeatedly without blocking if the
3654 # remote user aborts during a file transfer. I don't know how
3655 # they manage this, but the workaround is to abort if we get
3656 # more than SPIN_LOOP_MAX consecutive zero reads.
3657 if ($bytesRead == 0) {
3658 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3659 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3660 } else {
3661 $self->{ZERO_LOOP_COUNTER}=0;
3662 }
3663
3664 $self->{LENGTH} -= $bytesRead;
3665}
3666END_OF_FUNC
3667
3668
3669# Return true when we've finished reading
3670'eof' => <<'END_OF_FUNC'
3671sub eof {
3672 my($self) = @_;
3673 return 1 if (length($self->{BUFFER}) == 0)
3674 && ($self->{LENGTH} <= 0);
3675 undef;
3676}
3677END_OF_FUNC
3678
3679);
3680END_OF_AUTOLOAD
3681
3682####################################################################################
3683################################## TEMPORARY FILES #################################
3684####################################################################################
ac734d8b 3685package CGITempFile;
54310121 3686
cff99809
JH
3687sub find_tempdir {
3688 undef $TMPDIRECTORY;
3689 $SL = $CGI::SL;
3690 $MAC = $CGI::OS eq 'MACINTOSH';
3691 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3692 unless ($TMPDIRECTORY) {
424ec8fa 3693 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3538e1d5 3694 "C:${SL}temp","${SL}tmp","${SL}temp",
3d1a2ec4 3695 "${vol}${SL}Temporary Items",
ba056755
JH
3696 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3697 "C:${SL}system${SL}temp");
188ba755 3698 unshift(@TEMP,$ENV{'TMPDIR'}) if defined $ENV{'TMPDIR'};
3538e1d5 3699
3d1a2ec4
GS
3700 # this feature was supposed to provide per-user tmpfiles, but
3701 # it is problematic.
3538e1d5
GS
3702 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3703 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3704 # : can generate a 'getpwuid() not implemented' exception, even though
3705 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3706 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3d1a2ec4 3707 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3538e1d5 3708
54310121 3709 foreach (@TEMP) {
cff99809 3710 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
54310121 3711 }
cff99809
JH
3712 }
3713 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
54310121 3714}
3715
cff99809
JH
3716find_tempdir();
3717
424ec8fa 3718$MAXTRIES = 5000;
54310121 3719
3720# cute feature, but overload implementation broke it
3721# %OVERLOAD = ('""'=>'as_string');
ac734d8b 3722*CGITempFile::AUTOLOAD = \&CGI::AUTOLOAD;
54310121 3723
2371fea9
JH
3724sub DESTROY {
3725 my($self) = @_;
188ba755
JH
3726 $$self =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3727 my $safe = $1; # untaint operation
3728 unlink $safe; # get rid of the file
2371fea9
JH
3729}
3730
54310121 3731###############################################################################
3732################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3733###############################################################################
3734$AUTOLOADED_ROUTINES = ''; # prevent -w error
3735$AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3736%SUBS = (
3737
3738'new' => <<'END_OF_FUNC',
3739sub new {
3538e1d5
GS
3740 my($package,$sequence) = @_;
3741 my $filename;
cff99809 3742 find_tempdir() unless -w $TMPDIRECTORY;
3538e1d5
GS
3743 for (my $i = 0; $i < $MAXTRIES; $i++) {
3744 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
424ec8fa 3745 }
188ba755
JH
3746 # check that it is a more-or-less valid filename
3747 return unless $filename =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$!;
3748 # this used to untaint, now it doesn't
3749 # $filename = $1;
3538e1d5 3750 return bless \$filename;
54310121 3751}
3752END_OF_FUNC
3753
54310121 3754'as_string' => <<'END_OF_FUNC'
3755sub as_string {
3756 my($self) = @_;
3757 return $$self;
3758}
3759END_OF_FUNC
3760
3761);
3762END_OF_AUTOLOAD
3763
3764package CGI;
3765
3766# We get a whole bunch of warnings about "possibly uninitialized variables"
3767# when running with the -w switch. Touch them all once to get rid of the
3768# warnings. This is ugly and I hate it.
3769if ($^W) {
3770 $CGI::CGI = '';
3771 $CGI::CGI=<<EOF;
3772 $CGI::VERSION;
3773 $MultipartBuffer::SPIN_LOOP_MAX;
3774 $MultipartBuffer::CRLF;
3775 $MultipartBuffer::TIMEOUT;
424ec8fa 3776 $MultipartBuffer::INITIAL_FILLUNIT;
54310121 3777EOF
3778 ;
3779}
3780
424ec8fa 37811;
54310121 3782
3783__END__
3784
3785=head1 NAME
3786
3787CGI - Simple Common Gateway Interface Class
3788
dc848c6f 3789=head1 SYNOPSIS
3790
424ec8fa
GS
3791 # CGI script that creates a fill-out form
3792 # and echoes back its values.
3793
3794 use CGI qw/:standard/;
3795 print header,
3796 start_html('A Simple Example'),
3797 h1('A Simple Example'),
3798 start_form,
3799 "What's your name? ",textfield('name'),p,
3800 "What's the combination?", p,
3801 checkbox_group(-name=>'words',
3802 -values=>['eenie','meenie','minie','moe'],
3803 -defaults=>['eenie','minie']), p,
3804 "What's your favorite color? ",
3805 popup_menu(-name=>'color',
3806 -values=>['red','green','blue','chartreuse']),p,
3807 submit,
3808 end_form,
3809 hr;
3810
3811 if (param()) {
3812 print "Your name is",em(param('name')),p,
3813 "The keywords are: ",em(join(", ",param('words'))),p,
3814 "Your favorite color is ",em(param('color')),
3815 hr;
3816 }
dc848c6f 3817
54310121 3818=head1 ABSTRACT
3819
424ec8fa
GS
3820This perl library uses perl5 objects to make it easy to create Web
3821fill-out forms and parse their contents. This package defines CGI
3822objects, entities that contain the values of the current query string
3823and other state variables. Using a CGI object's methods, you can
3824examine keywords and parameters passed to your script, and create
3825forms whose initial values are taken from the current query (thereby
3826preserving state information). The module provides shortcut functions
3827that produce boilerplate HTML, reducing typing and coding errors. It
3828also provides functionality for some of the more advanced features of
3829CGI scripting, including support for file uploads, cookies, cascading
3830style sheets, server push, and frames.
3831
3832CGI.pm also provides a simple function-oriented programming style for
3833those who don't need its object-oriented features.
54310121 3834
3835The current version of CGI.pm is available at
3836
3837 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3838 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3839
424ec8fa 3840=head1 DESCRIPTION
47e3cabd 3841
424ec8fa
GS
3842=head2 PROGRAMMING STYLE
3843
3844There are two styles of programming with CGI.pm, an object-oriented
3845style and a function-oriented style. In the object-oriented style you
3846create one or more CGI objects and then use object methods to create
3847the various elements of the page. Each CGI object starts out with the
3848list of named parameters that were passed to your CGI script by the
3849server. You can modify the objects, save them to a file or database
3850and recreate them. Because each object corresponds to the "state" of
3851the CGI script, and because each object's parameter list is
3852independent of the others, this allows you to save the state of the
3853script and restore it later.
3854
f610777f 3855For example, using the object oriented style, here is how you create
424ec8fa
GS
3856a simple "Hello World" HTML page:
3857
3538e1d5 3858 #!/usr/local/bin/perl -w
424ec8fa
GS
3859 use CGI; # load CGI routines
3860 $q = new CGI; # create new CGI object
3861 print $q->header, # create the HTTP header
3862 $q->start_html('hello world'), # start the HTML
3863 $q->h1('hello world'), # level 1 header
3864 $q->end_html; # end the HTML
3865
3866In the function-oriented style, there is one default CGI object that
3867you rarely deal with directly. Instead you just call functions to
3868retrieve CGI parameters, create HTML tags, manage cookies, and so
3869on. This provides you with a cleaner programming interface, but
3870limits you to using one CGI object at a time. The following example
3871prints the same page, but uses the function-oriented interface.
3872The main differences are that we now need to import a set of functions
3873into our name space (usually the "standard" functions), and we don't
3874need to create the CGI object.
3875
71f3e297 3876 #!/usr/local/bin/perl
424ec8fa
GS
3877 use CGI qw/:standard/; # load standard CGI routines
3878 print header, # create the HTTP header
3879 start_html('hello world'), # start the HTML
3880 h1('hello world'), # level 1 header
3881 end_html; # end the HTML
3882
3883The examples in this document mainly use the object-oriented style.
3884See HOW TO IMPORT FUNCTIONS for important information on
3885function-oriented programming in CGI.pm
3886
3887=head2 CALLING CGI.PM ROUTINES
3888
3889Most CGI.pm routines accept several arguments, sometimes as many as 20
3890optional ones! To simplify this interface, all routines use a named
3891argument calling style that looks like this:
3892
3893 print $q->header(-type=>'image/gif',-expires=>'+3d');
3894
3895Each argument name is preceded by a dash. Neither case nor order
3896matters in the argument list. -type, -Type, and -TYPE are all
3897acceptable. In fact, only the first argument needs to begin with a
3898dash. If a dash is present in the first argument, CGI.pm assumes
3899dashes for the subsequent ones.
3900
424ec8fa
GS
3901Several routines are commonly called with just one argument. In the
3902case of these routines you can provide the single argument without an
3903argument name. header() happens to be one of these routines. In this
3904case, the single argument is the document type.
3905
3906 print $q->header('text/html');
3907
3908Other such routines are documented below.
3909
3910Sometimes named arguments expect a scalar, sometimes a reference to an
3911array, and sometimes a reference to a hash. Often, you can pass any
3912type of argument and the routine will do whatever is most appropriate.
3913For example, the param() routine is used to set a CGI parameter to a
3914single or a multi-valued value. The two cases are shown below:
3915
3916 $q->param(-name=>'veggie',-value=>'tomato');
3d1a2ec4 3917 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
424ec8fa
GS
3918
3919A large number of routines in CGI.pm actually aren't specifically
3920defined in the module, but are generated automatically as needed.
3921These are the "HTML shortcuts," routines that generate HTML tags for
3922use in dynamically-generated pages. HTML tags have both attributes
3923(the attribute="value" pairs within the tag itself) and contents (the
3924part between the opening and closing pairs.) To distinguish between
3925attributes and contents, CGI.pm uses the convention of passing HTML
3926attributes as a hash reference as the first argument, and the
3927contents, if any, as any subsequent arguments. It works out like
3928this:
3929
3930 Code Generated HTML
3931 ---- --------------
3acbd4f5
JH
3932 h1() <h1>
3933 h1('some','contents'); <h1>some contents</h1>
188ba755
JH
3934 h1({-align=>left}); <h1 align="LEFT">
3935 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
424ec8fa 3936
188ba755 3937HTML tags are described in more detail later.
424ec8fa
GS
3938
3939Many newcomers to CGI.pm are puzzled by the difference between the
3940calling conventions for the HTML shortcuts, which require curly braces
3941around the HTML tag attributes, and the calling conventions for other
3942routines, which manage to generate attributes without the curly
3943brackets. Don't be confused. As a convenience the curly braces are
3944optional in all but the HTML shortcuts. If you like, you can use
3945curly braces when calling any routine that takes named arguments. For
3946example:
3947
3948 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3949
3950If you use the B<-w> switch, you will be warned that some CGI.pm argument
3951names conflict with built-in Perl functions. The most frequent of
3952these is the -values argument, used to create multi-valued menus,
3953radio button clusters and the like. To get around this warning, you
3954have several choices:
54310121 3955
424ec8fa 3956=over 4
54310121 3957
551e1d92
RB
3958=item 1.
3959
3960Use another name for the argument, if one is available.
3961For example, -value is an alias for -values.
54310121 3962
551e1d92 3963=item 2.
54310121 3964
551e1d92
RB
3965Change the capitalization, e.g. -Values
3966
3967=item 3.
3968
3969Put quotes around the argument name, e.g. '-values'
54310121 3970
424ec8fa 3971=back
54310121 3972
424ec8fa
GS
3973Many routines will do something useful with a named argument that it
3974doesn't recognize. For example, you can produce non-standard HTTP
3975header fields by providing them as named arguments:
54310121 3976
424ec8fa
GS
3977 print $q->header(-type => 'text/html',
3978 -cost => 'Three smackers',
3979 -annoyance_level => 'high',
3980 -complaints_to => 'bit bucket');
54310121 3981
424ec8fa
GS
3982This will produce the following nonstandard HTTP header:
3983
3984 HTTP/1.0 200 OK
3985 Cost: Three smackers
3986 Annoyance-level: high
3987 Complaints-to: bit bucket
3988 Content-type: text/html
3989
3990Notice the way that underscores are translated automatically into
3991hyphens. HTML-generating routines perform a different type of
3992translation.
3993
3994This feature allows you to keep up with the rapidly changing HTTP and
3995HTML "standards".
54310121 3996
424ec8fa 3997=head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
54310121 3998
3999 $query = new CGI;
4000
4001This will parse the input (from both POST and GET methods) and store
4002it into a perl5 object called $query.
4003
4004=head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
4005
4006 $query = new CGI(INPUTFILE);
4007
424ec8fa
GS
4008If you provide a file handle to the new() method, it will read
4009parameters from the file (or STDIN, or whatever). The file can be in
4010any of the forms describing below under debugging (i.e. a series of
4011newline delimited TAG=VALUE pairs will work). Conveniently, this type
4012of file is created by the save() method (see below). Multiple records
4013can be saved and restored.
54310121 4014
4015Perl purists will be pleased to know that this syntax accepts
4016references to file handles, or even references to filehandle globs,
4017which is the "official" way to pass a filehandle:
4018
4019 $query = new CGI(\*STDIN);
4020
424ec8fa
GS
4021You can also initialize the CGI object with a FileHandle or IO::File
4022object.
4023
4024If you are using the function-oriented interface and want to
4025initialize CGI state from a file handle, the way to do this is with
4026B<restore_parameters()>. This will (re)initialize the
4027default CGI object from the indicated file handle.
4028
4029 open (IN,"test.in") || die;
4030 restore_parameters(IN);
4031 close IN;
4032
54310121 4033You can also initialize the query object from an associative array
4034reference:
4035
4036 $query = new CGI( {'dinosaur'=>'barney',
4037 'song'=>'I love you',
4038 'friends'=>[qw/Jessica George Nancy/]}
4039 );
4040
4041or from a properly formatted, URL-escaped query string:
4042
4043 $query = new CGI('dinosaur=barney&color=purple');
4044
424ec8fa
GS
4045or from a previously existing CGI object (currently this clones the
4046parameter list, but none of the other object-specific fields, such as
4047autoescaping):
4048
4049 $old_query = new CGI;
4050 $new_query = new CGI($old_query);
4051
54310121 4052To create an empty query, initialize it from an empty string or hash:
4053
424ec8fa
GS
4054 $empty_query = new CGI("");
4055
4056 -or-
4057
4058 $empty_query = new CGI({});
54310121 4059
4060=head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
4061
4062 @keywords = $query->keywords
4063
4064If the script was invoked as the result of an <ISINDEX> search, the
4065parsed keywords can be obtained as an array using the keywords() method.
4066
4067=head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
4068
4069 @names = $query->param
4070
4071If the script was invoked with a parameter list
3d1a2ec4
GS
4072(e.g. "name1=value1&name2=value2&name3=value3"), the param() method
4073will return the parameter names as a list. If the script was invoked
4074as an <ISINDEX> script and contains a string without ampersands
4075(e.g. "value1+value2+value3") , there will be a single parameter named
4076"keywords" containing the "+"-delimited keywords.
54310121 4077
4078NOTE: As of version 1.5, the array of parameter names returned will
4079be in the same order as they were submitted by the browser.
4080Usually this order is the same as the order in which the
4081parameters are defined in the form (however, this isn't part
4082of the spec, and so isn't guaranteed).
4083
4084=head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
4085
4086 @values = $query->param('foo');
4087
4088 -or-
4089
4090 $value = $query->param('foo');
4091
4092Pass the param() method a single argument to fetch the value of the
4093named parameter. If the parameter is multivalued (e.g. from multiple
4094selections in a scrolling list), you can ask to receive an array. Otherwise
4095the method will return a single value.
4096
3d1a2ec4
GS
4097If a value is not given in the query string, as in the queries
4098"name1=&name2=" or "name1&name2", it will be returned as an empty
4099string. This feature is new in 2.63.
4100
8f3ccfa2
JH
4101
4102If the parameter does not exist at all, then param() will return undef
4103in a scalar context, and the empty list in a list context.
4104
4105
54310121 4106=head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
4107
4108 $query->param('foo','an','array','of','values');
4109
4110This sets the value for the named parameter 'foo' to an array of
4111values. This is one way to change the value of a field AFTER
4112the script has been invoked once before. (Another way is with
4113the -override parameter accepted by all methods that generate
4114form elements.)
4115
4116param() also recognizes a named parameter style of calling described
4117in more detail later:
4118
4119 $query->param(-name=>'foo',-values=>['an','array','of','values']);
4120
4121 -or-
4122
4123 $query->param(-name=>'foo',-value=>'the value');
4124
4125=head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
4126
424ec8fa 4127 $query->append(-name=>'foo',-values=>['yet','more','values']);
54310121 4128
4129This adds a value or list of values to the named parameter. The
4130values are appended to the end of the parameter if it already exists.
4131Otherwise the parameter is created. Note that this method only
4132recognizes the named argument calling syntax.
4133
4134=head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
4135
4136 $query->import_names('R');
4137
4138This creates a series of variables in the 'R' namespace. For example,
4139$R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
4140If no namespace is given, this method will assume 'Q'.
4141WARNING: don't import anything into 'main'; this is a major security
4142risk!!!!
4143
8f3ccfa2
JH
4144NOTE 1: Variable names are transformed as necessary into legal Perl
4145variable names. All non-legal characters are transformed into
4146underscores. If you need to keep the original names, you should use
4147the param() method instead to access CGI variables by name.
4148
4149NOTE 2: In older versions, this method was called B<import()>. As of version 2.20,
54310121 4150this name has been removed completely to avoid conflict with the built-in
4151Perl module B<import> operator.
4152
4153=head2 DELETING A PARAMETER COMPLETELY:
4154
188ba755 4155 $query->delete('foo','bar','baz');
54310121 4156
188ba755
JH
4157This completely clears a list of parameters. It sometimes useful for
4158resetting parameters that you don't want passed down between script
4159invocations.
54310121 4160
424ec8fa
GS
4161If you are using the function call interface, use "Delete()" instead
4162to avoid conflicts with Perl's built-in delete operator.
4163
54310121 4164=head2 DELETING ALL PARAMETERS:
4165
424ec8fa 4166 $query->delete_all();
54310121 4167
4168This clears the CGI object completely. It might be useful to ensure
4169that all the defaults are taken when you create a fill-out form.
4170
424ec8fa
GS
4171Use Delete_all() instead if you are using the function call interface.
4172
4173=head2 DIRECT ACCESS TO THE PARAMETER LIST:
4174
4175 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
4176 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
4177
4178If you need access to the parameter list in a way that isn't covered
4179by the methods above, you can obtain a direct reference to it by
4180calling the B<param_fetch()> method with the name of the . This
4181will return an array reference to the named parameters, which you then
4182can manipulate in any way you like.
4183
4184You can also use a named argument style using the B<-name> argument.
4185
3538e1d5
GS
4186=head2 FETCHING THE PARAMETER LIST AS A HASH:
4187
4188 $params = $q->Vars;
4189 print $params->{'address'};
4190 @foo = split("\0",$params->{'foo'});
4191 %params = $q->Vars;
4192
4193 use CGI ':cgi-lib';
4194 $params = Vars;
4195
4196Many people want to fetch the entire parameter list as a hash in which
4197the keys are the names of the CGI parameters, and the values are the
4198parameters' values. The Vars() method does this. Called in a scalar
4199context, it returns the parameter list as a tied hash reference.
4200Changing a key changes the value of the parameter in the underlying
a3b3a725 4201CGI parameter list. Called in a list context, it returns the
3538e1d5
GS
4202parameter list as an ordinary hash. This allows you to read the
4203contents of the parameter list, but not to change it.
4204
4205When using this, the thing you must watch out for are multivalued CGI
4206parameters. Because a hash cannot distinguish between scalar and
a3b3a725 4207list context, multivalued parameters will be returned as a packed
3538e1d5
GS
4208string, separated by the "\0" (null) character. You must split this
4209packed string in order to get at the individual values. This is the
4210convention introduced long ago by Steve Brenner in his cgi-lib.pl
4211module for Perl version 4.
4212
4213If you wish to use Vars() as a function, import the I<:cgi-lib> set of
4214function calls (also see the section on CGI-LIB compatibility).
4215
424ec8fa 4216=head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
54310121 4217
4218 $query->save(FILEHANDLE)
4219
4220This will write the current state of the form to the provided
4221filehandle. You can read it back in by providing a filehandle
4222to the new() method. Note that the filehandle can be a file, a pipe,
4223or whatever!
4224
4225The format of the saved file is:
4226
4227 NAME1=VALUE1
4228 NAME1=VALUE1'
4229 NAME2=VALUE2
4230 NAME3=VALUE3
4231 =
4232
4233Both name and value are URL escaped. Multi-valued CGI parameters are
4234represented as repeated names. A session record is delimited by a
4235single = symbol. You can write out multiple records and read them
4236back in with several calls to B<new>. You can do this across several
4237sessions by opening the file in append mode, allowing you to create
4238primitive guest books, or to keep a history of users' queries. Here's
4239a short example of creating multiple session records:
4240
4241 use CGI;
4242
4243 open (OUT,">>test.out") || die;
4244 $records = 5;
4245 foreach (0..$records) {
4246 my $q = new CGI;
4247 $q->param(-name=>'counter',-value=>$_);
4248 $q->save(OUT);
4249 }
4250 close OUT;
4251
4252 # reopen for reading
4253 open (IN,"test.out") || die;
4254 while (!eof(IN)) {
4255 my $q = new CGI(IN);
4256 print $q->param('counter'),"\n";
4257 }
4258
4259The file format used for save/restore is identical to that used by the
4260Whitehead Genome Center's data exchange format "Boulderio", and can be
4261manipulated and even databased using Boulderio utilities. See
3cb6de81 4262
3538e1d5 4263 http://stein.cshl.org/boulder/
54310121 4264
4265for further details.
4266
424ec8fa
GS
4267If you wish to use this method from the function-oriented (non-OO)
4268interface, the exported name for this method is B<save_parameters()>.
54310121 4269
3538e1d5
GS
4270=head2 RETRIEVING CGI ERRORS
4271
4272Errors can occur while processing user input, particularly when
4273processing uploaded files. When these errors occur, CGI will stop
4274processing and return an empty parameter list. You can test for
4275the existence and nature of errors using the I<cgi_error()> function.
4276The error messages are formatted as HTTP status codes. You can either
4277incorporate the error text into an HTML page, or use it as the value
4278of the HTTP status:
4279
4280 my $error = $q->cgi_error;
4281 if ($error) {
4282 print $q->header(-status=>$error),
4283 $q->start_html('Problems'),
4284 $q->h2('Request not processed'),
4285 $q->strong($error);
4286 exit 0;
4287 }
4288
4289When using the function-oriented interface (see the next section),
4290errors may only occur the first time you call I<param()>. Be ready
4291for this!
4292
424ec8fa 4293=head2 USING THE FUNCTION-ORIENTED INTERFACE
54310121 4294
424ec8fa
GS
4295To use the function-oriented interface, you must specify which CGI.pm
4296routines or sets of routines to import into your script's namespace.
4297There is a small overhead associated with this importation, but it
4298isn't much.
54310121 4299
424ec8fa 4300 use CGI <list of methods>;
54310121 4301
424ec8fa
GS
4302The listed methods will be imported into the current package; you can
4303call them directly without creating a CGI object first. This example
4304shows how to import the B<param()> and B<header()>
4305methods, and then use them directly:
54310121 4306
424ec8fa
GS
4307 use CGI 'param','header';
4308 print header('text/plain');
4309 $zipcode = param('zipcode');
54310121 4310
424ec8fa 4311More frequently, you'll import common sets of functions by referring
f610777f 4312to the groups by name. All function sets are preceded with a ":"
424ec8fa 4313character as in ":html3" (for tags defined in the HTML 3 standard).
54310121 4314
424ec8fa 4315Here is a list of the function sets you can import:
54310121 4316
424ec8fa 4317=over 4
54310121 4318
424ec8fa 4319=item B<:cgi>
54310121 4320
424ec8fa
GS
4321Import all CGI-handling methods, such as B<param()>, B<path_info()>
4322and the like.
54310121 4323
424ec8fa 4324=item B<:form>
54310121 4325
424ec8fa 4326Import all fill-out form generating methods, such as B<textfield()>.
54310121 4327
424ec8fa 4328=item B<:html2>
54310121 4329
424ec8fa 4330Import all methods that generate HTML 2.0 standard elements.
54310121 4331
424ec8fa 4332=item B<:html3>
54310121 4333
3acbd4f5 4334Import all methods that generate HTML 3.0 elements (such as
424ec8fa 4335<table>, <super> and <sub>).
54310121 4336
3acbd4f5
JH
4337=item B<:html4>
4338
4339Import all methods that generate HTML 4 elements (such as
4340<abbrev>, <acronym> and <thead>).
4341
424ec8fa 4342=item B<:netscape>
54310121 4343
424ec8fa 4344Import all methods that generate Netscape-specific HTML extensions.
54310121 4345
424ec8fa 4346=item B<:html>
54310121 4347
424ec8fa
GS
4348Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4349'netscape')...
54310121 4350
424ec8fa 4351=item B<:standard>
54310121 4352
3acbd4f5 4353Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
54310121 4354
424ec8fa 4355=item B<:all>
54310121 4356
424ec8fa 4357Import all the available methods. For the full list, see the CGI.pm
3538e1d5 4358code, where the variable %EXPORT_TAGS is defined.
424ec8fa
GS
4359
4360=back
4361
4362If you import a function name that is not part of CGI.pm, the module
4363will treat it as a new HTML tag and generate the appropriate
4364subroutine. You can then use it like any other HTML tag. This is to
4365provide for the rapidly-evolving HTML "standard." For example, say
3acbd4f5 4366Microsoft comes out with a new tag called <gradient> (which causes the
424ec8fa
GS
4367user's desktop to be flooded with a rotating gradient fill until his
4368machine reboots). You don't need to wait for a new version of CGI.pm
d23a249d 4369to start using it immediately:
424ec8fa
GS
4370
4371 use CGI qw/:standard :html3 gradient/;
4372 print gradient({-start=>'red',-end=>'blue'});
4373
4374Note that in the interests of execution speed CGI.pm does B<not> use
4375the standard L<Exporter> syntax for specifying load symbols. This may
4376change in the future.
4377
4378If you import any of the state-maintaining CGI or form-generating
4379methods, a default CGI object will be created and initialized
4380automatically the first time you use any of the methods that require
4381one to be present. This includes B<param()>, B<textfield()>,
4382B<submit()> and the like. (If you need direct access to the CGI
4383object, you can find it in the global variable B<$CGI::Q>). By
4384importing CGI.pm methods, you can create visually elegant scripts:
4385
4386 use CGI qw/:standard/;
4387 print
4388 header,
4389 start_html('Simple Script'),
4390 h1('Simple Script'),
4391 start_form,
4392 "What's your name? ",textfield('name'),p,
4393 "What's the combination?",
4394 checkbox_group(-name=>'words',
4395 -values=>['eenie','meenie','minie','moe'],
4396 -defaults=>['eenie','moe']),p,
4397 "What's your favorite color?",
4398 popup_menu(-name=>'color',
4399 -values=>['red','green','blue','chartreuse']),p,
4400 submit,
4401 end_form,
4402 hr,"\n";
4403
4404 if (param) {
4405 print
4406 "Your name is ",em(param('name')),p,
4407 "The keywords are: ",em(join(", ",param('words'))),p,
4408 "Your favorite color is ",em(param('color')),".\n";
4409 }
4410 print end_html;
4411
4412=head2 PRAGMAS
4413
4414In addition to the function sets, there are a number of pragmas that
4415you can import. Pragmas, which are always preceded by a hyphen,
4416change the way that CGI.pm functions in various ways. Pragmas,
4417function sets, and individual functions can all be imported in the
4418same use() line. For example, the following use statement imports the
3d1a2ec4
GS
4419standard set of functions and enables debugging mode (pragma
4420-debug):
424ec8fa 4421
3d1a2ec4 4422 use CGI qw/:standard -debug/;
424ec8fa
GS
4423
4424The current list of pragmas is as follows:
4425
4426=over 4
4427
4428=item -any
4429
4430When you I<use CGI -any>, then any method that the query object
4431doesn't recognize will be interpreted as a new HTML tag. This allows
4432you to support the next I<ad hoc> Netscape or Microsoft HTML
4433extension. This lets you go wild with new and unsupported tags:
4434
4435 use CGI qw(-any);
4436 $q=new CGI;
4437 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4438
4439Since using <cite>any</cite> causes any mistyped method name
4440to be interpreted as an HTML tag, use it with care or not at
4441all.
54310121 4442
424ec8fa 4443=item -compile
54310121 4444
424ec8fa
GS
4445This causes the indicated autoloaded methods to be compiled up front,
4446rather than deferred to later. This is useful for scripts that run
4447for an extended period of time under FastCGI or mod_perl, and for
4448those destined to be crunched by Malcom Beattie's Perl compiler. Use
f610777f 4449it in conjunction with the methods or method families you plan to use.
424ec8fa
GS
4450
4451 use CGI qw(-compile :standard :html3);
4452
4453or even
4454
4455 use CGI qw(-compile :all);
4456
4457Note that using the -compile pragma in this way will always have
4458the effect of importing the compiled functions into the current
4459namespace. If you want to compile without importing use the
188ba755
JH
4460compile() method instead:
4461
4462 use CGI();
4463 CGI->compile();
4464
4465This is particularly useful in a mod_perl environment, in which you
4466might want to precompile all CGI routines in a startup script, and
4467then import the functions individually in each mod_perl script.
424ec8fa 4468
3d1a2ec4
GS
4469=item -nosticky
4470
4471This makes CGI.pm not generating the hidden fields .submit
4472and .cgifields. It is very useful if you don't want to
4473have the hidden fields appear in the querystring in a GET method.
4474For example, a search script generated this way will have
4475a very nice url with search parameters for bookmarking.
4476
199d4a26
JH
4477=item -no_undef_params
4478
4479This keeps CGI.pm from including undef params in the parameter list.
4480
6b4ac661
JH
4481=item -no_xhtml
4482
4483By default, CGI.pm versions 2.69 and higher emit XHTML
4484(http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4485feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4486feature.
4487
424ec8fa
GS
4488=item -nph
4489
4490This makes CGI.pm produce a header appropriate for an NPH (no
4491parsed header) script. You may need to do other things as well
4492to tell the server that the script is NPH. See the discussion
4493of NPH scripts below.
4494
71f3e297
JH
4495=item -newstyle_urls
4496
4497Separate the name=value pairs in CGI parameter query strings with
4498semicolons rather than ampersands. For example:
4499
4500 ?name=fred;age=24;favorite_color=3
4501
4502Semicolon-delimited query strings are always accepted, but will not be
4503emitted by self_url() and query_string() unless the -newstyle_urls
4504pragma is specified.
4505
3d1a2ec4
GS
4506This became the default in version 2.64.
4507
4508=item -oldstyle_urls
4509
4510Separate the name=value pairs in CGI parameter query strings with
4511ampersands rather than semicolons. This is no longer the default.
4512
424ec8fa
GS
4513=item -autoload
4514
4515This overrides the autoloader so that any function in your program
4516that is not recognized is referred to CGI.pm for possible evaluation.
4517This allows you to use all the CGI.pm functions without adding them to
4518your symbol table, which is of concern for mod_perl users who are
4519worried about memory consumption. I<Warning:> when
4520I<-autoload> is in effect, you cannot use "poetry mode"
4521(functions without the parenthesis). Use I<hr()> rather
4522than I<hr>, or add something like I<use subs qw/hr p header/>
4523to the top of your script.
4524
4525=item -no_debug
4526
4527This turns off the command-line processing features. If you want to
4528run a CGI.pm script from the command line to produce HTML, and you
3d1a2ec4
GS
4529don't want it to read CGI parameters from the command line or STDIN,
4530then use this pragma:
424ec8fa
GS
4531
4532 use CGI qw(-no_debug :standard);
4533
3d1a2ec4 4534=item -debug
424ec8fa 4535
3d1a2ec4
GS
4536This turns on full debugging. In addition to reading CGI arguments
4537from the command-line processing, CGI.pm will pause and try to read
4538arguments from STDIN, producing the message "(offline mode: enter
4539name=value pairs on standard input)" features.
3cb6de81 4540
424ec8fa
GS
4541See the section on debugging for more details.
4542
4543=item -private_tempfiles
4544
3538e1d5
GS
4545CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4546file to a temporary directory, then deletes the file when done.
4547However, this opens the risk of eavesdropping as described in the file
4548upload section. Another CGI script author could peek at this data
4549during the upload, even if it is confidential information. On Unix
4550systems, the -private_tempfiles pragma will cause the temporary file
4551to be unlinked as soon as it is opened and before any data is written
4552into it, reducing, but not eliminating the risk of eavesdropping
4553(there is still a potential race condition). To make life harder for
4554the attacker, the program chooses tempfile names by calculating a 32
4555bit checksum of the incoming HTTP headers.
4556
4557To ensure that the temporary file cannot be read by other CGI scripts,
4558use suEXEC or a CGI wrapper program to run your script. The temporary
4559file is created with mode 0600 (neither world nor group readable).
4560
4561The temporary directory is selected using the following algorithm:
4562
4563 1. if the current user (e.g. "nobody") has a directory named
4564 "tmp" in its home directory, use that (Unix systems only).
4565
4566 2. if the environment variable TMPDIR exists, use the location
4567 indicated.
4568
4569 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4570 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4571
4572Each of these locations is checked that it is a directory and is
4573writable. If not, the algorithm tries the next choice.
71f3e297
JH
4574
4575=back
4576
4577=head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4578
4579Many of the methods generate HTML tags. As described below, tag
4580functions automatically generate both the opening and closing tags.
4581For example:
4582
4583 print h1('Level 1 Header');
4584
4585produces
4586
3acbd4f5 4587 <h1>Level 1 Header</h1>
71f3e297
JH
4588
4589There will be some times when you want to produce the start and end
4590tags yourself. In this case, you can use the form start_I<tag_name>
4591and end_I<tag_name>, as in:
4592
4593 print start_h1,'Level 1 Header',end_h1;
4594
4595With a few exceptions (described below), start_I<tag_name> and
4596end_I<tag_name> functions are not generated automatically when you
4597I<use CGI>. However, you can specify the tags you want to generate
4598I<start/end> functions for by putting an asterisk in front of their
4599name, or, alternatively, requesting either "start_I<tag_name>" or
4600"end_I<tag_name>" in the import list.
4601
4602Example:
4603
4604 use CGI qw/:standard *table start_ul/;
4605
4606In this example, the following functions are generated in addition to
4607the standard ones:
4608
4609=over 4
4610
3acbd4f5 4611=item 1. start_table() (generates a <table> tag)
71f3e297 4612
3acbd4f5 4613=item 2. end_table() (generates a </table> tag)
71f3e297 4614
3acbd4f5 4615=item 3. start_ul() (generates a <ul> tag)
71f3e297 4616
3acbd4f5 4617=item 4. end_ul() (generates a </ul> tag)
71f3e297 4618
424ec8fa
GS
4619=back
4620
4621=head1 GENERATING DYNAMIC DOCUMENTS
4622
4623Most of CGI.pm's functions deal with creating documents on the fly.
4624Generally you will produce the HTTP header first, followed by the
4625document itself. CGI.pm provides functions for generating HTTP
4626headers of various types as well as for generating HTML. For creating
4627GIF images, see the GD.pm module.
4628
4629Each of these functions produces a fragment of HTML or HTTP which you
4630can print out directly so that it displays in the browser window,
4631append to a string, or save to a file for later use.
4632
4633=head2 CREATING A STANDARD HTTP HEADER:
4634
4635Normally the first thing you will do in any CGI script is print out an
4636HTTP header. This tells the browser what type of document to expect,
4637and gives other optional information, such as the language, expiration
4638date, and whether to cache the document. The header can also be
4639manipulated for special purposes, such as server push and pay per view
4640pages.
54310121 4641
4642 print $query->header;
4643
4644 -or-
4645
4646 print $query->header('image/gif');
4647
4648 -or-
4649
4650 print $query->header('text/html','204 No response');
4651
4652 -or-
4653
4654 print $query->header(-type=>'image/gif',
4655 -nph=>1,
4656 -status=>'402 Payment required',
4657 -expires=>'+3d',
4658 -cookie=>$cookie,
3d1a2ec4 4659 -charset=>'utf-7',
6b4ac661 4660 -attachment=>'foo.gif',
54310121 4661 -Cost=>'$2.00');
4662
4663header() returns the Content-type: header. You can provide your own
4664MIME type if you choose, otherwise it defaults to text/html. An
4665optional second parameter specifies the status code and a human-readable
4666message. For example, you can specify 204, "No response" to create a
424ec8fa 4667script that tells the browser to do nothing at all.
54310121 4668
4669The last example shows the named argument style for passing arguments
4670to the CGI methods using named parameters. Recognized parameters are
424ec8fa 4671B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
54310121 4672parameters will be stripped of their initial hyphens and turned into
4673header fields, allowing you to specify any HTTP header you desire.
424ec8fa
GS
4674Internal underscores will be turned into hyphens:
4675
4676 print $query->header(-Content_length=>3002);
54310121 4677
4678Most browsers will not cache the output from CGI scripts. Every time
4679the browser reloads the page, the script is invoked anew. You can
4680change this behavior with the B<-expires> parameter. When you specify
4681an absolute or relative expiration interval with this parameter, some
4682browsers and proxy servers will cache the script's output until the
4683indicated expiration date. The following forms are all valid for the
4684-expires field:
4685
4686 +30s 30 seconds from now
4687 +10m ten minutes from now
4688 +1h one hour from now
4689 -1d yesterday (i.e. "ASAP!")
4690 now immediately
4691 +3M in three months
4692 +10y in ten years time
424ec8fa 4693 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
54310121 4694
4695The B<-cookie> parameter generates a header that tells the browser to provide
4696a "magic cookie" during all subsequent transactions with your script.
4697Netscape cookies have a special format that includes interesting attributes
4698such as expiration time. Use the cookie() method to create and retrieve
4699session cookies.
4700
4701The B<-nph> parameter, if set to a true value, will issue the correct
8f3ccfa2 4702headers to work with a NPH (no-parse-header) script. This is important
3d1a2ec4
GS
4703to use with certain servers that expect all their scripts to be NPH.
4704
4705The B<-charset> parameter can be used to control the character set
4706sent to the browser. If not provided, defaults to ISO-8859-1. As a
4707side effect, this sets the charset() method as well.
54310121 4708
6b4ac661
JH
4709The B<-attachment> parameter can be used to turn the page into an
4710attachment. Instead of displaying the page, some browsers will prompt
4711the user to save it to disk. The value of the argument is the
4712suggested name for the saved file. In order for this to work, you may
4713have to set the B<-type> to "application/octet-stream".
4714
8f3ccfa2
JH
4715The B<-p3p> parameter will add a P3P tag to the outgoing header. The
4716parameter can be an arrayref or a space-delimited string of P3P tags.
4717For example:
4718
4719 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
4720 print header(-p3p=>'CAO DSP LAW CURa');
4721
4722In either case, the outgoing header will be formatted as:
4723
4724 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
4725
424ec8fa 4726=head2 GENERATING A REDIRECTION HEADER
54310121 4727
4728 print $query->redirect('http://somewhere.else/in/movie/land');
4729
424ec8fa
GS
4730Sometimes you don't want to produce a document yourself, but simply
4731redirect the browser elsewhere, perhaps choosing a URL based on the
4732time of day or the identity of the user.
4733
4734The redirect() function redirects the browser to a different URL. If
4735you use redirection like this, you should B<not> print out a header as
6b4ac661 4736well.
54310121 4737
2ed511ec
RGS
4738You should always use full URLs (including the http: or ftp: part) in
4739redirection requests. Relative URLs will not work correctly.
54310121 4740
424ec8fa 4741You can also use named arguments:
54310121 4742
4743 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4744 -nph=>1);
4745
4746The B<-nph> parameter, if set to a true value, will issue the correct
8f3ccfa2 4747headers to work with a NPH (no-parse-header) script. This is important
58129083 4748to use with certain servers, such as Microsoft IIS, which
54310121 4749expect all their scripts to be NPH.
4750
424ec8fa 4751=head2 CREATING THE HTML DOCUMENT HEADER
54310121 4752
4753 print $query->start_html(-title=>'Secrets of the Pyramids',
4754 -author=>'fred@capricorn.org',
4755 -base=>'true',
4756 -target=>'_blank',
4757 -meta=>{'keywords'=>'pharaoh secret mummy',
4758 'copyright'=>'copyright 1996 King Tut'},
7d37aa8e 4759 -style=>{'src'=>'/styles/style1.css'},
54310121 4760 -BGCOLOR=>'blue');
4761
424ec8fa
GS
4762After creating the HTTP header, most CGI scripts will start writing
4763out an HTML document. The start_html() routine creates the top of the
4764page, along with a lot of optional information that controls the
4765page's appearance and behavior.
54310121 4766
3acbd4f5 4767This method returns a canned HTML header and the opening <body> tag.
424ec8fa 4768All parameters are optional. In the named parameter form, recognized
6b4ac661
JH
4769parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4770(see below for the explanation). Any additional parameters you
4771provide, such as the Netscape unofficial BGCOLOR attribute, are added
3acbd4f5 4772to the <body> tag. Additional parameters must be proceeded by a
6b4ac661 4773hyphen.
54310121 4774
3acbd4f5 4775The argument B<-xbase> allows you to provide an HREF for the <base> tag
54310121 4776different from the current location, as in
4777
4778 -xbase=>"http://home.mcom.com/"
4779
4780All relative links will be interpreted relative to this tag.
4781
4782The argument B<-target> allows you to provide a default target frame
3d1a2ec4
GS
4783for all the links and fill-out forms on the page. B<This is a
4784non-standard HTTP feature which only works with Netscape browsers!>
4785See the Netscape documentation on frames for details of how to
4786manipulate this.
54310121 4787
4788 -target=>"answer_window"
4789
4790All relative links will be interpreted relative to this tag.
4791You add arbitrary meta information to the header with the B<-meta>
4792argument. This argument expects a reference to an associative array
4793containing name/value pairs of meta information. These will be turned
3acbd4f5 4794into a series of header <meta> tags that look something like this:
54310121 4795
3acbd4f5
JH
4796 <meta name="keywords" content="pharaoh secret mummy">
4797 <meta name="description" content="copyright 1996 King Tut">
424ec8fa 4798
3acbd4f5 4799To create an HTTP-EQUIV type of <meta> tag, use B<-head>, described
6b4ac661 4800below.
424ec8fa 4801
6b4ac661
JH
4802The B<-style> argument is used to incorporate cascading stylesheets
4803into your code. See the section on CASCADING STYLESHEETS for more
4804information.
424ec8fa 4805
6b4ac661 4806The B<-lang> argument is used to incorporate a language attribute into
3acbd4f5 4807the <html> tag. The default if not specified is "en-US" for US
6b4ac661
JH
4808English. For example:
4809
ba056755 4810 print $q->start_html(-lang=>'fr-CA');
424ec8fa 4811
8f3ccfa2
JH
4812To leave off the lang attribute, as you must do if you want to generate
4813legal HTML 3.2 or earlier, pass the empty string (-lang=>'').
4814
ac734d8b 4815The B<-encoding> argument can be used to specify the character set for
b2d0d414 4816XHTML. It defaults to iso-8859-1 if not specified.
ac734d8b 4817
3acbd4f5
JH
4818You can place other arbitrary HTML elements to the <head> section with the
4819B<-head> tag. For example, to place the rarely-used <link> element in the
424ec8fa
GS
4820head section, use this:
4821
3538e1d5 4822 print start_html(-head=>Link({-rel=>'next',
6b4ac661 4823 -href=>'http://www.capricorn.com/s2.html'}));
424ec8fa 4824
3acbd4f5 4825To incorporate multiple HTML elements into the <head> section, just pass an
424ec8fa
GS
4826array reference:
4827
3538e1d5
GS
4828 print start_html(-head=>[
4829 Link({-rel=>'next',
4830 -href=>'http://www.capricorn.com/s2.html'}),
4831 Link({-rel=>'previous',
4832 -href=>'http://www.capricorn.com/s1.html'})
424ec8fa
GS
4833 ]
4834 );
4835
3acbd4f5 4836And here's how to create an HTTP-EQUIV <meta> tag:
6b4ac661 4837
ba056755
JH
4838 print start_html(-head=>meta({-http_equiv => 'Content-Type',
4839 -content => 'text/html'}))
6b4ac661
JH
4840
4841
424ec8fa
GS
4842JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4843B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4844to add Netscape JavaScript calls to your pages. B<-script> should
4845point to a block of text containing JavaScript function definitions.
3acbd4f5 4846This block will be placed within a <script> block inside the HTML (not
424ec8fa
GS
4847HTTP) header. The block is placed in the header in order to give your
4848page a fighting chance of having all its JavaScript functions in place
4849even if the user presses the stop button before the page has loaded
4850completely. CGI.pm attempts to format the script in such a way that
4851JavaScript-naive browsers will not choke on the code: unfortunately
4852there are some browsers, such as Chimera for Unix, that get confused
4853by it nevertheless.
4854
4855The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4856code to execute when the page is respectively opened and closed by the
4857browser. Usually these parameters are calls to functions defined in the
4858B<-script> field:
4859
4860 $query = new CGI;
4861 print $query->header;
4862 $JSCRIPT=<<END;
4863 // Ask a silly question
4864 function riddle_me_this() {
4865 var r = prompt("What walks on four legs in the morning, " +
4866 "two legs in the afternoon, " +
4867 "and three legs in the evening?");
4868 response(r);
4869 }
4870 // Get a silly answer
4871 function response(answer) {
4872 if (answer == "man")
4873 alert("Right you are!");
4874 else
4875 alert("Wrong! Guess again.");
4876 }
4877 END
4878 print $query->start_html(-title=>'The Riddle of the Sphinx',
4879 -script=>$JSCRIPT);
4880
4881Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4882browsers that do not have JavaScript (or browsers where JavaScript is turned
4883off).
4884
3acbd4f5 4885Netscape 3.0 recognizes several attributes of the <script> tag,
424ec8fa
GS
4886including LANGUAGE and SRC. The latter is particularly interesting,
4887as it allows you to keep the JavaScript code in a file or CGI script
4888rather than cluttering up each page with the source. To use these
4889attributes pass a HASH reference in the B<-script> parameter containing
4890one or more of -language, -src, or -code:
4891
4892 print $q->start_html(-title=>'The Riddle of the Sphinx',
4893 -script=>{-language=>'JAVASCRIPT',
4894 -src=>'/javascript/sphinx.js'}
4895 );
4896
4897 print $q->(-title=>'The Riddle of the Sphinx',
3538e1d5
GS
4898 -script=>{-language=>'PERLSCRIPT',
4899 -code=>'print "hello world!\n;"'}
424ec8fa
GS
4900 );
4901
4902
3acbd4f5 4903A final feature allows you to incorporate multiple <script> sections into the
424ec8fa
GS
4904header. Just pass the list of script sections as an array reference.
4905this allows you to specify different source files for different dialects
4906of JavaScript. Example:
4907
3538e1d5
GS
4908 print $q->start_html(-title=>'The Riddle of the Sphinx',
4909 -script=>[
4910 { -language => 'JavaScript1.0',
4911 -src => '/javascript/utilities10.js'
424ec8fa 4912 },
3538e1d5
GS
4913 { -language => 'JavaScript1.1',
4914 -src => '/javascript/utilities11.js'
424ec8fa 4915 },
3538e1d5
GS
4916 { -language => 'JavaScript1.2',
4917 -src => '/javascript/utilities12.js'
424ec8fa 4918 },
3538e1d5
GS
4919 { -language => 'JavaScript28.2',
4920 -src => '/javascript/utilities219.js'
424ec8fa
GS
4921 }
4922 ]
4923 );
424ec8fa
GS
4924
4925If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4926
4927See
4928
4929 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4930
4931for more information about JavaScript.
4932
4933The old-style positional parameters are as follows:
4934
4935=over 4
4936
4937=item B<Parameters:>
4938
4939=item 1.
4940
4941The title
4942
4943=item 2.
4944
3acbd4f5 4945The author's e-mail address (will create a <link rev="MADE"> tag if present
424ec8fa
GS
4946
4947=item 3.
4948
3acbd4f5 4949A 'true' flag if you want to include a <base> tag in the header. This
424ec8fa
GS
4950helps resolve relative addresses to absolute ones when the document is moved,
4951but makes the document hierarchy non-portable. Use with care!
4952
4953=item 4, 5, 6...
4954
3acbd4f5 4955Any other parameters you want to include in the <body> tag. This is a good
424ec8fa
GS
4956place to put Netscape extensions, such as colors and wallpaper patterns.
4957
4958=back
4959
4960=head2 ENDING THE HTML DOCUMENT:
4961
4962 print $query->end_html
4963
3acbd4f5 4964This ends an HTML document by printing the </body></html> tags.
424ec8fa
GS
4965
4966=head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4967
4968 $myself = $query->self_url;
3acbd4f5 4969 print q(<a href="$myself">I'm talking to myself.</a>);
424ec8fa
GS
4970
4971self_url() will return a URL, that, when selected, will reinvoke
4972this script with all its state information intact. This is most
4973useful when you want to jump around within the document using
4974internal anchors but you don't want to disrupt the current contents
4975of the form(s). Something like this will do the trick.
4976
4977 $myself = $query->self_url;
188ba755
JH
4978 print "<a href=\"$myself#table1\">See table 1</a>";
4979 print "<a href=\"$myself#table2\">See table 2</a>";
4980 print "<a href=\"$myself#yourself\">See for yourself</a>";
424ec8fa
GS
4981
4982If you want more control over what's returned, using the B<url()>
4983method instead.
4984
4985You can also retrieve the unprocessed query string with query_string():
4986
4987 $the_string = $query->query_string;
4988
4989=head2 OBTAINING THE SCRIPT'S URL
4990
4991 $full_url = $query->url();
4992 $full_url = $query->url(-full=>1); #alternative syntax
4993 $relative_url = $query->url(-relative=>1);
4994 $absolute_url = $query->url(-absolute=>1);
4995 $url_with_path = $query->url(-path_info=>1);
4996 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
03b9648d 4997 $netloc = $query->url(-base => 1);
424ec8fa
GS
4998
4999B<url()> returns the script's URL in a variety of formats. Called
5000without any arguments, it returns the full form of the URL, including
5001host name and port number
5002
5003 http://your.host.com/path/to/script.cgi
5004
5005You can modify this format with the following named arguments:
5006
5007=over 4
5008
5009=item B<-absolute>
5010
5011If true, produce an absolute URL, e.g.
5012
5013 /path/to/script.cgi
5014
5015=item B<-relative>
5016
5017Produce a relative URL. This is useful if you want to reinvoke your
5018script with different parameters. For example:
5019
5020 script.cgi
5021
5022=item B<-full>
5023
5024Produce the full URL, exactly as if called without any arguments.
5025This overrides the -relative and -absolute arguments.
5026
5027=item B<-path> (B<-path_info>)
5028
5029Append the additional path information to the URL. This can be
5030combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
5031is provided as a synonym.
5032
5033=item B<-query> (B<-query_string>)
5034
5035Append the query string to the URL. This can be combined with
5036B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
5037as a synonym.
5038
03b9648d
JH
5039=item B<-base>
5040
5041Generate just the protocol and net location, as in http://www.foo.com:8000
5042
424ec8fa
GS
5043=back
5044
71f3e297
JH
5045=head2 MIXING POST AND URL PARAMETERS
5046
cff99809 5047 $color = $query->url_param('color');
71f3e297
JH
5048
5049It is possible for a script to receive CGI parameters in the URL as
5050well as in the fill-out form by creating a form that POSTs to a URL
5051containing a query string (a "?" mark followed by arguments). The
5052B<param()> method will always return the contents of the POSTed
5053fill-out form, ignoring the URL's query string. To retrieve URL
5054parameters, call the B<url_param()> method. Use it in the same way as
5055B<param()>. The main difference is that it allows you to read the
5056parameters, but not set them.
5057
5058
5059Under no circumstances will the contents of the URL query string
5060interfere with similarly-named CGI parameters in POSTed forms. If you
5061try to mix a URL query string with a form submitted with the GET
5062method, the results will not be what you expect.
5063
424ec8fa
GS
5064=head1 CREATING STANDARD HTML ELEMENTS:
5065
5066CGI.pm defines general HTML shortcut methods for most, if not all of
5067the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
5068HTML element and return a fragment of HTML text that you can then
5069print or manipulate as you like. Each shortcut returns a fragment of
5070HTML code that you can append to a string, save to a file, or, most
5071commonly, print out so that it displays in the browser window.
5072
5073This example shows how to use the HTML methods:
5074
5075 $q = new CGI;
5076 print $q->blockquote(
5077 "Many years ago on the island of",
5078 $q->a({href=>"http://crete.org/"},"Crete"),
3538e1d5 5079 "there lived a Minotaur named",
424ec8fa
GS
5080 $q->strong("Fred."),
5081 ),
5082 $q->hr;
5083
5084This results in the following HTML code (extra newlines have been
5085added for readability):
5086
5087 <blockquote>
5088 Many years ago on the island of
3acbd4f5 5089 <a href="http://crete.org/">Crete</a> there lived
424ec8fa
GS
5090 a minotaur named <strong>Fred.</strong>
5091 </blockquote>
5092 <hr>
5093
5094If you find the syntax for calling the HTML shortcuts awkward, you can
5095import them into your namespace and dispense with the object syntax
5096completely (see the next section for more details):
5097
5098 use CGI ':standard';
5099 print blockquote(
5100 "Many years ago on the island of",
5101 a({href=>"http://crete.org/"},"Crete"),
5102 "there lived a minotaur named",
5103 strong("Fred."),
5104 ),
5105 hr;
54310121 5106
424ec8fa 5107=head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
7d37aa8e 5108
424ec8fa
GS
5109The HTML methods will accept zero, one or multiple arguments. If you
5110provide no arguments, you get a single tag:
7d37aa8e 5111
3acbd4f5 5112 print hr; # <hr>
7d37aa8e 5113
424ec8fa
GS
5114If you provide one or more string arguments, they are concatenated
5115together with spaces and placed between opening and closing tags:
7d37aa8e 5116
3acbd4f5 5117 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
7d37aa8e 5118
424ec8fa
GS
5119If the first argument is an associative array reference, then the keys
5120and values of the associative array become the HTML tag's attributes:
7d37aa8e 5121
424ec8fa
GS
5122 print a({-href=>'fred.html',-target=>'_new'},
5123 "Open a new frame");
7d37aa8e 5124
3acbd4f5 5125 <a href="fred.html",target="_new">Open a new frame</a>
3cb6de81 5126
424ec8fa
GS
5127You may dispense with the dashes in front of the attribute names if
5128you prefer:
54310121 5129
424ec8fa 5130 print img {src=>'fred.gif',align=>'LEFT'};
54310121 5131
3acbd4f5 5132 <img align="LEFT" src="fred.gif">
54310121 5133
424ec8fa 5134Sometimes an HTML tag attribute has no argument. For example, ordered
8f3ccfa2 5135lists can be marked as COMPACT. The syntax for this is an argument that
424ec8fa 5136that points to an undef string:
54310121 5137
424ec8fa 5138 print ol({compact=>undef},li('one'),li('two'),li('three'));
47e3cabd 5139
424ec8fa
GS
5140Prior to CGI.pm version 2.41, providing an empty ('') string as an
5141attribute argument was the same as providing undef. However, this has
8f3ccfa2 5142changed in order to accommodate those who want to create tags of the form
3acbd4f5 5143<img alt="">. The difference is shown in these two pieces of code:
3cb6de81 5144
8f3ccfa2
JH
5145 CODE RESULT
5146 img({alt=>undef}) <img alt>
5147 img({alt=>''}) <img alt="">
7d37aa8e 5148
424ec8fa 5149=head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
7d37aa8e 5150
424ec8fa
GS
5151One of the cool features of the HTML shortcuts is that they are
5152distributive. If you give them an argument consisting of a
5153B<reference> to a list, the tag will be distributed across each
5154element of the list. For example, here's one way to make an ordered
5155list:
7d37aa8e 5156
424ec8fa 5157 print ul(
6b4ac661 5158 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
424ec8fa 5159 );
7d37aa8e 5160
424ec8fa 5161This example will result in HTML output that looks like this:
54310121 5162
3acbd4f5
JH
5163 <ul>
5164 <li type="disc">Sneezy</li>
5165 <li type="disc">Doc</li>
5166 <li type="disc">Sleepy</li>
5167 <li type="disc">Happy</li>
5168 </ul>
54310121 5169
424ec8fa 5170This is extremely useful for creating tables. For example:
54310121 5171
424ec8fa
GS
5172 print table({-border=>undef},
5173 caption('When Should You Eat Your Vegetables?'),
5174 Tr({-align=>CENTER,-valign=>TOP},
5175 [
5176 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
5177 td(['Tomatoes' , 'no', 'yes', 'yes']),
5178 td(['Broccoli' , 'no', 'no', 'yes']),
5179 td(['Onions' , 'yes','yes', 'yes'])
5180 ]
5181 )
5182 );
54310121 5183
424ec8fa 5184=head2 HTML SHORTCUTS AND LIST INTERPOLATION
54310121 5185
424ec8fa 5186Consider this bit of code:
54310121 5187
424ec8fa 5188 print blockquote(em('Hi'),'mom!'));
54310121 5189
424ec8fa 5190It will ordinarily return the string that you probably expect, namely:
54310121 5191
3acbd4f5 5192 <blockquote><em>Hi</em> mom!</blockquote>
54310121 5193
424ec8fa
GS
5194Note the space between the element "Hi" and the element "mom!".
5195CGI.pm puts the extra space there using array interpolation, which is
5196controlled by the magic $" variable. Sometimes this extra space is
5197not what you want, for example, when you are trying to align a series
5198of images. In this case, you can simply change the value of $" to an
5199empty string.
54310121 5200
424ec8fa
GS
5201 {
5202 local($") = '';
5203 print blockquote(em('Hi'),'mom!'));
5204 }
54310121 5205
424ec8fa
GS
5206I suggest you put the code in a block as shown here. Otherwise the
5207change to $" will affect all subsequent code until you explicitly
5208reset it.
54310121 5209
424ec8fa 5210=head2 NON-STANDARD HTML SHORTCUTS
54310121 5211
424ec8fa
GS
5212A few HTML tags don't follow the standard pattern for various
5213reasons.
54310121 5214
424ec8fa
GS
5215B<comment()> generates an HTML comment (<!-- comment -->). Call it
5216like
54310121 5217
424ec8fa 5218 print comment('here is my comment');
54310121 5219
424ec8fa
GS
5220Because of conflicts with built-in Perl functions, the following functions
5221begin with initial caps:
54310121 5222
424ec8fa
GS
5223 Select
5224 Tr
5225 Link
5226 Delete
71f3e297
JH
5227 Accept
5228 Sub
54310121 5229
424ec8fa
GS
5230In addition, start_html(), end_html(), start_form(), end_form(),
5231start_multipart_form() and all the fill-out form tags are special.
5232See their respective sections.
5233
3d1a2ec4
GS
5234=head2 AUTOESCAPING HTML
5235
5236By default, all HTML that is emitted by the form-generating functions
5237is passed through a function called escapeHTML():
5238
5239=over 4
5240
5241=item $escaped_string = escapeHTML("unescaped string");
5242
5243Escape HTML formatting characters in a string.
5244
5245=back
5246
5247Provided that you have specified a character set of ISO-8859-1 (the
5248default), the standard HTML escaping rules will be used. The "<"
5249character becomes "&lt;", ">" becomes "&gt;", "&" becomes "&amp;", and
5250the quote character becomes "&quot;". In addition, the hexadecimal
188ba755 52510x8b and 0x9b characters, which some browsers incorrectly interpret
3d1a2ec4 5252as the left and right angle-bracket characters, are replaced by their
188ba755 5253numeric character entities ("&#8249" and "&#8250;"). If you manually change
3d1a2ec4
GS
5254the charset, either by calling the charset() method explicitly or by
5255passing a -charset argument to header(), then B<all> characters will
5256be replaced by their numeric entities, since CGI.pm has no lookup
5257table for all the possible encodings.
5258
5259The automatic escaping does not apply to other shortcuts, such as
5260h1(). You should call escapeHTML() yourself on untrusted data in
5261order to protect your pages against nasty tricks that people may enter
5262into guestbooks, etc.. To change the character set, use charset().
188ba755 5263To turn autoescaping off completely, use autoEscape(0):
3d1a2ec4
GS
5264
5265=over 4
5266
5267=item $charset = charset([$charset]);
5268
5269Get or set the current character set.
5270
5271=item $flag = autoEscape([$flag]);
5272
5273Get or set the value of the autoescape flag.
5274
5275=back
5276
71f3e297
JH
5277=head2 PRETTY-PRINTING HTML
5278
5279By default, all the HTML produced by these functions comes out as one
5280long line without carriage returns or indentation. This is yuck, but
5281it does reduce the size of the documents by 10-20%. To get
5282pretty-printed output, please use L<CGI::Pretty>, a subclass
5283contributed by Brian Paulsen.
5284
424ec8fa 5285=head1 CREATING FILL-OUT FORMS:
54310121 5286
5287I<General note> The various form-creating methods all return strings
5288to the caller, containing the tag or tags that will create the requested
5289form element. You are responsible for actually printing out these strings.
5290It's set up this way so that you can place formatting tags
5291around the form elements.
5292
5293I<Another note> The default values that you specify for the forms are only
5294used the B<first> time the script is invoked (when there is no query
5295string). On subsequent invocations of the script (when there is a query
5296string), the former values are used even if they are blank.
5297
5298If you want to change the value of a field from its previous value, you have two
5299choices:
5300
5301(1) call the param() method to set it.
5302
5303(2) use the -override (alias -force) parameter (a new feature in version 2.15).
5304This forces the default value to be used, regardless of the previous value:
5305
5306 print $query->textfield(-name=>'field_name',
5307 -default=>'starting value',
5308 -override=>1,
5309 -size=>50,
5310 -maxlength=>80);
5311
5312I<Yet another note> By default, the text and labels of form elements are
5313escaped according to HTML rules. This means that you can safely use
5314"<CLICK ME>" as the label for a button. However, it also interferes with
5315your ability to incorporate special HTML character sequences, such as &Aacute;,
5316into your fields. If you wish to turn off automatic escaping, call the
5317autoEscape() method with a false value immediately after creating the CGI object:
5318
5319 $query = new CGI;
5320 $query->autoEscape(undef);
3cb6de81 5321
54310121 5322=head2 CREATING AN ISINDEX TAG
5323
5324 print $query->isindex(-action=>$action);
5325
5326 -or-
5327
5328 print $query->isindex($action);
5329
3acbd4f5 5330Prints out an <isindex> tag. Not very exciting. The parameter
54310121 5331-action specifies the URL of the script to process the query. The
5332default is to process the query with the current script.
5333
5334=head2 STARTING AND ENDING A FORM
5335
3d1a2ec4 5336 print $query->start_form(-method=>$method,
54310121 5337 -action=>$action,
71f3e297 5338 -enctype=>$encoding);
54310121 5339 <... various form stuff ...>
5340 print $query->endform;
5341
5342 -or-
5343
3d1a2ec4 5344 print $query->start_form($method,$action,$encoding);
54310121 5345 <... various form stuff ...>
5346 print $query->endform;
5347
3acbd4f5 5348start_form() will return a <form> tag with the optional method,
54310121 5349action and form encoding that you specify. The defaults are:
3cb6de81 5350
54310121 5351 method: POST
5352 action: this script
71f3e297 5353 enctype: application/x-www-form-urlencoded
54310121 5354
3acbd4f5 5355endform() returns the closing </form> tag.
54310121 5356
3d1a2ec4 5357Start_form()'s enctype argument tells the browser how to package the various
54310121 5358fields of the form before sending the form to the server. Two
5359values are possible:
5360
3d1a2ec4
GS
5361B<Note:> This method was previously named startform(), and startform()
5362is still recognized as an alias.
5363
54310121 5364=over 4
5365
5366=item B<application/x-www-form-urlencoded>
5367
5368This is the older type of encoding used by all browsers prior to
5369Netscape 2.0. It is compatible with many CGI scripts and is
5370suitable for short fields containing text data. For your
5371convenience, CGI.pm stores the name of this encoding
6b4ac661 5372type in B<&CGI::URL_ENCODED>.
54310121 5373
5374=item B<multipart/form-data>
5375
5376This is the newer type of encoding introduced by Netscape 2.0.
5377It is suitable for forms that contain very large fields or that
5378are intended for transferring binary data. Most importantly,
5379it enables the "file upload" feature of Netscape 2.0 forms. For
5380your convenience, CGI.pm stores the name of this encoding type
424ec8fa 5381in B<&CGI::MULTIPART>
54310121 5382
5383Forms that use this type of encoding are not easily interpreted
5384by CGI scripts unless they use CGI.pm or another library designed
5385to handle them.
5386
5387=back
5388
3d1a2ec4 5389For compatibility, the start_form() method uses the older form of
54310121 5390encoding by default. If you want to use the newer form of encoding
5391by default, you can call B<start_multipart_form()> instead of
3d1a2ec4 5392B<start_form()>.
54310121 5393
5394JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
5395for use with JavaScript. The -name parameter gives the
5396form a name so that it can be identified and manipulated by
5397JavaScript functions. -onSubmit should point to a JavaScript
5398function that will be executed just before the form is submitted to your
5399server. You can use this opportunity to check the contents of the form
5400for consistency and completeness. If you find something wrong, you
5401can put up an alert box or maybe fix things up yourself. You can
5402abort the submission by returning false from this function.
5403
3acbd4f5 5404Usually the bulk of JavaScript functions are defined in a <script>
54310121 5405block in the HTML header and -onSubmit points to one of these function
5406call. See start_html() for details.
5407
5408=head2 CREATING A TEXT FIELD
5409
5410 print $query->textfield(-name=>'field_name',
5411 -default=>'starting value',
5412 -size=>50,
5413 -maxlength=>80);
5414 -or-
5415
5416 print $query->textfield('field_name','starting value',50,80);
5417
5418textfield() will return a text input field.
5419
5420=over 4
5421
5422=item B<Parameters>
5423
5424=item 1.
5425
5426The first parameter is the required name for the field (-name).
5427
5428=item 2.
5429
5430The optional second parameter is the default starting value for the field
5431contents (-default).
5432
5433=item 3.
5434
5435The optional third parameter is the size of the field in
5436 characters (-size).
5437
5438=item 4.
5439
5440The optional fourth parameter is the maximum number of characters the
5441 field will accept (-maxlength).
5442
5443=back
5444
5445As with all these methods, the field will be initialized with its
5446previous contents from earlier invocations of the script.
5447When the form is processed, the value of the text field can be
5448retrieved with:
5449
5450 $value = $query->param('foo');
5451
5452If you want to reset it from its initial value after the script has been
5453called once, you can do so like this:
5454
5455 $query->param('foo',"I'm taking over this value!");
5456
5457NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5458value, you can force its current value by using the -override (alias -force)
5459parameter:
5460
5461 print $query->textfield(-name=>'field_name',
5462 -default=>'starting value',
5463 -override=>1,
5464 -size=>50,
5465 -maxlength=>80);
5466
424ec8fa
GS
5467JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5468B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5469parameters to register JavaScript event handlers. The onChange
5470handler will be called whenever the user changes the contents of the
5471text field. You can do text validation if you like. onFocus and
5472onBlur are called respectively when the insertion point moves into and
5473out of the text field. onSelect is called when the user changes the
5474portion of the text that is selected.
54310121 5475
5476=head2 CREATING A BIG TEXT FIELD
5477
5478 print $query->textarea(-name=>'foo',
5479 -default=>'starting value',
5480 -rows=>10,
5481 -columns=>50);
5482
5483 -or
5484
5485 print $query->textarea('foo','starting value',10,50);
5486
5487textarea() is just like textfield, but it allows you to specify
5488rows and columns for a multiline text entry box. You can provide
5489a starting value for the field, which can be long and contain
5490multiple lines.
5491
424ec8fa
GS
5492JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5493B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5494recognized. See textfield().
54310121 5495
5496=head2 CREATING A PASSWORD FIELD
5497
5498 print $query->password_field(-name=>'secret',
5499 -value=>'starting value',
5500 -size=>50,
5501 -maxlength=>80);
5502 -or-
5503
5504 print $query->password_field('secret','starting value',50,80);
5505
5506password_field() is identical to textfield(), except that its contents
5507will be starred out on the web page.
5508
424ec8fa
GS
5509JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5510B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5511recognized. See textfield().
54310121 5512
5513=head2 CREATING A FILE UPLOAD FIELD
5514
5515 print $query->filefield(-name=>'uploaded_file',
5516 -default=>'starting value',
5517 -size=>50,
5518 -maxlength=>80);
5519 -or-
5520
5521 print $query->filefield('uploaded_file','starting value',50,80);
5522
5523filefield() will return a file upload field for Netscape 2.0 browsers.
5524In order to take full advantage of this I<you must use the new
5525multipart encoding scheme> for the form. You can do this either
6b4ac661 5526by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
54310121 5527or by calling the new method B<start_multipart_form()> instead of
3d1a2ec4 5528vanilla B<start_form()>.
54310121 5529
5530=over 4
5531
5532=item B<Parameters>
5533
5534=item 1.
5535
5536The first parameter is the required name for the field (-name).
5537
5538=item 2.
5539
5540The optional second parameter is the starting value for the field contents
5541to be used as the default file name (-default).
5542
71f3e297
JH
5543For security reasons, browsers don't pay any attention to this field,
5544and so the starting value will always be blank. Worse, the field
5545loses its "sticky" behavior and forgets its previous contents. The
5546starting value field is called for in the HTML specification, however,
5547and possibly some browser will eventually provide support for it.
54310121 5548
5549=item 3.
5550
5551The optional third parameter is the size of the field in
5552characters (-size).
5553
5554=item 4.
5555
5556The optional fourth parameter is the maximum number of characters the
5557field will accept (-maxlength).
5558
5559=back
5560
5561When the form is processed, you can retrieve the entered filename
3538e1d5 5562by calling param():
54310121 5563
5564 $filename = $query->param('uploaded_file');
5565
3538e1d5
GS
5566Different browsers will return slightly different things for the
5567name. Some browsers return the filename only. Others return the full
5568path to the file, using the path conventions of the user's machine.
5569Regardless, the name returned is always the name of the file on the
5570I<user's> machine, and is unrelated to the name of the temporary file
5571that CGI.pm creates during upload spooling (see below).
54310121 5572
5573The filename returned is also a file handle. You can read the contents
5574of the file using standard Perl file reading calls:
5575
5576 # Read a text file and print it out
5577 while (<$filename>) {
5578 print;
5579 }
5580
5581 # Copy a binary file to somewhere safe
5582 open (OUTFILE,">>/usr/local/web/users/feedback");
5583 while ($bytesread=read($filename,$buffer,1024)) {
5584 print OUTFILE $buffer;
5585 }
5586
3538e1d5
GS
5587However, there are problems with the dual nature of the upload fields.
5588If you C<use strict>, then Perl will complain when you try to use a
5589string as a filehandle. You can get around this by placing the file
5590reading code in a block containing the C<no strict> pragma. More
5591seriously, it is possible for the remote user to type garbage into the
5592upload field, in which case what you get from param() is not a
5593filehandle at all, but a string.
5594
5595To be safe, use the I<upload()> function (new in version 2.47). When
5596called with the name of an upload field, I<upload()> returns a
5597filehandle, or undef if the parameter is not a valid filehandle.
5598
5599 $fh = $query->upload('uploaded_file');
5600 while (<$fh>) {
5601 print;
5602 }
5603
199d4a26
JH
5604In an array context, upload() will return an array of filehandles.
5605This makes it possible to create forms that use the same name for
5606multiple upload fields.
5607
3538e1d5
GS
5608This is the recommended idiom.
5609
54310121 5610When a file is uploaded the browser usually sends along some
5611information along with it in the format of headers. The information
5612usually includes the MIME content type. Future browsers may send
5613other information as well (such as modification date and size). To
5614retrieve this information, call uploadInfo(). It returns a reference to
5615an associative array containing all the document headers.
5616
5617 $filename = $query->param('uploaded_file');
5618 $type = $query->uploadInfo($filename)->{'Content-Type'};
5619 unless ($type eq 'text/html') {
5620 die "HTML FILES ONLY!";
5621 }
5622
5623If you are using a machine that recognizes "text" and "binary" data
5624modes, be sure to understand when and how to use them (see the Camel book).
3538e1d5
GS
5625Otherwise you may find that binary files are corrupted during file
5626uploads.
5627
5628There are occasionally problems involving parsing the uploaded file.
5629This usually happens when the user presses "Stop" before the upload is
5630finished. In this case, CGI.pm will return undef for the name of the
5631uploaded file and set I<cgi_error()> to the string "400 Bad request
5632(malformed multipart POST)". This error message is designed so that
5633you can incorporate it into a status code to be sent to the browser.
5634Example:
5635
5636 $file = $query->upload('uploaded_file');
5637 if (!$file && $query->cgi_error) {
ffd2dff2 5638 print $query->header(-status=>$query->cgi_error);
3538e1d5
GS
5639 exit 0;
5640 }
5641
5642You are free to create a custom HTML page to complain about the error,
5643if you wish.
54310121 5644
2ed511ec
RGS
5645You can set up a callback that will be called whenever a file upload
5646is being read during the form processing. This is much like the
5647UPLOAD_HOOK facility available in Apache::Request, with the exception
5648that the first argument to the callback is an Apache::Upload object,
5649here it's the remote filename.
5650
5651 $q = CGI->new();
5652 $q->upload_hook(\&hook,$data);
5653
5654 sub hook
5655 {
5656 my ($filename, $buffer, $bytes_read, $data) = @_;
5657 print "Read $bytes_read bytes of $filename\n";
5658 }
5659
5660If using the function-oriented interface, call the CGI::upload_hook()
5661method before calling param() or any other CGI functions:
5662
5663 CGI::upload_hook(\&hook,$data);
5664
5665This method is not exported by default. You will have to import it
5666explicitly if you wish to use it without the CGI:: prefix.
5667
199d4a26
JH
5668If you are using CGI.pm on a Windows platform and find that binary
5669files get slightly larger when uploaded but that text files remain the
5670same, then you have forgotten to activate binary mode on the output
5671filehandle. Be sure to call binmode() on any handle that you create
5672to write the uploaded file to disk.
5673
424ec8fa
GS
5674JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5675B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5676recognized. See textfield() for details.
54310121 5677
5678=head2 CREATING A POPUP MENU
5679
5680 print $query->popup_menu('menu_name',
5681 ['eenie','meenie','minie'],
5682 'meenie');
5683
5684 -or-
5685
5686 %labels = ('eenie'=>'your first choice',
5687 'meenie'=>'your second choice',
5688 'minie'=>'your third choice');
188ba755 5689 %attributes = ('eenie'=>{'class'=>'class of first choice'});
54310121 5690 print $query->popup_menu('menu_name',
5691 ['eenie','meenie','minie'],
188ba755 5692 'meenie',\%labels,\%attributes);
54310121 5693
5694 -or (named parameter style)-
5695
5696 print $query->popup_menu(-name=>'menu_name',
5697 -values=>['eenie','meenie','minie'],
5698 -default=>'meenie',
188ba755
JH
5699 -labels=>\%labels,
5700 -attributes=>\%attributes);
54310121 5701
5702popup_menu() creates a menu.
5703
5704=over 4
5705
5706=item 1.
5707
5708The required first argument is the menu's name (-name).
5709
5710=item 2.
5711
5712The required second argument (-values) is an array B<reference>
5713containing the list of menu items in the menu. You can pass the
5714method an anonymous array, as shown in the example, or a reference to
5715a named array, such as "\@foo".
5716
5717=item 3.
5718
5719The optional third parameter (-default) is the name of the default
5720menu choice. If not specified, the first item will be the default.
5721The values of the previous choice will be maintained across queries.
5722
5723=item 4.
5724
5725The optional fourth parameter (-labels) is provided for people who
5726want to use different values for the user-visible label inside the
188ba755 5727popup menu and the value returned to your script. It's a pointer to an
54310121 5728associative array relating menu values to user-visible labels. If you
5729leave this parameter blank, the menu values will be displayed by
5730default. (You can also leave a label undefined if you want to).
5731
188ba755
JH
5732=item 5.
5733
5734The optional fifth parameter (-attributes) is provided to assign
5735any of the common HTML attributes to an individual menu item. It's
5736a pointer to an associative array relating menu values to another
5737associative array with the attribute's name as the key and the
5738attribute's value as the value.
5739
54310121 5740=back
5741
5742When the form is processed, the selected value of the popup menu can
5743be retrieved using:
5744
5745 $popup_menu_value = $query->param('menu_name');
5746
5747JAVASCRIPTING: popup_menu() recognizes the following event handlers:
424ec8fa
GS
5748B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5749B<-onBlur>. See the textfield() section for details on when these
5750handlers are called.
54310121 5751
188ba755
JH
5752=head2 CREATING AN OPTION GROUP
5753
5754Named parameter style
5755
5756 print $query->popup_menu(-name=>'menu_name',
5757 -values=>[qw/eenie meenie minie/,
5758 $q->optgroup(-name=>'optgroup_name',
5759 -values ['moe','catch'],
5760 -attributes=>{'catch'=>{'class'=>'red'}}),
5761 -labels=>{'eenie'=>'one',
5762 'meenie'=>'two',
5763 'minie'=>'three'},
5764 -default=>'meenie');
5765
5766 Old style
5767 print $query->popup_menu('menu_name',
5768 ['eenie','meenie','minie',
5769 $q->optgroup('optgroup_name', ['moe', 'catch'],
5770 {'catch'=>{'class'=>'red'}})],'meenie',
5771 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
5772
5773optgroup creates an option group within a popup menu.
5774
5775=over 4
5776
5777=item 1.
5778
5779The required first argument (B<-name>) is the label attribute of the
5780optgroup and is B<not> inserted in the parameter list of the query.
5781
5782=item 2.
5783
5784The required second argument (B<-values>) is an array reference
5785containing the list of menu items in the menu. You can pass the
5786method an anonymous array, as shown in the example, or a reference
5787to a named array, such as \@foo. If you pass a HASH reference,
5788the keys will be used for the menu values, and the values will be
5789used for the menu labels (see -labels below).
5790
5791=item 3.
5792
5793The optional third parameter (B<-labels>) allows you to pass a reference
5794to an associative array containing user-visible labels for one or more
5795of the menu items. You can use this when you want the user to see one
5796menu string, but have the browser return your program a different one.
5797If you don't specify this, the value string will be used instead
5798("eenie", "meenie" and "minie" in this example). This is equivalent
5799to using a hash reference for the -values parameter.
5800
5801=item 4.
5802
5803An optional fourth parameter (B<-labeled>) can be set to a true value
5804and indicates that the values should be used as the label attribute
5805for each option element within the optgroup.
5806
5807=item 5.
5808
5809An optional fifth parameter (-novals) can be set to a true value and
5810indicates to suppress the val attribut in each option element within
5811the optgroup.
5812
5813See the discussion on optgroup at W3C
5814(http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
5815for details.
5816
5817=item 6.
5818
5819An optional sixth parameter (-attributes) is provided to assign
5820any of the common HTML attributes to an individual menu item. It's
5821a pointer to an associative array relating menu values to another
5822associative array with the attribute's name as the key and the
5823attribute's value as the value.
5824
cff99809
JH
5825=back
5826
54310121 5827=head2 CREATING A SCROLLING LIST
5828
5829 print $query->scrolling_list('list_name',
5830 ['eenie','meenie','minie','moe'],
188ba755 5831 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
54310121 5832 -or-
5833
5834 print $query->scrolling_list('list_name',
5835 ['eenie','meenie','minie','moe'],
5836 ['eenie','moe'],5,'true',
188ba755 5837 \%labels,%attributes);
54310121 5838
5839 -or-
5840
5841 print $query->scrolling_list(-name=>'list_name',
5842 -values=>['eenie','meenie','minie','moe'],
5843 -default=>['eenie','moe'],
5844 -size=>5,
5845 -multiple=>'true',
188ba755
JH
5846 -labels=>\%labels,
5847 -attributes=>\%attributes);
54310121 5848
5849scrolling_list() creates a scrolling list.
5850
5851=over 4
5852
5853=item B<Parameters:>
5854
5855=item 1.
5856
5857The first and second arguments are the list name (-name) and values
5858(-values). As in the popup menu, the second argument should be an
5859array reference.
5860
5861=item 2.
5862
5863The optional third argument (-default) can be either a reference to a
5864list containing the values to be selected by default, or can be a
5865single value to select. If this argument is missing or undefined,
5866then nothing is selected when the list first appears. In the named
5867parameter version, you can use the synonym "-defaults" for this
5868parameter.
5869
5870=item 3.
5871
5872The optional fourth argument is the size of the list (-size).
5873
5874=item 4.
5875
5876The optional fifth argument can be set to true to allow multiple
5877simultaneous selections (-multiple). Otherwise only one selection
5878will be allowed at a time.
5879
5880=item 5.
5881
5882The optional sixth argument is a pointer to an associative array
5883containing long user-visible labels for the list items (-labels).
5884If not provided, the values will be displayed.
5885
188ba755
JH
5886=item 6.
5887
5888The optional sixth parameter (-attributes) is provided to assign
5889any of the common HTML attributes to an individual menu item. It's
5890a pointer to an associative array relating menu values to another
5891associative array with the attribute's name as the key and the
5892attribute's value as the value.
5893
54310121 5894When this form is processed, all selected list items will be returned as
5895a list under the parameter name 'list_name'. The values of the
5896selected items can be retrieved with:
5897
5898 @selected = $query->param('list_name');
5899
5900=back
5901
424ec8fa
GS
5902JAVASCRIPTING: scrolling_list() recognizes the following event
5903handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5904and B<-onBlur>. See textfield() for the description of when these
5905handlers are called.
54310121 5906
5907=head2 CREATING A GROUP OF RELATED CHECKBOXES
5908
5909 print $query->checkbox_group(-name=>'group_name',
5910 -values=>['eenie','meenie','minie','moe'],
5911 -default=>['eenie','moe'],
5912 -linebreak=>'true',
188ba755
JH
5913 -labels=>\%labels,
5914 -attributes=>\%attributes);
54310121 5915
5916 print $query->checkbox_group('group_name',
5917 ['eenie','meenie','minie','moe'],
188ba755
JH
5918 ['eenie','moe'],'true',\%labels,
5919 {'moe'=>{'class'=>'red'}});
54310121 5920
5921 HTML3-COMPATIBLE BROWSERS ONLY:
5922
5923 print $query->checkbox_group(-name=>'group_name',
5924 -values=>['eenie','meenie','minie','moe'],
5925 -rows=2,-columns=>2);
3cb6de81 5926
54310121 5927
5928checkbox_group() creates a list of checkboxes that are related
5929by the same name.
5930
5931=over 4
5932
5933=item B<Parameters:>
5934
5935=item 1.
5936
5937The first and second arguments are the checkbox name and values,
5938respectively (-name and -values). As in the popup menu, the second
5939argument should be an array reference. These values are used for the
5940user-readable labels printed next to the checkboxes as well as for the
5941values passed to your script in the query string.
5942
5943=item 2.
5944
5945The optional third argument (-default) can be either a reference to a
5946list containing the values to be checked by default, or can be a
5947single value to checked. If this argument is missing or undefined,
5948then nothing is selected when the list first appears.
5949
5950=item 3.
5951
5952The optional fourth argument (-linebreak) can be set to true to place
5953line breaks between the checkboxes so that they appear as a vertical
5954list. Otherwise, they will be strung together on a horizontal line.
5955
5956=item 4.
5957
5958The optional fifth argument is a pointer to an associative array
7a2e2cd6 5959relating the checkbox values to the user-visible labels that will
54310121 5960be printed next to them (-labels). If not provided, the values will
5961be used as the default.
5962
5963=item 5.
5964
424ec8fa
GS
5965B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5966the optional parameters B<-rows>, and B<-columns>. These parameters
5967cause checkbox_group() to return an HTML3 compatible table containing
5968the checkbox group formatted with the specified number of rows and
5969columns. You can provide just the -columns parameter if you wish;
5970checkbox_group will calculate the correct number of rows for you.
54310121 5971
188ba755
JH
5972=item 6.
5973
5974The optional sixth parameter (-attributes) is provided to assign
5975any of the common HTML attributes to an individual menu item. It's
5976a pointer to an associative array relating menu values to another
5977associative array with the attribute's name as the key and the
5978attribute's value as the value.
5979
54310121 5980To include row and column headings in the returned table, you
424ec8fa 5981can use the B<-rowheaders> and B<-colheaders> parameters. Both
54310121 5982of these accept a pointer to an array of headings to use.
5983The headings are just decorative. They don't reorganize the
5984interpretation of the checkboxes -- they're still a single named
5985unit.
5986
5987=back
5988
5989When the form is processed, all checked boxes will be returned as
5990a list under the parameter name 'group_name'. The values of the
5991"on" checkboxes can be retrieved with:
5992
5993 @turned_on = $query->param('group_name');
5994
5995The value returned by checkbox_group() is actually an array of button
5996elements. You can capture them and use them within tables, lists,
5997or in other creative ways:
5998
5999 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
6000 &use_in_creative_way(@h);
6001
6002JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
6003parameter. This specifies a JavaScript code fragment or
6004function call to be executed every time the user clicks on
6005any of the buttons in the group. You can retrieve the identity
6006of the particular button clicked on using the "this" variable.
6007
6008=head2 CREATING A STANDALONE CHECKBOX
6009
6010 print $query->checkbox(-name=>'checkbox_name',
ac734d8b 6011 -checked=>1,
54310121 6012 -value=>'ON',
6013 -label=>'CLICK ME');
6014
6015 -or-
6016
6017 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
6018
6019checkbox() is used to create an isolated checkbox that isn't logically
6020related to any others.
6021
6022=over 4
6023
6024=item B<Parameters:>
6025
6026=item 1.
6027
6028The first parameter is the required name for the checkbox (-name). It
6029will also be used for the user-readable label printed next to the
6030checkbox.
6031
6032=item 2.
6033
6034The optional second parameter (-checked) specifies that the checkbox
6035is turned on by default. Synonyms are -selected and -on.
6036
6037=item 3.
6038
6039The optional third parameter (-value) specifies the value of the
6040checkbox when it is checked. If not provided, the word "on" is
6041assumed.
6042
6043=item 4.
6044
6045The optional fourth parameter (-label) is the user-readable label to
6046be attached to the checkbox. If not provided, the checkbox name is
6047used.
6048
6049=back
6050
6051The value of the checkbox can be retrieved using:
6052
6053 $turned_on = $query->param('checkbox_name');
6054
6055JAVASCRIPTING: checkbox() recognizes the B<-onClick>
6056parameter. See checkbox_group() for further details.
6057
6058=head2 CREATING A RADIO BUTTON GROUP
6059
6060 print $query->radio_group(-name=>'group_name',
6061 -values=>['eenie','meenie','minie'],
6062 -default=>'meenie',
6063 -linebreak=>'true',
188ba755
JH
6064 -labels=>\%labels,
6065 -attributes=>\%attributes);
54310121 6066
6067 -or-
6068
6069 print $query->radio_group('group_name',['eenie','meenie','minie'],
188ba755 6070 'meenie','true',\%labels,\%attributes);
54310121 6071
6072
6073 HTML3-COMPATIBLE BROWSERS ONLY:
6074
6075 print $query->radio_group(-name=>'group_name',
6076 -values=>['eenie','meenie','minie','moe'],
6077 -rows=2,-columns=>2);
6078
6079radio_group() creates a set of logically-related radio buttons
6080(turning one member of the group on turns the others off)
6081
6082=over 4
6083
6084=item B<Parameters:>
6085
6086=item 1.
6087
6088The first argument is the name of the group and is required (-name).
6089
6090=item 2.
6091
6092The second argument (-values) is the list of values for the radio
6093buttons. The values and the labels that appear on the page are
6094identical. Pass an array I<reference> in the second argument, either
6095using an anonymous array, as shown, or by referencing a named array as
6096in "\@foo".
6097
6098=item 3.
6099
6100The optional third parameter (-default) is the name of the default
6101button to turn on. If not specified, the first item will be the
6102default. You can provide a nonexistent button name, such as "-" to
6103start up with no buttons selected.
6104
6105=item 4.
6106
6107The optional fourth parameter (-linebreak) can be set to 'true' to put
6108line breaks between the buttons, creating a vertical list.
6109
6110=item 5.
6111
6112The optional fifth parameter (-labels) is a pointer to an associative
6113array relating the radio button values to user-visible labels to be
6114used in the display. If not provided, the values themselves are
6115displayed.
6116
6117=item 6.
6118
6119B<HTML3-compatible browsers> (such as Netscape) can take advantage
6120of the optional
6121parameters B<-rows>, and B<-columns>. These parameters cause
6122radio_group() to return an HTML3 compatible table containing
6123the radio group formatted with the specified number of rows
6124and columns. You can provide just the -columns parameter if you
6125wish; radio_group will calculate the correct number of rows
6126for you.
6127
188ba755
JH
6128=item 6.
6129
6130The optional sixth parameter (-attributes) is provided to assign
6131any of the common HTML attributes to an individual menu item. It's
6132a pointer to an associative array relating menu values to another
6133associative array with the attribute's name as the key and the
6134attribute's value as the value.
6135
54310121 6136To include row and column headings in the returned table, you
6137can use the B<-rowheader> and B<-colheader> parameters. Both
6138of these accept a pointer to an array of headings to use.
6139The headings are just decorative. They don't reorganize the
f610777f 6140interpretation of the radio buttons -- they're still a single named
54310121 6141unit.
6142
6143=back
6144
6145When the form is processed, the selected radio button can
6146be retrieved using:
6147
6148 $which_radio_button = $query->param('group_name');
6149
6150The value returned by radio_group() is actually an array of button
6151elements. You can capture them and use them within tables, lists,
6152or in other creative ways:
6153
6154 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
6155 &use_in_creative_way(@h);
6156
6157=head2 CREATING A SUBMIT BUTTON
6158
6159 print $query->submit(-name=>'button_name',
6160 -value=>'value');
6161
6162 -or-
6163
6164 print $query->submit('button_name','value');
6165
6166submit() will create the query submission button. Every form
6167should have one of these.
6168
6169=over 4
6170
6171=item B<Parameters:>
6172
6173=item 1.
6174
6175The first argument (-name) is optional. You can give the button a
6176name if you have several submission buttons in your form and you want
6177to distinguish between them. The name will also be used as the
6178user-visible label. Be aware that a few older browsers don't deal with this correctly and
6179B<never> send back a value from a button.
6180
6181=item 2.
6182
6183The second argument (-value) is also optional. This gives the button
6184a value that will be passed to your script in the query string.
6185
6186=back
6187
6188You can figure out which button was pressed by using different
6189values for each one:
6190
6191 $which_one = $query->param('button_name');
6192
6193JAVASCRIPTING: radio_group() recognizes the B<-onClick>
6194parameter. See checkbox_group() for further details.
6195
6196=head2 CREATING A RESET BUTTON
6197
6198 print $query->reset
6199
6200reset() creates the "reset" button. Note that it restores the
6201form to its value from the last time the script was called,
6202NOT necessarily to the defaults.
6203
71f3e297
JH
6204Note that this conflicts with the Perl reset() built-in. Use
6205CORE::reset() to get the original reset function.
6206
54310121 6207=head2 CREATING A DEFAULT BUTTON
6208
6209 print $query->defaults('button_label')
6210
6211defaults() creates a button that, when invoked, will cause the
6212form to be completely reset to its defaults, wiping out all the
6213changes the user ever made.
6214
6215=head2 CREATING A HIDDEN FIELD
6216
6217 print $query->hidden(-name=>'hidden_name',
6218 -default=>['value1','value2'...]);
6219
6220 -or-
6221
6222 print $query->hidden('hidden_name','value1','value2'...);
6223
6224hidden() produces a text field that can't be seen by the user. It
6225is useful for passing state variable information from one invocation
6226of the script to the next.
6227
6228=over 4
6229
6230=item B<Parameters:>
6231
6232=item 1.
6233
6234The first argument is required and specifies the name of this
6235field (-name).
6236
6237=item 2.
6238
6239The second argument is also required and specifies its value
6240(-default). In the named parameter style of calling, you can provide
6241a single value here or a reference to a whole list
6242
6243=back
6244
6245Fetch the value of a hidden field this way:
6246
6247 $hidden_value = $query->param('hidden_name');
6248
6249Note, that just like all the other form elements, the value of a
6250hidden field is "sticky". If you want to replace a hidden field with
6251some other values after the script has been called once you'll have to
6252do it manually:
6253
6254 $query->param('hidden_name','new','values','here');
6255
6256=head2 CREATING A CLICKABLE IMAGE BUTTON
6257
6258 print $query->image_button(-name=>'button_name',
6259 -src=>'/source/URL',
6260 -align=>'MIDDLE');
6261
6262 -or-
6263
6264 print $query->image_button('button_name','/source/URL','MIDDLE');
6265
6266image_button() produces a clickable image. When it's clicked on the
6267position of the click is returned to your script as "button_name.x"
6268and "button_name.y", where "button_name" is the name you've assigned
6269to it.
6270
6271JAVASCRIPTING: image_button() recognizes the B<-onClick>
6272parameter. See checkbox_group() for further details.
6273
6274=over 4
6275
6276=item B<Parameters:>
6277
6278=item 1.
6279
6280The first argument (-name) is required and specifies the name of this
6281field.
6282
6283=item 2.
6284
6285The second argument (-src) is also required and specifies the URL
6286
6287=item 3.
6288The third option (-align, optional) is an alignment type, and may be
6289TOP, BOTTOM or MIDDLE
6290
6291=back
6292
6293Fetch the value of the button this way:
6294 $x = $query->param('button_name.x');
6295 $y = $query->param('button_name.y');
6296
6297=head2 CREATING A JAVASCRIPT ACTION BUTTON
6298
6299 print $query->button(-name=>'button_name',
6300 -value=>'user visible label',
6301 -onClick=>"do_something()");
6302
6303 -or-
6304
6305 print $query->button('button_name',"do_something()");
6306
6307button() produces a button that is compatible with Netscape 2.0's
6308JavaScript. When it's pressed the fragment of JavaScript code
6309pointed to by the B<-onClick> parameter will be executed. On
6310non-Netscape browsers this form element will probably not even
6311display.
6312
71f3e297 6313=head1 HTTP COOKIES
54310121 6314
71f3e297
JH
6315Netscape browsers versions 1.1 and higher, and all versions of
6316Internet Explorer, support a so-called "cookie" designed to help
6317maintain state within a browser session. CGI.pm has several methods
6318that support cookies.
54310121 6319
6320A cookie is a name=value pair much like the named parameters in a CGI
6321query string. CGI scripts create one or more cookies and send
6322them to the browser in the HTTP header. The browser maintains a list
6323of cookies that belong to a particular Web server, and returns them
6324to the CGI script during subsequent interactions.
6325
6326In addition to the required name=value pair, each cookie has several
6327optional attributes:
6328
6329=over 4
6330
6331=item 1. an expiration time
6332
6333This is a time/date string (in a special GMT format) that indicates
6334when a cookie expires. The cookie will be saved and returned to your
6335script until this expiration date is reached if the user exits
71f3e297
JH
6336the browser and restarts it. If an expiration date isn't specified, the cookie
6337will remain active until the user quits the browser.
54310121 6338
6339=item 2. a domain
6340
6341This is a partial or complete domain name for which the cookie is
6342valid. The browser will return the cookie to any host that matches
6343the partial domain name. For example, if you specify a domain name
71f3e297 6344of ".capricorn.com", then the browser will return the cookie to
54310121 6345Web servers running on any of the machines "www.capricorn.com",
6346"www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
6347must contain at least two periods to prevent attempts to match
6348on top level domains like ".edu". If no domain is specified, then
6349the browser will only return the cookie to servers on the host the
6350cookie originated from.
6351
6352=item 3. a path
6353
6354If you provide a cookie path attribute, the browser will check it
6355against your script's URL before returning the cookie. For example,
6356if you specify the path "/cgi-bin", then the cookie will be returned
6357to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
6358and "/cgi-bin/customer_service/complain.pl", but not to the script
6359"/cgi-private/site_admin.pl". By default, path is set to "/", which
6360causes the cookie to be sent to any CGI script on your site.
6361
6362=item 4. a "secure" flag
6363
6364If the "secure" attribute is set, the cookie will only be sent to your
6365script if the CGI request is occurring on a secure channel, such as SSL.
6366
6367=back
6368
71f3e297 6369The interface to HTTP cookies is the B<cookie()> method:
54310121 6370
6371 $cookie = $query->cookie(-name=>'sessionID',
6372 -value=>'xyzzy',
6373 -expires=>'+1h',
6374 -path=>'/cgi-bin/database',
6375 -domain=>'.capricorn.org',
6376 -secure=>1);
6377 print $query->header(-cookie=>$cookie);
6378
6379B<cookie()> creates a new cookie. Its parameters include:
6380
6381=over 4
6382
6383=item B<-name>
6384
6385The name of the cookie (required). This can be any string at all.
71f3e297 6386Although browsers limit their cookie names to non-whitespace
54310121 6387alphanumeric characters, CGI.pm removes this restriction by escaping
6388and unescaping cookies behind the scenes.
6389
6390=item B<-value>
6391
6392The value of the cookie. This can be any scalar value,
6393array reference, or even associative array reference. For example,
6394you can store an entire associative array into a cookie this way:
6395
6396 $cookie=$query->cookie(-name=>'family information',
6397 -value=>\%childrens_ages);
6398
6399=item B<-path>
6400
6401The optional partial path for which this cookie will be valid, as described
6402above.
6403
6404=item B<-domain>
6405
6406The optional partial domain for which this cookie will be valid, as described
6407above.
6408
6409=item B<-expires>
6410
6411The optional expiration date for this cookie. The format is as described
6412in the section on the B<header()> method:
6413
6414 "+1h" one hour from now
6415
6416=item B<-secure>
6417
6418If set to true, this cookie will only be used within a secure
6419SSL session.
6420
6421=back
6422
6423The cookie created by cookie() must be incorporated into the HTTP
6424header within the string returned by the header() method:
6425
6426 print $query->header(-cookie=>$my_cookie);
6427
6428To create multiple cookies, give header() an array reference:
6429
6430 $cookie1 = $query->cookie(-name=>'riddle_name',
6431 -value=>"The Sphynx's Question");
6432 $cookie2 = $query->cookie(-name=>'answers',
6433 -value=>\%answers);
6434 print $query->header(-cookie=>[$cookie1,$cookie2]);
6435
03b9648d
JH
6436To retrieve a cookie, request it by name by calling cookie() method
6437without the B<-value> parameter:
54310121 6438
6439 use CGI;
6440 $query = new CGI;
03b9648d
JH
6441 $riddle = $query->cookie('riddle_name');
6442 %answers = $query->cookie('answers');
6443
6444Cookies created with a single scalar value, such as the "riddle_name"
6445cookie, will be returned in that form. Cookies with array and hash
6446values can also be retrieved.
54310121 6447
6448The cookie and CGI namespaces are separate. If you have a parameter
6449named 'answers' and a cookie named 'answers', the values retrieved by
6450param() and cookie() are independent of each other. However, it's
6451simple to turn a CGI parameter into a cookie, and vice-versa:
6452
6453 # turn a CGI parameter into a cookie
6454 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
6455 # vice-versa
6456 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
6457
6458See the B<cookie.cgi> example script for some ideas on how to use
6459cookies effectively.
6460
71f3e297 6461=head1 WORKING WITH FRAMES
54310121 6462
71f3e297
JH
6463It's possible for CGI.pm scripts to write into several browser panels
6464and windows using the HTML 4 frame mechanism. There are three
6465techniques for defining new frames programmatically:
54310121 6466
6467=over 4
6468
6469=item 1. Create a <Frameset> document
6470
6471After writing out the HTTP header, instead of creating a standard
3acbd4f5 6472HTML document using the start_html() call, create a <frameset>
54310121 6473document that defines the frames on the page. Specify your script(s)
6474(with appropriate parameters) as the SRC for each of the frames.
6475
3acbd4f5 6476There is no specific support for creating <frameset> sections
54310121 6477in CGI.pm, but the HTML is very simple to write. See the frame
6478documentation in Netscape's home pages for details
6479
6480 http://home.netscape.com/assist/net_sites/frames.html
6481
6482=item 2. Specify the destination for the document in the HTTP header
6483
6484You may provide a B<-target> parameter to the header() method:
3cb6de81 6485
54310121 6486 print $q->header(-target=>'ResultsWindow');
6487
71f3e297
JH
6488This will tell the browser to load the output of your script into the
6489frame named "ResultsWindow". If a frame of that name doesn't already
6490exist, the browser will pop up a new window and load your script's
6491document into that. There are a number of magic names that you can
6492use for targets. See the frame documents on Netscape's home pages for
6493details.
54310121 6494
3acbd4f5 6495=item 3. Specify the destination for the document in the <form> tag
54310121 6496
6497You can specify the frame to load in the FORM tag itself. With
6498CGI.pm it looks like this:
6499
3d1a2ec4 6500 print $q->start_form(-target=>'ResultsWindow');
54310121 6501
6502When your script is reinvoked by the form, its output will be loaded
6503into the frame named "ResultsWindow". If one doesn't already exist
6504a new window will be created.
6505
6506=back
6507
6508The script "frameset.cgi" in the examples directory shows one way to
6509create pages in which the fill-out form and the response live in
6510side-by-side frames.
6511
7d37aa8e
LS
6512=head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
6513
6514CGI.pm has limited support for HTML3's cascading style sheets (css).
6515To incorporate a stylesheet into your document, pass the
6516start_html() method a B<-style> parameter. The value of this
2ed511ec
RGS
6517parameter may be a scalar, in which case it is treated as the source
6518URL for the stylesheet, or it may be a hash reference. In the latter
7d37aa8e
LS
6519case you should provide the hash with one or more of B<-src> or
6520B<-code>. B<-src> points to a URL where an externally-defined
6521stylesheet can be found. B<-code> points to a scalar value to be
3acbd4f5 6522incorporated into a <style> section. Style definitions in B<-code>
7d37aa8e
LS
6523override similarly-named ones in B<-src>, hence the name "cascading."
6524
424ec8fa
GS
6525You may also specify the type of the stylesheet by adding the optional
6526B<-type> parameter to the hash pointed to by B<-style>. If not
6527specified, the style defaults to 'text/css'.
6528
7d37aa8e
LS
6529To refer to a style within the body of your document, add the
6530B<-class> parameter to any HTML element:
6531
6532 print h1({-class=>'Fancy'},'Welcome to the Party');
6533
6534Or define styles on the fly with the B<-style> parameter:
6535
6536 print h1({-style=>'Color: red;'},'Welcome to Hell');
6537
6538You may also use the new B<span()> element to apply a style to a
6539section of text:
6540
6541 print span({-style=>'Color: red;'},
6542 h1('Welcome to Hell'),
6543 "Where did that handbasket get to?"
6544 );
6545
6546Note that you must import the ":html3" definitions to have the
6547B<span()> method available. Here's a quick and dirty example of using
6548CSS's. See the CSS specification at
6549http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
6550
6551 use CGI qw/:standard :html3/;
6552
6553 #here's a stylesheet incorporated directly into the page
6554 $newStyle=<<END;
6555 <!--
6556 P.Tip {
6557 margin-right: 50pt;
6558 margin-left: 50pt;
6559 color: red;
6560 }
6561 P.Alert {
6562 font-size: 30pt;
6563 font-family: sans-serif;
6564 color: red;
6565 }
6566 -->
6567 END
6568 print header();
6569 print start_html( -title=>'CGI with Style',
6570 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6571 -code=>$newStyle}
6572 );
6573 print h1('CGI with Style'),
6574 p({-class=>'Tip'},
6575 "Better read the cascading style sheet spec before playing with this!"),
6576 span({-style=>'color: magenta'},
6577 "Look Mom, no hands!",
6578 p(),
6579 "Whooo wee!"
6580 );
6581 print end_html;
6582
6b4ac661
JH
6583Pass an array reference to B<-style> in order to incorporate multiple
6584stylesheets into your document.
6585
8f3ccfa2
JH
6586Should you wish to incorporate a verbatim stylesheet that includes
6587arbitrary formatting in the header, you may pass a -verbatim tag to
6588the -style hash, as follows:
6589
6590print $q->start_html (-STYLE => {-verbatim => '@import
6591url("/server-common/css/'.$cssFile.'");',
6592 -src => '/server-common/css/core.css'});
6593</blockquote></pre>
6594
6595
6596This will generate an HTML header that contains this:
6597
6598 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
6599 <style type="text/css">
6600 @import url("/server-common/css/main.css");
6601 </style>
6602
1c87da1d
JH
6603Any additional arguments passed in the -style value will be
6604incorporated into the <link> tag. For example:
6605
6606 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
6607 -media => 'all'});
6608
6609This will give:
6610
6611 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
6612 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
6613
6614<p>
6615
6616To make more complicated <link> tags, use the Link() function
6617and pass it to start_html() in the -head argument, as in:
6618
6619 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
6620 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
6621 print start_html({-head=>\@h})
6622
54310121 6623=head1 DEBUGGING
6624
3d1a2ec4
GS
6625If you are running the script from the command line or in the perl
6626debugger, you can pass the script a list of keywords or
6627parameter=value pairs on the command line or from standard input (you
6628don't have to worry about tricking your script into reading from
6629environment variables). You can pass keywords like this:
54310121 6630
6631 your_script.pl keyword1 keyword2 keyword3
6632
6633or this:
6634
6635 your_script.pl keyword1+keyword2+keyword3
6636
6637or this:
6638
6639 your_script.pl name1=value1 name2=value2
6640
6641or this:
6642
6643 your_script.pl name1=value1&name2=value2
6644
3d1a2ec4
GS
6645To turn off this feature, use the -no_debug pragma.
6646
6647To test the POST method, you may enable full debugging with the -debug
6648pragma. This will allow you to feed newline-delimited name=value
6649pairs to the script on standard input.
54310121 6650
6651When debugging, you can use quotes and backslashes to escape
6652characters in the familiar shell manner, letting you place
6653spaces and other funny characters in your parameter=value
6654pairs:
6655
6656 your_script.pl "name1='I am a long value'" "name2=two\ words"
6657
2ed511ec
RGS
6658Finally, you can set the path info for the script by prefixing the first
6659name/value parameter with the path followed by a question mark (?):
6660
6661 your_script.pl /your/path/here?name1=value1&name2=value2
6662
54310121 6663=head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6664
3d1a2ec4 6665The Dump() method produces a string consisting of all the query's
54310121 6666name/value pairs formatted nicely as a nested list. This is useful
6667for debugging purposes:
6668
3d1a2ec4 6669 print $query->Dump
3cb6de81 6670
54310121 6671
6672Produces something that looks like:
6673
3acbd4f5
JH
6674 <ul>
6675 <li>name1
6676 <ul>
6677 <li>value1
6678 <li>value2
6679 </ul>
6680 <li>name2
6681 <ul>
6682 <li>value1
6683 </ul>
6684 </ul>
54310121 6685
71f3e297
JH
6686As a shortcut, you can interpolate the entire CGI object into a string
6687and it will be replaced with the a nice HTML dump shown above:
54310121 6688
6689 $query=new CGI;
3acbd4f5 6690 print "<h2>Current Values</h2> $query\n";
54310121 6691
6692=head1 FETCHING ENVIRONMENT VARIABLES
6693
6694Some of the more useful environment variables can be fetched
6695through this interface. The methods are as follows:
6696
6697=over 4
6698
71f3e297
JH
6699=item B<Accept()>
6700
6701Return a list of MIME types that the remote browser accepts. If you
6702give this method a single argument corresponding to a MIME type, as in
6703$query->Accept('text/html'), it will return a floating point value
6704corresponding to the browser's preference for this type from 0.0
6705(don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
6706list are handled correctly.
54310121 6707
71f3e297
JH
6708Note that the capitalization changed between version 2.43 and 2.44 in
6709order to avoid conflict with Perl's accept() function.
54310121 6710
6711=item B<raw_cookie()>
6712
424ec8fa 6713Returns the HTTP_COOKIE variable, an HTTP extension implemented by
71f3e297
JH
6714Netscape browsers version 1.1 and higher, and all versions of Internet
6715Explorer. Cookies have a special format, and this method call just
6716returns the raw form (?cookie dough). See cookie() for ways of
6717setting and retrieving cooked cookies.
424ec8fa
GS
6718
6719Called with no parameters, raw_cookie() returns the packed cookie
6720structure. You can separate it into individual cookies by splitting
6721on the character sequence "; ". Called with the name of a cookie,
6722retrieves the B<unescaped> form of the cookie. You can use the
6723regular cookie() method to get the names, or use the raw_fetch()
6724method from the CGI::Cookie module.
54310121 6725
6726=item B<user_agent()>
6727
6728Returns the HTTP_USER_AGENT variable. If you give
6729this method a single argument, it will attempt to
6730pattern match on it, allowing you to do something
6731like $query->user_agent(netscape);
6732
6733=item B<path_info()>
6734
6735Returns additional path information from the script URL.
6b4ac661
JH
6736E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6737$query->path_info() returning "/additional/stuff".
54310121 6738
6739NOTE: The Microsoft Internet Information Server
6740is broken with respect to additional path information. If
6741you use the Perl DLL library, the IIS server will attempt to
6742execute the additional path information as a Perl script.
6743If you use the ordinary file associations mapping, the
6744path information will be present in the environment,
6745but incorrect. The best thing to do is to avoid using additional
6746path information in CGI scripts destined for use with IIS.
6747
6748=item B<path_translated()>
6749
6750As per path_info() but returns the additional
6751path information translated into a physical path, e.g.
6752"/usr/local/etc/httpd/htdocs/additional/stuff".
6753
6754The Microsoft IIS is broken with respect to the translated
6755path as well.
6756
6757=item B<remote_host()>
6758
6759Returns either the remote host name or IP address.
6760if the former is unavailable.
6761
6762=item B<script_name()>
6763Return the script name as a partial URL, for self-refering
6764scripts.
6765
6766=item B<referer()>
6767
6768Return the URL of the page the browser was viewing
6769prior to fetching your script. Not available for all
6770browsers.
6771
6772=item B<auth_type ()>
6773
6774Return the authorization/verification method in use for this
6775script, if any.
6776
6777=item B<server_name ()>
6778
6779Returns the name of the server, usually the machine's host
6780name.
6781
6782=item B<virtual_host ()>
6783
6784When using virtual hosts, returns the name of the host that
6785the browser attempted to contact
6786
03b9648d
JH
6787=item B<server_port ()>
6788
6789Return the port that the server is listening on.
6790
2ed511ec
RGS
6791=item B<virtual_port ()>
6792
6793Like server_port() except that it takes virtual hosts into account.
6794Use this when running with virtual hosts.
6795
54310121 6796=item B<server_software ()>
6797
6798Returns the server software and version number.
6799
6800=item B<remote_user ()>
6801
6802Return the authorization/verification name used for user
6803verification, if this script is protected.
6804
6805=item B<user_name ()>
6806
71f3e297
JH
6807Attempt to obtain the remote user's name, using a variety of different
6808techniques. This only works with older browsers such as Mosaic.
6809Newer browsers do not report the user name for privacy reasons!
54310121 6810
6811=item B<request_method()>
6812
6813Returns the method used to access your script, usually
6814one of 'POST', 'GET' or 'HEAD'.
6815
3538e1d5
GS
6816=item B<content_type()>
6817
6818Returns the content_type of data submitted in a POST, generally
6819multipart/form-data or application/x-www-form-urlencoded
6820
6821=item B<http()>
6822
6823Called with no arguments returns the list of HTTP environment
6824variables, including such things as HTTP_USER_AGENT,
6825HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6826like-named HTTP header fields in the request. Called with the name of
6827an HTTP header field, returns its value. Capitalization and the use
6828of hyphens versus underscores are not significant.
6829
6830For example, all three of these examples are equivalent:
6831
6832 $requested_language = $q->http('Accept-language');
6833 $requested_language = $q->http('Accept_language');
6834 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6835
6836=item B<https()>
6837
6838The same as I<http()>, but operates on the HTTPS environment variables
6839present when the SSL protocol is in effect. Can be used to determine
6840whether SSL is turned on.
6841
54310121 6842=back
6843
424ec8fa 6844=head1 USING NPH SCRIPTS
54310121 6845
424ec8fa
GS
6846NPH, or "no-parsed-header", scripts bypass the server completely by
6847sending the complete HTTP header directly to the browser. This has
6848slight performance benefits, but is of most use for taking advantage
6849of HTTP extensions that are not directly supported by your server,
6850such as server push and PICS headers.
54310121 6851
424ec8fa
GS
6852Servers use a variety of conventions for designating CGI scripts as
6853NPH. Many Unix servers look at the beginning of the script's name for
6854the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6855Internet Information Server, in contrast, try to decide whether a
6856program is an NPH script by examining the first line of script output.
54310121 6857
54310121 6858
424ec8fa
GS
6859CGI.pm supports NPH scripts with a special NPH mode. When in this
6860mode, CGI.pm will output the necessary extra header information when
6861the header() and redirect() methods are
6862called.
54310121 6863
69c89ae7
JH
6864The Microsoft Internet Information Server requires NPH mode. As of
6865version 2.30, CGI.pm will automatically detect when the script is
6866running under IIS and put itself into this mode. You do not need to
6867do this manually, although it won't hurt anything if you do. However,
6868note that if you have applied Service Pack 6, much of the
6869functionality of NPH scripts, including the ability to redirect while
6870setting a cookie, b<do not work at all> on IIS without a special patch
6871from Microsoft. See
6872http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
6873Non-Parsed Headers Stripped From CGI Applications That Have nph-
6874Prefix in Name.
54310121 6875
424ec8fa 6876=over 4
54310121 6877
424ec8fa 6878=item In the B<use> statement
54310121 6879
424ec8fa
GS
6880Simply add the "-nph" pragmato the list of symbols to be imported into
6881your script:
54310121 6882
424ec8fa 6883 use CGI qw(:standard -nph)
54310121 6884
424ec8fa 6885=item By calling the B<nph()> method:
54310121 6886
424ec8fa 6887Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
54310121 6888
424ec8fa 6889 CGI->nph(1)
54310121 6890
551e1d92
RB
6891=item By using B<-nph> parameters
6892
6893in the B<header()> and B<redirect()> statements:
54310121 6894
424ec8fa 6895 print $q->header(-nph=>1);
54310121 6896
424ec8fa 6897=back
54310121 6898
424ec8fa
GS
6899=head1 Server Push
6900
ba056755 6901CGI.pm provides four simple functions for producing multipart
424ec8fa
GS
6902documents of the type needed to implement server push. These
6903functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6904import these into your namespace, you must import the ":push" set.
6905You are also advised to put the script into NPH mode and to set $| to
69061 to avoid buffering problems.
6907
6908Here is a simple script that demonstrates server push:
6909
6910 #!/usr/local/bin/perl
6911 use CGI qw/:push -nph/;
6912 $| = 1;
ba056755
JH
6913 print multipart_init(-boundary=>'----here we go!');
6914 foreach (0 .. 4) {
424ec8fa 6915 print multipart_start(-type=>'text/plain'),
ba056755
JH
6916 "The current time is ",scalar(localtime),"\n";
6917 if ($_ < 4) {
6918 print multipart_end;
6919 } else {
6920 print multipart_final;
6921 }
424ec8fa
GS
6922 sleep 1;
6923 }
54310121 6924
424ec8fa 6925This script initializes server push by calling B<multipart_init()>.
ba056755
JH
6926It then enters a loop in which it begins a new multipart section by
6927calling B<multipart_start()>, prints the current local time,
424ec8fa 6928and ends a multipart section with B<multipart_end()>. It then sleeps
ba056755
JH
6929a second, and begins again. On the final iteration, it ends the
6930multipart section with B<multipart_final()> rather than with
6931B<multipart_end()>.
54310121 6932
424ec8fa 6933=over 4
54310121 6934
424ec8fa 6935=item multipart_init()
3cb6de81 6936
424ec8fa 6937 multipart_init(-boundary=>$boundary);
54310121 6938
424ec8fa
GS
6939Initialize the multipart system. The -boundary argument specifies
6940what MIME boundary string to use to separate parts of the document.
6941If not provided, CGI.pm chooses a reasonable boundary for you.
54310121 6942
424ec8fa 6943=item multipart_start()
54310121 6944
424ec8fa 6945 multipart_start(-type=>$type)
54310121 6946
424ec8fa
GS
6947Start a new part of the multipart document using the specified MIME
6948type. If not specified, text/html is assumed.
54310121 6949
424ec8fa 6950=item multipart_end()
54310121 6951
424ec8fa 6952 multipart_end()
54310121 6953
424ec8fa 6954End a part. You must remember to call multipart_end() once for each
ba056755
JH
6955multipart_start(), except at the end of the last part of the multipart
6956document when multipart_final() should be called instead of multipart_end().
6957
6958=item multipart_final()
6959
6960 multipart_final()
6961
6962End all parts. You should call multipart_final() rather than
6963multipart_end() at the end of the last part of the multipart document.
54310121 6964
424ec8fa 6965=back
54310121 6966
424ec8fa
GS
6967Users interested in server push applications should also have a look
6968at the CGI::Push module.
54310121 6969
ba056755
JH
6970Only Netscape Navigator supports server push. Internet Explorer
6971browsers do not.
6972
424ec8fa 6973=head1 Avoiding Denial of Service Attacks
54310121 6974
424ec8fa
GS
6975A potential problem with CGI.pm is that, by default, it attempts to
6976process form POSTings no matter how large they are. A wily hacker
6977could attack your site by sending a CGI script a huge POST of many
6978megabytes. CGI.pm will attempt to read the entire POST into a
6979variable, growing hugely in size until it runs out of memory. While
6980the script attempts to allocate the memory the system may slow down
6981dramatically. This is a form of denial of service attack.
54310121 6982
424ec8fa
GS
6983Another possible attack is for the remote user to force CGI.pm to
6984accept a huge file upload. CGI.pm will accept the upload and store it
6985in a temporary directory even if your script doesn't expect to receive
6986an uploaded file. CGI.pm will delete the file automatically when it
6987terminates, but in the meantime the remote user may have filled up the
6988server's disk space, causing problems for other programs.
54310121 6989
424ec8fa
GS
6990The best way to avoid denial of service attacks is to limit the amount
6991of memory, CPU time and disk space that CGI scripts can use. Some Web
6992servers come with built-in facilities to accomplish this. In other
6993cases, you can use the shell I<limit> or I<ulimit>
6994commands to put ceilings on CGI resource usage.
54310121 6995
54310121 6996
424ec8fa
GS
6997CGI.pm also has some simple built-in protections against denial of
6998service attacks, but you must activate them before you can use them.
6999These take the form of two global variables in the CGI name space:
54310121 7000
424ec8fa 7001=over 4
54310121 7002
424ec8fa 7003=item B<$CGI::POST_MAX>
54310121 7004
424ec8fa
GS
7005If set to a non-negative integer, this variable puts a ceiling
7006on the size of POSTings, in bytes. If CGI.pm detects a POST
7007that is greater than the ceiling, it will immediately exit with an error
7008message. This value will affect both ordinary POSTs and
7009multipart POSTs, meaning that it limits the maximum size of file
7010uploads as well. You should set this to a reasonably high
7011value, such as 1 megabyte.
54310121 7012
424ec8fa 7013=item B<$CGI::DISABLE_UPLOADS>
54310121 7014
424ec8fa
GS
7015If set to a non-zero value, this will disable file uploads
7016completely. Other fill-out form values will work as usual.
54310121 7017
7018=back
7019
424ec8fa 7020You can use these variables in either of two ways.
54310121 7021
424ec8fa 7022=over 4
54310121 7023
424ec8fa 7024=item B<1. On a script-by-script basis>
54310121 7025
424ec8fa 7026Set the variable at the top of the script, right after the "use" statement:
54310121 7027
424ec8fa
GS
7028 use CGI qw/:standard/;
7029 use CGI::Carp 'fatalsToBrowser';
7030 $CGI::POST_MAX=1024 * 100; # max 100K posts
7031 $CGI::DISABLE_UPLOADS = 1; # no uploads
54310121 7032
424ec8fa 7033=item B<2. Globally for all scripts>
54310121 7034
424ec8fa
GS
7035Open up CGI.pm, find the definitions for $POST_MAX and
7036$DISABLE_UPLOADS, and set them to the desired values. You'll
7037find them towards the top of the file in a subroutine named
7038initialize_globals().
54310121 7039
424ec8fa 7040=back
54310121 7041
3538e1d5
GS
7042An attempt to send a POST larger than $POST_MAX bytes will cause
7043I<param()> to return an empty CGI parameter list. You can test for
7044this event by checking I<cgi_error()>, either after you create the CGI
7045object or, if you are using the function-oriented interface, call
7046<param()> for the first time. If the POST was intercepted, then
7047cgi_error() will return the message "413 POST too large".
7048
7049This error message is actually defined by the HTTP protocol, and is
7050designed to be returned to the browser as the CGI script's status
7051 code. For example:
7052
7053 $uploaded_file = param('upload');
7054 if (!$uploaded_file && cgi_error()) {
7055 print header(-status=>cgi_error());
7056 exit 0;
7057 }
7058
7059However it isn't clear that any browser currently knows what to do
7060with this status code. It might be better just to create an
7061HTML page that warns the user of the problem.
54310121 7062
424ec8fa 7063=head1 COMPATIBILITY WITH CGI-LIB.PL
54310121 7064
3538e1d5
GS
7065To make it easier to port existing programs that use cgi-lib.pl the
7066compatibility routine "ReadParse" is provided. Porting is simple:
54310121 7067
424ec8fa
GS
7068OLD VERSION
7069 require "cgi-lib.pl";
7070 &ReadParse;
7071 print "The value of the antique is $in{antique}.\n";
54310121 7072
424ec8fa
GS
7073NEW VERSION
7074 use CGI;
7075 CGI::ReadParse
7076 print "The value of the antique is $in{antique}.\n";
54310121 7077
424ec8fa
GS
7078CGI.pm's ReadParse() routine creates a tied variable named %in,
7079which can be accessed to obtain the query variables. Like
7080ReadParse, you can also provide your own variable. Infrequently
7081used features of ReadParse, such as the creation of @in and $in
7082variables, are not supported.
54310121 7083
424ec8fa
GS
7084Once you use ReadParse, you can retrieve the query object itself
7085this way:
54310121 7086
424ec8fa
GS
7087 $q = $in{CGI};
7088 print $q->textfield(-name=>'wow',
7089 -value=>'does this really work?');
54310121 7090
424ec8fa
GS
7091This allows you to start using the more interesting features
7092of CGI.pm without rewriting your old scripts from scratch.
54310121 7093
7094=head1 AUTHOR INFORMATION
7095
71f3e297
JH
7096Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
7097
7098This library is free software; you can redistribute it and/or modify
7099it under the same terms as Perl itself.
54310121 7100
71f3e297
JH
7101Address bug reports and comments to: lstein@cshl.org. When sending
7102bug reports, please provide the version of CGI.pm, the version of
7103Perl, the name and version of your Web server, and the name and
7104version of the operating system you are using. If the problem is even
7105remotely browser dependent, please provide information about the
7106affected browers as well.
54310121 7107
7108=head1 CREDITS
7109
7110Thanks very much to:
7111
7112=over 4
7113
7114=item Matt Heffron (heffron@falstaff.css.beckman.com)
7115
7116=item James Taylor (james.taylor@srs.gov)
7117
7118=item Scott Anguish <sanguish@digifix.com>
7119
7120=item Mike Jewell (mlj3u@virginia.edu)
7121
7122=item Timothy Shimmin (tes@kbs.citri.edu.au)
7123
7124=item Joergen Haegg (jh@axis.se)
7125
71f3e297 7126=item Laurent Delfosse (delfosse@delfosse.com)
54310121 7127
7128=item Richard Resnick (applepi1@aol.com)
7129
7130=item Craig Bishop (csb@barwonwater.vic.gov.au)
7131
7132=item Tony Curtis (tc@vcpc.univie.ac.at)
7133
7134=item Tim Bunce (Tim.Bunce@ig.co.uk)
7135
7136=item Tom Christiansen (tchrist@convex.com)
7137
7138=item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
7139
7140=item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
7141
7142=item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
7143
7144=item Stephen Dahmen (joyfire@inxpress.net)
7145
7146=item Ed Jordan (ed@fidalgo.net)
7147
7148=item David Alan Pisoni (david@cnation.com)
7149
424ec8fa
GS
7150=item Doug MacEachern (dougm@opengroup.org)
7151
7152=item Robin Houston (robin@oneworld.org)
7153
54310121 7154=item ...and many many more...
7155
7156for suggestions and bug fixes.
7157
7158=back
7159
7160=head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
7161
7162
7163 #!/usr/local/bin/perl
3cb6de81 7164
54310121 7165 use CGI;
3cb6de81 7166
54310121 7167 $query = new CGI;
7168
7169 print $query->header;
7170 print $query->start_html("Example CGI.pm Form");
3acbd4f5 7171 print "<h1> Example CGI.pm Form</h1>\n";
54310121 7172 &print_prompt($query);
7173 &do_work($query);
7174 &print_tail;
7175 print $query->end_html;
3cb6de81 7176
54310121 7177 sub print_prompt {
7178 my($query) = @_;
3cb6de81 7179
3d1a2ec4 7180 print $query->start_form;
3acbd4f5 7181 print "<em>What's your name?</em><br>";
54310121 7182 print $query->textfield('name');
7183 print $query->checkbox('Not my real name');
3cb6de81 7184
3acbd4f5 7185 print "<p><em>Where can you find English Sparrows?</em><br>";
54310121 7186 print $query->checkbox_group(
7187 -name=>'Sparrow locations',
7188 -values=>[England,France,Spain,Asia,Hoboken],
7189 -linebreak=>'yes',
7190 -defaults=>[England,Asia]);
3cb6de81 7191
3acbd4f5 7192 print "<p><em>How far can they fly?</em><br>",
54310121 7193 $query->radio_group(
7194 -name=>'how far',
7195 -values=>['10 ft','1 mile','10 miles','real far'],
7196 -default=>'1 mile');
3cb6de81 7197
3acbd4f5 7198 print "<p><em>What's your favorite color?</em> ";
54310121 7199 print $query->popup_menu(-name=>'Color',
7200 -values=>['black','brown','red','yellow'],
7201 -default=>'red');
3cb6de81 7202
54310121 7203 print $query->hidden('Reference','Monty Python and the Holy Grail');
3cb6de81 7204
3acbd4f5 7205 print "<p><em>What have you got there?</em><br>";
54310121 7206 print $query->scrolling_list(
7207 -name=>'possessions',
7208 -values=>['A Coconut','A Grail','An Icon',
7209 'A Sword','A Ticket'],
7210 -size=>5,
7211 -multiple=>'true');
3cb6de81 7212
3acbd4f5 7213 print "<p><em>Any parting comments?</em><br>";
54310121 7214 print $query->textarea(-name=>'Comments',
7215 -rows=>10,
7216 -columns=>50);
3cb6de81 7217
3acbd4f5 7218 print "<p>",$query->reset;
54310121 7219 print $query->submit('Action','Shout');
7220 print $query->submit('Action','Scream');
7221 print $query->endform;
3acbd4f5 7222 print "<hr>\n";
54310121 7223 }
3cb6de81 7224
54310121 7225 sub do_work {
7226 my($query) = @_;
7227 my(@values,$key);
7228
3acbd4f5 7229 print "<h2>Here are the current settings in this form</h2>";
54310121 7230
7231 foreach $key ($query->param) {
3acbd4f5 7232 print "<strong>$key</strong> -> ";
54310121 7233 @values = $query->param($key);
3acbd4f5 7234 print join(", ",@values),"<br>\n";
54310121 7235 }
7236 }
3cb6de81 7237
54310121 7238 sub print_tail {
7239 print <<END;
3acbd4f5
JH
7240 <hr>
7241 <address>Lincoln D. Stein</address><br>
7242 <a href="/">Home Page</a>
54310121 7243 END
7244 }
7245
7246=head1 BUGS
7247
188ba755 7248Please report them.
54310121 7249
7250=head1 SEE ALSO
7251
b2d0d414 7252L<CGI::Carp>, L<CGI::Fast>, L<CGI::Pretty>
54310121 7253
7254=cut
7255