Leaked source code of windows server 2003
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.

6639 lines
210 KiB

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