5 # See the bottom of this file for the POD documentation. Search for the
8 # You can run this file through either pod2man or pod2html to produce pretty
9 # documentation in manual or html file format (these utilities are part of the
10 # Perl 5 distribution).
12 # Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
13 # It may be used and modified freely, but I do request that this copyright
14 # notice remain attached to the file. You may modify this module as you
15 # wish, but if you redistribute a modified version, please attach a note
16 # listing the modifications you have made.
18 # The most recent version and complete docs are available at:
19 # http://stein.cshl.org/WWW/software/CGI/
21 $CGI::revision = '$Id: CGI.pm,v 1.257 2008/08/06 14:01:06 lstein Exp $';
24 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
26 # $CGITempFile::TMPDIRECTORY = '/usr/tmp';
27 use CGI::Util qw(rearrange make_attributes unescape escape expires ebcdic2ascii ascii2ebcdic);
29 #use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 # 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
32 use constant XHTML_DTD => ['-//W3C//DTD XHTML 1.0 Transitional//EN',
33 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'];
37 $TAINTED = substr("$0$^X",0,0);
40 $MOD_PERL = 0; # no mod_perl by default
43 $POST_MAX = -1; # no limit to uploaded files
49 # >>>>> Here are some globals that you might want to adjust <<<<<<
50 sub initialize_globals {
51 # Set this to 1 to enable copious autoloader debugging messages
54 # Set this to 1 to generate XTML-compatible output
57 # Change this to the preferred DTD to print in start_html()
58 # or use default_dtd('text of DTD to use');
59 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
60 'http://www.w3.org/TR/html4/loose.dtd' ] ;
62 # Set this to 1 to enable NOSTICKY scripts
64 # 1) use CGI qw(-nosticky)
65 # 2) $CGI::nosticky(1)
68 # Set this to 1 to enable NPH scripts
72 # 3) print header(-nph=>1)
75 # Set this to 1 to enable debugging from @ARGV
76 # Set to 2 to enable debugging from STDIN
79 # Set this to 1 to make the temporary files created
80 # during file uploads safe from prying eyes
82 # 1) use CGI qw(:private_tempfiles)
83 # 2) CGI::private_tempfiles(1);
84 $PRIVATE_TEMPFILES = 0;
86 # Set this to 1 to generate automatic tab indexes
89 # Set this to 1 to cause files uploaded in multipart documents
90 # to be closed, instead of caching the file handle
92 # 1) use CGI qw(:close_upload_files)
93 # 2) $CGI::close_upload_files(1);
94 # Uploads with many files run out of file handles.
95 # Also, for performance, since the file is already on disk,
96 # it can just be renamed, instead of read and written.
97 $CLOSE_UPLOAD_FILES = 0;
99 # Automatically determined -- don't change
102 # Change this to 1 to suppress redundant HTTP headers
105 # separate the name=value pairs by semicolons rather than ampersands
106 $USE_PARAM_SEMICOLONS = 1;
108 # Do not include undefined params parsed from query string
109 # use CGI qw(-no_undef_params);
110 $NO_UNDEF_PARAMS = 0;
112 # return everything as utf-8
115 # Other globals that you shouldn't worry about.
118 $DTD_PUBLIC_IDENTIFIER = "";
121 undef $QUERY_CHARSET;
122 undef %QUERY_FIELDNAMES;
123 undef %QUERY_TMPFILES;
125 # prevent complaints by mod_perl
129 # ------------------ START OF THE LIBRARY ------------
131 *end_form = \&endform;
134 initialize_globals();
136 # FIGURE OUT THE OS WE'RE RUNNING UNDER
137 # Some systems support the $^O variable. If not
138 # available then require() the Config library
142 $OS = $Config::Config{'osname'};
145 if ($OS =~ /^MSWin/i) {
147 } elsif ($OS =~ /^VMS/i) {
149 } elsif ($OS =~ /^dos/i) {
151 } elsif ($OS =~ /^MacOS/i) {
153 } elsif ($OS =~ /^os2/i) {
155 } elsif ($OS =~ /^epoc/i) {
157 } elsif ($OS =~ /^cygwin/i) {
163 # Some OS logic. Binary mode enabled on DOS, NT and VMS
164 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin|CYGWIN)/;
166 # This is the default class for the CGI object to use when all else fails.
167 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
169 # This is where to look for autoloaded routines.
170 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
172 # The path separator is a slash, backslash or semicolon, depending
175 UNIX => '/', OS2 => '\\', EPOC => '/', CYGWIN => '/',
176 WINDOWS => '\\', DOS => '\\', MACINTOSH => ':', VMS => '/'
179 # This no longer seems to be necessary
180 # Turn on NPH scripts by default when running under IIS server!
181 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
182 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
184 # Turn on special checking for Doug MacEachern's modperl
185 if (exists $ENV{MOD_PERL}) {
186 # mod_perl handlers may run system() on scripts using CGI.pm;
187 # Make sure so we don't get fooled by inherited $ENV{MOD_PERL}
188 if (exists $ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
190 require Apache2::Response;
191 require Apache2::RequestRec;
192 require Apache2::RequestUtil;
193 require Apache2::RequestIO;
201 # Turn on special checking for ActiveState's PerlEx
202 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
204 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
205 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
206 # and sometimes CR). The most popular VMS web server
207 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
208 # use ASCII, so \015\012 means something different. I find this all
210 $EBCDIC = "\t" ne "\011";
219 if ($needs_binmode) {
220 $CGI::DefaultClass->binmode(\*main::STDOUT);
221 $CGI::DefaultClass->binmode(\*main::STDIN);
222 $CGI::DefaultClass->binmode(\*main::STDERR);
226 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
227 tt u i b blockquote pre img a address cite samp dfn html head
228 base body Link nextid title meta kbd start_html end_html
229 input Select option comment charset escapeHTML/],
230 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param nobr
231 embed basefont style span layer ilayer font frameset frame script small big Area Map/],
232 ':html4'=>[qw/abbr acronym bdo col colgroup del fieldset iframe
233 ins label legend noframes noscript object optgroup Q
235 ':netscape'=>[qw/blink fontsize center/],
236 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
237 submit reset defaults radio_group popup_menu button autoEscape
238 scrolling_list image_button start_form end_form startform endform
239 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
240 ':cgi'=>[qw/param upload path_info path_translated request_uri url self_url script_name
242 raw_cookie request_method query_string Accept user_agent remote_host content_type
243 remote_addr referer server_name server_software server_port server_protocol virtual_port
244 virtual_host remote_ident auth_type http append
245 save_parameters restore_parameters param_fetch
246 remote_user user_name header redirect import_names put
247 Delete Delete_all url_param cgi_error/],
248 ':ssl' => [qw/https/],
249 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
250 ':html' => [qw/:html2 :html3 :html4 :netscape/],
251 ':standard' => [qw/:html2 :html3 :html4 :form :cgi/],
252 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
253 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal :html4/]
256 # Custom 'can' method for both autoloaded and non-autoloaded subroutines.
257 # Author: Cees Hek <cees@sitesuite.com.au>
260 my($class, $method) = @_;
262 # See if UNIVERSAL::can finds it.
264 if (my $func = $class -> SUPER::can($method) ){
268 # Try to compile the function.
271 # _compile looks at $AUTOLOAD for the function name.
273 local $AUTOLOAD = join "::", $class, $method;
277 # Now that the function is loaded (if it exists)
278 # just use UNIVERSAL::can again to do the work.
280 return $class -> SUPER::can($method);
283 # to import symbols into caller
287 # This causes modules to clash.
291 $self->_setup_symbols(@_);
292 my ($callpack, $callfile, $callline) = caller;
294 # To allow overriding, search through the packages
295 # Till we find one in which the correct subroutine is defined.
296 my @packages = ($self,@{"$self\:\:ISA"});
297 foreach $sym (keys %EXPORT) {
299 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
300 foreach $pck (@packages) {
301 if (defined(&{"$pck\:\:$sym"})) {
306 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
312 $pack->_setup_symbols('-compile',@_);
317 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
319 return ($tag) unless $EXPORT_TAGS{$tag};
320 foreach (@{$EXPORT_TAGS{$tag}}) {
321 push(@r,&expand_tags($_));
327 # The new routine. This will check the current environment
328 # for an existing query string, and initialize itself, if so.
331 my($class,@initializer) = @_;
334 bless $self,ref $class || $class || $DefaultClass;
336 # always use a tempfile
337 $self->{'use_tempfile'} = 1;
339 if (ref($initializer[0])
340 && (UNIVERSAL::isa($initializer[0],'Apache')
342 UNIVERSAL::isa($initializer[0],'Apache2::RequestRec')
344 $self->r(shift @initializer);
346 if (ref($initializer[0])
347 && (UNIVERSAL::isa($initializer[0],'CODE'))) {
348 $self->upload_hook(shift @initializer, shift @initializer);
349 $self->{'use_tempfile'} = shift @initializer if (@initializer > 0);
352 if ($MOD_PERL == 1) {
353 $self->r(Apache->request) unless $self->r;
355 $r->register_cleanup(\&CGI::_reset_globals);
356 $self->_setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
359 # XXX: once we have the new API
360 # will do a real PerlOptions -SetupEnv check
361 $self->r(Apache2::RequestUtil->request) unless $self->r;
363 $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
364 $r->pool->cleanup_register(\&CGI::_reset_globals);
365 $self->_setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
369 $self->_reset_globals if $PERLEX;
370 $self->init(@initializer);
374 # We provide a DESTROY method so that we can ensure that
375 # temporary files are closed (via Fh->DESTROY) before they
376 # are unlinked (via CGITempFile->DESTROY) because it is not
377 # possible to unlink an open file on Win32. We explicitly
378 # call DESTROY on each, rather than just undefing them and
379 # letting Perl DESTROY them by garbage collection, in case the
380 # user is still holding any reference to them as well.
383 if ($OS eq 'WINDOWS') {
384 foreach my $href (values %{$self->{'.tmpfiles'}}) {
385 $href->{hndl}->DESTROY if defined $href->{hndl};
386 $href->{name}->DESTROY if defined $href->{name};
393 my $r = $self->{'.r'};
394 $self->{'.r'} = shift if @_;
400 if (ref $_[0] eq 'CODE') {
401 $CGI::Q = $self = $CGI::DefaultClass->new(@_);
405 my ($hook,$data,$use_tempfile) = @_;
406 $self->{'.upload_hook'} = $hook;
407 $self->{'.upload_data'} = $data;
408 $self->{'use_tempfile'} = $use_tempfile if defined $use_tempfile;
412 # Returns the value(s)of a named parameter.
413 # If invoked in a list context, returns the
414 # entire list. Otherwise returns the first
415 # member of the list.
416 # If name is not provided, return a list of all
417 # the known parameters names available.
418 # If more than one argument is provided, the
419 # second and subsequent arguments are used to
420 # set the value of the parameter.
423 my($self,@p) = self_or_default(@_);
424 return $self->all_parameters unless @p;
425 my($name,$value,@other);
427 # For compatibility between old calling style and use_named_parameters() style,
428 # we have to special case for a single parameter present.
430 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
433 if (substr($p[0],0,1) eq '-') {
434 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
436 foreach ($value,@other) {
437 push(@values,$_) if defined($_);
440 # If values is provided, then we set it.
441 if (@values or defined $value) {
442 $self->add_parameter($name);
443 $self->{param}{$name}=[@values];
449 return unless defined($name) && $self->{param}{$name};
451 my @result = @{$self->{param}{$name}};
454 eval "require Encode; 1;" unless Encode->can('decode'); # bring in these functions
455 @result = map {ref $_ ? $_ : Encode::decode(utf8=>$_) } @result;
458 return wantarray ? @result : $result[0];
461 sub self_or_default {
462 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
463 unless (defined($_[0]) &&
464 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
466 $Q = $CGI::DefaultClass->new unless defined($Q);
469 return wantarray ? @_ : $Q;
473 local $^W=0; # prevent a warning
474 if (defined($_[0]) &&
475 (substr(ref($_[0]),0,3) eq 'CGI'
476 || UNIVERSAL::isa($_[0],'CGI'))) {
479 return ($DefaultClass,@_);
483 ########################################
484 # THESE METHODS ARE MORE OR LESS PRIVATE
485 # GO TO THE __DATA__ SECTION TO SEE MORE
487 ########################################
489 # Initialize the query object from the environment.
490 # If a parameter list is found, this object will be set
491 # to an associative array in which parameter names are keys
492 # and the values are stored as lists
493 # If a keyword list is found, this method creates a bogus
494 # parameter list with the single parameter 'keywords'.
498 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
502 my $initializer = shift; # for backward compatibility
505 # set autoescaping on by default
506 $self->{'escape'} = 1;
508 # if we get called more than once, we want to initialize
509 # ourselves from the original query (which may be gone
510 # if it was read from STDIN originally.)
511 if (defined(@QUERY_PARAM) && !defined($initializer)) {
512 for my $name (@QUERY_PARAM) {
513 my $val = $QUERY_PARAM{$name}; # always an arrayref;
514 $self->param('-name'=>$name,'-value'=> $val);
515 if (defined $val and ref $val eq 'ARRAY') {
516 for my $fh (grep {defined(fileno($_))} @$val) {
517 seek($fh,0,0); # reset the filehandle.
522 $self->charset($QUERY_CHARSET);
523 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
524 $self->{'.tmpfiles'} = {%QUERY_TMPFILES};
528 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
529 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
531 $fh = to_filehandle($initializer) if $initializer;
533 # set charset to the safe ISO-8859-1
534 $self->charset('ISO-8859-1');
538 # avoid unreasonably large postings
539 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
540 #discard the post, unread
541 $self->cgi_error("413 Request entity too large");
545 # Process multipart postings, but only if the initializer is
548 && defined($ENV{'CONTENT_TYPE'})
549 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
550 && !defined($initializer)
552 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
553 $self->read_multipart($boundary,$content_length);
557 # Process XForms postings. We know that we have XForms in the
559 # method eq 'POST' && content-type eq 'application/xml'
560 # method eq 'POST' && content-type =~ /multipart\/related.+start=/
561 # There are more cases, actually, but for now, we don't support other
562 # methods for XForm posts.
563 # In a XForm POST, the QUERY_STRING is parsed normally.
564 # If the content-type is 'application/xml', we just set the param
565 # XForms:Model (referring to the xml syntax) param containing the
567 # In the case of multipart/related we set XForms:Model as above, but
568 # the other parts are available as uploads with the Content-ID as the
570 # See the URL below for XForms specs on this issue.
571 # http://www.w3.org/TR/2006/REC-xforms-20060314/slice11.html#submit-options
572 if ($meth eq 'POST' && defined($ENV{'CONTENT_TYPE'})) {
573 if ($ENV{'CONTENT_TYPE'} eq 'application/xml') {
574 my($param) = 'XForms:Model';
576 $self->add_parameter($param);
577 $self->read_from_client(\$value,$content_length,0)
578 if $content_length > 0;
579 push (@{$self->{param}{$param}},$value);
581 } elsif ($ENV{'CONTENT_TYPE'} =~ /multipart\/related.+boundary=\"?([^\";,]+)\"?.+start=\"?\<?([^\"\>]+)\>?\"?/) {
582 my($boundary,$start) = ($1,$2);
583 my($param) = 'XForms:Model';
584 $self->add_parameter($param);
585 my($value) = $self->read_multipart_related($start,$boundary,$content_length,0);
586 push (@{$self->{param}{$param}},$value);
588 $query_string = $self->r->args;
590 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
591 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
598 # If initializer is defined, then read parameters
600 if (!$is_xforms && defined($initializer)) {
601 if (UNIVERSAL::isa($initializer,'CGI')) {
602 $query_string = $initializer->query_string;
605 if (ref($initializer) && ref($initializer) eq 'HASH') {
606 foreach (keys %$initializer) {
607 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
612 if (defined($fh) && ($fh ne '')) {
618 # massage back into standard format
619 if ("@lines" =~ /=/) {
620 $query_string=join("&",@lines);
622 $query_string=join("+",@lines);
627 # last chance -- treat it as a string
628 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
629 $query_string = $initializer;
634 # If method is GET or HEAD, fetch the query from
636 if ($is_xforms || $meth=~/^(GET|HEAD)$/) {
638 $query_string = $self->r->args;
640 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
641 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
646 if ($meth eq 'POST' || $meth eq 'PUT') {
647 $self->read_from_client(\$query_string,$content_length,0)
648 if $content_length > 0;
649 # Some people want to have their cake and eat it too!
650 # Uncomment this line to have the contents of the query string
651 # APPENDED to the POST data.
652 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
656 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
657 # Check the command line and then the standard input for data.
658 # We use the shellwords package in order to behave the way that
659 # UN*X programmers expect.
662 my $cmdline_ret = read_from_cmdline();
663 $query_string = $cmdline_ret->{'query_string'};
664 if (defined($cmdline_ret->{'subpath'}))
666 $self->path_info($cmdline_ret->{'subpath'});
671 # YL: Begin Change for XML handler 10/19/2001
672 if (!$is_xforms && ($meth eq 'POST' || $meth eq 'PUT')
673 && defined($ENV{'CONTENT_TYPE'})
674 && $ENV{'CONTENT_TYPE'} !~ m|^application/x-www-form-urlencoded|
675 && $ENV{'CONTENT_TYPE'} !~ m|^multipart/form-data| ) {
676 my($param) = $meth . 'DATA' ;
677 $self->add_parameter($param) ;
678 push (@{$self->{param}{$param}},$query_string);
679 undef $query_string ;
681 # YL: End Change for XML handler 10/19/2001
683 # We now have the query string in hand. We do slightly
684 # different things for keyword lists and parameter lists.
685 if (defined $query_string && length $query_string) {
686 if ($query_string =~ /[&=;]/) {
687 $self->parse_params($query_string);
689 $self->add_parameter('keywords');
690 $self->{param}{'keywords'} = [$self->parse_keywordlist($query_string)];
694 # Special case. Erase everything if there is a field named
696 if ($self->param('.defaults')) {
700 # Associative array containing our defined fieldnames
701 $self->{'.fieldnames'} = {};
702 foreach ($self->param('.cgifields')) {
703 $self->{'.fieldnames'}->{$_}++;
706 # Clear out our default submission button flag if present
707 $self->delete('.submit');
708 $self->delete('.cgifields');
710 $self->save_request unless defined $initializer;
713 # FUNCTIONS TO OVERRIDE:
714 # Turn a string into a filehandle
717 return undef unless $thingy;
718 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
719 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
722 while (my $package = caller($caller++)) {
723 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
724 return $tmp if defined(fileno($tmp));
730 # send output to the browser
732 my($self,@p) = self_or_default(@_);
736 # print to standard output (for overriding in mod_perl)
742 # get/set last cgi_error
744 my ($self,$err) = self_or_default(@_);
745 $self->{'.cgi_error'} = $err if defined $err;
746 return $self->{'.cgi_error'};
751 # We're going to play with the package globals now so that if we get called
752 # again, we initialize ourselves in exactly the same way. This allows
753 # us to have several of these objects.
754 @QUERY_PARAM = $self->param; # save list of parameters
755 foreach (@QUERY_PARAM) {
756 next unless defined $_;
757 $QUERY_PARAM{$_}=$self->{param}{$_};
759 $QUERY_CHARSET = $self->charset;
760 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
761 %QUERY_TMPFILES = %{ $self->{'.tmpfiles'} || {} };
765 my($self,$tosplit) = @_;
766 my(@pairs) = split(/[&;]/,$tosplit);
769 ($param,$value) = split('=',$_,2);
770 next unless defined $param;
771 next if $NO_UNDEF_PARAMS and not defined $value;
772 $value = '' unless defined $value;
773 $param = unescape($param);
774 $value = unescape($value);
775 $self->add_parameter($param);
776 push (@{$self->{param}{$param}},$value);
782 return unless defined $param;
783 push (@{$self->{'.parameters'}},$param)
784 unless defined($self->{param}{$param});
789 return () unless defined($self) && $self->{'.parameters'};
790 return () unless @{$self->{'.parameters'}};
791 return @{$self->{'.parameters'}};
794 # put a filehandle into binary mode (DOS)
796 return unless defined($_[1]) && defined fileno($_[1]);
797 CORE::binmode($_[1]);
801 my ($self,$tagname) = @_;
804 my (\$q,\$a,\@rest) = self_or_default(\@_);
806 if (ref(\$a) && ref(\$a) eq 'HASH') {
807 my(\@attr) = make_attributes(\$a,\$q->{'escape'});
808 \$attr = " \@attr" if \@attr;
810 unshift \@rest,\$a if defined \$a;
813 if ($tagname=~/start_(\w+)/i) {
814 $func .= qq! return "<\L$1\E\$attr>";} !;
815 } elsif ($tagname=~/end_(\w+)/i) {
816 $func .= qq! return "<\L/$1\E>"; } !;
819 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@rest;
820 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
821 my \@result = map { "\$tag\$_\$untag" }
822 (ref(\$rest[0]) eq 'ARRAY') ? \@{\$rest[0]} : "\@rest";
830 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
831 my $func = &_compile;
836 my($func) = $AUTOLOAD;
837 my($pack,$func_name);
839 local($1,$2); # this fixes an obscure variable suicide problem.
840 $func=~/(.+)::([^:]+)$/;
841 ($pack,$func_name) = ($1,$2);
842 $pack=~s/::SUPER$//; # fix another obscure problem
843 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
844 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
846 my($sub) = \%{"$pack\:\:SUBS"};
848 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
850 eval "package $pack; $$auto";
851 croak("$AUTOLOAD: $@") if $@;
852 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
854 my($code) = $sub->{$func_name};
856 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
858 (my $base = $func_name) =~ s/^(start_|end_)//i;
859 if ($EXPORT{':any'} ||
862 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
863 && $EXPORT_OK{$base}) {
864 $code = $CGI::DefaultClass->_make_tag_func($func_name);
867 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
869 eval "package $pack; $code";
872 croak("$AUTOLOAD: $@");
875 CORE::delete($sub->{$func_name}); #free storage
876 return "$pack\:\:$func_name";
882 return '' unless $value;
883 return $XHTML ? qq(selected="selected" ) : qq(selected );
889 return '' unless $value;
890 return $XHTML ? qq(checked="checked" ) : qq(checked );
893 sub _reset_globals { initialize_globals(); }
899 # to avoid reexporting unwanted variables
903 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
904 $NPH++, next if /^[:-]nph$/;
905 $NOSTICKY++, next if /^[:-]nosticky$/;
906 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
907 $DEBUG=2, next if /^[:-][Dd]ebug$/;
908 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
909 $PARAM_UTF8++, next if /^[:-]utf8$/;
910 $XHTML++, next if /^[:-]xhtml$/;
911 $XHTML=0, next if /^[:-]no_?xhtml$/;
912 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
913 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
914 $TABINDEX++, next if /^[:-]tabindex$/;
915 $CLOSE_UPLOAD_FILES++, next if /^[:-]close_upload_files$/;
916 $EXPORT{$_}++, next if /^[:-]any$/;
917 $compile++, next if /^[:-]compile$/;
918 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
920 # This is probably extremely evil code -- to be deleted some day.
921 if (/^[-]autoload$/) {
922 my($pkg) = caller(1);
923 *{"${pkg}::AUTOLOAD"} = sub {
924 my($routine) = $AUTOLOAD;
925 $routine =~ s/^.*::/CGI::/;
931 foreach (&expand_tags($_)) {
932 tr/a-zA-Z0-9_//cd; # don't allow weird function names
936 _compile_all(keys %EXPORT) if $compile;
941 my ($self,$charset) = self_or_default(@_);
942 $self->{'.charset'} = $charset if defined $charset;
947 my ($self,$new_value) = self_or_default(@_);
948 $self->{'.elid'} = $new_value if defined $new_value;
949 sprintf('%010d',$self->{'.elid'}++);
953 my ($self,$new_value) = self_or_default(@_);
954 $self->{'.etab'} ||= 1;
955 $self->{'.etab'} = $new_value if defined $new_value;
956 my $tab = $self->{'.etab'}++;
957 return '' unless $TABINDEX or defined $new_value;
958 return qq(tabindex="$tab" );
961 ###############################################################################
962 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
963 ###############################################################################
964 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
965 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
969 'URL_ENCODED'=> <<'END_OF_FUNC',
970 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
973 'MULTIPART' => <<'END_OF_FUNC',
974 sub MULTIPART { 'multipart/form-data'; }
977 'SERVER_PUSH' => <<'END_OF_FUNC',
978 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
981 'new_MultipartBuffer' => <<'END_OF_FUNC',
982 # Create a new multipart buffer
983 sub new_MultipartBuffer {
984 my($self,$boundary,$length) = @_;
985 return MultipartBuffer->new($self,$boundary,$length);
989 'read_from_client' => <<'END_OF_FUNC',
990 # Read data from a file handle
991 sub read_from_client {
992 my($self, $buff, $len, $offset) = @_;
993 local $^W=0; # prevent a warning
995 ? $self->r->read($$buff, $len, $offset)
996 : read(\*STDIN, $$buff, $len, $offset);
1000 'delete' => <<'END_OF_FUNC',
1002 # Deletes the named parameter entirely.
1005 my($self,@p) = self_or_default(@_);
1006 my(@names) = rearrange([NAME],@p);
1007 my @to_delete = ref($names[0]) eq 'ARRAY' ? @$names[0] : @names;
1009 foreach my $name (@to_delete)
1011 CORE::delete $self->{param}{$name};
1012 CORE::delete $self->{'.fieldnames'}->{$name};
1013 $to_delete{$name}++;
1015 @{$self->{'.parameters'}}=grep { !exists($to_delete{$_}) } $self->param();
1020 #### Method: import_names
1021 # Import all parameters into the given namespace.
1022 # Assumes namespace 'Q' if not specified
1024 'import_names' => <<'END_OF_FUNC',
1026 my($self,$namespace,$delete) = self_or_default(@_);
1027 $namespace = 'Q' unless defined($namespace);
1028 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
1029 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
1030 # can anyone find an easier way to do this?
1031 foreach (keys %{"${namespace}::"}) {
1032 local *symbol = "${namespace}::${_}";
1038 my($param,@value,$var);
1039 foreach $param ($self->param) {
1040 # protect against silly names
1041 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
1042 $var =~ s/^(?=\d)/_/;
1043 local *symbol = "${namespace}::$var";
1044 @value = $self->param($param);
1046 $symbol = $value[0];
1051 #### Method: keywords
1052 # Keywords acts a bit differently. Calling it in a list context
1053 # returns the list of keywords.
1054 # Calling it in a scalar context gives you the size of the list.
1056 'keywords' => <<'END_OF_FUNC',
1058 my($self,@values) = self_or_default(@_);
1059 # If values is provided, then we set it.
1060 $self->{param}{'keywords'}=[@values] if @values;
1061 my(@result) = defined($self->{param}{'keywords'}) ? @{$self->{param}{'keywords'}} : ();
1066 # These are some tie() interfaces for compatibility
1067 # with Steve Brenner's cgi-lib.pl routines
1068 'Vars' => <<'END_OF_FUNC',
1073 return %in if wantarray;
1078 # These are some tie() interfaces for compatibility
1079 # with Steve Brenner's cgi-lib.pl routines
1080 'ReadParse' => <<'END_OF_FUNC',
1087 *in=*{"${pkg}::in"};
1090 return scalar(keys %in);
1094 'PrintHeader' => <<'END_OF_FUNC',
1096 my($self) = self_or_default(@_);
1097 return $self->header();
1101 'HtmlTop' => <<'END_OF_FUNC',
1103 my($self,@p) = self_or_default(@_);
1104 return $self->start_html(@p);
1108 'HtmlBot' => <<'END_OF_FUNC',
1110 my($self,@p) = self_or_default(@_);
1111 return $self->end_html(@p);
1115 'SplitParam' => <<'END_OF_FUNC',
1118 my (@params) = split ("\0", $param);
1119 return (wantarray ? @params : $params[0]);
1123 'MethGet' => <<'END_OF_FUNC',
1125 return request_method() eq 'GET';
1129 'MethPost' => <<'END_OF_FUNC',
1131 return request_method() eq 'POST';
1135 'TIEHASH' => <<'END_OF_FUNC',
1139 if (ref($arg) && UNIVERSAL::isa($arg,'CGI')) {
1142 return $Q ||= $class->new(@_);
1146 'STORE' => <<'END_OF_FUNC',
1151 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
1152 $self->param(-name=>$tag,-value=>\@vals);
1156 'FETCH' => <<'END_OF_FUNC',
1158 return $_[0] if $_[1] eq 'CGI';
1159 return undef unless defined $_[0]->param($_[1]);
1160 return join("\0",$_[0]->param($_[1]));
1164 'FIRSTKEY' => <<'END_OF_FUNC',
1166 $_[0]->{'.iterator'}=0;
1167 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1171 'NEXTKEY' => <<'END_OF_FUNC',
1173 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1177 'EXISTS' => <<'END_OF_FUNC',
1179 exists $_[0]->{param}{$_[1]};
1183 'DELETE' => <<'END_OF_FUNC',
1185 $_[0]->delete($_[1]);
1189 'CLEAR' => <<'END_OF_FUNC',
1197 # Append a new value to an existing query
1199 'append' => <<'EOF',
1201 my($self,@p) = self_or_default(@_);
1202 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
1203 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
1205 $self->add_parameter($name);
1206 push(@{$self->{param}{$name}},@values);
1208 return $self->param($name);
1212 #### Method: delete_all
1213 # Delete all parameters
1215 'delete_all' => <<'EOF',
1217 my($self) = self_or_default(@_);
1218 my @param = $self->param();
1219 $self->delete(@param);
1223 'Delete' => <<'EOF',
1225 my($self,@p) = self_or_default(@_);
1230 'Delete_all' => <<'EOF',
1232 my($self,@p) = self_or_default(@_);
1233 $self->delete_all(@p);
1237 #### Method: autoescape
1238 # If you want to turn off the autoescaping features,
1239 # call this method with undef as the argument
1240 'autoEscape' => <<'END_OF_FUNC',
1242 my($self,$escape) = self_or_default(@_);
1243 my $d = $self->{'escape'};
1244 $self->{'escape'} = $escape;
1250 #### Method: version
1251 # Return the current version
1253 'version' => <<'END_OF_FUNC',
1259 #### Method: url_param
1260 # Return a parameter in the QUERY_STRING, regardless of
1261 # whether this was a POST or a GET
1263 'url_param' => <<'END_OF_FUNC',
1265 my ($self,@p) = self_or_default(@_);
1266 my $name = shift(@p);
1267 return undef unless exists($ENV{QUERY_STRING});
1268 unless (exists($self->{'.url_param'})) {
1269 $self->{'.url_param'}={}; # empty hash
1270 if ($ENV{QUERY_STRING} =~ /=/) {
1271 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
1274 ($param,$value) = split('=',$_,2);
1275 $param = unescape($param);
1276 $value = unescape($value);
1277 push(@{$self->{'.url_param'}->{$param}},$value);
1280 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1283 return keys %{$self->{'.url_param'}} unless defined($name);
1284 return () unless $self->{'.url_param'}->{$name};
1285 return wantarray ? @{$self->{'.url_param'}->{$name}}
1286 : $self->{'.url_param'}->{$name}->[0];
1291 # Returns a string in which all the known parameter/value
1292 # pairs are represented as nested lists, mainly for the purposes
1295 'Dump' => <<'END_OF_FUNC',
1297 my($self) = self_or_default(@_);
1298 my($param,$value,@result);
1299 return '<ul></ul>' unless $self->param;
1300 push(@result,"<ul>");
1301 foreach $param ($self->param) {
1302 my($name)=$self->escapeHTML($param);
1303 push(@result,"<li><strong>$param</strong></li>");
1304 push(@result,"<ul>");
1305 foreach $value ($self->param($param)) {
1306 $value = $self->escapeHTML($value);
1307 $value =~ s/\n/<br \/>\n/g;
1308 push(@result,"<li>$value</li>");
1310 push(@result,"</ul>");
1312 push(@result,"</ul>");
1313 return join("\n",@result);
1317 #### Method as_string
1319 # synonym for "dump"
1321 'as_string' => <<'END_OF_FUNC',
1328 # Write values out to a filehandle in such a way that they can
1329 # be reinitialized by the filehandle form of the new() method
1331 'save' => <<'END_OF_FUNC',
1333 my($self,$filehandle) = self_or_default(@_);
1334 $filehandle = to_filehandle($filehandle);
1336 local($,) = ''; # set print field separator back to a sane value
1337 local($\) = ''; # set output line separator to a sane value
1338 foreach $param ($self->param) {
1339 my($escaped_param) = escape($param);
1341 foreach $value ($self->param($param)) {
1342 print $filehandle "$escaped_param=",escape("$value"),"\n";
1345 foreach (keys %{$self->{'.fieldnames'}}) {
1346 print $filehandle ".cgifields=",escape("$_"),"\n";
1348 print $filehandle "=\n"; # end of record
1353 #### Method: save_parameters
1354 # An alias for save() that is a better name for exportation.
1355 # Only intended to be used with the function (non-OO) interface.
1357 'save_parameters' => <<'END_OF_FUNC',
1358 sub save_parameters {
1360 return save(to_filehandle($fh));
1364 #### Method: restore_parameters
1365 # A way to restore CGI parameters from an initializer.
1366 # Only intended to be used with the function (non-OO) interface.
1368 'restore_parameters' => <<'END_OF_FUNC',
1369 sub restore_parameters {
1370 $Q = $CGI::DefaultClass->new(@_);
1374 #### Method: multipart_init
1375 # Return a Content-Type: style header for server-push
1376 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1378 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1379 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1381 'multipart_init' => <<'END_OF_FUNC',
1382 sub multipart_init {
1383 my($self,@p) = self_or_default(@_);
1384 my($boundary,@other) = rearrange([BOUNDARY],@p);
1385 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1386 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1387 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1388 $type = SERVER_PUSH($boundary);
1389 return $self->header(
1392 (map { split "=", $_, 2 } @other),
1393 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1398 #### Method: multipart_start
1399 # Return a Content-Type: style header for server-push, start of section
1401 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1402 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1404 'multipart_start' => <<'END_OF_FUNC',
1405 sub multipart_start {
1407 my($self,@p) = self_or_default(@_);
1408 my($type,@other) = rearrange([TYPE],@p);
1409 $type = $type || 'text/html';
1410 push(@header,"Content-Type: $type");
1412 # rearrange() was designed for the HTML portion, so we
1413 # need to fix it up a little.
1415 # Don't use \s because of perl bug 21951
1416 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1417 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1419 push(@header,@other);
1420 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1426 #### Method: multipart_end
1427 # Return a MIME boundary separator for server-push, end of section
1429 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1432 'multipart_end' => <<'END_OF_FUNC',
1434 my($self,@p) = self_or_default(@_);
1435 return $self->{'separator'};
1440 #### Method: multipart_final
1441 # Return a MIME boundary separator for server-push, end of all sections
1443 # Contributed by Andrew Benham (adsb@bigfoot.com)
1445 'multipart_final' => <<'END_OF_FUNC',
1446 sub multipart_final {
1447 my($self,@p) = self_or_default(@_);
1448 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1454 # Return a Content-Type: style header
1457 'header' => <<'END_OF_FUNC',
1459 my($self,@p) = self_or_default(@_);
1462 return "" if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1464 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,$p3p,@other) =
1465 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1466 'STATUS',['COOKIE','COOKIES'],'TARGET',
1467 'EXPIRES','NPH','CHARSET',
1468 'ATTACHMENT','P3P'],@p);
1472 $type ||= 'text/html' unless defined($type);
1474 if (defined $charset) {
1475 $self->charset($charset);
1477 $charset = $self->charset if $type =~ /^text\//;
1481 # rearrange() was designed for the HTML portion, so we
1482 # need to fix it up a little.
1484 # Don't use \s because of perl bug 21951
1485 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1486 ($_ = $header) =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
1489 $type .= "; charset=$charset"
1491 and $type !~ /\bcharset\b/
1492 and defined $charset
1495 # Maybe future compatibility. Maybe not.
1496 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1497 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1498 push(@header,"Server: " . &server_software()) if $nph;
1500 push(@header,"Status: $status") if $status;
1501 push(@header,"Window-Target: $target") if $target;
1503 $p3p = join ' ',@$p3p if ref($p3p) eq 'ARRAY';
1504 push(@header,qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p"));
1506 # push all the cookies -- there may be several
1508 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1510 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1511 push(@header,"Set-Cookie: $cs") if $cs ne '';
1514 # if the user indicates an expiration time, then we need
1515 # both an Expires and a Date header (so that the browser is
1517 push(@header,"Expires: " . expires($expires,'http'))
1519 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1520 push(@header,"Pragma: no-cache") if $self->cache();
1521 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1522 push(@header,map {ucfirst $_} @other);
1523 push(@header,"Content-Type: $type") if $type ne '';
1524 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1525 if (($MOD_PERL >= 1) && !$nph) {
1526 $self->r->send_cgi_header($header);
1535 # Control whether header() will produce the no-cache
1538 'cache' => <<'END_OF_FUNC',
1540 my($self,$new_value) = self_or_default(@_);
1541 $new_value = '' unless $new_value;
1542 if ($new_value ne '') {
1543 $self->{'cache'} = $new_value;
1545 return $self->{'cache'};
1550 #### Method: redirect
1551 # Return a Location: style header
1554 'redirect' => <<'END_OF_FUNC',
1556 my($self,@p) = self_or_default(@_);
1557 my($url,$target,$status,$cookie,$nph,@other) =
1558 rearrange([[LOCATION,URI,URL],TARGET,STATUS,['COOKIE','COOKIES'],NPH],@p);
1559 $status = '302 Found' unless defined $status;
1560 $url ||= $self->self_url;
1562 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1564 '-Status' => $status,
1567 unshift(@o,'-Target'=>$target) if $target;
1568 unshift(@o,'-Type'=>'');
1570 unshift(@unescaped,'-Cookie'=>$cookie) if $cookie;
1571 return $self->header((map {$self->unescapeHTML($_)} @o),@unescaped);
1576 #### Method: start_html
1577 # Canned HTML header
1580 # $title -> (optional) The title for this HTML document (-title)
1581 # $author -> (optional) e-mail address of the author (-author)
1582 # $base -> (optional) if set to true, will enter the BASE address of this document
1583 # for resolving relative references (-base)
1584 # $xbase -> (optional) alternative base at some remote location (-xbase)
1585 # $target -> (optional) target window to load all links into (-target)
1586 # $script -> (option) Javascript code (-script)
1587 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1588 # $meta -> (optional) Meta information tags
1589 # $head -> (optional) any other elements you'd like to incorporate into the <head> tag
1590 # (a scalar or array ref)
1591 # $style -> (optional) reference to an external style sheet
1592 # @other -> (optional) any other named parameters you'd like to incorporate into
1595 'start_html' => <<'END_OF_FUNC',
1597 my($self,@p) = &self_or_default(@_);
1598 my($title,$author,$base,$xbase,$script,$noscript,
1599 $target,$meta,$head,$style,$dtd,$lang,$encoding,$declare_xml,@other) =
1600 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,
1601 META,HEAD,STYLE,DTD,LANG,ENCODING,DECLARE_XML],@p);
1603 $self->element_id(0);
1604 $self->element_tab(0);
1606 $encoding = lc($self->charset) unless defined $encoding;
1608 # Need to sort out the DTD before it's okay to call escapeHTML().
1609 my(@result,$xml_dtd);
1611 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1612 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1614 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1617 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1620 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1621 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1622 push @result,qq(<?xml version="1.0" encoding="$encoding"?>) if $xml_dtd && $declare_xml;
1624 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1625 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t "$dtd->[1]">));
1626 $DTD_PUBLIC_IDENTIFIER = $dtd->[0];
1628 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1629 $DTD_PUBLIC_IDENTIFIER = $dtd;
1632 # Now that we know whether we're using the HTML 3.2 DTD or not, it's okay to
1633 # call escapeHTML(). Strangely enough, the title needs to be escaped as
1634 # HTML while the author needs to be escaped as a URL.
1635 $title = $self->escapeHTML($title || 'Untitled Document');
1636 $author = $self->escape($author);
1638 if ($DTD_PUBLIC_IDENTIFIER =~ /[^X]HTML (2\.0|3\.2)/i) {
1639 $lang = "" unless defined $lang;
1643 $lang = 'en-US' unless defined $lang;
1646 my $lang_bits = $lang ne '' ? qq( lang="$lang" xml:lang="$lang") : '';
1647 my $meta_bits = qq(<meta http-equiv="Content-Type" content="text/html; charset=$encoding" />)
1648 if $XHTML && $encoding && !$declare_xml;
1650 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml"$lang_bits>\n<head>\n<title>$title</title>)
1651 : ($lang ? qq(<html lang="$lang">) : "<html>")
1652 . "<head><title>$title</title>");
1653 if (defined $author) {
1654 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1655 : "<link rev=\"made\" href=\"mailto:$author\">");
1658 if ($base || $xbase || $target) {
1659 my $href = $xbase || $self->url('-path'=>1);
1660 my $t = $target ? qq/ target="$target"/ : '';
1661 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1664 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1665 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1666 : qq(<meta name="$_" content="$meta->{$_}">)); }
1669 my $meta_bits_set = 0;
1672 push @result, @$head;
1673 $meta_bits_set = 1 if grep { /http-equiv=["']Content-Type/i }@$head;
1676 push @result, $head;
1677 $meta_bits_set = 1 if $head =~ /http-equiv=["']Content-Type/i;
1681 # handle the infrequently-used -style and -script parameters
1682 push(@result,$self->_style($style)) if defined $style;
1683 push(@result,$self->_script($script)) if defined $script;
1684 push(@result,$meta_bits) if defined $meta_bits and !$meta_bits_set;
1686 # handle -noscript parameter
1687 push(@result,<<END) if $noscript;
1693 my($other) = @other ? " @other" : '';
1694 push(@result,"</head>\n<body$other>\n");
1695 return join("\n",@result);
1700 # internal method for generating a CSS style section
1702 '_style' => <<'END_OF_FUNC',
1704 my ($self,$style) = @_;
1707 my $type = 'text/css';
1708 my $rel = 'stylesheet';
1711 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1712 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1714 my @s = ref($style) eq 'ARRAY' ? @$style : $style;
1719 my($src,$code,$verbatim,$stype,$alternate,$foo,@other) =
1720 rearrange([qw(SRC CODE VERBATIM TYPE ALTERNATE FOO)],
1722 ref($s) eq 'ARRAY' ? @$s : %$s));
1723 my $type = defined $stype ? $stype : 'text/css';
1724 my $rel = $alternate ? 'alternate stylesheet' : 'stylesheet';
1725 $other = "@other" if @other;
1727 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1728 { # If it is, push a LINK tag for each one
1729 foreach $src (@$src)
1731 push(@result,$XHTML ? qq(<link rel="$rel" type="$type" href="$src" $other/>)
1732 : qq(<link rel="$rel" type="$type" href="$src"$other>)) if $src;
1736 { # Otherwise, push the single -src, if it exists.
1737 push(@result,$XHTML ? qq(<link rel="$rel" type="$type" href="$src" $other/>)
1738 : qq(<link rel="$rel" type="$type" href="$src"$other>)
1742 my @v = ref($verbatim) eq 'ARRAY' ? @$verbatim : $verbatim;
1743 push(@result, "<style type=\"text/css\">\n$_\n</style>") foreach @v;
1745 my @c = ref($code) eq 'ARRAY' ? @$code : $code if $code;
1746 push(@result,style({'type'=>$type},"$cdata_start\n$_\n$cdata_end")) foreach @c;
1750 push(@result,$XHTML ? qq(<link rel="$rel" type="$type" href="$src" $other/>)
1751 : qq(<link rel="$rel" type="$type" href="$src"$other>));
1758 '_script' => <<'END_OF_FUNC',
1760 my ($self,$script) = @_;
1763 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1764 foreach $script (@scripts) {
1765 my($src,$code,$language);
1766 if (ref($script)) { # script is a hash
1767 ($src,$code,$type) =
1768 rearrange(['SRC','CODE',['LANGUAGE','TYPE']],
1769 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1770 ref($script) eq 'ARRAY' ? @$script : %$script);
1771 $type ||= 'text/javascript';
1772 unless ($type =~ m!\w+/\w+!) {
1773 $type =~ s/[\d.]+$//;
1774 $type = "text/$type";
1777 ($src,$code,$type) = ('',$script, 'text/javascript');
1780 my $comment = '//'; # javascript by default
1781 $comment = '#' if $type=~/perl|tcl/i;
1782 $comment = "'" if $type=~/vbscript/i;
1784 my ($cdata_start,$cdata_end);
1786 $cdata_start = "$comment<![CDATA[\n";
1787 $cdata_end .= "\n$comment]]>";
1789 $cdata_start = "\n<!-- Hide script\n";
1790 $cdata_end = $comment;
1791 $cdata_end .= " End script hiding -->\n";
1794 push(@satts,'src'=>$src) if $src;
1795 push(@satts,'type'=>$type);
1796 $code = $cdata_start . $code . $cdata_end if defined $code;
1797 push(@result,$self->script({@satts},$code || ''));
1803 #### Method: end_html
1804 # End an HTML document.
1805 # Trivial method for completeness. Just returns "</body>"
1807 'end_html' => <<'END_OF_FUNC',
1809 return "\n</body>\n</html>";
1814 ################################
1815 # METHODS USED IN BUILDING FORMS
1816 ################################
1818 #### Method: isindex
1819 # Just prints out the isindex tag.
1821 # $action -> optional URL of script to run
1823 # A string containing a <isindex> tag
1824 'isindex' => <<'END_OF_FUNC',
1826 my($self,@p) = self_or_default(@_);
1827 my($action,@other) = rearrange([ACTION],@p);
1828 $action = qq/ action="$action"/ if $action;
1829 my($other) = @other ? " @other" : '';
1830 return $XHTML ? "<isindex$action$other />" : "<isindex$action$other>";
1835 #### Method: startform
1838 # $method -> optional submission method to use (GET or POST)
1839 # $action -> optional URL of script to run
1840 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1841 'startform' => <<'END_OF_FUNC',
1843 my($self,@p) = self_or_default(@_);
1845 my($method,$action,$enctype,@other) =
1846 rearrange([METHOD,ACTION,ENCTYPE],@p);
1848 $method = $self->escapeHTML(lc($method || 'post'));
1849 $enctype = $self->escapeHTML($enctype || &URL_ENCODED);
1850 if (defined $action) {
1851 $action = $self->escapeHTML($action);
1854 $action = $self->escapeHTML($self->request_uri || $self->self_url);
1856 $action = qq(action="$action");
1857 my($other) = @other ? " @other" : '';
1858 $self->{'.parametersToAdd'}={};
1859 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1864 #### Method: start_form
1865 # synonym for startform
1866 'start_form' => <<'END_OF_FUNC',
1868 $XHTML ? &start_multipart_form : &startform;
1872 'end_multipart_form' => <<'END_OF_FUNC',
1873 sub end_multipart_form {
1878 #### Method: start_multipart_form
1879 # synonym for startform
1880 'start_multipart_form' => <<'END_OF_FUNC',
1881 sub start_multipart_form {
1882 my($self,@p) = self_or_default(@_);
1883 if (defined($p[0]) && substr($p[0],0,1) eq '-') {
1884 return $self->startform(-enctype=>&MULTIPART,@p);
1886 my($method,$action,@other) =
1887 rearrange([METHOD,ACTION],@p);
1888 return $self->startform($method,$action,&MULTIPART,@other);
1894 #### Method: endform
1896 'endform' => <<'END_OF_FUNC',
1898 my($self,@p) = self_or_default(@_);
1900 return wantarray ? ("</form>") : "\n</form>";
1902 if (my @fields = $self->get_fields) {
1903 return wantarray ? ("<div>",@fields,"</div>","</form>")
1904 : "<div>".(join '',@fields)."</div>\n</form>";
1913 '_textfield' => <<'END_OF_FUNC',
1915 my($self,$tag,@p) = self_or_default(@_);
1916 my($name,$default,$size,$maxlength,$override,$tabindex,@other) =
1917 rearrange([NAME,[DEFAULT,VALUE,VALUES],SIZE,MAXLENGTH,[OVERRIDE,FORCE],TABINDEX],@p);
1919 my $current = $override ? $default :
1920 (defined($self->param($name)) ? $self->param($name) : $default);
1922 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1923 $name = defined($name) ? $self->escapeHTML($name) : '';
1924 my($s) = defined($size) ? qq/ size="$size"/ : '';
1925 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1926 my($other) = @other ? " @other" : '';
1927 # this entered at cristy's request to fix problems with file upload fields
1928 # and WebTV -- not sure it won't break stuff
1929 my($value) = $current ne '' ? qq(value="$current") : '';
1930 $tabindex = $self->element_tab($tabindex);
1931 return $XHTML ? qq(<input type="$tag" name="$name" $tabindex$value$s$m$other />)
1932 : qq(<input type="$tag" name="$name" $value$s$m$other>);
1936 #### Method: textfield
1938 # $name -> Name of the text field
1939 # $default -> Optional default value of the field if not
1941 # $size -> Optional width of field in characaters.
1942 # $maxlength -> Optional maximum number of characters.
1944 # A string containing a <input type="text"> field
1946 'textfield' => <<'END_OF_FUNC',
1948 my($self,@p) = self_or_default(@_);
1949 $self->_textfield('text',@p);
1954 #### Method: filefield
1956 # $name -> Name of the file upload field
1957 # $size -> Optional width of field in characaters.
1958 # $maxlength -> Optional maximum number of characters.
1960 # A string containing a <input type="file"> field
1962 'filefield' => <<'END_OF_FUNC',
1964 my($self,@p) = self_or_default(@_);
1965 $self->_textfield('file',@p);
1970 #### Method: password
1971 # Create a "secret password" entry field
1973 # $name -> Name of the field
1974 # $default -> Optional default value of the field if not
1976 # $size -> Optional width of field in characters.
1977 # $maxlength -> Optional maximum characters that can be entered.
1979 # A string containing a <input type="password"> field
1981 'password_field' => <<'END_OF_FUNC',
1982 sub password_field {
1983 my ($self,@p) = self_or_default(@_);
1984 $self->_textfield('password',@p);
1988 #### Method: textarea
1990 # $name -> Name of the text field
1991 # $default -> Optional default value of the field if not
1993 # $rows -> Optional number of rows in text area
1994 # $columns -> Optional number of columns in text area
1996 # A string containing a <textarea></textarea> tag
1998 'textarea' => <<'END_OF_FUNC',
2000 my($self,@p) = self_or_default(@_);
2001 my($name,$default,$rows,$cols,$override,$tabindex,@other) =
2002 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE],TABINDEX],@p);
2004 my($current)= $override ? $default :
2005 (defined($self->param($name)) ? $self->param($name) : $default);
2007 $name = defined($name) ? $self->escapeHTML($name) : '';
2008 $current = defined($current) ? $self->escapeHTML($current) : '';
2009 my($r) = $rows ? qq/ rows="$rows"/ : '';
2010 my($c) = $cols ? qq/ cols="$cols"/ : '';
2011 my($other) = @other ? " @other" : '';
2012 $tabindex = $self->element_tab($tabindex);
2013 return qq{<textarea name="$name" $tabindex$r$c$other>$current</textarea>};
2019 # Create a javascript button.
2021 # $name -> (optional) Name for the button. (-name)
2022 # $value -> (optional) Value of the button when selected (and visible name) (-value)
2023 # $onclick -> (optional) Text of the JavaScript to run when the button is
2026 # A string containing a <input type="button"> tag
2028 'button' => <<'END_OF_FUNC',
2030 my($self,@p) = self_or_default(@_);
2032 my($label,$value,$script,$tabindex,@other) = rearrange([NAME,[VALUE,LABEL],
2033 [ONCLICK,SCRIPT],TABINDEX],@p);
2035 $label=$self->escapeHTML($label);
2036 $value=$self->escapeHTML($value,1);
2037 $script=$self->escapeHTML($script);
2040 $name = qq/ name="$label"/ if $label;
2041 $value = $value || $label;
2043 $val = qq/ value="$value"/ if $value;
2044 $script = qq/ onclick="$script"/ if $script;
2045 my($other) = @other ? " @other" : '';
2046 $tabindex = $self->element_tab($tabindex);
2047 return $XHTML ? qq(<input type="button" $tabindex$name$val$script$other />)
2048 : qq(<input type="button"$name$val$script$other>);
2054 # Create a "submit query" button.
2056 # $name -> (optional) Name for the button.
2057 # $value -> (optional) Value of the button when selected (also doubles as label).
2058 # $label -> (optional) Label printed on the button(also doubles as the value).
2060 # A string containing a <input type="submit"> tag
2062 'submit' => <<'END_OF_FUNC',
2064 my($self,@p) = self_or_default(@_);
2066 my($label,$value,$tabindex,@other) = rearrange([NAME,[VALUE,LABEL],TABINDEX],@p);
2068 $label=$self->escapeHTML($label);
2069 $value=$self->escapeHTML($value,1);
2071 my $name = $NOSTICKY ? '' : 'name=".submit" ';
2072 $name = qq/name="$label" / if defined($label);
2073 $value = defined($value) ? $value : $label;
2075 $val = qq/value="$value" / if defined($value);
2076 $tabindex = $self->element_tab($tabindex);
2077 my($other) = @other ? "@other " : '';
2078 return $XHTML ? qq(<input type="submit" $tabindex$name$val$other/>)
2079 : qq(<input type="submit" $name$val$other>);
2085 # Create a "reset" button.
2087 # $name -> (optional) Name for the button.
2089 # A string containing a <input type="reset"> tag
2091 'reset' => <<'END_OF_FUNC',
2093 my($self,@p) = self_or_default(@_);
2094 my($label,$value,$tabindex,@other) = rearrange(['NAME',['VALUE','LABEL'],TABINDEX],@p);
2095 $label=$self->escapeHTML($label);
2096 $value=$self->escapeHTML($value,1);
2097 my ($name) = ' name=".reset"';
2098 $name = qq/ name="$label"/ if defined($label);
2099 $value = defined($value) ? $value : $label;
2101 $val = qq/ value="$value"/ if defined($value);
2102 my($other) = @other ? " @other" : '';
2103 $tabindex = $self->element_tab($tabindex);
2104 return $XHTML ? qq(<input type="reset" $tabindex$name$val$other />)
2105 : qq(<input type="reset"$name$val$other>);
2110 #### Method: defaults
2111 # Create a "defaults" button.
2113 # $name -> (optional) Name for the button.
2115 # A string containing a <input type="submit" name=".defaults"> tag
2117 # Note: this button has a special meaning to the initialization script,
2118 # and tells it to ERASE the current query string so that your defaults
2121 'defaults' => <<'END_OF_FUNC',
2123 my($self,@p) = self_or_default(@_);
2125 my($label,$tabindex,@other) = rearrange([[NAME,VALUE],TABINDEX],@p);
2127 $label=$self->escapeHTML($label,1);
2128 $label = $label || "Defaults";
2129 my($value) = qq/ value="$label"/;
2130 my($other) = @other ? " @other" : '';
2131 $tabindex = $self->element_tab($tabindex);
2132 return $XHTML ? qq(<input type="submit" name=".defaults" $tabindex$value$other />)
2133 : qq/<input type="submit" NAME=".defaults"$value$other>/;
2138 #### Method: comment
2139 # Create an HTML <!-- comment -->
2140 # Parameters: a string
2141 'comment' => <<'END_OF_FUNC',
2143 my($self,@p) = self_or_CGI(@_);
2144 return "<!-- @p -->";
2148 #### Method: checkbox
2149 # Create a checkbox that is not logically linked to any others.
2150 # The field value is "on" when the button is checked.
2152 # $name -> Name of the checkbox
2153 # $checked -> (optional) turned on by default if true
2154 # $value -> (optional) value of the checkbox, 'on' by default
2155 # $label -> (optional) a user-readable label printed next to the box.
2156 # Otherwise the checkbox name is used.
2158 # A string containing a <input type="checkbox"> field
2160 'checkbox' => <<'END_OF_FUNC',
2162 my($self,@p) = self_or_default(@_);
2164 my($name,$checked,$value,$label,$labelattributes,$override,$tabindex,@other) =
2165 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,LABELATTRIBUTES,
2166 [OVERRIDE,FORCE],TABINDEX],@p);
2168 $value = defined $value ? $value : 'on';
2170 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2171 defined $self->param($name))) {
2172 $checked = grep($_ eq $value,$self->param($name)) ? $self->_checked(1) : '';
2174 $checked = $self->_checked($checked);
2176 my($the_label) = defined $label ? $label : $name;
2177 $name = $self->escapeHTML($name);
2178 $value = $self->escapeHTML($value,1);
2179 $the_label = $self->escapeHTML($the_label);
2180 my($other) = @other ? "@other " : '';
2181 $tabindex = $self->element_tab($tabindex);
2182 $self->register_parameter($name);
2183 return $XHTML ? CGI::label($labelattributes,
2184 qq{<input type="checkbox" name="$name" value="$value" $tabindex$checked$other/>$the_label})
2185 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
2191 # Escape HTML -- used internally
2192 'escapeHTML' => <<'END_OF_FUNC',
2194 # hack to work around earlier hacks
2195 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2196 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
2197 return undef unless defined($toencode);
2198 return $toencode if ref($self) && !$self->{'escape'};
2199 $toencode =~ s{&}{&}gso;
2200 $toencode =~ s{<}{<}gso;
2201 $toencode =~ s{>}{>}gso;
2202 if ($DTD_PUBLIC_IDENTIFIER =~ /[^X]HTML 3\.2/i) {
2203 # $quot; was accidentally omitted from the HTML 3.2 DTD -- see
2204 # <http://validator.w3.org/docs/errors.html#bad-entity> /
2205 # <http://lists.w3.org/Archives/Public/www-html/1997Mar/0003.html>.
2206 $toencode =~ s{"}{"}gso;
2209 $toencode =~ s{"}{"}gso;
2211 # Handle bug in some browsers with Latin charsets
2212 if ($self->{'.charset'} &&
2213 (uc($self->{'.charset'}) eq 'ISO-8859-1' ||
2214 uc($self->{'.charset'}) eq 'WINDOWS-1252'))
2216 $toencode =~ s{'}{'}gso;
2217 $toencode =~ s{\x8b}{‹}gso;
2218 $toencode =~ s{\x9b}{›}gso;
2219 if (defined $newlinestoo && $newlinestoo) {
2220 $toencode =~ s{\012}{ }gso;
2221 $toencode =~ s{\015}{ }gso;
2228 # unescape HTML -- used internally
2229 'unescapeHTML' => <<'END_OF_FUNC',
2231 # hack to work around earlier hacks
2232 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2233 my ($self,$string) = CGI::self_or_default(@_);
2234 return undef unless defined($string);
2235 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
2237 # thanks to Randal Schwartz for the correct solution to this one
2238 $string=~ s[&(.*?);]{
2244 /^#(\d+)$/ && $latin ? chr($1) :
2245 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
2252 # Internal procedure - don't use
2253 '_tableize' => <<'END_OF_FUNC',
2255 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
2256 my @rowheaders = $rowheaders ? @$rowheaders : ();
2257 my @colheaders = $colheaders ? @$colheaders : ();
2260 if (defined($columns)) {
2261 $rows = int(0.99 + @elements/$columns) unless defined($rows);
2263 if (defined($rows)) {
2264 $columns = int(0.99 + @elements/$rows) unless defined($columns);
2267 # rearrange into a pretty table
2268 $result = "<table>";
2270 unshift(@colheaders,'') if @colheaders && @rowheaders;
2271 $result .= "<tr>" if @colheaders;
2272 foreach (@colheaders) {
2273 $result .= "<th>$_</th>";
2275 for ($row=0;$row<$rows;$row++) {
2277 $result .= "<th>$rowheaders[$row]</th>" if @rowheaders;
2278 for ($column=0;$column<$columns;$column++) {
2279 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
2280 if defined($elements[$column*$rows + $row]);
2284 $result .= "</table>";
2290 #### Method: radio_group
2291 # Create a list of logically-linked radio buttons.
2293 # $name -> Common name for all the buttons.
2294 # $values -> A pointer to a regular array containing the
2295 # values for each button in the group.
2296 # $default -> (optional) Value of the button to turn on by default. Pass '-'
2297 # to turn _nothing_ on.
2298 # $linebreak -> (optional) Set to true to place linebreaks
2299 # between the buttons.
2300 # $labels -> (optional)
2301 # A pointer to an associative array of labels to print next to each checkbox
2302 # in the form $label{'value'}="Long explanatory label".
2303 # Otherwise the provided values are used as the labels.
2305 # An ARRAY containing a series of <input type="radio"> fields
2307 'radio_group' => <<'END_OF_FUNC',
2309 my($self,@p) = self_or_default(@_);
2310 $self->_box_group('radio',@p);
2314 #### Method: checkbox_group
2315 # Create a list of logically-linked checkboxes.
2317 # $name -> Common name for all the check boxes
2318 # $values -> A pointer to a regular array containing the
2319 # values for each checkbox in the group.
2320 # $defaults -> (optional)
2321 # 1. If a pointer to a regular array of checkbox values,
2322 # then this will be used to decide which
2323 # checkboxes to turn on by default.
2324 # 2. If a scalar, will be assumed to hold the
2325 # value of a single checkbox in the group to turn on.
2326 # $linebreak -> (optional) Set to true to place linebreaks
2327 # between the buttons.
2328 # $labels -> (optional)
2329 # A pointer to an associative array of labels to print next to each checkbox
2330 # in the form $label{'value'}="Long explanatory label".
2331 # Otherwise the provided values are used as the labels.
2333 # An ARRAY containing a series of <input type="checkbox"> fields
2336 'checkbox_group' => <<'END_OF_FUNC',
2337 sub checkbox_group {
2338 my($self,@p) = self_or_default(@_);
2339 $self->_box_group('checkbox',@p);
2343 '_box_group' => <<'END_OF_FUNC',
2346 my $box_type = shift;
2348 my($name,$values,$defaults,$linebreak,$labels,$labelattributes,
2349 $attributes,$rows,$columns,$rowheaders,$colheaders,
2350 $override,$nolabels,$tabindex,$disabled,@other) =
2351 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LINEBREAK,LABELS,LABELATTRIBUTES,
2352 ATTRIBUTES,ROWS,[COLUMNS,COLS],[ROWHEADERS,ROWHEADER],[COLHEADERS,COLHEADER],
2353 [OVERRIDE,FORCE],NOLABELS,TABINDEX,DISABLED
2357 my($result,$checked,@elements,@values);
2359 @values = $self->_set_values_and_labels($values,\$labels,$name);
2360 my %checked = $self->previous_or_default($name,$defaults,$override);
2362 # If no check array is specified, check the first by default
2363 $checked{$values[0]}++ if $box_type eq 'radio' && !%checked;
2365 $name=$self->escapeHTML($name);
2368 if ($TABINDEX && $tabindex) {
2369 if (!ref $tabindex) {
2370 $self->element_tab($tabindex);
2371 } elsif (ref $tabindex eq 'ARRAY') {
2372 %tabs = map {$_=>$self->element_tab} @$tabindex;
2373 } elsif (ref $tabindex eq 'HASH') {
2377 %tabs = map {$_=>$self->element_tab} @values unless %tabs;
2378 my $other = @other ? "@other " : '';
2381 # for disabling groups of radio/checkbox buttons
2383 foreach (@{$disabled}) {
2389 if ($disabled{$_}) {
2390 $disable="disabled='1'";
2393 my $checkit = $self->_checked($box_type eq 'radio' ? ($checked{$_} && !$radio_checked++)
2397 $break = $XHTML ? "<br />" : "<br>";
2403 unless (defined($nolabels) && $nolabels) {
2405 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2406 $label = $self->escapeHTML($label,1);
2407 $label = "<span style=\"color:gray\">$label</span>" if $disabled{$_};
2409 my $attribs = $self->_set_attributes($_, $attributes);
2410 my $tab = $tabs{$_};
2411 $_=$self->escapeHTML($_);
2415 CGI::label($labelattributes,
2416 qq(<input type="$box_type" name="$name" value="$_" $checkit$other$tab$attribs$disable/>$label)).${break};
2418 push(@elements,qq/<input type="$box_type" name="$name" value="$_"$checkit$other$tab$attribs$disable>${label}${break}/);
2421 $self->register_parameter($name);
2422 return wantarray ? @elements : "@elements"
2423 unless defined($columns) || defined($rows);
2424 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2429 #### Method: popup_menu
2430 # Create a popup menu.
2432 # $name -> Name for all the menu
2433 # $values -> A pointer to a regular array containing the
2434 # text of each menu item.
2435 # $default -> (optional) Default item to display
2436 # $labels -> (optional)
2437 # A pointer to an associative array of labels to print next to each checkbox
2438 # in the form $label{'value'}="Long explanatory label".
2439 # Otherwise the provided values are used as the labels.
2441 # A string containing the definition of a popup menu.
2443 'popup_menu' => <<'END_OF_FUNC',
2445 my($self,@p) = self_or_default(@_);
2447 my($name,$values,$default,$labels,$attributes,$override,$tabindex,@other) =
2448 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,
2449 ATTRIBUTES,[OVERRIDE,FORCE],TABINDEX],@p);
2450 my($result,%selected);
2452 if (!$override && defined($self->param($name))) {
2453 $selected{$self->param($name)}++;
2454 } elsif ($default) {
2455 %selected = map {$_=>1} ref($default) eq 'ARRAY'
2459 $name=$self->escapeHTML($name);
2460 my($other) = @other ? " @other" : '';
2463 @values = $self->_set_values_and_labels($values,\$labels,$name);
2464 $tabindex = $self->element_tab($tabindex);
2465 $result = qq/<select name="$name" $tabindex$other>\n/;
2468 for my $v (split(/\n/)) {
2469 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2470 for my $selected (keys %selected) {
2471 $v =~ s/(value="$selected")/$selectit $1/;
2477 my $attribs = $self->_set_attributes($_, $attributes);
2478 my($selectit) = $self->_selected($selected{$_});
2480 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2481 my($value) = $self->escapeHTML($_);
2482 $label = $self->escapeHTML($label,1);
2483 $result .= "<option${attribs} ${selectit}value=\"$value\">$label</option>\n";
2487 $result .= "</select>";
2493 #### Method: optgroup
2494 # Create a optgroup.
2496 # $name -> Label for the group
2497 # $values -> A pointer to a regular array containing the
2498 # values for each option line in the group.
2499 # $labels -> (optional)
2500 # A pointer to an associative array of labels to print next to each item
2501 # in the form $label{'value'}="Long explanatory label".
2502 # Otherwise the provided values are used as the labels.
2503 # $labeled -> (optional)
2504 # A true value indicates the value should be used as the label attribute
2505 # in the option elements.
2506 # The label attribute specifies the option label presented to the user.
2507 # This defaults to the content of the <option> element, but the label
2508 # attribute allows authors to more easily use optgroup without sacrificing
2509 # compatibility with browsers that do not support option groups.
2510 # $novals -> (optional)
2511 # A true value indicates to suppress the val attribute in the option elements
2513 # A string containing the definition of an option group.
2515 'optgroup' => <<'END_OF_FUNC',
2517 my($self,@p) = self_or_default(@_);
2518 my($name,$values,$attributes,$labeled,$noval,$labels,@other)
2519 = rearrange([NAME,[VALUES,VALUE],ATTRIBUTES,LABELED,NOVALS,LABELS],@p);
2521 my($result,@values);
2522 @values = $self->_set_values_and_labels($values,\$labels,$name,$labeled,$novals);
2523 my($other) = @other ? " @other" : '';
2525 $name=$self->escapeHTML($name);
2526 $result = qq/<optgroup label="$name"$other>\n/;
2529 foreach (split(/\n/)) {
2530 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2531 s/(value="$selected")/$selectit $1/ if defined $selected;
2536 my $attribs = $self->_set_attributes($_, $attributes);
2538 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2539 $label=$self->escapeHTML($label);
2540 my($value)=$self->escapeHTML($_,1);
2541 $result .= $labeled ? $novals ? "<option$attribs label=\"$value\">$label</option>\n"
2542 : "<option$attribs label=\"$value\" value=\"$value\">$label</option>\n"
2543 : $novals ? "<option$attribs>$label</option>\n"
2544 : "<option$attribs value=\"$value\">$label</option>\n";
2547 $result .= "</optgroup>";
2553 #### Method: scrolling_list
2554 # Create a scrolling list.
2556 # $name -> name for the list
2557 # $values -> A pointer to a regular array containing the
2558 # values for each option line in the list.
2559 # $defaults -> (optional)
2560 # 1. If a pointer to a regular array of options,
2561 # then this will be used to decide which
2562 # lines to turn on by default.
2563 # 2. Otherwise holds the value of the single line to turn on.
2564 # $size -> (optional) Size of the list.
2565 # $multiple -> (optional) If set, allow multiple selections.
2566 # $labels -> (optional)
2567 # A pointer to an associative array of labels to print next to each checkbox
2568 # in the form $label{'value'}="Long explanatory label".
2569 # Otherwise the provided values are used as the labels.
2571 # A string containing the definition of a scrolling list.
2573 'scrolling_list' => <<'END_OF_FUNC',
2574 sub scrolling_list {
2575 my($self,@p) = self_or_default(@_);
2576 my($name,$values,$defaults,$size,$multiple,$labels,$attributes,$override,$tabindex,@other)
2577 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2578 SIZE,MULTIPLE,LABELS,ATTRIBUTES,[OVERRIDE,FORCE],TABINDEX],@p);
2580 my($result,@values);
2581 @values = $self->_set_values_and_labels($values,\$labels,$name);
2583 $size = $size || scalar(@values);
2585 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2587 my($is_multiple) = $multiple ? qq/ multiple="multiple"/ : '';
2588 my($has_size) = $size ? qq/ size="$size"/: '';
2589 my($other) = @other ? " @other" : '';
2591 $name=$self->escapeHTML($name);
2592 $tabindex = $self->element_tab($tabindex);
2593 $result = qq/<select name="$name" $tabindex$has_size$is_multiple$other>\n/;
2595 my($selectit) = $self->_selected($selected{$_});
2597 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2598 $label=$self->escapeHTML($label);
2599 my($value)=$self->escapeHTML($_,1);
2600 my $attribs = $self->_set_attributes($_, $attributes);
2601 $result .= "<option ${selectit}${attribs}value=\"$value\">$label</option>\n";
2603 $result .= "</select>";
2604 $self->register_parameter($name);
2612 # $name -> Name of the hidden field
2613 # @default -> (optional) Initial values of field (may be an array)
2615 # $default->[initial values of field]
2617 # A string containing a <input type="hidden" name="name" value="value">
2619 'hidden' => <<'END_OF_FUNC',
2621 my($self,@p) = self_or_default(@_);
2623 # this is the one place where we departed from our standard
2624 # calling scheme, so we have to special-case (darn)
2626 my($name,$default,$override,@other) =
2627 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2629 my $do_override = 0;
2630 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2631 @value = ref($default) ? @{$default} : $default;
2632 $do_override = $override;
2634 foreach ($default,$override,@other) {
2635 push(@value,$_) if defined($_);
2639 # use previous values if override is not set
2640 my @prev = $self->param($name);
2641 @value = @prev if !$do_override && @prev;
2643 $name=$self->escapeHTML($name);
2645 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2646 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" @other />)
2647 : qq(<input type="hidden" name="$name" value="$_" @other>);
2649 return wantarray ? @result : join('',@result);
2654 #### Method: image_button
2656 # $name -> Name of the button
2657 # $src -> URL of the image source
2658 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2660 # A string containing a <input type="image" name="name" src="url" align="alignment">
2662 'image_button' => <<'END_OF_FUNC',
2664 my($self,@p) = self_or_default(@_);
2666 my($name,$src,$alignment,@other) =
2667 rearrange([NAME,SRC,ALIGN],@p);
2669 my($align) = $alignment ? " align=\L\"$alignment\"" : '';
2670 my($other) = @other ? " @other" : '';
2671 $name=$self->escapeHTML($name);
2672 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2673 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2678 #### Method: self_url
2679 # Returns a URL containing the current script and all its
2680 # param/value pairs arranged as a query. You can use this
2681 # to create a link that, when selected, will reinvoke the
2682 # script with all its state information preserved.
2684 'self_url' => <<'END_OF_FUNC',
2686 my($self,@p) = self_or_default(@_);
2687 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2692 # This is provided as a synonym to self_url() for people unfortunate
2693 # enough to have incorporated it into their programs already!
2694 'state' => <<'END_OF_FUNC',
2702 # Like self_url, but doesn't return the query string part of
2705 'url' => <<'END_OF_FUNC',
2707 my($self,@p) = self_or_default(@_);
2708 my ($relative,$absolute,$full,$path_info,$query,$base,$rewrite) =
2709 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE','REWRITE'],@p);
2711 $full++ if $base || !($relative || $absolute);
2712 $rewrite++ unless defined $rewrite;
2714 my $path = $self->path_info;
2715 my $script_name = $self->script_name;
2716 my $request_uri = unescape($self->request_uri) || '';
2717 my $query_str = $self->query_string;
2719 my $rewrite_in_use = $request_uri && $request_uri !~ /^\Q$script_name/;
2720 undef $path if $rewrite_in_use && $rewrite; # path not valid when rewriting active
2722 my $uri = $rewrite && $request_uri ? $request_uri : $script_name;
2723 $uri =~ s/\?.*$//; # remove query string
2724 $uri =~ s/\Q$path\E$// if defined $path; # remove path
2727 my $protocol = $self->protocol();
2728 $url = "$protocol://";
2729 my $vh = http('x_forwarded_host') || http('host') || '';
2730 $vh =~ s/\:\d+$//; # some clients add the port number (incorrectly). Get rid of it.
2734 $url .= server_name();
2736 my $port = $self->server_port;
2738 unless (lc($protocol) eq 'http' && $port == 80)
2739 || (lc($protocol) eq 'https' && $port == 443);
2740 return $url if $base;
2742 } elsif ($relative) {
2743 ($url) = $uri =~ m!([^/]+)$!;
2744 } elsif ($absolute) {
2748 $url .= $path if $path_info and defined $path;
2749 $url .= "?$query_str" if $query and $query_str ne '';
2751 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
2758 # Set or read a cookie from the specified name.
2759 # Cookie can then be passed to header().
2760 # Usual rules apply to the stickiness of -value.
2762 # -name -> name for this cookie (optional)
2763 # -value -> value of this cookie (scalar, array or hash)
2764 # -path -> paths for which this cookie is valid (optional)
2765 # -domain -> internet domain in which this cookie is valid (optional)
2766 # -secure -> if true, cookie only passed through secure channel (optional)
2767 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2769 'cookie' => <<'END_OF_FUNC',
2771 my($self,@p) = self_or_default(@_);
2772 my($name,$value,$path,$domain,$secure,$expires,$httponly) =
2773 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES,HTTPONLY],@p);
2775 require CGI::Cookie;
2777 # if no value is supplied, then we retrieve the
2778 # value of the cookie, if any. For efficiency, we cache the parsed
2779 # cookies in our state variables.
2780 unless ( defined($value) ) {
2781 $self->{'.cookies'} = CGI::Cookie->fetch
2782 unless $self->{'.cookies'};
2784 # If no name is supplied, then retrieve the names of all our cookies.
2785 return () unless $self->{'.cookies'};
2786 return keys %{$self->{'.cookies'}} unless $name;
2787 return () unless $self->{'.cookies'}->{$name};
2788 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2791 # If we get here, we're creating a new cookie
2792 return undef unless defined($name) && $name ne ''; # this is an error
2795 push(@param,'-name'=>$name);
2796 push(@param,'-value'=>$value);
2797 push(@param,'-domain'=>$domain) if $domain;
2798 push(@param,'-path'=>$path) if $path;
2799 push(@param,'-expires'=>$expires) if $expires;
2800 push(@param,'-secure'=>$secure) if $secure;
2801 push(@param,'-httponly'=>$httponly) if $httponly;
2803 return new CGI::Cookie(@param);
2807 'parse_keywordlist' => <<'END_OF_FUNC',
2808 sub parse_keywordlist {
2809 my($self,$tosplit) = @_;
2810 $tosplit = unescape($tosplit); # unescape the keywords
2811 $tosplit=~tr/+/ /; # pluses to spaces
2812 my(@keywords) = split(/\s+/,$tosplit);
2817 'param_fetch' => <<'END_OF_FUNC',
2819 my($self,@p) = self_or_default(@_);
2820 my($name) = rearrange([NAME],@p);
2821 unless (exists($self->{param}{$name})) {
2822 $self->add_parameter($name);
2823 $self->{param}{$name} = [];
2826 return $self->{param}{$name};
2830 ###############################################
2831 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2832 ###############################################
2834 #### Method: path_info
2835 # Return the extra virtual path information provided
2836 # after the URL (if any)
2838 'path_info' => <<'END_OF_FUNC',
2840 my ($self,$info) = self_or_default(@_);
2841 if (defined($info)) {
2842 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2843 $self->{'.path_info'} = $info;
2844 } elsif (! defined($self->{'.path_info'}) ) {
2845 my (undef,$path_info) = $self->_name_and_path_from_env;
2846 $self->{'.path_info'} = $path_info || '';
2848 return $self->{'.path_info'};
2852 # This function returns a potentially modified version of SCRIPT_NAME
2853 # and PATH_INFO. Some HTTP servers do sanitise the paths in those
2854 # variables. It is the case of at least Apache 2. If for instance the
2855 # user requests: /path/./to/script.cgi/x//y/z/../x?y, Apache will set:
2856 # REQUEST_URI=/path/./to/script.cgi/x//y/z/../x?y
2857 # SCRIPT_NAME=/path/to/env.cgi
2860 # This is all fine except that some bogus CGI scripts expect
2861 # PATH_INFO=/http://foo when the user requests
2862 # http://xxx/script.cgi/http://foo
2864 # Old versions of this module used to accomodate with those scripts, so
2865 # this is why we do this here to keep those scripts backward compatible.
2866 # Basically, we accomodate with those scripts but within limits, that is
2867 # we only try to preserve the number of / that were provided by the user
2868 # if $REQUEST_URI and "$SCRIPT_NAME$PATH_INFO" only differ by the number
2871 # So for instance, in: http://foo/x//y/script.cgi/a//b, we'll return a
2872 # script_name of /x//y/script.cgi and a path_info of /a//b, but in:
2873 # http://foo/./x//z/script.cgi/a/../b//c, we'll return the versions
2874 # possibly sanitised by the HTTP server, so in the case of Apache 2:
2875 # script_name == /foo/x/z/script.cgi and path_info == /b/c.
2877 # Future versions of this module may no longer do that, so one should
2878 # avoid relying on the browser, proxy, server, and CGI.pm preserving the
2879 # number of consecutive slashes as no guarantee can be made there.
2880 '_name_and_path_from_env' => <<'END_OF_FUNC',
2881 sub _name_and_path_from_env {
2883 my $script_name = $ENV{SCRIPT_NAME} || '';
2884 my $path_info = $ENV{PATH_INFO} || '';
2885 my $uri = $self->request_uri || '';
2888 $uri = unescape($uri);
2890 if ($uri ne "$script_name$path_info") {
2891 my $script_name_pattern = quotemeta($script_name);
2892 my $path_info_pattern = quotemeta($path_info);
2893 $script_name_pattern =~ s{(?:\\/)+}{/+}g;
2894 $path_info_pattern =~ s{(?:\\/)+}{/+}g;
2896 if ($uri =~ /^($script_name_pattern)($path_info_pattern)$/s) {
2897 # REQUEST_URI and SCRIPT_NAME . PATH_INFO only differ by the
2898 # numer of consecutive slashes, so we can extract the info from
2900 ($script_name, $path_info) = ($1, $2);
2903 return ($script_name,$path_info);
2908 #### Method: request_method
2909 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2911 'request_method' => <<'END_OF_FUNC',
2912 sub request_method {
2913 return $ENV{'REQUEST_METHOD'};
2917 #### Method: content_type
2918 # Returns the content_type string
2920 'content_type' => <<'END_OF_FUNC',
2922 return $ENV{'CONTENT_TYPE'};
2926 #### Method: path_translated
2927 # Return the physical path information provided
2928 # by the URL (if any)
2930 'path_translated' => <<'END_OF_FUNC',
2931 sub path_translated {
2932 return $ENV{'PATH_TRANSLATED'};
2937 #### Method: request_uri
2938 # Return the literal request URI
2940 'request_uri' => <<'END_OF_FUNC',
2942 return $ENV{'REQUEST_URI'};
2947 #### Method: query_string
2948 # Synthesize a query string from our current
2951 'query_string' => <<'END_OF_FUNC',
2953 my($self) = self_or_default(@_);
2954 my($param,$value,@pairs);
2955 foreach $param ($self->param) {
2956 my($eparam) = escape($param);
2957 foreach $value ($self->param($param)) {
2958 $value = escape($value);
2959 next unless defined $value;
2960 push(@pairs,"$eparam=$value");
2963 foreach (keys %{$self->{'.fieldnames'}}) {
2964 push(@pairs,".cgifields=".escape("$_"));
2966 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2972 # Without parameters, returns an array of the
2973 # MIME types the browser accepts.
2974 # With a single parameter equal to a MIME
2975 # type, will return undef if the browser won't
2976 # accept it, 1 if the browser accepts it but
2977 # doesn't give a preference, or a floating point
2978 # value between 0.0 and 1.0 if the browser
2979 # declares a quantitative score for it.
2980 # This handles MIME type globs correctly.
2982 'Accept' => <<'END_OF_FUNC',
2984 my($self,$search) = self_or_CGI(@_);
2985 my(%prefs,$type,$pref,$pat);
2987 my(@accept) = defined $self->http('accept')
2988 ? split(',',$self->http('accept'))
2992 ($pref) = /q=(\d\.\d+|\d+)/;
2993 ($type) = m#(\S+/[^;]+)#;
2995 $prefs{$type}=$pref || 1;
2998 return keys %prefs unless $search;
3000 # if a search type is provided, we may need to
3001 # perform a pattern matching operation.
3002 # The MIME types use a glob mechanism, which
3003 # is easily translated into a perl pattern match
3005 # First return the preference for directly supported
3007 return $prefs{$search} if $prefs{$search};
3009 # Didn't get it, so try pattern matching.
3010 foreach (keys %prefs) {
3011 next unless /\*/; # not a pattern match
3012 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
3013 $pat =~ s/\*/.*/g; # turn it into a pattern
3014 return $prefs{$_} if $search=~/$pat/;
3020 #### Method: user_agent
3021 # If called with no parameters, returns the user agent.
3022 # If called with one parameter, does a pattern match (case
3023 # insensitive) on the user agent.
3025 'user_agent' => <<'END_OF_FUNC',
3027 my($self,$match)=self_or_CGI(@_);
3028 return $self->http('user_agent') unless $match;
3029 return $self->http('user_agent') =~ /$match/i;
3034 #### Method: raw_cookie
3035 # Returns the magic cookies for the session.
3036 # The cookies are not parsed or altered in any way, i.e.
3037 # cookies are returned exactly as given in the HTTP
3038 # headers. If a cookie name is given, only that cookie's
3039 # value is returned, otherwise the entire raw cookie
3042 'raw_cookie' => <<'END_OF_FUNC',
3044 my($self,$key) = self_or_CGI(@_);
3046 require CGI::Cookie;
3048 if (defined($key)) {
3049 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
3050 unless $self->{'.raw_cookies'};
3052 return () unless $self->{'.raw_cookies'};
3053 return () unless $self->{'.raw_cookies'}->{$key};
3054 return $self->{'.raw_cookies'}->{$key};
3056 return $self->http('cookie') || $ENV{'COOKIE'} || '';
3060 #### Method: virtual_host
3061 # Return the name of the virtual_host, which
3062 # is not always the same as the server
3064 'virtual_host' => <<'END_OF_FUNC',
3066 my $vh = http('x_forwarded_host') || http('host') || server_name();
3067 $vh =~ s/:\d+$//; # get rid of port number
3072 #### Method: remote_host
3073 # Return the name of the remote host, or its IP
3074 # address if unavailable. If this variable isn't
3075 # defined, it returns "localhost" for debugging
3078 'remote_host' => <<'END_OF_FUNC',
3080 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
3086 #### Method: remote_addr
3087 # Return the IP addr of the remote host.
3089 'remote_addr' => <<'END_OF_FUNC',
3091 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
3096 #### Method: script_name
3097 # Return the partial URL to this script for
3098 # self-referencing scripts. Also see
3099 # self_url(), which returns a URL with all state information
3102 'script_name' => <<'END_OF_FUNC',
3104 my ($self,@p) = self_or_default(@_);
3106 $self->{'.script_name'} = shift @p;
3107 } elsif (!exists $self->{'.script_name'}) {
3108 my ($script_name,$path_info) = $self->_name_and_path_from_env();
3109 $self->{'.script_name'} = $script_name;
3111 return $self->{'.script_name'};
3116 #### Method: referer
3117 # Return the HTTP_REFERER: useful for generating
3120 'referer' => <<'END_OF_FUNC',
3122 my($self) = self_or_CGI(@_);
3123 return $self->http('referer');
3128 #### Method: server_name
3129 # Return the name of the server
3131 'server_name' => <<'END_OF_FUNC',
3133 return $ENV{'SERVER_NAME'} || 'localhost';
3137 #### Method: server_software
3138 # Return the name of the server software
3140 'server_software' => <<'END_OF_FUNC',
3141 sub server_software {
3142 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
3146 #### Method: virtual_port
3147 # Return the server port, taking virtual hosts into account
3149 'virtual_port' => <<'END_OF_FUNC',
3151 my($self) = self_or_default(@_);
3152 my $vh = $self->http('x_forwarded_host') || $self->http('host');
3153 my $protocol = $self->protocol;
3155 return ($vh =~ /:(\d+)$/)[0] || ($protocol eq 'https' ? 443 : 80);
3157 return $self->server_port();
3162 #### Method: server_port
3163 # Return the tcp/ip port the server is running on
3165 'server_port' => <<'END_OF_FUNC',
3167 return $ENV{'SERVER_PORT'} || 80; # for debugging
3171 #### Method: server_protocol
3172 # Return the protocol (usually HTTP/1.0)
3174 'server_protocol' => <<'END_OF_FUNC',
3175 sub server_protocol {
3176 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
3181 # Return the value of an HTTP variable, or
3182 # the list of variables if none provided
3184 'http' => <<'END_OF_FUNC',
3186 my ($self,$parameter) = self_or_CGI(@_);
3187 return $ENV{$parameter} if $parameter=~/^HTTP/;
3188 $parameter =~ tr/-/_/;
3189 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
3191 foreach (keys %ENV) {
3192 push(@p,$_) if /^HTTP/;
3199 # Return the value of HTTPS
3201 'https' => <<'END_OF_FUNC',
3204 my ($self,$parameter) = self_or_CGI(@_);
3205 return $ENV{HTTPS} unless $parameter;
3206 return $ENV{$parameter} if $parameter=~/^HTTPS/;
3207 $parameter =~ tr/-/_/;
3208 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
3210 foreach (keys %ENV) {
3211 push(@p,$_) if /^HTTPS/;
3217 #### Method: protocol
3218 # Return the protocol (http or https currently)
3220 'protocol' => <<'END_OF_FUNC',
3224 return 'https' if uc($self->https()) eq 'ON';
3225 return 'https' if $self->server_port == 443;
3226 my $prot = $self->server_protocol;
3227 my($protocol,$version) = split('/',$prot);
3228 return "\L$protocol\E";
3232 #### Method: remote_ident
3233 # Return the identity of the remote user
3234 # (but only if his host is running identd)
3236 'remote_ident' => <<'END_OF_FUNC',
3238 return $ENV{'REMOTE_IDENT'};
3243 #### Method: auth_type
3244 # Return the type of use verification/authorization in use, if any.
3246 'auth_type' => <<'END_OF_FUNC',
3248 return $ENV{'AUTH_TYPE'};
3253 #### Method: remote_user
3254 # Return the authorization name used for user
3257 'remote_user' => <<'END_OF_FUNC',
3259 return $ENV{'REMOTE_USER'};
3264 #### Method: user_name
3265 # Try to return the remote user's name by hook or by
3268 'user_name' => <<'END_OF_FUNC',
3270 my ($self) = self_or_CGI(@_);
3271 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
3275 #### Method: nosticky
3276 # Set or return the NOSTICKY global flag
3278 'nosticky' => <<'END_OF_FUNC',
3280 my ($self,$param) = self_or_CGI(@_);
3281 $CGI::NOSTICKY = $param if defined($param);
3282 return $CGI::NOSTICKY;
3287 # Set or return the NPH global flag
3289 'nph' => <<'END_OF_FUNC',
3291 my ($self,$param) = self_or_CGI(@_);
3292 $CGI::NPH = $param if defined($param);
3297 #### Method: private_tempfiles
3298 # Set or return the private_tempfiles global flag
3300 'private_tempfiles' => <<'END_OF_FUNC',
3301 sub private_tempfiles {
3302 my ($self,$param) = self_or_CGI(@_);
3303 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
3304 return $CGI::PRIVATE_TEMPFILES;
3307 #### Method: close_upload_files
3308 # Set or return the close_upload_files global flag
3310 'close_upload_files' => <<'END_OF_FUNC',
3311 sub close_upload_files {
3312 my ($self,$param) = self_or_CGI(@_);
3313 $CGI::CLOSE_UPLOAD_FILES = $param if defined($param);
3314 return $CGI::CLOSE_UPLOAD_FILES;
3319 #### Method: default_dtd
3320 # Set or return the default_dtd global
3322 'default_dtd' => <<'END_OF_FUNC',
3324 my ($self,$param,$param2) = self_or_CGI(@_);
3325 if (defined $param2 && defined $param) {
3326 $CGI::DEFAULT_DTD = [ $param, $param2 ];
3327 } elsif (defined $param) {
3328 $CGI::DEFAULT_DTD = $param;
3330 return $CGI::DEFAULT_DTD;
3334 # -------------- really private subroutines -----------------
3335 'previous_or_default' => <<'END_OF_FUNC',
3336 sub previous_or_default {
3337 my($self,$name,$defaults,$override) = @_;
3340 if (!$override && ($self->{'.fieldnames'}->{$name} ||
3341 defined($self->param($name)) ) ) {
3342 $selected{$_}++ for $self->param($name);
3343 } elsif (defined($defaults) && ref($defaults) &&
3344 (ref($defaults) eq 'ARRAY')) {
3345 $selected{$_}++ for @{$defaults};
3347 $selected{$defaults}++ if defined($defaults);
3354 'register_parameter' => <<'END_OF_FUNC',
3355 sub register_parameter {
3356 my($self,$param) = @_;
3357 $self->{'.parametersToAdd'}->{$param}++;
3361 'get_fields' => <<'END_OF_FUNC',
3364 return $self->CGI::hidden('-name'=>'.cgifields',
3365 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
3370 'read_from_cmdline' => <<'END_OF_FUNC',
3371 sub read_from_cmdline {
3375 if ($DEBUG && @ARGV) {
3377 } elsif ($DEBUG > 1) {
3378 require "shellwords.pl";
3379 print STDERR "(offline mode: enter name=value pairs on standard input; press ^D or ^Z when done)\n";
3380 chomp(@lines = <STDIN>); # remove newlines
3381 $input = join(" ",@lines);
3382 @words = &shellwords($input);
3389 if ("@words"=~/=/) {
3390 $query_string = join('&',@words);
3392 $query_string = join('+',@words);
3394 if ($query_string =~ /^(.*?)\?(.*)$/)
3399 return { 'query_string' => $query_string, 'subpath' => $subpath };
3404 # subroutine: read_multipart
3406 # Read multipart data and store it into our parameters.
3407 # An interesting feature is that if any of the parts is a file, we
3408 # create a temporary file and open up a filehandle on it so that the
3409 # caller can read from it if necessary.
3411 'read_multipart' => <<'END_OF_FUNC',
3412 sub read_multipart {
3413 my($self,$boundary,$length) = @_;
3414 my($buffer) = $self->new_MultipartBuffer($boundary,$length);
3415 return unless $buffer;
3418 while (!$buffer->eof) {
3419 %header = $buffer->readHeader;
3422 $self->cgi_error("400 Bad request (malformed multipart POST)");
3426 $header{'Content-Disposition'} ||= ''; # quench uninit variable warning
3428 my($param)= $header{'Content-Disposition'}=~/ name="([^"]*)"/;
3431 # See RFC 1867, 2183, 2045
3432 # NB: File content will be loaded into memory should
3433 # content-disposition parsing fail.
3434 my ($filename) = $header{'Content-Disposition'}
3435 =~/ filename=(("[^"]*")|([a-z\d!\#'\*\+,\.^_\`\{\}\|\~]*))/i;
3437 $filename ||= ''; # quench uninit variable warning
3439 $filename =~ s/^"([^"]*)"$/$1/;
3440 # Test for Opera's multiple upload feature
3441 my($multipart) = ( defined( $header{'Content-Type'} ) &&
3442 $header{'Content-Type'} =~ /multipart\/mixed/ ) ?
3445 # add this parameter to our list
3446 $self->add_parameter($param);
3448 # If no filename specified, then just read the data and assign it
3449 # to our parameter list.
3450 if ( ( !defined($filename) || $filename eq '' ) && !$multipart ) {
3451 my($value) = $buffer->readBody;
3453 push(@{$self->{param}{$param}},$value);
3457 my ($tmpfile,$tmp,$filehandle);
3459 # If we get here, then we are dealing with a potentially large
3460 # uploaded form. Save the data to a temporary file, then open
3461 # the file for reading.
3463 # skip the file if uploads disabled
3464 if ($DISABLE_UPLOADS) {
3465 while (defined($data = $buffer->read)) { }
3469 # set the filename to some recognizable value
3470 if ( ( !defined($filename) || $filename eq '' ) && $multipart ) {
3471 $filename = "multipart/mixed";
3474 # choose a relatively unpredictable tmpfile sequence number
3475 my $seqno = unpack("%16C*",join('',localtime,grep {defined $_} values %ENV));
3476 for (my $cnt=10;$cnt>0;$cnt--) {
3477 next unless $tmpfile = new CGITempFile($seqno);
3478 $tmp = $tmpfile->as_string;
3479 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
3480 $seqno += int rand(100);
3482 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
3483 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode
3484 && defined fileno($filehandle);
3486 # if this is an multipart/mixed attachment, save the header
3487 # together with the body for later parsing with an external
3488 # MIME parser module
3490 foreach ( keys %header ) {
3491 print $filehandle "$_: $header{$_}${CRLF}";
3493 print $filehandle "${CRLF}";
3499 while (defined($data = $buffer->read)) {
3500 if (defined $self->{'.upload_hook'})
3502 $totalbytes += length($data);
3503 &{$self->{'.upload_hook'}}($filename ,$data, $totalbytes, $self->{'.upload_data'});
3505 print $filehandle $data if ($self->{'use_tempfile'});
3508 # back up to beginning of file
3509 seek($filehandle,0,0);
3511 ## Close the filehandle if requested this allows a multipart MIME
3512 ## upload to contain many files, and we won't die due to too many
3513 ## open file handles. The user can access the files using the hash
3515 close $filehandle if $CLOSE_UPLOAD_FILES;
3516 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3518 # Save some information about the uploaded file where we can get
3520 # Use the typeglob as the key, as this is guaranteed to be
3521 # unique for each filehandle. Don't use the file descriptor as
3522 # this will be re-used for each filehandle if the
3523 # close_upload_files feature is used.
3524 $self->{'.tmpfiles'}->{$$filehandle}= {
3525 hndl => $filehandle,
3529 push(@{$self->{param}{$param}},$filehandle);
3536 # subroutine: read_multipart_related
3538 # Read multipart/related data and store it into our parameters. The
3539 # first parameter sets the start of the data. The part identified by
3540 # this Content-ID will not be stored as a file upload, but will be
3541 # returned by this method. All other parts will be available as file
3542 # uploads accessible by their Content-ID
3544 'read_multipart_related' => <<'END_OF_FUNC',
3545 sub read_multipart_related {
3546 my($self,$start,$boundary,$length) = @_;
3547 my($buffer) = $self->new_MultipartBuffer($boundary,$length);
3548 return unless $buffer;
3552 while (!$buffer->eof) {
3553 %header = $buffer->readHeader;
3556 $self->cgi_error("400 Bad request (malformed multipart POST)");
3560 my($param) = $header{'Content-ID'}=~/\<([^\>]*)\>/;
3563 # If this is the start part, then just read the data and assign it
3564 # to our return variable.
3565 if ( $param eq $start ) {
3566 $returnvalue = $buffer->readBody;
3567 $returnvalue .= $TAINTED;
3571 # add this parameter to our list
3572 $self->add_parameter($param);
3574 my ($tmpfile,$tmp,$filehandle);
3576 # If we get here, then we are dealing with a potentially large
3577 # uploaded form. Save the data to a temporary file, then open
3578 # the file for reading.
3580 # skip the file if uploads disabled
3581 if ($DISABLE_UPLOADS) {
3582 while (defined($data = $buffer->read)) { }
3586 # choose a relatively unpredictable tmpfile sequence number
3587 my $seqno = unpack("%16C*",join('',localtime,grep {defined $_} values %ENV));
3588 for (my $cnt=10;$cnt>0;$cnt--) {
3589 next unless $tmpfile = new CGITempFile($seqno);
3590 $tmp = $tmpfile->as_string;
3591 last if defined($filehandle = Fh->new($param,$tmp,$PRIVATE_TEMPFILES));
3592 $seqno += int rand(100);
3594 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
3595 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode
3596 && defined fileno($filehandle);
3601 while (defined($data = $buffer->read)) {
3602 if (defined $self->{'.upload_hook'})
3604 $totalbytes += length($data);
3605 &{$self->{'.upload_hook'}}($param ,$data, $totalbytes, $self->{'.upload_data'});
3607 print $filehandle $data if ($self->{'use_tempfile'});
3610 # back up to beginning of file
3611 seek($filehandle,0,0);
3613 ## Close the filehandle if requested this allows a multipart MIME
3614 ## upload to contain many files, and we won't die due to too many
3615 ## open file handles. The user can access the files using the hash
3617 close $filehandle if $CLOSE_UPLOAD_FILES;
3618 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3620 # Save some information about the uploaded file where we can get
3622 # Use the typeglob as the key, as this is guaranteed to be
3623 # unique for each filehandle. Don't use the file descriptor as
3624 # this will be re-used for each filehandle if the
3625 # close_upload_files feature is used.
3626 $self->{'.tmpfiles'}->{$$filehandle}= {
3627 hndl => $filehandle,
3631 push(@{$self->{param}{$param}},$filehandle);
3634 return $returnvalue;
3639 'upload' =><<'END_OF_FUNC',
3641 my($self,$param_name) = self_or_default(@_);
3642 my @param = grep {ref($_) && defined(fileno($_))} $self->param($param_name);
3643 return unless @param;
3644 return wantarray ? @param : $param[0];
3648 'tmpFileName' => <<'END_OF_FUNC',
3650 my($self,$filename) = self_or_default(@_);
3651 return $self->{'.tmpfiles'}->{$$filename}->{name} ?
3652 $self->{'.tmpfiles'}->{$$filename}->{name}->as_string
3657 'uploadInfo' => <<'END_OF_FUNC',
3659 my($self,$filename) = self_or_default(@_);
3660 return $self->{'.tmpfiles'}->{$$filename}->{info};
3664 # internal routine, don't use
3665 '_set_values_and_labels' => <<'END_OF_FUNC',
3666 sub _set_values_and_labels {
3669 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
3670 return $self->param($n) if !defined($v);
3671 return $v if !ref($v);
3672 return ref($v) eq 'HASH' ? keys %$v : @$v;
3676 # internal routine, don't use
3677 '_set_attributes' => <<'END_OF_FUNC',
3678 sub _set_attributes {
3680 my($element, $attributes) = @_;
3681 return '' unless defined($attributes->{$element});
3683 foreach my $attrib (keys %{$attributes->{$element}}) {
3684 (my $clean_attrib = $attrib) =~ s/^-//;
3685 $attribs .= "@{[lc($clean_attrib)]}=\"$attributes->{$element}{$attrib}\" ";
3692 '_compile_all' => <<'END_OF_FUNC',
3695 next if defined(&$_);
3696 $AUTOLOAD = "CGI::$_";
3706 #########################################################
3707 # Globals and stubs for other packages that we use.
3708 #########################################################
3710 ################### Fh -- lightweight filehandle ###############
3719 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3726 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3727 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3729 'asString' => <<'END_OF_FUNC',
3732 # get rid of package name
3733 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3734 $i =~ s/%(..)/ chr(hex($1)) /eg;
3735 return $i.$CGI::TAINTED;
3737 # This was an extremely clever patch that allowed "use strict refs".
3738 # Unfortunately it relied on another bug that caused leaky file descriptors.
3739 # The underlying bug has been fixed, so this no longer works. However
3740 # "strict refs" still works for some reason.
3742 # return ${*{$self}{SCALAR}};
3747 'compare' => <<'END_OF_FUNC',
3751 return "$self" cmp $value;
3755 'new' => <<'END_OF_FUNC',
3757 my($pack,$name,$file,$delete) = @_;
3758 _setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
3759 require Fcntl unless defined &Fcntl::O_RDWR;
3760 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3761 my $fv = ++$FH . $safename;
3762 my $ref = \*{"Fh::$fv"};
3763 $file =~ m!^([a-zA-Z0-9_\+ \'\":/.\$\\-]+)$! || return;
3765 sysopen($ref,$safe,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3766 unlink($safe) if $delete;
3767 CORE::delete $Fh::{$fv};
3768 return bless $ref,$pack;
3775 ######################## MultipartBuffer ####################
3776 package MultipartBuffer;
3778 use constant DEBUG => 0;
3780 # how many bytes to read at a time. We use
3781 # a 4K buffer by default.
3782 $INITIAL_FILLUNIT = 1024 * 4;
3783 $TIMEOUT = 240*60; # 4 hour timeout for big files
3784 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3787 #reuse the autoload function
3788 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3790 # avoid autoloader warnings
3793 ###############################################################################
3794 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3795 ###############################################################################
3796 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3797 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3800 'new' => <<'END_OF_FUNC',
3802 my($package,$interface,$boundary,$length) = @_;
3803 $FILLUNIT = $INITIAL_FILLUNIT;
3804 $CGI::DefaultClass->binmode($IN); # if $CGI::needs_binmode; # just do it always
3806 # If the user types garbage into the file upload field,
3807 # then Netscape passes NOTHING to the server (not good).
3808 # We may hang on this read in that case. So we implement
3809 # a read timeout. If nothing is ready to read
3810 # by then, we return.
3812 # Netscape seems to be a little bit unreliable
3813 # about providing boundary strings.
3814 my $boundary_read = 0;
3817 # Under the MIME spec, the boundary consists of the
3818 # characters "--" PLUS the Boundary string
3820 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3821 # the two extra hyphens. We do a special case here on the user-agent!!!!
3822 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
3824 } else { # otherwise we find it ourselves
3826 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3827 $boundary = <STDIN>; # BUG: This won't work correctly under mod_perl
3828 $length -= length($boundary);
3829 chomp($boundary); # remove the CRLF
3830 $/ = $old; # restore old line separator
3834 my $self = {LENGTH=>$length,
3836 BOUNDARY=>$boundary,
3837 INTERFACE=>$interface,
3841 $FILLUNIT = length($boundary)
3842 if length($boundary) > $FILLUNIT;
3844 my $retval = bless $self,ref $package || $package;
3846 # Read the preamble and the topmost (boundary) line plus the CRLF.
3847 unless ($boundary_read) {
3848 while ($self->read(0)) { }
3850 die "Malformed multipart POST: data truncated\n" if $self->eof;
3856 'readHeader' => <<'END_OF_FUNC',
3863 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS' || $CGI::EBCDIC;
3866 $self->fillBuffer($FILLUNIT);
3867 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3868 $ok++ if $self->{BUFFER} eq '';
3869 $bad++ if !$ok && $self->{LENGTH} <= 0;
3870 # this was a bad idea
3871 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3872 } until $ok || $bad;
3875 #EBCDIC NOTE: translate header into EBCDIC, but watch out for continuation lines!
3877 my($header) = substr($self->{BUFFER},0,$end+2);
3878 substr($self->{BUFFER},0,$end+4) = '';
3882 warn "untranslated header=$header\n" if DEBUG;
3883 $header = CGI::Util::ascii2ebcdic($header);
3884 warn "translated header=$header\n" if DEBUG;
3887 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3888 # (Folding Long Header Fields), 3.4.3 (Comments)
3889 # and 3.4.5 (Quoted-Strings).
3891 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3892 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3894 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3895 my ($field_name,$field_value) = ($1,$2);
3896 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3897 $return{$field_name}=$field_value;
3903 # This reads and returns the body as a single scalar value.
3904 'readBody' => <<'END_OF_FUNC',
3910 #EBCDIC NOTE: want to translate returnval into EBCDIC HERE
3912 while (defined($data = $self->read)) {
3913 $returnval .= $data;
3917 warn "untranslated body=$returnval\n" if DEBUG;
3918 $returnval = CGI::Util::ascii2ebcdic($returnval);
3919 warn "translated body=$returnval\n" if DEBUG;
3925 # This will read $bytes or until the boundary is hit, whichever happens
3926 # first. After the boundary is hit, we return undef. The next read will
3927 # skip over the boundary and begin reading again;
3928 'read' => <<'END_OF_FUNC',
3930 my($self,$bytes) = @_;
3932 # default number of bytes to read
3933 $bytes = $bytes || $FILLUNIT;
3935 # Fill up our internal buffer in such a way that the boundary
3936 # is never split between reads.
3937 $self->fillBuffer($bytes);
3939 my $boundary_start = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}) : $self->{BOUNDARY};
3940 my $boundary_end = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}.'--') : $self->{BOUNDARY}.'--';
3942 # Find the boundary in the buffer (it may not be there).
3943 my $start = index($self->{BUFFER},$boundary_start);
3945 warn "boundary=$self->{BOUNDARY} length=$self->{LENGTH} start=$start\n" if DEBUG;
3947 # protect against malformed multipart POST operations
3948 die "Malformed multipart POST\n" unless $self->{CHUNKED} || ($start >= 0 || $self->{LENGTH} > 0);
3950 #EBCDIC NOTE: want to translate boundary search into ASCII here.
3952 # If the boundary begins the data, then skip past it
3956 # clear us out completely if we've hit the last boundary.
3957 if (index($self->{BUFFER},$boundary_end)==0) {
3963 # just remove the boundary.
3964 substr($self->{BUFFER},0,length($boundary_start))='';
3965 $self->{BUFFER} =~ s/^\012\015?//;
3970 if ($start > 0) { # read up to the boundary
3971 $bytesToReturn = $start-2 > $bytes ? $bytes : $start;
3972 } else { # read the requested number of bytes
3973 # leave enough bytes in the buffer to allow us to read
3974 # the boundary. Thanks to Kevin Hendrick for finding
3976 $bytesToReturn = $bytes - (length($boundary_start)+1);
3979 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3980 substr($self->{BUFFER},0,$bytesToReturn)='';
3982 # If we hit the boundary, remove the CRLF from the end.
3983 return ($bytesToReturn==$start)
3984 ? substr($returnval,0,-2) : $returnval;
3989 # This fills up our internal buffer in such a way that the
3990 # boundary is never split between reads
3991 'fillBuffer' => <<'END_OF_FUNC',
3993 my($self,$bytes) = @_;
3994 return unless $self->{CHUNKED} || $self->{LENGTH};
3996 my($boundaryLength) = length($self->{BOUNDARY});
3997 my($bufferLength) = length($self->{BUFFER});
3998 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3999 $bytesToRead = $self->{LENGTH} if !$self->{CHUNKED} && $self->{LENGTH} < $bytesToRead;
4001 # Try to read some data. We may hang here if the browser is screwed up.
4002 my $bytesRead = $self->{INTERFACE}->read_from_client(\$self->{BUFFER},
4005 warn "bytesToRead=$bytesToRead, bufferLength=$bufferLength, buffer=$self->{BUFFER}\n" if DEBUG;
4006 $self->{BUFFER} = '' unless defined $self->{BUFFER};
4008 # An apparent bug in the Apache server causes the read()
4009 # to return zero bytes repeatedly without blocking if the
4010 # remote user aborts during a file transfer. I don't know how
4011 # they manage this, but the workaround is to abort if we get
4012 # more than SPIN_LOOP_MAX consecutive zero reads.
4013 if ($bytesRead <= 0) {
4014 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
4015 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
4017 $self->{ZERO_LOOP_COUNTER}=0;
4020 $self->{LENGTH} -= $bytesRead if !$self->{CHUNKED} && $bytesRead;
4025 # Return true when we've finished reading
4026 'eof' => <<'END_OF_FUNC'
4029 return 1 if (length($self->{BUFFER}) == 0)
4030 && ($self->{LENGTH} <= 0);
4038 ####################################################################################
4039 ################################## TEMPORARY FILES #################################
4040 ####################################################################################
4041 package CGITempFile;
4045 $MAC = $CGI::OS eq 'MACINTOSH';
4046 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
4047 unless (defined $TMPDIRECTORY) {
4048 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
4049 "C:${SL}temp","${SL}tmp","${SL}temp",
4050 "${vol}${SL}Temporary Items",
4051 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
4052 "C:${SL}system${SL}temp");
4053 unshift(@TEMP,$ENV{'TMPDIR'}) if defined $ENV{'TMPDIR'};
4055 # this feature was supposed to provide per-user tmpfiles, but
4056 # it is problematic.
4057 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
4058 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
4059 # : can generate a 'getpwuid() not implemented' exception, even though
4060 # : it's never called. Found under DOS/Win with the DJGPP perl port.
4061 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
4062 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
4065 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
4068 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
4075 # cute feature, but overload implementation broke it
4076 # %OVERLOAD = ('""'=>'as_string');
4077 *CGITempFile::AUTOLOAD = \&CGI::AUTOLOAD;
4081 $$self =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
4082 my $safe = $1; # untaint operation
4083 unlink $safe; # get rid of the file
4086 ###############################################################################
4087 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
4088 ###############################################################################
4089 $AUTOLOADED_ROUTINES = ''; # prevent -w error
4090 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
4093 'new' => <<'END_OF_FUNC',
4095 my($package,$sequence) = @_;
4097 find_tempdir() unless -w $TMPDIRECTORY;
4098 for (my $i = 0; $i < $MAXTRIES; $i++) {
4099 last if ! -f ($filename = sprintf("\%s${SL}CGItemp%d", $TMPDIRECTORY, $sequence++));
4101 # check that it is a more-or-less valid filename
4102 return unless $filename =~ m!^([a-zA-Z0-9_\+ \'\":/.\$\\-]+)$!;
4103 # this used to untaint, now it doesn't
4105 return bless \$filename;
4109 'as_string' => <<'END_OF_FUNC'
4121 # We get a whole bunch of warnings about "possibly uninitialized variables"
4122 # when running with the -w switch. Touch them all once to get rid of the
4123 # warnings. This is ugly and I hate it.
4128 $MultipartBuffer::SPIN_LOOP_MAX;
4129 $MultipartBuffer::CRLF;
4130 $MultipartBuffer::TIMEOUT;
4131 $MultipartBuffer::INITIAL_FILLUNIT;
4142 CGI - Simple Common Gateway Interface Class
4146 # CGI script that creates a fill-out form
4147 # and echoes back its values.
4149 use CGI qw/:standard/;
4151 start_html('A Simple Example'),
4152 h1('A Simple Example'),
4154 "What's your name? ",textfield('name'),p,
4155 "What's the combination?", p,
4156 checkbox_group(-name=>'words',
4157 -values=>['eenie','meenie','minie','moe'],
4158 -defaults=>['eenie','minie']), p,
4159 "What's your favorite color? ",
4160 popup_menu(-name=>'color',
4161 -values=>['red','green','blue','chartreuse']),p,
4167 my $name = param('name');
4168 my $keywords = join ', ',param('words');
4169 my $color = param('color');
4170 print "Your name is",em(escapeHTML($name)),p,
4171 "The keywords are: ",em(escapeHTML($keywords)),p,
4172 "Your favorite color is ",em(escapeHTML($color)),
4180 This perl library uses perl5 objects to make it easy to create Web
4181 fill-out forms and parse their contents. This package defines CGI
4182 objects, entities that contain the values of the current query string
4183 and other state variables. Using a CGI object's methods, you can
4184 examine keywords and parameters passed to your script, and create
4185 forms whose initial values are taken from the current query (thereby
4186 preserving state information). The module provides shortcut functions
4187 that produce boilerplate HTML, reducing typing and coding errors. It
4188 also provides functionality for some of the more advanced features of
4189 CGI scripting, including support for file uploads, cookies, cascading
4190 style sheets, server push, and frames.
4192 CGI.pm also provides a simple function-oriented programming style for
4193 those who don't need its object-oriented features.
4195 The current version of CGI.pm is available at
4197 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
4198 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
4202 =head2 PROGRAMMING STYLE
4204 There are two styles of programming with CGI.pm, an object-oriented
4205 style and a function-oriented style. In the object-oriented style you
4206 create one or more CGI objects and then use object methods to create
4207 the various elements of the page. Each CGI object starts out with the
4208 list of named parameters that were passed to your CGI script by the
4209 server. You can modify the objects, save them to a file or database
4210 and recreate them. Because each object corresponds to the "state" of
4211 the CGI script, and because each object's parameter list is
4212 independent of the others, this allows you to save the state of the
4213 script and restore it later.
4215 For example, using the object oriented style, here is how you create
4216 a simple "Hello World" HTML page:
4218 #!/usr/local/bin/perl -w
4219 use CGI; # load CGI routines
4220 $q = new CGI; # create new CGI object
4221 print $q->header, # create the HTTP header
4222 $q->start_html('hello world'), # start the HTML
4223 $q->h1('hello world'), # level 1 header
4224 $q->end_html; # end the HTML
4226 In the function-oriented style, there is one default CGI object that
4227 you rarely deal with directly. Instead you just call functions to
4228 retrieve CGI parameters, create HTML tags, manage cookies, and so
4229 on. This provides you with a cleaner programming interface, but
4230 limits you to using one CGI object at a time. The following example
4231 prints the same page, but uses the function-oriented interface.
4232 The main differences are that we now need to import a set of functions
4233 into our name space (usually the "standard" functions), and we don't
4234 need to create the CGI object.
4236 #!/usr/local/bin/perl
4237 use CGI qw/:standard/; # load standard CGI routines
4238 print header, # create the HTTP header
4239 start_html('hello world'), # start the HTML
4240 h1('hello world'), # level 1 header
4241 end_html; # end the HTML
4243 The examples in this document mainly use the object-oriented style.
4244 See HOW TO IMPORT FUNCTIONS for important information on
4245 function-oriented programming in CGI.pm
4247 =head2 CALLING CGI.PM ROUTINES
4249 Most CGI.pm routines accept several arguments, sometimes as many as 20
4250 optional ones! To simplify this interface, all routines use a named
4251 argument calling style that looks like this:
4253 print $q->header(-type=>'image/gif',-expires=>'+3d');
4255 Each argument name is preceded by a dash. Neither case nor order
4256 matters in the argument list. -type, -Type, and -TYPE are all
4257 acceptable. In fact, only the first argument needs to begin with a
4258 dash. If a dash is present in the first argument, CGI.pm assumes
4259 dashes for the subsequent ones.
4261 Several routines are commonly called with just one argument. In the
4262 case of these routines you can provide the single argument without an
4263 argument name. header() happens to be one of these routines. In this
4264 case, the single argument is the document type.
4266 print $q->header('text/html');
4268 Other such routines are documented below.
4270 Sometimes named arguments expect a scalar, sometimes a reference to an
4271 array, and sometimes a reference to a hash. Often, you can pass any
4272 type of argument and the routine will do whatever is most appropriate.
4273 For example, the param() routine is used to set a CGI parameter to a
4274 single or a multi-valued value. The two cases are shown below:
4276 $q->param(-name=>'veggie',-value=>'tomato');
4277 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
4279 A large number of routines in CGI.pm actually aren't specifically
4280 defined in the module, but are generated automatically as needed.
4281 These are the "HTML shortcuts," routines that generate HTML tags for
4282 use in dynamically-generated pages. HTML tags have both attributes
4283 (the attribute="value" pairs within the tag itself) and contents (the
4284 part between the opening and closing pairs.) To distinguish between
4285 attributes and contents, CGI.pm uses the convention of passing HTML
4286 attributes as a hash reference as the first argument, and the
4287 contents, if any, as any subsequent arguments. It works out like
4293 h1('some','contents'); <h1>some contents</h1>
4294 h1({-align=>left}); <h1 align="LEFT">
4295 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
4297 HTML tags are described in more detail later.
4299 Many newcomers to CGI.pm are puzzled by the difference between the
4300 calling conventions for the HTML shortcuts, which require curly braces
4301 around the HTML tag attributes, and the calling conventions for other
4302 routines, which manage to generate attributes without the curly
4303 brackets. Don't be confused. As a convenience the curly braces are
4304 optional in all but the HTML shortcuts. If you like, you can use
4305 curly braces when calling any routine that takes named arguments. For
4308 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
4310 If you use the B<-w> switch, you will be warned that some CGI.pm argument
4311 names conflict with built-in Perl functions. The most frequent of
4312 these is the -values argument, used to create multi-valued menus,
4313 radio button clusters and the like. To get around this warning, you
4314 have several choices:
4320 Use another name for the argument, if one is available.
4321 For example, -value is an alias for -values.
4325 Change the capitalization, e.g. -Values
4329 Put quotes around the argument name, e.g. '-values'
4333 Many routines will do something useful with a named argument that it
4334 doesn't recognize. For example, you can produce non-standard HTTP
4335 header fields by providing them as named arguments:
4337 print $q->header(-type => 'text/html',
4338 -cost => 'Three smackers',
4339 -annoyance_level => 'high',
4340 -complaints_to => 'bit bucket');
4342 This will produce the following nonstandard HTTP header:
4345 Cost: Three smackers
4346 Annoyance-level: high
4347 Complaints-to: bit bucket
4348 Content-type: text/html
4350 Notice the way that underscores are translated automatically into
4351 hyphens. HTML-generating routines perform a different type of
4354 This feature allows you to keep up with the rapidly changing HTTP and
4357 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
4361 This will parse the input (from both POST and GET methods) and store
4362 it into a perl5 object called $query.
4364 Any filehandles from file uploads will have their position reset to
4365 the beginning of the file.
4367 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
4369 $query = new CGI(INPUTFILE);
4371 If you provide a file handle to the new() method, it will read
4372 parameters from the file (or STDIN, or whatever). The file can be in
4373 any of the forms describing below under debugging (i.e. a series of
4374 newline delimited TAG=VALUE pairs will work). Conveniently, this type
4375 of file is created by the save() method (see below). Multiple records
4376 can be saved and restored.
4378 Perl purists will be pleased to know that this syntax accepts
4379 references to file handles, or even references to filehandle globs,
4380 which is the "official" way to pass a filehandle:
4382 $query = new CGI(\*STDIN);
4384 You can also initialize the CGI object with a FileHandle or IO::File
4387 If you are using the function-oriented interface and want to
4388 initialize CGI state from a file handle, the way to do this is with
4389 B<restore_parameters()>. This will (re)initialize the
4390 default CGI object from the indicated file handle.
4392 open (IN,"test.in") || die;
4393 restore_parameters(IN);
4396 You can also initialize the query object from an associative array
4399 $query = new CGI( {'dinosaur'=>'barney',
4400 'song'=>'I love you',
4401 'friends'=>[qw/Jessica George Nancy/]}
4404 or from a properly formatted, URL-escaped query string:
4406 $query = new CGI('dinosaur=barney&color=purple');
4408 or from a previously existing CGI object (currently this clones the
4409 parameter list, but none of the other object-specific fields, such as
4412 $old_query = new CGI;
4413 $new_query = new CGI($old_query);
4415 To create an empty query, initialize it from an empty string or hash:
4417 $empty_query = new CGI("");
4421 $empty_query = new CGI({});
4423 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
4425 @keywords = $query->keywords
4427 If the script was invoked as the result of an <ISINDEX> search, the
4428 parsed keywords can be obtained as an array using the keywords() method.
4430 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
4432 @names = $query->param
4434 If the script was invoked with a parameter list
4435 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
4436 will return the parameter names as a list. If the script was invoked
4437 as an <ISINDEX> script and contains a string without ampersands
4438 (e.g. "value1+value2+value3") , there will be a single parameter named
4439 "keywords" containing the "+"-delimited keywords.
4441 NOTE: As of version 1.5, the array of parameter names returned will
4442 be in the same order as they were submitted by the browser.
4443 Usually this order is the same as the order in which the
4444 parameters are defined in the form (however, this isn't part
4445 of the spec, and so isn't guaranteed).
4447 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
4449 @values = $query->param('foo');
4453 $value = $query->param('foo');
4455 Pass the param() method a single argument to fetch the value of the
4456 named parameter. If the parameter is multivalued (e.g. from multiple
4457 selections in a scrolling list), you can ask to receive an array. Otherwise
4458 the method will return a single value.
4460 If a value is not given in the query string, as in the queries
4461 "name1=&name2=", it will be returned as an empty string.
4464 If the parameter does not exist at all, then param() will return undef
4465 in a scalar context, and the empty list in a list context.
4468 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
4470 $query->param('foo','an','array','of','values');
4472 This sets the value for the named parameter 'foo' to an array of
4473 values. This is one way to change the value of a field AFTER
4474 the script has been invoked once before. (Another way is with
4475 the -override parameter accepted by all methods that generate
4478 param() also recognizes a named parameter style of calling described
4479 in more detail later:
4481 $query->param(-name=>'foo',-values=>['an','array','of','values']);
4485 $query->param(-name=>'foo',-value=>'the value');
4487 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
4489 $query->append(-name=>'foo',-values=>['yet','more','values']);
4491 This adds a value or list of values to the named parameter. The
4492 values are appended to the end of the parameter if it already exists.
4493 Otherwise the parameter is created. Note that this method only
4494 recognizes the named argument calling syntax.
4496 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
4498 $query->import_names('R');
4500 This creates a series of variables in the 'R' namespace. For example,
4501 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
4502 If no namespace is given, this method will assume 'Q'.
4503 WARNING: don't import anything into 'main'; this is a major security
4506 NOTE 1: Variable names are transformed as necessary into legal Perl
4507 variable names. All non-legal characters are transformed into
4508 underscores. If you need to keep the original names, you should use
4509 the param() method instead to access CGI variables by name.
4511 NOTE 2: In older versions, this method was called B<import()>. As of version 2.20,
4512 this name has been removed completely to avoid conflict with the built-in
4513 Perl module B<import> operator.
4515 =head2 DELETING A PARAMETER COMPLETELY:
4517 $query->delete('foo','bar','baz');
4519 This completely clears a list of parameters. It sometimes useful for
4520 resetting parameters that you don't want passed down between script
4523 If you are using the function call interface, use "Delete()" instead
4524 to avoid conflicts with Perl's built-in delete operator.
4526 =head2 DELETING ALL PARAMETERS:
4528 $query->delete_all();
4530 This clears the CGI object completely. It might be useful to ensure
4531 that all the defaults are taken when you create a fill-out form.
4533 Use Delete_all() instead if you are using the function call interface.
4535 =head2 HANDLING NON-URLENCODED ARGUMENTS
4538 If POSTed data is not of type application/x-www-form-urlencoded or
4539 multipart/form-data, then the POSTed data will not be processed, but
4540 instead be returned as-is in a parameter named POSTDATA. To retrieve
4541 it, use code like this:
4543 my $data = $query->param('POSTDATA');
4545 Likewise if PUTed data can be retrieved with code like this:
4547 my $data = $query->param('PUTDATA');
4549 (If you don't know what the preceding means, don't worry about it. It
4550 only affects people trying to use CGI for XML processing and other
4554 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
4556 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
4557 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
4559 If you need access to the parameter list in a way that isn't covered
4560 by the methods above, you can obtain a direct reference to it by
4561 calling the B<param_fetch()> method with the name of the . This
4562 will return an array reference to the named parameters, which you then
4563 can manipulate in any way you like.
4565 You can also use a named argument style using the B<-name> argument.
4567 =head2 FETCHING THE PARAMETER LIST AS A HASH:
4570 print $params->{'address'};
4571 @foo = split("\0",$params->{'foo'});
4577 Many people want to fetch the entire parameter list as a hash in which
4578 the keys are the names of the CGI parameters, and the values are the
4579 parameters' values. The Vars() method does this. Called in a scalar
4580 context, it returns the parameter list as a tied hash reference.
4581 Changing a key changes the value of the parameter in the underlying
4582 CGI parameter list. Called in a list context, it returns the
4583 parameter list as an ordinary hash. This allows you to read the
4584 contents of the parameter list, but not to change it.
4586 When using this, the thing you must watch out for are multivalued CGI
4587 parameters. Because a hash cannot distinguish between scalar and
4588 list context, multivalued parameters will be returned as a packed
4589 string, separated by the "\0" (null) character. You must split this
4590 packed string in order to get at the individual values. This is the
4591 convention introduced long ago by Steve Brenner in his cgi-lib.pl
4592 module for Perl version 4.
4594 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
4595 function calls (also see the section on CGI-LIB compatibility).
4597 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
4599 $query->save(\*FILEHANDLE)
4601 This will write the current state of the form to the provided
4602 filehandle. You can read it back in by providing a filehandle
4603 to the new() method. Note that the filehandle can be a file, a pipe,
4606 The format of the saved file is:
4614 Both name and value are URL escaped. Multi-valued CGI parameters are
4615 represented as repeated names. A session record is delimited by a
4616 single = symbol. You can write out multiple records and read them
4617 back in with several calls to B<new>. You can do this across several
4618 sessions by opening the file in append mode, allowing you to create
4619 primitive guest books, or to keep a history of users' queries. Here's
4620 a short example of creating multiple session records:
4624 open (OUT,">>test.out") || die;
4626 foreach (0..$records) {
4628 $q->param(-name=>'counter',-value=>$_);
4633 # reopen for reading
4634 open (IN,"test.out") || die;
4636 my $q = new CGI(\*IN);
4637 print $q->param('counter'),"\n";
4640 The file format used for save/restore is identical to that used by the
4641 Whitehead Genome Center's data exchange format "Boulderio", and can be
4642 manipulated and even databased using Boulderio utilities. See
4644 http://stein.cshl.org/boulder/
4646 for further details.
4648 If you wish to use this method from the function-oriented (non-OO)
4649 interface, the exported name for this method is B<save_parameters()>.
4651 =head2 RETRIEVING CGI ERRORS
4653 Errors can occur while processing user input, particularly when
4654 processing uploaded files. When these errors occur, CGI will stop
4655 processing and return an empty parameter list. You can test for
4656 the existence and nature of errors using the I<cgi_error()> function.
4657 The error messages are formatted as HTTP status codes. You can either
4658 incorporate the error text into an HTML page, or use it as the value
4661 my $error = $q->cgi_error;
4663 print $q->header(-status=>$error),
4664 $q->start_html('Problems'),
4665 $q->h2('Request not processed'),
4670 When using the function-oriented interface (see the next section),
4671 errors may only occur the first time you call I<param()>. Be ready
4674 =head2 USING THE FUNCTION-ORIENTED INTERFACE
4676 To use the function-oriented interface, you must specify which CGI.pm
4677 routines or sets of routines to import into your script's namespace.
4678 There is a small overhead associated with this importation, but it
4681 use CGI <list of methods>;
4683 The listed methods will be imported into the current package; you can
4684 call them directly without creating a CGI object first. This example
4685 shows how to import the B<param()> and B<header()>
4686 methods, and then use them directly:
4688 use CGI 'param','header';
4689 print header('text/plain');
4690 $zipcode = param('zipcode');
4692 More frequently, you'll import common sets of functions by referring
4693 to the groups by name. All function sets are preceded with a ":"
4694 character as in ":html3" (for tags defined in the HTML 3 standard).
4696 Here is a list of the function sets you can import:
4702 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4707 Import all fill-out form generating methods, such as B<textfield()>.
4711 Import all methods that generate HTML 2.0 standard elements.
4715 Import all methods that generate HTML 3.0 elements (such as
4716 <table>, <super> and <sub>).
4720 Import all methods that generate HTML 4 elements (such as
4721 <abbrev>, <acronym> and <thead>).
4725 Import all methods that generate Netscape-specific HTML extensions.
4729 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4734 Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
4738 Import all the available methods. For the full list, see the CGI.pm
4739 code, where the variable %EXPORT_TAGS is defined.
4743 If you import a function name that is not part of CGI.pm, the module
4744 will treat it as a new HTML tag and generate the appropriate
4745 subroutine. You can then use it like any other HTML tag. This is to
4746 provide for the rapidly-evolving HTML "standard." For example, say
4747 Microsoft comes out with a new tag called <gradient> (which causes the
4748 user's desktop to be flooded with a rotating gradient fill until his
4749 machine reboots). You don't need to wait for a new version of CGI.pm
4750 to start using it immediately:
4752 use CGI qw/:standard :html3 gradient/;
4753 print gradient({-start=>'red',-end=>'blue'});
4755 Note that in the interests of execution speed CGI.pm does B<not> use
4756 the standard L<Exporter> syntax for specifying load symbols. This may
4757 change in the future.
4759 If you import any of the state-maintaining CGI or form-generating
4760 methods, a default CGI object will be created and initialized
4761 automatically the first time you use any of the methods that require
4762 one to be present. This includes B<param()>, B<textfield()>,
4763 B<submit()> and the like. (If you need direct access to the CGI
4764 object, you can find it in the global variable B<$CGI::Q>). By
4765 importing CGI.pm methods, you can create visually elegant scripts:
4767 use CGI qw/:standard/;
4770 start_html('Simple Script'),
4771 h1('Simple Script'),
4773 "What's your name? ",textfield('name'),p,
4774 "What's the combination?",
4775 checkbox_group(-name=>'words',
4776 -values=>['eenie','meenie','minie','moe'],
4777 -defaults=>['eenie','moe']),p,
4778 "What's your favorite color?",
4779 popup_menu(-name=>'color',
4780 -values=>['red','green','blue','chartreuse']),p,
4787 "Your name is ",em(param('name')),p,
4788 "The keywords are: ",em(join(", ",param('words'))),p,
4789 "Your favorite color is ",em(param('color')),".\n";
4795 In addition to the function sets, there are a number of pragmas that
4796 you can import. Pragmas, which are always preceded by a hyphen,
4797 change the way that CGI.pm functions in various ways. Pragmas,
4798 function sets, and individual functions can all be imported in the
4799 same use() line. For example, the following use statement imports the
4800 standard set of functions and enables debugging mode (pragma
4803 use CGI qw/:standard -debug/;
4805 The current list of pragmas is as follows:
4811 When you I<use CGI -any>, then any method that the query object
4812 doesn't recognize will be interpreted as a new HTML tag. This allows
4813 you to support the next I<ad hoc> Netscape or Microsoft HTML
4814 extension. This lets you go wild with new and unsupported tags:
4818 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4820 Since using <cite>any</cite> causes any mistyped method name
4821 to be interpreted as an HTML tag, use it with care or not at
4826 This causes the indicated autoloaded methods to be compiled up front,
4827 rather than deferred to later. This is useful for scripts that run
4828 for an extended period of time under FastCGI or mod_perl, and for
4829 those destined to be crunched by Malcolm Beattie's Perl compiler. Use
4830 it in conjunction with the methods or method families you plan to use.
4832 use CGI qw(-compile :standard :html3);
4836 use CGI qw(-compile :all);
4838 Note that using the -compile pragma in this way will always have
4839 the effect of importing the compiled functions into the current
4840 namespace. If you want to compile without importing use the
4841 compile() method instead:
4846 This is particularly useful in a mod_perl environment, in which you
4847 might want to precompile all CGI routines in a startup script, and
4848 then import the functions individually in each mod_perl script.
4852 By default the CGI module implements a state-preserving behavior
4853 called "sticky" fields. The way this works is that if you are
4854 regenerating a form, the methods that generate the form field values
4855 will interrogate param() to see if similarly-named parameters are
4856 present in the query string. If they find a like-named parameter, they
4857 will use it to set their default values.
4859 Sometimes this isn't what you want. The B<-nosticky> pragma prevents
4860 this behavior. You can also selectively change the sticky behavior in
4861 each element that you generate.
4865 Automatically add tab index attributes to each form field. With this
4866 option turned off, you can still add tab indexes manually by passing a
4867 -tabindex option to each field-generating method.
4869 =item -no_undef_params
4871 This keeps CGI.pm from including undef params in the parameter list.
4875 By default, CGI.pm versions 2.69 and higher emit XHTML
4876 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4877 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4880 If start_html()'s -dtd parameter specifies an HTML 2.0 or 3.2 DTD,
4881 XHTML will automatically be disabled without needing to use this
4886 This makes CGI.pm treat all parameters as UTF-8 strings. Use this with
4887 care, as it will interfere with the processing of binary uploads. It
4888 is better to manually select which fields are expected to return utf-8
4889 strings and convert them using code like this:
4892 my $arg = decode utf8=>param('foo');
4896 This makes CGI.pm produce a header appropriate for an NPH (no
4897 parsed header) script. You may need to do other things as well
4898 to tell the server that the script is NPH. See the discussion
4899 of NPH scripts below.
4901 =item -newstyle_urls
4903 Separate the name=value pairs in CGI parameter query strings with
4904 semicolons rather than ampersands. For example:
4906 ?name=fred;age=24;favorite_color=3
4908 Semicolon-delimited query strings are always accepted, but will not be
4909 emitted by self_url() and query_string() unless the -newstyle_urls
4910 pragma is specified.
4912 This became the default in version 2.64.
4914 =item -oldstyle_urls
4916 Separate the name=value pairs in CGI parameter query strings with
4917 ampersands rather than semicolons. This is no longer the default.
4921 This overrides the autoloader so that any function in your program
4922 that is not recognized is referred to CGI.pm for possible evaluation.
4923 This allows you to use all the CGI.pm functions without adding them to
4924 your symbol table, which is of concern for mod_perl users who are
4925 worried about memory consumption. I<Warning:> when
4926 I<-autoload> is in effect, you cannot use "poetry mode"
4927 (functions without the parenthesis). Use I<hr()> rather
4928 than I<hr>, or add something like I<use subs qw/hr p header/>
4929 to the top of your script.
4933 This turns off the command-line processing features. If you want to
4934 run a CGI.pm script from the command line to produce HTML, and you
4935 don't want it to read CGI parameters from the command line or STDIN,
4936 then use this pragma:
4938 use CGI qw(-no_debug :standard);
4942 This turns on full debugging. In addition to reading CGI arguments
4943 from the command-line processing, CGI.pm will pause and try to read
4944 arguments from STDIN, producing the message "(offline mode: enter
4945 name=value pairs on standard input)" features.
4947 See the section on debugging for more details.
4949 =item -private_tempfiles
4951 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4952 file to a temporary directory, then deletes the file when done.
4953 However, this opens the risk of eavesdropping as described in the file
4954 upload section. Another CGI script author could peek at this data
4955 during the upload, even if it is confidential information. On Unix
4956 systems, the -private_tempfiles pragma will cause the temporary file
4957 to be unlinked as soon as it is opened and before any data is written
4958 into it, reducing, but not eliminating the risk of eavesdropping
4959 (there is still a potential race condition). To make life harder for
4960 the attacker, the program chooses tempfile names by calculating a 32
4961 bit checksum of the incoming HTTP headers.
4963 To ensure that the temporary file cannot be read by other CGI scripts,
4964 use suEXEC or a CGI wrapper program to run your script. The temporary
4965 file is created with mode 0600 (neither world nor group readable).
4967 The temporary directory is selected using the following algorithm:
4969 1. if the current user (e.g. "nobody") has a directory named
4970 "tmp" in its home directory, use that (Unix systems only).
4972 2. if the environment variable TMPDIR exists, use the location
4975 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4976 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4978 Each of these locations is checked that it is a directory and is
4979 writable. If not, the algorithm tries the next choice.
4983 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4985 Many of the methods generate HTML tags. As described below, tag
4986 functions automatically generate both the opening and closing tags.
4989 print h1('Level 1 Header');
4993 <h1>Level 1 Header</h1>
4995 There will be some times when you want to produce the start and end
4996 tags yourself. In this case, you can use the form start_I<tag_name>
4997 and end_I<tag_name>, as in:
4999 print start_h1,'Level 1 Header',end_h1;
5001 With a few exceptions (described below), start_I<tag_name> and
5002 end_I<tag_name> functions are not generated automatically when you
5003 I<use CGI>. However, you can specify the tags you want to generate
5004 I<start/end> functions for by putting an asterisk in front of their
5005 name, or, alternatively, requesting either "start_I<tag_name>" or
5006 "end_I<tag_name>" in the import list.
5010 use CGI qw/:standard *table start_ul/;
5012 In this example, the following functions are generated in addition to
5017 =item 1. start_table() (generates a <table> tag)
5019 =item 2. end_table() (generates a </table> tag)
5021 =item 3. start_ul() (generates a <ul> tag)
5023 =item 4. end_ul() (generates a </ul> tag)
5027 =head1 GENERATING DYNAMIC DOCUMENTS
5029 Most of CGI.pm's functions deal with creating documents on the fly.
5030 Generally you will produce the HTTP header first, followed by the
5031 document itself. CGI.pm provides functions for generating HTTP
5032 headers of various types as well as for generating HTML. For creating
5033 GIF images, see the GD.pm module.
5035 Each of these functions produces a fragment of HTML or HTTP which you
5036 can print out directly so that it displays in the browser window,
5037 append to a string, or save to a file for later use.
5039 =head2 CREATING A STANDARD HTTP HEADER:
5041 Normally the first thing you will do in any CGI script is print out an
5042 HTTP header. This tells the browser what type of document to expect,
5043 and gives other optional information, such as the language, expiration
5044 date, and whether to cache the document. The header can also be
5045 manipulated for special purposes, such as server push and pay per view
5052 print header('image/gif');
5056 print header('text/html','204 No response');
5060 print header(-type=>'image/gif',
5062 -status=>'402 Payment required',
5066 -attachment=>'foo.gif',
5069 header() returns the Content-type: header. You can provide your own
5070 MIME type if you choose, otherwise it defaults to text/html. An
5071 optional second parameter specifies the status code and a human-readable
5072 message. For example, you can specify 204, "No response" to create a
5073 script that tells the browser to do nothing at all.
5075 The last example shows the named argument style for passing arguments
5076 to the CGI methods using named parameters. Recognized parameters are
5077 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
5078 parameters will be stripped of their initial hyphens and turned into
5079 header fields, allowing you to specify any HTTP header you desire.
5080 Internal underscores will be turned into hyphens:
5082 print header(-Content_length=>3002);
5084 Most browsers will not cache the output from CGI scripts. Every time
5085 the browser reloads the page, the script is invoked anew. You can
5086 change this behavior with the B<-expires> parameter. When you specify
5087 an absolute or relative expiration interval with this parameter, some
5088 browsers and proxy servers will cache the script's output until the
5089 indicated expiration date. The following forms are all valid for the
5092 +30s 30 seconds from now
5093 +10m ten minutes from now
5094 +1h one hour from now
5095 -1d yesterday (i.e. "ASAP!")
5098 +10y in ten years time
5099 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
5101 The B<-cookie> parameter generates a header that tells the browser to provide
5102 a "magic cookie" during all subsequent transactions with your script.
5103 Netscape cookies have a special format that includes interesting attributes
5104 such as expiration time. Use the cookie() method to create and retrieve
5107 The B<-nph> parameter, if set to a true value, will issue the correct
5108 headers to work with a NPH (no-parse-header) script. This is important
5109 to use with certain servers that expect all their scripts to be NPH.
5111 The B<-charset> parameter can be used to control the character set
5112 sent to the browser. If not provided, defaults to ISO-8859-1. As a
5113 side effect, this sets the charset() method as well.
5115 The B<-attachment> parameter can be used to turn the page into an
5116 attachment. Instead of displaying the page, some browsers will prompt
5117 the user to save it to disk. The value of the argument is the
5118 suggested name for the saved file. In order for this to work, you may
5119 have to set the B<-type> to "application/octet-stream".
5121 The B<-p3p> parameter will add a P3P tag to the outgoing header. The
5122 parameter can be an arrayref or a space-delimited string of P3P tags.
5125 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
5126 print header(-p3p=>'CAO DSP LAW CURa');
5128 In either case, the outgoing header will be formatted as:
5130 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
5132 =head2 GENERATING A REDIRECTION HEADER
5134 print redirect('http://somewhere.else/in/movie/land');
5136 Sometimes you don't want to produce a document yourself, but simply
5137 redirect the browser elsewhere, perhaps choosing a URL based on the
5138 time of day or the identity of the user.
5140 The redirect() function redirects the browser to a different URL. If
5141 you use redirection like this, you should B<not> print out a header as
5144 You should always use full URLs (including the http: or ftp: part) in
5145 redirection requests. Relative URLs will not work correctly.
5147 You can also use named arguments:
5149 print redirect(-uri=>'http://somewhere.else/in/movie/land',
5153 The B<-nph> parameter, if set to a true value, will issue the correct
5154 headers to work with a NPH (no-parse-header) script. This is important
5155 to use with certain servers, such as Microsoft IIS, which
5156 expect all their scripts to be NPH.
5158 The B<-status> parameter will set the status of the redirect. HTTP
5159 defines three different possible redirection status codes:
5161 301 Moved Permanently
5165 The default if not specified is 302, which means "moved temporarily."
5166 You may change the status to another status code if you wish. Be
5167 advised that changing the status to anything other than 301, 302 or
5168 303 will probably break redirection.
5170 =head2 CREATING THE HTML DOCUMENT HEADER
5172 print start_html(-title=>'Secrets of the Pyramids',
5173 -author=>'fred@capricorn.org',
5176 -meta=>{'keywords'=>'pharaoh secret mummy',
5177 'copyright'=>'copyright 1996 King Tut'},
5178 -style=>{'src'=>'/styles/style1.css'},
5181 After creating the HTTP header, most CGI scripts will start writing
5182 out an HTML document. The start_html() routine creates the top of the
5183 page, along with a lot of optional information that controls the
5184 page's appearance and behavior.
5186 This method returns a canned HTML header and the opening <body> tag.
5187 All parameters are optional. In the named parameter form, recognized
5188 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
5189 (see below for the explanation). Any additional parameters you
5190 provide, such as the Netscape unofficial BGCOLOR attribute, are added
5191 to the <body> tag. Additional parameters must be proceeded by a
5194 The argument B<-xbase> allows you to provide an HREF for the <base> tag
5195 different from the current location, as in
5197 -xbase=>"http://home.mcom.com/"
5199 All relative links will be interpreted relative to this tag.
5201 The argument B<-target> allows you to provide a default target frame
5202 for all the links and fill-out forms on the page. B<This is a
5203 non-standard HTTP feature which only works with Netscape browsers!>
5204 See the Netscape documentation on frames for details of how to
5207 -target=>"answer_window"
5209 All relative links will be interpreted relative to this tag.
5210 You add arbitrary meta information to the header with the B<-meta>
5211 argument. This argument expects a reference to an associative array
5212 containing name/value pairs of meta information. These will be turned
5213 into a series of header <meta> tags that look something like this:
5215 <meta name="keywords" content="pharaoh secret mummy">
5216 <meta name="description" content="copyright 1996 King Tut">
5218 To create an HTTP-EQUIV type of <meta> tag, use B<-head>, described
5221 The B<-style> argument is used to incorporate cascading stylesheets
5222 into your code. See the section on CASCADING STYLESHEETS for more
5225 The B<-lang> argument is used to incorporate a language attribute into
5226 the <html> tag. For example:
5228 print $q->start_html(-lang=>'fr-CA');
5230 The default if not specified is "en-US" for US English, unless the
5231 -dtd parameter specifies an HTML 2.0 or 3.2 DTD, in which case the
5232 lang attribute is left off. You can force the lang attribute to left
5233 off in other cases by passing an empty string (-lang=>'').
5235 The B<-encoding> argument can be used to specify the character set for
5236 XHTML. It defaults to iso-8859-1 if not specified.
5238 The B<-declare_xml> argument, when used in conjunction with XHTML,
5239 will put a <?xml> declaration at the top of the HTML header. The sole
5240 purpose of this declaration is to declare the character set
5241 encoding. In the absence of -declare_xml, the output HTML will contain
5242 a <meta> tag that specifies the encoding, allowing the HTML to pass
5243 most validators. The default for -declare_xml is false.
5245 You can place other arbitrary HTML elements to the <head> section with the
5246 B<-head> tag. For example, to place the rarely-used <link> element in the
5247 head section, use this:
5249 print start_html(-head=>Link({-rel=>'next',
5250 -href=>'http://www.capricorn.com/s2.html'}));
5252 To incorporate multiple HTML elements into the <head> section, just pass an
5255 print start_html(-head=>[
5257 -href=>'http://www.capricorn.com/s2.html'}),
5258 Link({-rel=>'previous',
5259 -href=>'http://www.capricorn.com/s1.html'})
5263 And here's how to create an HTTP-EQUIV <meta> tag:
5265 print start_html(-head=>meta({-http_equiv => 'Content-Type',
5266 -content => 'text/html'}))
5269 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
5270 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
5271 to add Netscape JavaScript calls to your pages. B<-script> should
5272 point to a block of text containing JavaScript function definitions.
5273 This block will be placed within a <script> block inside the HTML (not
5274 HTTP) header. The block is placed in the header in order to give your
5275 page a fighting chance of having all its JavaScript functions in place
5276 even if the user presses the stop button before the page has loaded
5277 completely. CGI.pm attempts to format the script in such a way that
5278 JavaScript-naive browsers will not choke on the code: unfortunately
5279 there are some browsers, such as Chimera for Unix, that get confused
5282 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
5283 code to execute when the page is respectively opened and closed by the
5284 browser. Usually these parameters are calls to functions defined in the
5290 // Ask a silly question
5291 function riddle_me_this() {
5292 var r = prompt("What walks on four legs in the morning, " +
5293 "two legs in the afternoon, " +
5294 "and three legs in the evening?");
5297 // Get a silly answer
5298 function response(answer) {
5299 if (answer == "man")
5300 alert("Right you are!");
5302 alert("Wrong! Guess again.");
5305 print start_html(-title=>'The Riddle of the Sphinx',
5308 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
5309 browsers that do not have JavaScript (or browsers where JavaScript is turned
5312 The <script> tag, has several attributes including "type" and src.
5313 The latter is particularly interesting, as it allows you to keep the
5314 JavaScript code in a file or CGI script rather than cluttering up each
5315 page with the source. To use these attributes pass a HASH reference
5316 in the B<-script> parameter containing one or more of -type, -src, or
5319 print $q->start_html(-title=>'The Riddle of the Sphinx',
5320 -script=>{-type=>'JAVASCRIPT',
5321 -src=>'/javascript/sphinx.js'}
5324 print $q->(-title=>'The Riddle of the Sphinx',
5325 -script=>{-type=>'PERLSCRIPT',
5326 -code=>'print "hello world!\n;"'}
5330 A final feature allows you to incorporate multiple <script> sections into the
5331 header. Just pass the list of script sections as an array reference.
5332 this allows you to specify different source files for different dialects
5333 of JavaScript. Example:
5335 print $q->start_html(-title=>'The Riddle of the Sphinx',
5337 { -type => 'text/javascript',
5338 -src => '/javascript/utilities10.js'
5340 { -type => 'text/javascript',
5341 -src => '/javascript/utilities11.js'
5343 { -type => 'text/jscript',
5344 -src => '/javascript/utilities12.js'
5346 { -type => 'text/ecmascript',
5347 -src => '/javascript/utilities219.js'
5352 The option "-language" is a synonym for -type, and is supported for
5353 backwad compatibility.
5355 The old-style positional parameters are as follows:
5359 =item B<Parameters:>
5367 The author's e-mail address (will create a <link rev="MADE"> tag if present
5371 A 'true' flag if you want to include a <base> tag in the header. This
5372 helps resolve relative addresses to absolute ones when the document is moved,
5373 but makes the document hierarchy non-portable. Use with care!
5377 Any other parameters you want to include in the <body> tag. This is a good
5378 place to put Netscape extensions, such as colors and wallpaper patterns.
5382 =head2 ENDING THE HTML DOCUMENT:
5386 This ends an HTML document by printing the </body></html> tags.
5388 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
5391 print q(<a href="$myself">I'm talking to myself.</a>);
5393 self_url() will return a URL, that, when selected, will reinvoke
5394 this script with all its state information intact. This is most
5395 useful when you want to jump around within the document using
5396 internal anchors but you don't want to disrupt the current contents
5397 of the form(s). Something like this will do the trick.
5400 print "<a href=\"$myself#table1\">See table 1</a>";
5401 print "<a href=\"$myself#table2\">See table 2</a>";
5402 print "<a href=\"$myself#yourself\">See for yourself</a>";
5404 If you want more control over what's returned, using the B<url()>
5407 You can also retrieve the unprocessed query string with query_string():
5409 $the_string = query_string;
5411 =head2 OBTAINING THE SCRIPT'S URL
5414 $full_url = url(-full=>1); #alternative syntax
5415 $relative_url = url(-relative=>1);
5416 $absolute_url = url(-absolute=>1);
5417 $url_with_path = url(-path_info=>1);
5418 $url_with_path_and_query = url(-path_info=>1,-query=>1);
5419 $netloc = url(-base => 1);
5421 B<url()> returns the script's URL in a variety of formats. Called
5422 without any arguments, it returns the full form of the URL, including
5423 host name and port number
5425 http://your.host.com/path/to/script.cgi
5427 You can modify this format with the following named arguments:
5433 If true, produce an absolute URL, e.g.
5439 Produce a relative URL. This is useful if you want to reinvoke your
5440 script with different parameters. For example:
5446 Produce the full URL, exactly as if called without any arguments.
5447 This overrides the -relative and -absolute arguments.
5449 =item B<-path> (B<-path_info>)
5451 Append the additional path information to the URL. This can be
5452 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
5453 is provided as a synonym.
5455 =item B<-query> (B<-query_string>)
5457 Append the query string to the URL. This can be combined with
5458 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
5463 Generate just the protocol and net location, as in http://www.foo.com:8000
5467 If Apache's mod_rewrite is turned on, then the script name and path
5468 info probably won't match the request that the user sent. Set
5469 -rewrite=>1 (default) to return URLs that match what the user sent
5470 (the original request URI). Set -rewrite=>0 to return URLs that match
5471 the URL after mod_rewrite's rules have run. Because the additional
5472 path information only makes sense in the context of the rewritten URL,
5473 -rewrite is set to false when you request path info in the URL.
5477 =head2 MIXING POST AND URL PARAMETERS
5479 $color = url_param('color');
5481 It is possible for a script to receive CGI parameters in the URL as
5482 well as in the fill-out form by creating a form that POSTs to a URL
5483 containing a query string (a "?" mark followed by arguments). The
5484 B<param()> method will always return the contents of the POSTed
5485 fill-out form, ignoring the URL's query string. To retrieve URL
5486 parameters, call the B<url_param()> method. Use it in the same way as
5487 B<param()>. The main difference is that it allows you to read the
5488 parameters, but not set them.
5491 Under no circumstances will the contents of the URL query string
5492 interfere with similarly-named CGI parameters in POSTed forms. If you
5493 try to mix a URL query string with a form submitted with the GET
5494 method, the results will not be what you expect.
5496 =head1 CREATING STANDARD HTML ELEMENTS:
5498 CGI.pm defines general HTML shortcut methods for most, if not all of
5499 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
5500 HTML element and return a fragment of HTML text that you can then
5501 print or manipulate as you like. Each shortcut returns a fragment of
5502 HTML code that you can append to a string, save to a file, or, most
5503 commonly, print out so that it displays in the browser window.
5505 This example shows how to use the HTML methods:
5507 print $q->blockquote(
5508 "Many years ago on the island of",
5509 $q->a({href=>"http://crete.org/"},"Crete"),
5510 "there lived a Minotaur named",
5511 $q->strong("Fred."),
5515 This results in the following HTML code (extra newlines have been
5516 added for readability):
5519 Many years ago on the island of
5520 <a href="http://crete.org/">Crete</a> there lived
5521 a minotaur named <strong>Fred.</strong>
5525 If you find the syntax for calling the HTML shortcuts awkward, you can
5526 import them into your namespace and dispense with the object syntax
5527 completely (see the next section for more details):
5529 use CGI ':standard';
5531 "Many years ago on the island of",
5532 a({href=>"http://crete.org/"},"Crete"),
5533 "there lived a minotaur named",
5538 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
5540 The HTML methods will accept zero, one or multiple arguments. If you
5541 provide no arguments, you get a single tag:
5545 If you provide one or more string arguments, they are concatenated
5546 together with spaces and placed between opening and closing tags:
5548 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
5550 If the first argument is an associative array reference, then the keys
5551 and values of the associative array become the HTML tag's attributes:
5553 print a({-href=>'fred.html',-target=>'_new'},
5554 "Open a new frame");
5556 <a href="fred.html",target="_new">Open a new frame</a>
5558 You may dispense with the dashes in front of the attribute names if
5561 print img {src=>'fred.gif',align=>'LEFT'};
5563 <img align="LEFT" src="fred.gif">
5565 Sometimes an HTML tag attribute has no argument. For example, ordered
5566 lists can be marked as COMPACT. The syntax for this is an argument that
5567 that points to an undef string:
5569 print ol({compact=>undef},li('one'),li('two'),li('three'));
5571 Prior to CGI.pm version 2.41, providing an empty ('') string as an
5572 attribute argument was the same as providing undef. However, this has
5573 changed in order to accommodate those who want to create tags of the form
5574 <img alt="">. The difference is shown in these two pieces of code:
5577 img({alt=>undef}) <img alt>
5578 img({alt=>''}) <img alt="">
5580 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
5582 One of the cool features of the HTML shortcuts is that they are
5583 distributive. If you give them an argument consisting of a
5584 B<reference> to a list, the tag will be distributed across each
5585 element of the list. For example, here's one way to make an ordered
5589 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
5592 This example will result in HTML output that looks like this:
5595 <li type="disc">Sneezy</li>
5596 <li type="disc">Doc</li>
5597 <li type="disc">Sleepy</li>
5598 <li type="disc">Happy</li>
5601 This is extremely useful for creating tables. For example:
5603 print table({-border=>undef},
5604 caption('When Should You Eat Your Vegetables?'),
5605 Tr({-align=>CENTER,-valign=>TOP},
5607 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
5608 td(['Tomatoes' , 'no', 'yes', 'yes']),
5609 td(['Broccoli' , 'no', 'no', 'yes']),
5610 td(['Onions' , 'yes','yes', 'yes'])
5615 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
5617 Consider this bit of code:
5619 print blockquote(em('Hi'),'mom!'));
5621 It will ordinarily return the string that you probably expect, namely:
5623 <blockquote><em>Hi</em> mom!</blockquote>
5625 Note the space between the element "Hi" and the element "mom!".
5626 CGI.pm puts the extra space there using array interpolation, which is
5627 controlled by the magic $" variable. Sometimes this extra space is
5628 not what you want, for example, when you are trying to align a series
5629 of images. In this case, you can simply change the value of $" to an
5634 print blockquote(em('Hi'),'mom!'));
5637 I suggest you put the code in a block as shown here. Otherwise the
5638 change to $" will affect all subsequent code until you explicitly
5641 =head2 NON-STANDARD HTML SHORTCUTS
5643 A few HTML tags don't follow the standard pattern for various
5646 B<comment()> generates an HTML comment (<!-- comment -->). Call it
5649 print comment('here is my comment');
5651 Because of conflicts with built-in Perl functions, the following functions
5652 begin with initial caps:
5661 In addition, start_html(), end_html(), start_form(), end_form(),
5662 start_multipart_form() and all the fill-out form tags are special.
5663 See their respective sections.
5665 =head2 AUTOESCAPING HTML
5667 By default, all HTML that is emitted by the form-generating functions
5668 is passed through a function called escapeHTML():
5672 =item $escaped_string = escapeHTML("unescaped string");
5674 Escape HTML formatting characters in a string.
5678 Provided that you have specified a character set of ISO-8859-1 (the
5679 default), the standard HTML escaping rules will be used. The "<"
5680 character becomes "<", ">" becomes ">", "&" becomes "&", and
5681 the quote character becomes """. In addition, the hexadecimal
5682 0x8b and 0x9b characters, which some browsers incorrectly interpret
5683 as the left and right angle-bracket characters, are replaced by their
5684 numeric character entities ("‹" and "›"). If you manually change
5685 the charset, either by calling the charset() method explicitly or by
5686 passing a -charset argument to header(), then B<all> characters will
5687 be replaced by their numeric entities, since CGI.pm has no lookup
5688 table for all the possible encodings.
5690 The automatic escaping does not apply to other shortcuts, such as
5691 h1(). You should call escapeHTML() yourself on untrusted data in
5692 order to protect your pages against nasty tricks that people may enter
5693 into guestbooks, etc.. To change the character set, use charset().
5694 To turn autoescaping off completely, use autoEscape(0):
5698 =item $charset = charset([$charset]);
5700 Get or set the current character set.
5702 =item $flag = autoEscape([$flag]);
5704 Get or set the value of the autoescape flag.
5708 =head2 PRETTY-PRINTING HTML
5710 By default, all the HTML produced by these functions comes out as one
5711 long line without carriage returns or indentation. This is yuck, but
5712 it does reduce the size of the documents by 10-20%. To get
5713 pretty-printed output, please use L<CGI::Pretty>, a subclass
5714 contributed by Brian Paulsen.
5716 =head1 CREATING FILL-OUT FORMS:
5718 I<General note> The various form-creating methods all return strings
5719 to the caller, containing the tag or tags that will create the requested
5720 form element. You are responsible for actually printing out these strings.
5721 It's set up this way so that you can place formatting tags
5722 around the form elements.
5724 I<Another note> The default values that you specify for the forms are only
5725 used the B<first> time the script is invoked (when there is no query
5726 string). On subsequent invocations of the script (when there is a query
5727 string), the former values are used even if they are blank.
5729 If you want to change the value of a field from its previous value, you have two
5732 (1) call the param() method to set it.
5734 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
5735 This forces the default value to be used, regardless of the previous value:
5737 print textfield(-name=>'field_name',
5738 -default=>'starting value',
5743 I<Yet another note> By default, the text and labels of form elements are
5744 escaped according to HTML rules. This means that you can safely use
5745 "<CLICK ME>" as the label for a button. However, it also interferes with
5746 your ability to incorporate special HTML character sequences, such as Á,
5747 into your fields. If you wish to turn off automatic escaping, call the
5748 autoEscape() method with a false value immediately after creating the CGI object:
5753 I<A Lurking Trap!> Some of the form-element generating methods return
5754 multiple tags. In a scalar context, the tags will be concatenated
5755 together with spaces, or whatever is the current value of the $"
5756 global. In a list context, the methods will return a list of
5757 elements, allowing you to modify them if you wish. Usually you will
5758 not notice this behavior, but beware of this:
5760 printf("%s\n",end_form())
5762 end_form() produces several tags, and only the first of them will be
5763 printed because the format only expects one value.
5768 =head2 CREATING AN ISINDEX TAG
5770 print isindex(-action=>$action);
5774 print isindex($action);
5776 Prints out an <isindex> tag. Not very exciting. The parameter
5777 -action specifies the URL of the script to process the query. The
5778 default is to process the query with the current script.
5780 =head2 STARTING AND ENDING A FORM
5782 print start_form(-method=>$method,
5784 -enctype=>$encoding);
5785 <... various form stuff ...>
5790 print start_form($method,$action,$encoding);
5791 <... various form stuff ...>
5794 start_form() will return a <form> tag with the optional method,
5795 action and form encoding that you specify. The defaults are:
5799 enctype: application/x-www-form-urlencoded
5801 endform() returns the closing </form> tag.
5803 Start_form()'s enctype argument tells the browser how to package the various
5804 fields of the form before sending the form to the server. Two
5805 values are possible:
5807 B<Note:> This method was previously named startform(), and startform()
5808 is still recognized as an alias.
5812 =item B<application/x-www-form-urlencoded>
5814 This is the older type of encoding used by all browsers prior to
5815 Netscape 2.0. It is compatible with many CGI scripts and is
5816 suitable for short fields containing text data. For your
5817 convenience, CGI.pm stores the name of this encoding
5818 type in B<&CGI::URL_ENCODED>.
5820 =item B<multipart/form-data>
5822 This is the newer type of encoding introduced by Netscape 2.0.
5823 It is suitable for forms that contain very large fields or that
5824 are intended for transferring binary data. Most importantly,
5825 it enables the "file upload" feature of Netscape 2.0 forms. For
5826 your convenience, CGI.pm stores the name of this encoding type
5827 in B<&CGI::MULTIPART>
5829 Forms that use this type of encoding are not easily interpreted
5830 by CGI scripts unless they use CGI.pm or another library designed
5833 If XHTML is activated (the default), then forms will be automatically
5834 created using this type of encoding.
5838 For compatibility, the start_form() method uses the older form of
5839 encoding by default. If you want to use the newer form of encoding
5840 by default, you can call B<start_multipart_form()> instead of
5843 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
5844 for use with JavaScript. The -name parameter gives the
5845 form a name so that it can be identified and manipulated by
5846 JavaScript functions. -onSubmit should point to a JavaScript
5847 function that will be executed just before the form is submitted to your
5848 server. You can use this opportunity to check the contents of the form
5849 for consistency and completeness. If you find something wrong, you
5850 can put up an alert box or maybe fix things up yourself. You can
5851 abort the submission by returning false from this function.
5853 Usually the bulk of JavaScript functions are defined in a <script>
5854 block in the HTML header and -onSubmit points to one of these function
5855 call. See start_html() for details.
5857 =head2 FORM ELEMENTS
5859 After starting a form, you will typically create one or more
5860 textfields, popup menus, radio groups and other form elements. Each
5861 of these elements takes a standard set of named arguments. Some
5862 elements also have optional arguments. The standard arguments are as
5869 The name of the field. After submission this name can be used to
5870 retrieve the field's value using the param() method.
5872 =item B<-value>, B<-values>
5874 The initial value of the field which will be returned to the script
5875 after form submission. Some form elements, such as text fields, take
5876 a single scalar -value argument. Others, such as popup menus, take a
5877 reference to an array of values. The two arguments are synonyms.
5881 A numeric value that sets the order in which the form element receives
5882 focus when the user presses the tab key. Elements with lower values
5883 receive focus first.
5887 A string identifier that can be used to identify this element to
5888 JavaScript and DHTML.
5892 A boolean, which, if true, forces the element to take on the value
5893 specified by B<-value>, overriding the sticky behavior described
5894 earlier for the B<-no_sticky> pragma.
5896 =item B<-onChange>, B<-onFocus>, B<-onBlur>, B<-onMouseOver>, B<-onMouseOut>, B<-onSelect>
5898 These are used to assign JavaScript event handlers. See the
5899 JavaScripting section for more details.
5903 Other common arguments are described in the next section. In addition
5904 to these, all attributes described in the HTML specifications are
5907 =head2 CREATING A TEXT FIELD
5909 print textfield(-name=>'field_name',
5910 -value=>'starting value',
5915 print textfield('field_name','starting value',50,80);
5917 textfield() will return a text input field.
5925 The first parameter is the required name for the field (-name).
5929 The optional second parameter is the default starting value for the field
5930 contents (-value, formerly known as -default).
5934 The optional third parameter is the size of the field in
5939 The optional fourth parameter is the maximum number of characters the
5940 field will accept (-maxlength).
5944 As with all these methods, the field will be initialized with its
5945 previous contents from earlier invocations of the script.
5946 When the form is processed, the value of the text field can be
5949 $value = param('foo');
5951 If you want to reset it from its initial value after the script has been
5952 called once, you can do so like this:
5954 param('foo',"I'm taking over this value!");
5956 =head2 CREATING A BIG TEXT FIELD
5958 print textarea(-name=>'foo',
5959 -default=>'starting value',
5965 print textarea('foo','starting value',10,50);
5967 textarea() is just like textfield, but it allows you to specify
5968 rows and columns for a multiline text entry box. You can provide
5969 a starting value for the field, which can be long and contain
5972 =head2 CREATING A PASSWORD FIELD
5974 print password_field(-name=>'secret',
5975 -value=>'starting value',
5980 print password_field('secret','starting value',50,80);
5982 password_field() is identical to textfield(), except that its contents
5983 will be starred out on the web page.
5985 =head2 CREATING A FILE UPLOAD FIELD
5987 print filefield(-name=>'uploaded_file',
5988 -default=>'starting value',
5993 print filefield('uploaded_file','starting value',50,80);
5995 filefield() will return a file upload field for Netscape 2.0 browsers.
5996 In order to take full advantage of this I<you must use the new
5997 multipart encoding scheme> for the form. You can do this either
5998 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5999 or by calling the new method B<start_multipart_form()> instead of
6000 vanilla B<start_form()>.
6008 The first parameter is the required name for the field (-name).
6012 The optional second parameter is the starting value for the field contents
6013 to be used as the default file name (-default).
6015 For security reasons, browsers don't pay any attention to this field,
6016 and so the starting value will always be blank. Worse, the field
6017 loses its "sticky" behavior and forgets its previous contents. The
6018 starting value field is called for in the HTML specification, however,
6019 and possibly some browser will eventually provide support for it.
6023 The optional third parameter is the size of the field in
6028 The optional fourth parameter is the maximum number of characters the
6029 field will accept (-maxlength).
6033 When the form is processed, you can retrieve the entered filename
6036 $filename = param('uploaded_file');
6038 Different browsers will return slightly different things for the
6039 name. Some browsers return the filename only. Others return the full
6040 path to the file, using the path conventions of the user's machine.
6041 Regardless, the name returned is always the name of the file on the
6042 I<user's> machine, and is unrelated to the name of the temporary file
6043 that CGI.pm creates during upload spooling (see below).
6045 The filename returned is also a file handle. You can read the contents
6046 of the file using standard Perl file reading calls:
6048 # Read a text file and print it out
6049 while (<$filename>) {
6053 # Copy a binary file to somewhere safe
6054 open (OUTFILE,">>/usr/local/web/users/feedback");
6055 while ($bytesread=read($filename,$buffer,1024)) {
6056 print OUTFILE $buffer;
6059 However, there are problems with the dual nature of the upload fields.
6060 If you C<use strict>, then Perl will complain when you try to use a
6061 string as a filehandle. You can get around this by placing the file
6062 reading code in a block containing the C<no strict> pragma. More
6063 seriously, it is possible for the remote user to type garbage into the
6064 upload field, in which case what you get from param() is not a
6065 filehandle at all, but a string.
6067 To be safe, use the I<upload()> function (new in version 2.47). When
6068 called with the name of an upload field, I<upload()> returns a
6069 filehandle, or undef if the parameter is not a valid filehandle.
6071 $fh = upload('uploaded_file');
6076 In an list context, upload() will return an array of filehandles.
6077 This makes it possible to create forms that use the same name for
6078 multiple upload fields.
6080 This is the recommended idiom.
6082 For robust code, consider reseting the file handle position to beginning of the
6083 file. Inside of larger frameworks, other code may have already used the query
6084 object and changed the filehandle postion:
6086 seek($fh,0,0); # reset postion to beginning of file.
6088 When a file is uploaded the browser usually sends along some
6089 information along with it in the format of headers. The information
6090 usually includes the MIME content type. Future browsers may send
6091 other information as well (such as modification date and size). To
6092 retrieve this information, call uploadInfo(). It returns a reference to
6093 an associative array containing all the document headers.
6095 $filename = param('uploaded_file');
6096 $type = uploadInfo($filename)->{'Content-Type'};
6097 unless ($type eq 'text/html') {
6098 die "HTML FILES ONLY!";
6101 If you are using a machine that recognizes "text" and "binary" data
6102 modes, be sure to understand when and how to use them (see the Camel book).
6103 Otherwise you may find that binary files are corrupted during file
6106 There are occasionally problems involving parsing the uploaded file.
6107 This usually happens when the user presses "Stop" before the upload is
6108 finished. In this case, CGI.pm will return undef for the name of the
6109 uploaded file and set I<cgi_error()> to the string "400 Bad request
6110 (malformed multipart POST)". This error message is designed so that
6111 you can incorporate it into a status code to be sent to the browser.
6114 $file = upload('uploaded_file');
6115 if (!$file && cgi_error) {
6116 print header(-status=>cgi_error);
6120 You are free to create a custom HTML page to complain about the error,
6123 You can set up a callback that will be called whenever a file upload
6124 is being read during the form processing. This is much like the
6125 UPLOAD_HOOK facility available in Apache::Request, with the exception
6126 that the first argument to the callback is an Apache::Upload object,
6127 here it's the remote filename.
6129 $q = CGI->new(\&hook [,$data [,$use_tempfile]]);
6133 my ($filename, $buffer, $bytes_read, $data) = @_;
6134 print "Read $bytes_read bytes of $filename\n";
6137 The $data field is optional; it lets you pass configuration
6138 information (e.g. a database handle) to your hook callback.
6140 The $use_tempfile field is a flag that lets you turn on and off
6141 CGI.pm's use of a temporary disk-based file during file upload. If you
6142 set this to a FALSE value (default true) then param('uploaded_file')
6143 will no longer work, and the only way to get at the uploaded data is
6144 via the hook you provide.
6146 If using the function-oriented interface, call the CGI::upload_hook()
6147 method before calling param() or any other CGI functions:
6149 CGI::upload_hook(\&hook [,$data [,$use_tempfile]]);
6151 This method is not exported by default. You will have to import it
6152 explicitly if you wish to use it without the CGI:: prefix.
6154 If you are using CGI.pm on a Windows platform and find that binary
6155 files get slightly larger when uploaded but that text files remain the
6156 same, then you have forgotten to activate binary mode on the output
6157 filehandle. Be sure to call binmode() on any handle that you create
6158 to write the uploaded file to disk.
6160 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
6161 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
6162 recognized. See textfield() for details.
6164 =head2 CREATING A POPUP MENU
6166 print popup_menu('menu_name',
6167 ['eenie','meenie','minie'],
6172 %labels = ('eenie'=>'your first choice',
6173 'meenie'=>'your second choice',
6174 'minie'=>'your third choice');
6175 %attributes = ('eenie'=>{'class'=>'class of first choice'});
6176 print popup_menu('menu_name',
6177 ['eenie','meenie','minie'],
6178 'meenie',\%labels,\%attributes);
6180 -or (named parameter style)-
6182 print popup_menu(-name=>'menu_name',
6183 -values=>['eenie','meenie','minie'],
6184 -default=>['meenie','minie'],
6186 -attributes=>\%attributes);
6188 popup_menu() creates a menu.
6194 The required first argument is the menu's name (-name).
6198 The required second argument (-values) is an array B<reference>
6199 containing the list of menu items in the menu. You can pass the
6200 method an anonymous array, as shown in the example, or a reference to
6201 a named array, such as "\@foo".
6205 The optional third parameter (-default) is the name of the default
6206 menu choice. If not specified, the first item will be the default.
6207 The values of the previous choice will be maintained across
6208 queries. Pass an array reference to select multiple defaults.
6212 The optional fourth parameter (-labels) is provided for people who
6213 want to use different values for the user-visible label inside the
6214 popup menu and the value returned to your script. It's a pointer to an
6215 associative array relating menu values to user-visible labels. If you
6216 leave this parameter blank, the menu values will be displayed by
6217 default. (You can also leave a label undefined if you want to).
6221 The optional fifth parameter (-attributes) is provided to assign
6222 any of the common HTML attributes to an individual menu item. It's
6223 a pointer to an associative array relating menu values to another
6224 associative array with the attribute's name as the key and the
6225 attribute's value as the value.
6229 When the form is processed, the selected value of the popup menu can
6232 $popup_menu_value = param('menu_name');
6234 =head2 CREATING AN OPTION GROUP
6236 Named parameter style
6238 print popup_menu(-name=>'menu_name',
6239 -values=>[qw/eenie meenie minie/,
6240 optgroup(-name=>'optgroup_name',
6241 -values => ['moe','catch'],
6242 -attributes=>{'catch'=>{'class'=>'red'}})],
6243 -labels=>{'eenie'=>'one',
6246 -default=>'meenie');
6249 print popup_menu('menu_name',
6250 ['eenie','meenie','minie',
6251 optgroup('optgroup_name', ['moe', 'catch'],
6252 {'catch'=>{'class'=>'red'}})],'meenie',
6253 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
6255 optgroup() creates an option group within a popup menu.
6261 The required first argument (B<-name>) is the label attribute of the
6262 optgroup and is B<not> inserted in the parameter list of the query.
6266 The required second argument (B<-values>) is an array reference
6267 containing the list of menu items in the menu. You can pass the
6268 method an anonymous array, as shown in the example, or a reference
6269 to a named array, such as \@foo. If you pass a HASH reference,
6270 the keys will be used for the menu values, and the values will be
6271 used for the menu labels (see -labels below).
6275 The optional third parameter (B<-labels>) allows you to pass a reference
6276 to an associative array containing user-visible labels for one or more
6277 of the menu items. You can use this when you want the user to see one
6278 menu string, but have the browser return your program a different one.
6279 If you don't specify this, the value string will be used instead
6280 ("eenie", "meenie" and "minie" in this example). This is equivalent
6281 to using a hash reference for the -values parameter.
6285 An optional fourth parameter (B<-labeled>) can be set to a true value
6286 and indicates that the values should be used as the label attribute
6287 for each option element within the optgroup.
6291 An optional fifth parameter (-novals) can be set to a true value and
6292 indicates to suppress the val attribute in each option element within
6295 See the discussion on optgroup at W3C
6296 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
6301 An optional sixth parameter (-attributes) is provided to assign
6302 any of the common HTML attributes to an individual menu item. It's
6303 a pointer to an associative array relating menu values to another
6304 associative array with the attribute's name as the key and the
6305 attribute's value as the value.
6309 =head2 CREATING A SCROLLING LIST
6311 print scrolling_list('list_name',
6312 ['eenie','meenie','minie','moe'],
6313 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
6316 print scrolling_list('list_name',
6317 ['eenie','meenie','minie','moe'],
6318 ['eenie','moe'],5,'true',
6319 \%labels,%attributes);
6323 print scrolling_list(-name=>'list_name',
6324 -values=>['eenie','meenie','minie','moe'],
6325 -default=>['eenie','moe'],
6329 -attributes=>\%attributes);
6331 scrolling_list() creates a scrolling list.
6335 =item B<Parameters:>
6339 The first and second arguments are the list name (-name) and values
6340 (-values). As in the popup menu, the second argument should be an
6345 The optional third argument (-default) can be either a reference to a
6346 list containing the values to be selected by default, or can be a
6347 single value to select. If this argument is missing or undefined,
6348 then nothing is selected when the list first appears. In the named
6349 parameter version, you can use the synonym "-defaults" for this
6354 The optional fourth argument is the size of the list (-size).
6358 The optional fifth argument can be set to true to allow multiple
6359 simultaneous selections (-multiple). Otherwise only one selection
6360 will be allowed at a time.
6364 The optional sixth argument is a pointer to an associative array
6365 containing long user-visible labels for the list items (-labels).
6366 If not provided, the values will be displayed.
6370 The optional sixth parameter (-attributes) is provided to assign
6371 any of the common HTML attributes to an individual menu item. It's
6372 a pointer to an associative array relating menu values to another
6373 associative array with the attribute's name as the key and the
6374 attribute's value as the value.
6376 When this form is processed, all selected list items will be returned as
6377 a list under the parameter name 'list_name'. The values of the
6378 selected items can be retrieved with:
6380 @selected = param('list_name');
6384 =head2 CREATING A GROUP OF RELATED CHECKBOXES
6386 print checkbox_group(-name=>'group_name',
6387 -values=>['eenie','meenie','minie','moe'],
6388 -default=>['eenie','moe'],
6390 -disabled => ['moe'],
6392 -attributes=>\%attributes);
6394 print checkbox_group('group_name',
6395 ['eenie','meenie','minie','moe'],
6396 ['eenie','moe'],'true',\%labels,
6397 {'moe'=>{'class'=>'red'}});
6399 HTML3-COMPATIBLE BROWSERS ONLY:
6401 print checkbox_group(-name=>'group_name',
6402 -values=>['eenie','meenie','minie','moe'],
6403 -rows=2,-columns=>2);
6406 checkbox_group() creates a list of checkboxes that are related
6411 =item B<Parameters:>
6415 The first and second arguments are the checkbox name and values,
6416 respectively (-name and -values). As in the popup menu, the second
6417 argument should be an array reference. These values are used for the
6418 user-readable labels printed next to the checkboxes as well as for the
6419 values passed to your script in the query string.
6423 The optional third argument (-default) can be either a reference to a
6424 list containing the values to be checked by default, or can be a
6425 single value to checked. If this argument is missing or undefined,
6426 then nothing is selected when the list first appears.
6430 The optional fourth argument (-linebreak) can be set to true to place
6431 line breaks between the checkboxes so that they appear as a vertical
6432 list. Otherwise, they will be strung together on a horizontal line.
6437 The optional b<-labels> argument is a pointer to an associative array
6438 relating the checkbox values to the user-visible labels that will be
6439 printed next to them. If not provided, the values will be used as the
6443 The optional parameters B<-rows>, and B<-columns> cause
6444 checkbox_group() to return an HTML3 compatible table containing the
6445 checkbox group formatted with the specified number of rows and
6446 columns. You can provide just the -columns parameter if you wish;
6447 checkbox_group will calculate the correct number of rows for you.
6449 The option b<-disabled> takes an array of checkbox values and disables
6450 them by greying them out (this may not be supported by all browsers).
6452 The optional B<-attributes> argument is provided to assign any of the
6453 common HTML attributes to an individual menu item. It's a pointer to
6454 an associative array relating menu values to another associative array
6455 with the attribute's name as the key and the attribute's value as the
6458 The optional B<-tabindex> argument can be used to control the order in which
6459 radio buttons receive focus when the user presses the tab button. If
6460 passed a scalar numeric value, the first element in the group will
6461 receive this tab index and subsequent elements will be incremented by
6462 one. If given a reference to an array of radio button values, then
6463 the indexes will be jiggered so that the order specified in the array
6464 will correspond to the tab order. You can also pass a reference to a
6465 hash in which the hash keys are the radio button values and the values
6466 are the tab indexes of each button. Examples:
6468 -tabindex => 100 # this group starts at index 100 and counts up
6469 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
6470 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
6472 The optional B<-labelattributes> argument will contain attributes
6473 attached to the <label> element that surrounds each button.
6475 When the form is processed, all checked boxes will be returned as
6476 a list under the parameter name 'group_name'. The values of the
6477 "on" checkboxes can be retrieved with:
6479 @turned_on = param('group_name');
6481 The value returned by checkbox_group() is actually an array of button
6482 elements. You can capture them and use them within tables, lists,
6483 or in other creative ways:
6485 @h = checkbox_group(-name=>'group_name',-values=>\@values);
6486 &use_in_creative_way(@h);
6488 =head2 CREATING A STANDALONE CHECKBOX
6490 print checkbox(-name=>'checkbox_name',
6493 -label=>'CLICK ME');
6497 print checkbox('checkbox_name','checked','ON','CLICK ME');
6499 checkbox() is used to create an isolated checkbox that isn't logically
6500 related to any others.
6504 =item B<Parameters:>
6508 The first parameter is the required name for the checkbox (-name). It
6509 will also be used for the user-readable label printed next to the
6514 The optional second parameter (-checked) specifies that the checkbox
6515 is turned on by default. Synonyms are -selected and -on.
6519 The optional third parameter (-value) specifies the value of the
6520 checkbox when it is checked. If not provided, the word "on" is
6525 The optional fourth parameter (-label) is the user-readable label to
6526 be attached to the checkbox. If not provided, the checkbox name is
6531 The value of the checkbox can be retrieved using:
6533 $turned_on = param('checkbox_name');
6535 =head2 CREATING A RADIO BUTTON GROUP
6537 print radio_group(-name=>'group_name',
6538 -values=>['eenie','meenie','minie'],
6542 -attributes=>\%attributes);
6546 print radio_group('group_name',['eenie','meenie','minie'],
6547 'meenie','true',\%labels,\%attributes);
6550 HTML3-COMPATIBLE BROWSERS ONLY:
6552 print radio_group(-name=>'group_name',
6553 -values=>['eenie','meenie','minie','moe'],
6554 -rows=2,-columns=>2);
6556 radio_group() creates a set of logically-related radio buttons
6557 (turning one member of the group on turns the others off)
6561 =item B<Parameters:>
6565 The first argument is the name of the group and is required (-name).
6569 The second argument (-values) is the list of values for the radio
6570 buttons. The values and the labels that appear on the page are
6571 identical. Pass an array I<reference> in the second argument, either
6572 using an anonymous array, as shown, or by referencing a named array as
6577 The optional third parameter (-default) is the name of the default
6578 button to turn on. If not specified, the first item will be the
6579 default. You can provide a nonexistent button name, such as "-" to
6580 start up with no buttons selected.
6584 The optional fourth parameter (-linebreak) can be set to 'true' to put
6585 line breaks between the buttons, creating a vertical list.
6589 The optional fifth parameter (-labels) is a pointer to an associative
6590 array relating the radio button values to user-visible labels to be
6591 used in the display. If not provided, the values themselves are
6597 All modern browsers can take advantage of the optional parameters
6598 B<-rows>, and B<-columns>. These parameters cause radio_group() to
6599 return an HTML3 compatible table containing the radio group formatted
6600 with the specified number of rows and columns. You can provide just
6601 the -columns parameter if you wish; radio_group will calculate the
6602 correct number of rows for you.
6604 To include row and column headings in the returned table, you
6605 can use the B<-rowheaders> and B<-colheaders> parameters. Both
6606 of these accept a pointer to an array of headings to use.
6607 The headings are just decorative. They don't reorganize the
6608 interpretation of the radio buttons -- they're still a single named
6611 The optional B<-tabindex> argument can be used to control the order in which
6612 radio buttons receive focus when the user presses the tab button. If
6613 passed a scalar numeric value, the first element in the group will
6614 receive this tab index and subsequent elements will be incremented by
6615 one. If given a reference to an array of radio button values, then
6616 the indexes will be jiggered so that the order specified in the array
6617 will correspond to the tab order. You can also pass a reference to a
6618 hash in which the hash keys are the radio button values and the values
6619 are the tab indexes of each button. Examples:
6621 -tabindex => 100 # this group starts at index 100 and counts up
6622 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
6623 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
6626 The optional B<-attributes> argument is provided to assign any of the
6627 common HTML attributes to an individual menu item. It's a pointer to
6628 an associative array relating menu values to another associative array
6629 with the attribute's name as the key and the attribute's value as the
6632 The optional B<-labelattributes> argument will contain attributes
6633 attached to the <label> element that surrounds each button.
6635 When the form is processed, the selected radio button can
6638 $which_radio_button = param('group_name');
6640 The value returned by radio_group() is actually an array of button
6641 elements. You can capture them and use them within tables, lists,
6642 or in other creative ways:
6644 @h = radio_group(-name=>'group_name',-values=>\@values);
6645 &use_in_creative_way(@h);
6647 =head2 CREATING A SUBMIT BUTTON
6649 print submit(-name=>'button_name',
6654 print submit('button_name','value');
6656 submit() will create the query submission button. Every form
6657 should have one of these.
6661 =item B<Parameters:>
6665 The first argument (-name) is optional. You can give the button a
6666 name if you have several submission buttons in your form and you want
6667 to distinguish between them.
6671 The second argument (-value) is also optional. This gives the button
6672 a value that will be passed to your script in the query string. The
6673 name will also be used as the user-visible label.
6677 You can use -label as an alias for -value. I always get confused
6678 about which of -name and -value changes the user-visible label on the
6683 You can figure out which button was pressed by using different
6684 values for each one:
6686 $which_one = param('button_name');
6688 =head2 CREATING A RESET BUTTON
6692 reset() creates the "reset" button. Note that it restores the
6693 form to its value from the last time the script was called,
6694 NOT necessarily to the defaults.
6696 Note that this conflicts with the Perl reset() built-in. Use
6697 CORE::reset() to get the original reset function.
6699 =head2 CREATING A DEFAULT BUTTON
6701 print defaults('button_label')
6703 defaults() creates a button that, when invoked, will cause the
6704 form to be completely reset to its defaults, wiping out all the
6705 changes the user ever made.
6707 =head2 CREATING A HIDDEN FIELD
6709 print hidden(-name=>'hidden_name',
6710 -default=>['value1','value2'...]);
6714 print hidden('hidden_name','value1','value2'...);
6716 hidden() produces a text field that can't be seen by the user. It
6717 is useful for passing state variable information from one invocation
6718 of the script to the next.
6722 =item B<Parameters:>
6726 The first argument is required and specifies the name of this
6731 The second argument is also required and specifies its value
6732 (-default). In the named parameter style of calling, you can provide
6733 a single value here or a reference to a whole list
6737 Fetch the value of a hidden field this way:
6739 $hidden_value = param('hidden_name');
6741 Note, that just like all the other form elements, the value of a
6742 hidden field is "sticky". If you want to replace a hidden field with
6743 some other values after the script has been called once you'll have to
6746 param('hidden_name','new','values','here');
6748 =head2 CREATING A CLICKABLE IMAGE BUTTON
6750 print image_button(-name=>'button_name',
6751 -src=>'/source/URL',
6756 print image_button('button_name','/source/URL','MIDDLE');
6758 image_button() produces a clickable image. When it's clicked on the
6759 position of the click is returned to your script as "button_name.x"
6760 and "button_name.y", where "button_name" is the name you've assigned
6765 =item B<Parameters:>
6769 The first argument (-name) is required and specifies the name of this
6774 The second argument (-src) is also required and specifies the URL
6777 The third option (-align, optional) is an alignment type, and may be
6778 TOP, BOTTOM or MIDDLE
6782 Fetch the value of the button this way:
6783 $x = param('button_name.x');
6784 $y = param('button_name.y');
6786 =head2 CREATING A JAVASCRIPT ACTION BUTTON
6788 print button(-name=>'button_name',
6789 -value=>'user visible label',
6790 -onClick=>"do_something()");
6794 print button('button_name',"do_something()");
6796 button() produces a button that is compatible with Netscape 2.0's
6797 JavaScript. When it's pressed the fragment of JavaScript code
6798 pointed to by the B<-onClick> parameter will be executed. On
6799 non-Netscape browsers this form element will probably not even
6804 Netscape browsers versions 1.1 and higher, and all versions of
6805 Internet Explorer, support a so-called "cookie" designed to help
6806 maintain state within a browser session. CGI.pm has several methods
6807 that support cookies.
6809 A cookie is a name=value pair much like the named parameters in a CGI
6810 query string. CGI scripts create one or more cookies and send
6811 them to the browser in the HTTP header. The browser maintains a list
6812 of cookies that belong to a particular Web server, and returns them
6813 to the CGI script during subsequent interactions.
6815 In addition to the required name=value pair, each cookie has several
6816 optional attributes:
6820 =item 1. an expiration time
6822 This is a time/date string (in a special GMT format) that indicates
6823 when a cookie expires. The cookie will be saved and returned to your
6824 script until this expiration date is reached if the user exits
6825 the browser and restarts it. If an expiration date isn't specified, the cookie
6826 will remain active until the user quits the browser.
6830 This is a partial or complete domain name for which the cookie is
6831 valid. The browser will return the cookie to any host that matches
6832 the partial domain name. For example, if you specify a domain name
6833 of ".capricorn.com", then the browser will return the cookie to
6834 Web servers running on any of the machines "www.capricorn.com",
6835 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
6836 must contain at least two periods to prevent attempts to match
6837 on top level domains like ".edu". If no domain is specified, then
6838 the browser will only return the cookie to servers on the host the
6839 cookie originated from.
6843 If you provide a cookie path attribute, the browser will check it
6844 against your script's URL before returning the cookie. For example,
6845 if you specify the path "/cgi-bin", then the cookie will be returned
6846 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
6847 and "/cgi-bin/customer_service/complain.pl", but not to the script
6848 "/cgi-private/site_admin.pl". By default, path is set to "/", which
6849 causes the cookie to be sent to any CGI script on your site.
6851 =item 4. a "secure" flag
6853 If the "secure" attribute is set, the cookie will only be sent to your
6854 script if the CGI request is occurring on a secure channel, such as SSL.
6858 The interface to HTTP cookies is the B<cookie()> method:
6860 $cookie = cookie(-name=>'sessionID',
6863 -path=>'/cgi-bin/database',
6864 -domain=>'.capricorn.org',
6866 print header(-cookie=>$cookie);
6868 B<cookie()> creates a new cookie. Its parameters include:
6874 The name of the cookie (required). This can be any string at all.
6875 Although browsers limit their cookie names to non-whitespace
6876 alphanumeric characters, CGI.pm removes this restriction by escaping
6877 and unescaping cookies behind the scenes.
6881 The value of the cookie. This can be any scalar value,
6882 array reference, or even associative array reference. For example,
6883 you can store an entire associative array into a cookie this way:
6885 $cookie=cookie(-name=>'family information',
6886 -value=>\%childrens_ages);
6890 The optional partial path for which this cookie will be valid, as described
6895 The optional partial domain for which this cookie will be valid, as described
6900 The optional expiration date for this cookie. The format is as described
6901 in the section on the B<header()> method:
6903 "+1h" one hour from now
6907 If set to true, this cookie will only be used within a secure
6912 The cookie created by cookie() must be incorporated into the HTTP
6913 header within the string returned by the header() method:
6915 use CGI ':standard';
6916 print header(-cookie=>$my_cookie);
6918 To create multiple cookies, give header() an array reference:
6920 $cookie1 = cookie(-name=>'riddle_name',
6921 -value=>"The Sphynx's Question");
6922 $cookie2 = cookie(-name=>'answers',
6924 print header(-cookie=>[$cookie1,$cookie2]);
6926 To retrieve a cookie, request it by name by calling cookie() method
6927 without the B<-value> parameter. This example uses the object-oriented
6932 $riddle = $query->cookie('riddle_name');
6933 %answers = $query->cookie('answers');
6935 Cookies created with a single scalar value, such as the "riddle_name"
6936 cookie, will be returned in that form. Cookies with array and hash
6937 values can also be retrieved.
6939 The cookie and CGI namespaces are separate. If you have a parameter
6940 named 'answers' and a cookie named 'answers', the values retrieved by
6941 param() and cookie() are independent of each other. However, it's
6942 simple to turn a CGI parameter into a cookie, and vice-versa:
6944 # turn a CGI parameter into a cookie
6945 $c=cookie(-name=>'answers',-value=>[param('answers')]);
6947 param(-name=>'answers',-value=>[cookie('answers')]);
6949 If you call cookie() without any parameters, it will return a list of
6950 the names of all cookies passed to your script:
6952 @cookies = cookie();
6954 See the B<cookie.cgi> example script for some ideas on how to use
6955 cookies effectively.
6957 =head1 WORKING WITH FRAMES
6959 It's possible for CGI.pm scripts to write into several browser panels
6960 and windows using the HTML 4 frame mechanism. There are three
6961 techniques for defining new frames programmatically:
6965 =item 1. Create a <Frameset> document
6967 After writing out the HTTP header, instead of creating a standard
6968 HTML document using the start_html() call, create a <frameset>
6969 document that defines the frames on the page. Specify your script(s)
6970 (with appropriate parameters) as the SRC for each of the frames.
6972 There is no specific support for creating <frameset> sections
6973 in CGI.pm, but the HTML is very simple to write. See the frame
6974 documentation in Netscape's home pages for details
6976 http://wp.netscape.com/assist/net_sites/frames.html
6978 =item 2. Specify the destination for the document in the HTTP header
6980 You may provide a B<-target> parameter to the header() method:
6982 print header(-target=>'ResultsWindow');
6984 This will tell the browser to load the output of your script into the
6985 frame named "ResultsWindow". If a frame of that name doesn't already
6986 exist, the browser will pop up a new window and load your script's
6987 document into that. There are a number of magic names that you can
6988 use for targets. See the frame documents on Netscape's home pages for
6991 =item 3. Specify the destination for the document in the <form> tag
6993 You can specify the frame to load in the FORM tag itself. With
6994 CGI.pm it looks like this:
6996 print start_form(-target=>'ResultsWindow');
6998 When your script is reinvoked by the form, its output will be loaded
6999 into the frame named "ResultsWindow". If one doesn't already exist
7000 a new window will be created.
7004 The script "frameset.cgi" in the examples directory shows one way to
7005 create pages in which the fill-out form and the response live in
7006 side-by-side frames.
7008 =head1 SUPPORT FOR JAVASCRIPT
7010 Netscape versions 2.0 and higher incorporate an interpreted language
7011 called JavaScript. Internet Explorer, 3.0 and higher, supports a
7012 closely-related dialect called JScript. JavaScript isn't the same as
7013 Java, and certainly isn't at all the same as Perl, which is a great
7014 pity. JavaScript allows you to programmatically change the contents of
7015 fill-out forms, create new windows, and pop up dialog box from within
7016 Netscape itself. From the point of view of CGI scripting, JavaScript
7017 is quite useful for validating fill-out forms prior to submitting
7020 You'll need to know JavaScript in order to use it. There are many good
7021 sources in bookstores and on the web.
7023 The usual way to use JavaScript is to define a set of functions in a
7024 <SCRIPT> block inside the HTML header and then to register event
7025 handlers in the various elements of the page. Events include such
7026 things as the mouse passing over a form element, a button being
7027 clicked, the contents of a text field changing, or a form being
7028 submitted. When an event occurs that involves an element that has
7029 registered an event handler, its associated JavaScript code gets
7032 The elements that can register event handlers include the <BODY> of an
7033 HTML document, hypertext links, all the various elements of a fill-out
7034 form, and the form itself. There are a large number of events, and
7035 each applies only to the elements for which it is relevant. Here is a
7042 The browser is loading the current document. Valid in:
7044 + The HTML <BODY> section only.
7048 The browser is closing the current page or frame. Valid for:
7050 + The HTML <BODY> section only.
7054 The user has pressed the submit button of a form. This event happens
7055 just before the form is submitted, and your function can return a
7056 value of false in order to abort the submission. Valid for:
7062 The mouse has clicked on an item in a fill-out form. Valid for:
7064 + Buttons (including submit, reset, and image buttons)
7070 The user has changed the contents of a field. Valid for:
7081 The user has selected a field to work with. Valid for:
7092 The user has deselected a field (gone to work somewhere else). Valid
7104 The user has changed the part of a text field that is selected. Valid
7112 =item B<onMouseOver>
7114 The mouse has moved over an element.
7125 The mouse has moved off an element.
7136 In order to register a JavaScript event handler with an HTML element,
7137 just use the event name as a parameter when you call the corresponding
7138 CGI method. For example, to have your validateAge() JavaScript code
7139 executed every time the textfield named "age" changes, generate the
7142 print textfield(-name=>'age',-onChange=>"validateAge(this)");
7144 This example assumes that you've already declared the validateAge()
7145 function by incorporating it into a <SCRIPT> block. The CGI.pm
7146 start_html() method provides a convenient way to create this section.
7148 Similarly, you can create a form that checks itself over for
7149 consistency and alerts the user if some essential value is missing by
7150 creating it this way:
7151 print startform(-onSubmit=>"validateMe(this)");
7153 See the javascript.cgi script for a demonstration of how this all
7157 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
7159 CGI.pm has limited support for HTML3's cascading style sheets (css).
7160 To incorporate a stylesheet into your document, pass the
7161 start_html() method a B<-style> parameter. The value of this
7162 parameter may be a scalar, in which case it is treated as the source
7163 URL for the stylesheet, or it may be a hash reference. In the latter
7164 case you should provide the hash with one or more of B<-src> or
7165 B<-code>. B<-src> points to a URL where an externally-defined
7166 stylesheet can be found. B<-code> points to a scalar value to be
7167 incorporated into a <style> section. Style definitions in B<-code>
7168 override similarly-named ones in B<-src>, hence the name "cascading."
7170 You may also specify the type of the stylesheet by adding the optional
7171 B<-type> parameter to the hash pointed to by B<-style>. If not
7172 specified, the style defaults to 'text/css'.
7174 To refer to a style within the body of your document, add the
7175 B<-class> parameter to any HTML element:
7177 print h1({-class=>'Fancy'},'Welcome to the Party');
7179 Or define styles on the fly with the B<-style> parameter:
7181 print h1({-style=>'Color: red;'},'Welcome to Hell');
7183 You may also use the new B<span()> element to apply a style to a
7186 print span({-style=>'Color: red;'},
7187 h1('Welcome to Hell'),
7188 "Where did that handbasket get to?"
7191 Note that you must import the ":html3" definitions to have the
7192 B<span()> method available. Here's a quick and dirty example of using
7193 CSS's. See the CSS specification at
7194 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
7196 use CGI qw/:standard :html3/;
7198 #here's a stylesheet incorporated directly into the page
7208 font-family: sans-serif;
7214 print start_html( -title=>'CGI with Style',
7215 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
7218 print h1('CGI with Style'),
7220 "Better read the cascading style sheet spec before playing with this!"),
7221 span({-style=>'color: magenta'},
7222 "Look Mom, no hands!",
7228 Pass an array reference to B<-code> or B<-src> in order to incorporate
7229 multiple stylesheets into your document.
7231 Should you wish to incorporate a verbatim stylesheet that includes
7232 arbitrary formatting in the header, you may pass a -verbatim tag to
7233 the -style hash, as follows:
7235 print start_html (-style => {-verbatim => '@import url("/server-common/css/'.$cssFile.'");',
7236 -src => '/server-common/css/core.css'});
7239 This will generate an HTML header that contains this:
7241 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
7242 <style type="text/css">
7243 @import url("/server-common/css/main.css");
7246 Any additional arguments passed in the -style value will be
7247 incorporated into the <link> tag. For example:
7249 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
7254 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
7255 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
7259 To make more complicated <link> tags, use the Link() function
7260 and pass it to start_html() in the -head argument, as in:
7262 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
7263 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
7264 print start_html({-head=>\@h})
7266 To create primary and "alternate" stylesheet, use the B<-alternate> option:
7268 start_html(-style=>{-src=>[
7269 {-src=>'/styles/print.css'},
7270 {-src=>'/styles/alt.css',-alternate=>1}
7276 If you are running the script from the command line or in the perl
7277 debugger, you can pass the script a list of keywords or
7278 parameter=value pairs on the command line or from standard input (you
7279 don't have to worry about tricking your script into reading from
7280 environment variables). You can pass keywords like this:
7282 your_script.pl keyword1 keyword2 keyword3
7286 your_script.pl keyword1+keyword2+keyword3
7290 your_script.pl name1=value1 name2=value2
7294 your_script.pl name1=value1&name2=value2
7296 To turn off this feature, use the -no_debug pragma.
7298 To test the POST method, you may enable full debugging with the -debug
7299 pragma. This will allow you to feed newline-delimited name=value
7300 pairs to the script on standard input.
7302 When debugging, you can use quotes and backslashes to escape
7303 characters in the familiar shell manner, letting you place
7304 spaces and other funny characters in your parameter=value
7307 your_script.pl "name1='I am a long value'" "name2=two\ words"
7309 Finally, you can set the path info for the script by prefixing the first
7310 name/value parameter with the path followed by a question mark (?):
7312 your_script.pl /your/path/here?name1=value1&name2=value2
7314 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
7316 The Dump() method produces a string consisting of all the query's
7317 name/value pairs formatted nicely as a nested list. This is useful
7318 for debugging purposes:
7323 Produces something that looks like:
7337 As a shortcut, you can interpolate the entire CGI object into a string
7338 and it will be replaced with the a nice HTML dump shown above:
7341 print "<h2>Current Values</h2> $query\n";
7343 =head1 FETCHING ENVIRONMENT VARIABLES
7345 Some of the more useful environment variables can be fetched
7346 through this interface. The methods are as follows:
7352 Return a list of MIME types that the remote browser accepts. If you
7353 give this method a single argument corresponding to a MIME type, as in
7354 Accept('text/html'), it will return a floating point value
7355 corresponding to the browser's preference for this type from 0.0
7356 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
7357 list are handled correctly.
7359 Note that the capitalization changed between version 2.43 and 2.44 in
7360 order to avoid conflict with Perl's accept() function.
7362 =item B<raw_cookie()>
7364 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
7365 Netscape browsers version 1.1 and higher, and all versions of Internet
7366 Explorer. Cookies have a special format, and this method call just
7367 returns the raw form (?cookie dough). See cookie() for ways of
7368 setting and retrieving cooked cookies.
7370 Called with no parameters, raw_cookie() returns the packed cookie
7371 structure. You can separate it into individual cookies by splitting
7372 on the character sequence "; ". Called with the name of a cookie,
7373 retrieves the B<unescaped> form of the cookie. You can use the
7374 regular cookie() method to get the names, or use the raw_fetch()
7375 method from the CGI::Cookie module.
7377 =item B<user_agent()>
7379 Returns the HTTP_USER_AGENT variable. If you give
7380 this method a single argument, it will attempt to
7381 pattern match on it, allowing you to do something
7382 like user_agent(netscape);
7384 =item B<path_info()>
7386 Returns additional path information from the script URL.
7387 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
7388 path_info() returning "/additional/stuff".
7390 NOTE: The Microsoft Internet Information Server
7391 is broken with respect to additional path information. If
7392 you use the Perl DLL library, the IIS server will attempt to
7393 execute the additional path information as a Perl script.
7394 If you use the ordinary file associations mapping, the
7395 path information will be present in the environment,
7396 but incorrect. The best thing to do is to avoid using additional
7397 path information in CGI scripts destined for use with IIS.
7399 =item B<path_translated()>
7401 As per path_info() but returns the additional
7402 path information translated into a physical path, e.g.
7403 "/usr/local/etc/httpd/htdocs/additional/stuff".
7405 The Microsoft IIS is broken with respect to the translated
7408 =item B<remote_host()>
7410 Returns either the remote host name or IP address.
7411 if the former is unavailable.
7413 =item B<script_name()>
7414 Return the script name as a partial URL, for self-refering
7419 Return the URL of the page the browser was viewing
7420 prior to fetching your script. Not available for all
7423 =item B<auth_type ()>
7425 Return the authorization/verification method in use for this
7428 =item B<server_name ()>
7430 Returns the name of the server, usually the machine's host
7433 =item B<virtual_host ()>
7435 When using virtual hosts, returns the name of the host that
7436 the browser attempted to contact
7438 =item B<server_port ()>
7440 Return the port that the server is listening on.
7442 =item B<virtual_port ()>
7444 Like server_port() except that it takes virtual hosts into account.
7445 Use this when running with virtual hosts.
7447 =item B<server_software ()>
7449 Returns the server software and version number.
7451 =item B<remote_user ()>
7453 Return the authorization/verification name used for user
7454 verification, if this script is protected.
7456 =item B<user_name ()>
7458 Attempt to obtain the remote user's name, using a variety of different
7459 techniques. This only works with older browsers such as Mosaic.
7460 Newer browsers do not report the user name for privacy reasons!
7462 =item B<request_method()>
7464 Returns the method used to access your script, usually
7465 one of 'POST', 'GET' or 'HEAD'.
7467 =item B<content_type()>
7469 Returns the content_type of data submitted in a POST, generally
7470 multipart/form-data or application/x-www-form-urlencoded
7474 Called with no arguments returns the list of HTTP environment
7475 variables, including such things as HTTP_USER_AGENT,
7476 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
7477 like-named HTTP header fields in the request. Called with the name of
7478 an HTTP header field, returns its value. Capitalization and the use
7479 of hyphens versus underscores are not significant.
7481 For example, all three of these examples are equivalent:
7483 $requested_language = http('Accept-language');
7484 $requested_language = http('Accept_language');
7485 $requested_language = http('HTTP_ACCEPT_LANGUAGE');
7489 The same as I<http()>, but operates on the HTTPS environment variables
7490 present when the SSL protocol is in effect. Can be used to determine
7491 whether SSL is turned on.
7495 =head1 USING NPH SCRIPTS
7497 NPH, or "no-parsed-header", scripts bypass the server completely by
7498 sending the complete HTTP header directly to the browser. This has
7499 slight performance benefits, but is of most use for taking advantage
7500 of HTTP extensions that are not directly supported by your server,
7501 such as server push and PICS headers.
7503 Servers use a variety of conventions for designating CGI scripts as
7504 NPH. Many Unix servers look at the beginning of the script's name for
7505 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
7506 Internet Information Server, in contrast, try to decide whether a
7507 program is an NPH script by examining the first line of script output.
7510 CGI.pm supports NPH scripts with a special NPH mode. When in this
7511 mode, CGI.pm will output the necessary extra header information when
7512 the header() and redirect() methods are
7515 The Microsoft Internet Information Server requires NPH mode. As of
7516 version 2.30, CGI.pm will automatically detect when the script is
7517 running under IIS and put itself into this mode. You do not need to
7518 do this manually, although it won't hurt anything if you do. However,
7519 note that if you have applied Service Pack 6, much of the
7520 functionality of NPH scripts, including the ability to redirect while
7521 setting a cookie, b<do not work at all> on IIS without a special patch
7523 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
7524 Non-Parsed Headers Stripped From CGI Applications That Have nph-
7529 =item In the B<use> statement
7531 Simply add the "-nph" pragmato the list of symbols to be imported into
7534 use CGI qw(:standard -nph)
7536 =item By calling the B<nph()> method:
7538 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
7542 =item By using B<-nph> parameters
7544 in the B<header()> and B<redirect()> statements:
7546 print header(-nph=>1);
7552 CGI.pm provides four simple functions for producing multipart
7553 documents of the type needed to implement server push. These
7554 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
7555 import these into your namespace, you must import the ":push" set.
7556 You are also advised to put the script into NPH mode and to set $| to
7557 1 to avoid buffering problems.
7559 Here is a simple script that demonstrates server push:
7561 #!/usr/local/bin/perl
7562 use CGI qw/:push -nph/;
7564 print multipart_init(-boundary=>'----here we go!');
7566 print multipart_start(-type=>'text/plain'),
7567 "The current time is ",scalar(localtime),"\n";
7569 print multipart_end;
7571 print multipart_final;
7576 This script initializes server push by calling B<multipart_init()>.
7577 It then enters a loop in which it begins a new multipart section by
7578 calling B<multipart_start()>, prints the current local time,
7579 and ends a multipart section with B<multipart_end()>. It then sleeps
7580 a second, and begins again. On the final iteration, it ends the
7581 multipart section with B<multipart_final()> rather than with
7586 =item multipart_init()
7588 multipart_init(-boundary=>$boundary);
7590 Initialize the multipart system. The -boundary argument specifies
7591 what MIME boundary string to use to separate parts of the document.
7592 If not provided, CGI.pm chooses a reasonable boundary for you.
7594 =item multipart_start()
7596 multipart_start(-type=>$type)
7598 Start a new part of the multipart document using the specified MIME
7599 type. If not specified, text/html is assumed.
7601 =item multipart_end()
7605 End a part. You must remember to call multipart_end() once for each
7606 multipart_start(), except at the end of the last part of the multipart
7607 document when multipart_final() should be called instead of multipart_end().
7609 =item multipart_final()
7613 End all parts. You should call multipart_final() rather than
7614 multipart_end() at the end of the last part of the multipart document.
7618 Users interested in server push applications should also have a look
7619 at the CGI::Push module.
7621 Only Netscape Navigator supports server push. Internet Explorer
7624 =head1 Avoiding Denial of Service Attacks
7626 A potential problem with CGI.pm is that, by default, it attempts to
7627 process form POSTings no matter how large they are. A wily hacker
7628 could attack your site by sending a CGI script a huge POST of many
7629 megabytes. CGI.pm will attempt to read the entire POST into a
7630 variable, growing hugely in size until it runs out of memory. While
7631 the script attempts to allocate the memory the system may slow down
7632 dramatically. This is a form of denial of service attack.
7634 Another possible attack is for the remote user to force CGI.pm to
7635 accept a huge file upload. CGI.pm will accept the upload and store it
7636 in a temporary directory even if your script doesn't expect to receive
7637 an uploaded file. CGI.pm will delete the file automatically when it
7638 terminates, but in the meantime the remote user may have filled up the
7639 server's disk space, causing problems for other programs.
7641 The best way to avoid denial of service attacks is to limit the amount
7642 of memory, CPU time and disk space that CGI scripts can use. Some Web
7643 servers come with built-in facilities to accomplish this. In other
7644 cases, you can use the shell I<limit> or I<ulimit>
7645 commands to put ceilings on CGI resource usage.
7648 CGI.pm also has some simple built-in protections against denial of
7649 service attacks, but you must activate them before you can use them.
7650 These take the form of two global variables in the CGI name space:
7654 =item B<$CGI::POST_MAX>
7656 If set to a non-negative integer, this variable puts a ceiling
7657 on the size of POSTings, in bytes. If CGI.pm detects a POST
7658 that is greater than the ceiling, it will immediately exit with an error
7659 message. This value will affect both ordinary POSTs and
7660 multipart POSTs, meaning that it limits the maximum size of file
7661 uploads as well. You should set this to a reasonably high
7662 value, such as 1 megabyte.
7664 =item B<$CGI::DISABLE_UPLOADS>
7666 If set to a non-zero value, this will disable file uploads
7667 completely. Other fill-out form values will work as usual.
7671 You can use these variables in either of two ways.
7675 =item B<1. On a script-by-script basis>
7677 Set the variable at the top of the script, right after the "use" statement:
7679 use CGI qw/:standard/;
7680 use CGI::Carp 'fatalsToBrowser';
7681 $CGI::POST_MAX=1024 * 100; # max 100K posts
7682 $CGI::DISABLE_UPLOADS = 1; # no uploads
7684 =item B<2. Globally for all scripts>
7686 Open up CGI.pm, find the definitions for $POST_MAX and
7687 $DISABLE_UPLOADS, and set them to the desired values. You'll
7688 find them towards the top of the file in a subroutine named
7689 initialize_globals().
7693 An attempt to send a POST larger than $POST_MAX bytes will cause
7694 I<param()> to return an empty CGI parameter list. You can test for
7695 this event by checking I<cgi_error()>, either after you create the CGI
7696 object or, if you are using the function-oriented interface, call
7697 <param()> for the first time. If the POST was intercepted, then
7698 cgi_error() will return the message "413 POST too large".
7700 This error message is actually defined by the HTTP protocol, and is
7701 designed to be returned to the browser as the CGI script's status
7704 $uploaded_file = param('upload');
7705 if (!$uploaded_file && cgi_error()) {
7706 print header(-status=>cgi_error());
7710 However it isn't clear that any browser currently knows what to do
7711 with this status code. It might be better just to create an
7712 HTML page that warns the user of the problem.
7714 =head1 COMPATIBILITY WITH CGI-LIB.PL
7716 To make it easier to port existing programs that use cgi-lib.pl the
7717 compatibility routine "ReadParse" is provided. Porting is simple:
7720 require "cgi-lib.pl";
7722 print "The value of the antique is $in{antique}.\n";
7727 print "The value of the antique is $in{antique}.\n";
7729 CGI.pm's ReadParse() routine creates a tied variable named %in,
7730 which can be accessed to obtain the query variables. Like
7731 ReadParse, you can also provide your own variable. Infrequently
7732 used features of ReadParse, such as the creation of @in and $in
7733 variables, are not supported.
7735 Once you use ReadParse, you can retrieve the query object itself
7739 print textfield(-name=>'wow',
7740 -value=>'does this really work?');
7742 This allows you to start using the more interesting features
7743 of CGI.pm without rewriting your old scripts from scratch.
7745 =head1 AUTHOR INFORMATION
7747 The GD.pm interface is copyright 1995-2007, Lincoln D. Stein. It is
7748 distributed under GPL and the Artistic License 2.0.
7750 Address bug reports and comments to: lstein@cshl.org. When sending
7751 bug reports, please provide the version of CGI.pm, the version of
7752 Perl, the name and version of your Web server, and the name and
7753 version of the operating system you are using. If the problem is even
7754 remotely browser dependent, please provide information about the
7755 affected browers as well.
7759 Thanks very much to:
7763 =item Matt Heffron (heffron@falstaff.css.beckman.com)
7765 =item James Taylor (james.taylor@srs.gov)
7767 =item Scott Anguish <sanguish@digifix.com>
7769 =item Mike Jewell (mlj3u@virginia.edu)
7771 =item Timothy Shimmin (tes@kbs.citri.edu.au)
7773 =item Joergen Haegg (jh@axis.se)
7775 =item Laurent Delfosse (delfosse@delfosse.com)
7777 =item Richard Resnick (applepi1@aol.com)
7779 =item Craig Bishop (csb@barwonwater.vic.gov.au)
7781 =item Tony Curtis (tc@vcpc.univie.ac.at)
7783 =item Tim Bunce (Tim.Bunce@ig.co.uk)
7785 =item Tom Christiansen (tchrist@convex.com)
7787 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
7789 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
7791 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
7793 =item Stephen Dahmen (joyfire@inxpress.net)
7795 =item Ed Jordan (ed@fidalgo.net)
7797 =item David Alan Pisoni (david@cnation.com)
7799 =item Doug MacEachern (dougm@opengroup.org)
7801 =item Robin Houston (robin@oneworld.org)
7803 =item ...and many many more...
7805 for suggestions and bug fixes.
7809 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
7812 #!/usr/local/bin/perl
7814 use CGI ':standard';
7817 print start_html("Example CGI.pm Form");
7818 print "<h1> Example CGI.pm Form</h1>\n";
7826 print "<em>What's your name?</em><br>";
7827 print textfield('name');
7828 print checkbox('Not my real name');
7830 print "<p><em>Where can you find English Sparrows?</em><br>";
7831 print checkbox_group(
7832 -name=>'Sparrow locations',
7833 -values=>[England,France,Spain,Asia,Hoboken],
7835 -defaults=>[England,Asia]);
7837 print "<p><em>How far can they fly?</em><br>",
7840 -values=>['10 ft','1 mile','10 miles','real far'],
7841 -default=>'1 mile');
7843 print "<p><em>What's your favorite color?</em> ";
7844 print popup_menu(-name=>'Color',
7845 -values=>['black','brown','red','yellow'],
7848 print hidden('Reference','Monty Python and the Holy Grail');
7850 print "<p><em>What have you got there?</em><br>";
7851 print scrolling_list(
7852 -name=>'possessions',
7853 -values=>['A Coconut','A Grail','An Icon',
7854 'A Sword','A Ticket'],
7858 print "<p><em>Any parting comments?</em><br>";
7859 print textarea(-name=>'Comments',
7864 print submit('Action','Shout');
7865 print submit('Action','Scream');
7873 print "<h2>Here are the current settings in this form</h2>";
7875 foreach $key (param) {
7876 print "<strong>$key</strong> -> ";
7877 @values = param($key);
7878 print join(", ",@values),"<br>\n";
7885 <address>Lincoln D. Stein</address><br>
7886 <a href="/">Home Page</a>
7896 L<CGI::Carp>, L<CGI::Fast>, L<CGI::Pretty>