Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6225 lines
186 KiB

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