home *** CD-ROM | disk | FTP | other *** search
/ Datatid 2000 #2 / Datatid-2000-02.iso / internet / ecpro / setup.exe / CGI.PM < prev    next >
Encoding:
Perl POD Document  |  1996-10-11  |  138.6 KB  |  4,558 lines

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