home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2004 July / APC0407D2.iso / workshop / apache / files / ActivePerl-5.8.3.809-MSWin32-x86.msi / _5d05288bac5579cce37290807fab6dd0 < prev    next >
Encoding:
Text File  |  2004-02-02  |  29.2 KB  |  1,201 lines

  1. package HTML::Form;
  2.  
  3. # $Id: Form.pm,v 1.38 2003/10/23 19:11:32 uid39246 Exp $
  4.  
  5. use strict;
  6. use URI;
  7. use Carp ();
  8.  
  9. use vars qw($VERSION);
  10. $VERSION = sprintf("%d.%03d", q$Revision: 1.38 $ =~ /(\d+)\.(\d+)/);
  11.  
  12. my %form_tags = map {$_ => 1} qw(input textarea button select option);
  13.  
  14. my %type2class = (
  15.  text     => "TextInput",
  16.  password => "TextInput",
  17.  hidden   => "TextInput",
  18.  textarea => "TextInput",
  19.  
  20.  button   => "IgnoreInput",
  21.  "reset"  => "IgnoreInput",
  22.  
  23.  radio    => "ListInput",
  24.  checkbox => "ListInput",
  25.  option   => "ListInput",
  26.  
  27.  submit   => "SubmitInput",
  28.  image    => "ImageInput",
  29.  file     => "FileInput",
  30. );
  31.  
  32. =head1 NAME
  33.  
  34. HTML::Form - Class that represents an HTML form element
  35.  
  36. =head1 SYNOPSIS
  37.  
  38.  use HTML::Form;
  39.  $form = HTML::Form->parse($html, $base_uri);
  40.  $form->value(query => "Perl");
  41.  
  42.  use LWP::UserAgent;
  43.  $ua = LWP::UserAgent->new;
  44.  $response = $ua->request($form->click);
  45.  
  46. =head1 DESCRIPTION
  47.  
  48. Objects of the C<HTML::Form> class represents a single HTML
  49. C<E<lt>formE<gt> ... E<lt>/formE<gt>> instance.  A form consists of a
  50. sequence of inputs that usually have names, and which can take on
  51. various values.  The state of a form can be tweaked and it can then be
  52. asked to provide C<HTTP::Request> objects that can be passed to the
  53. request() method of C<LWP::UserAgent>.
  54.  
  55. The following methods are available:
  56.  
  57. =over 4
  58.  
  59. =item @forms = HTML::Form->parse( $html_document, $base_uri )
  60.  
  61. =item @forms = HTML::Form->parse( $response )
  62.  
  63. The parse() class method will parse an HTML document and build up
  64. C<HTML::Form> objects for each <form> element found.  If called in scalar
  65. context only returns the first <form>.  Returns an empty list if there
  66. are no forms to be found.
  67.  
  68. The $base_uri is the URI used to retrieve the $html_document.  It is
  69. needed to resolve relative action URIs.  If the document was retrieved
  70. with LWP then this this parameter is obtained from the
  71. $response->base() method, as shown by the following example:
  72.  
  73.     my $ua = LWP::UserAgent->new;
  74.     my $response = $ua->get("http://www.example.com/form.html");
  75.     my @forms = HTML::Form->parse($response->content,
  76.                   $response->base);
  77.  
  78. The parse() method can parse from an C<HTTP::Response> object
  79. directly, so the example above can be better written as:
  80.  
  81.     my $ua = LWP::UserAgent->new;
  82.     my $response = $ua->get("http://www.example.com/form.html");
  83.     my @forms = HTML::Form->parse($response);
  84.  
  85. Note that any object that implements a content_ref() and base() method
  86. with similar behaviour as C<HTTP::Response> will do.
  87.  
  88. =cut
  89.  
  90. sub parse
  91. {
  92.     my($class, $html, $base_uri) = @_;
  93.     require HTML::TokeParser;
  94.     my $p = HTML::TokeParser->new(ref($html) ? $html->content_ref : \$html);
  95.     eval {
  96.     # optimization
  97.     $p->report_tags(qw(form input textarea select optgroup option));
  98.     };
  99.  
  100.     unless (defined $base_uri) {
  101.     if (ref($html)) {
  102.         $base_uri = $html->base;
  103.     }
  104.     else {
  105.         Carp::croak("HTML::Form::parse: No \$base_uri provided");
  106.     }
  107.     }
  108.  
  109.     my @forms;
  110.     my $f;  # current form
  111.  
  112.     while (my $t = $p->get_tag) {
  113.     my($tag,$attr) = @$t;
  114.     if ($tag eq "form") {
  115.         my $action = delete $attr->{'action'};
  116.         $action = "" unless defined $action;
  117.         $action = URI->new_abs($action, $base_uri);
  118.         $f = $class->new($attr->{'method'},
  119.                  $action,
  120.                  $attr->{'enctype'});
  121.         $f->{attr} = $attr;
  122.         push(@forms, $f);
  123.         while (my $t = $p->get_tag) {
  124.         my($tag, $attr) = @$t;
  125.         last if $tag eq "/form";
  126.         if ($tag eq "input") {
  127.             my $type = delete $attr->{type} || "text";
  128.             $attr->{value_name} = $p->get_phrase;
  129.             $f->push_input($type, $attr);
  130.         }
  131.         elsif ($tag eq "textarea") {
  132.             $attr->{textarea_value} = $attr->{value}
  133.                 if exists $attr->{value};
  134.             my $text = $p->get_text("/textarea");
  135.             $attr->{value} = $text;
  136.             $f->push_input("textarea", $attr);
  137.         }
  138.         elsif ($tag eq "select") {
  139.             $attr->{select_value} = $attr->{value}
  140.                 if exists $attr->{value};
  141.             while ($t = $p->get_tag) {
  142.             my $tag = shift @$t;
  143.             last if $tag eq "/select";
  144.             next if $tag =~ m,/?optgroup,;
  145.             next if $tag eq "/option";
  146.             if ($tag eq "option") {
  147.                 my %a = (%$attr, %{$t->[0]});
  148.                 $a{value_name} = $p->get_trimmed_text;
  149.                 $a{value} = delete $a{value_name}
  150.                 unless defined $a{value};
  151.                 $f->push_input("option", \%a);
  152.             }
  153.             else {
  154.                 Carp::carp("Bad <select> tag '$tag'") if $^W;
  155.             }
  156.             }
  157.         }
  158.         }
  159.     }
  160.     elsif ($form_tags{$tag}) {
  161.         Carp::carp("<$tag> outside <form>") if $^W;
  162.     }
  163.     }
  164.     for (@forms) {
  165.     $_->fixup;
  166.     }
  167.  
  168.     wantarray ? @forms : $forms[0];
  169. }
  170.  
  171. sub new {
  172.     my $class = shift;
  173.     my $self = bless {}, $class;
  174.     $self->{method} = uc(shift  || "GET");
  175.     $self->{action} = shift  || Carp::croak("No action defined");
  176.     $self->{enctype} = lc(shift || "application/x-www-form-urlencoded");
  177.     $self->{inputs} = [@_];
  178.     $self;
  179. }
  180.  
  181.  
  182. sub push_input
  183. {
  184.     my($self, $type, $attr) = @_;
  185.     $type = lc $type;
  186.     my $class = $type2class{$type};
  187.     unless ($class) {
  188.     Carp::carp("Unknown input type '$type'") if $^W;
  189.     $class = "TextInput";
  190.     }
  191.     $class = "IgnoreInput" if exists $attr->{disabled};
  192.     $class = "HTML::Form::$class";
  193.  
  194.     my $input = $class->new(type => $type, %$attr);
  195.     $input->add_to_form($self);
  196. }
  197.  
  198.  
  199. =item $method = $form->method
  200.  
  201. =item $form->method( $new_method )
  202.  
  203. This method is gets/sets the I<method> name used for the
  204. C<HTTP::Request> generated.  It is a string like "GET" or "POST".
  205.  
  206. =item $action = $form->action
  207.  
  208. =item $form->action( $new_action )
  209.  
  210. This method gets/sets the URI which we want to apply the request
  211. I<method> to.
  212.  
  213. =item $enctype = $form->enctype
  214.  
  215. =item $form->enctype( $new_enctype )
  216.  
  217. This method gets/sets the encoding type for the form data.  It is a
  218. string like "application/x-www-form-urlencoded" or "multipart/form-data".
  219.  
  220. =cut
  221.  
  222. BEGIN {
  223.     # Set up some accesor
  224.     for (qw(method action enctype)) {
  225.     my $m = $_;
  226.     no strict 'refs';
  227.     *{$m} = sub {
  228.         my $self = shift;
  229.         my $old = $self->{$m};
  230.         $self->{$m} = shift if @_;
  231.         $old;
  232.     };
  233.     }
  234.     *uri = \&action;  # alias
  235. }
  236.  
  237. =item $value = $form->attr( $name )
  238.  
  239. =item $form->attr( $name, $new_value )
  240.  
  241. This method give access to the original HTML attributes of the <form> tag.
  242. The $name should always be passed in lower case.
  243.  
  244. Example:
  245.  
  246.    @f = HTML::Form->parse( $html, $foo );
  247.    @f = grep $_->attr("id") == "foo", @f;
  248.    die "No form named 'foo' found" unless @f;
  249.    $foo = shift @f;
  250.  
  251. =cut
  252.  
  253. sub attr {
  254.     my $self = shift;
  255.     my $name = shift;
  256.     return undef unless defined $name;
  257.  
  258.     my $old = $self->{attr}{$name};
  259.     $self->{attr}{$name} = shift if @_;
  260.     return $old;
  261. }
  262.  
  263. =item @inputs = $form->inputs
  264.  
  265. This method returns the list of inputs in the form.  If called in
  266. scalar context it returns the number of inputs contained in the form.
  267. See L</INPUTS> for what methods are available for the input objects
  268. returned.
  269.  
  270. =cut
  271.  
  272. sub inputs
  273. {
  274.     my $self = shift;
  275.     @{$self->{'inputs'}};
  276. }
  277.  
  278.  
  279. =item $input = $form->find_input( $name )
  280.  
  281. =item $input = $form->find_input( $name, $type )
  282.  
  283. =item $input = $form->find_input( $name, $type, $index )
  284.  
  285. This method is used to locate specific inputs within the form.  All
  286. inputs that match the arguments given are returned.  In scalar context
  287. only the first is returned, or C<undef> if none match.
  288.  
  289. If $name is specified, then the input must have the indicated name.
  290.  
  291. If $type is specified, then the input must have the specified type.
  292. The following type names are used: "text", "password", "hidden",
  293. "textarea", "file", "image", "submit", "radio", "checkbox" and "option".
  294.  
  295. The $index is the sequence number of the input matched where 1 is the
  296. first.  If combined with $name and/or $type then it select the I<n>th
  297. input with the given name and/or type.
  298.  
  299. =cut
  300.  
  301. sub find_input
  302. {
  303.     my($self, $name, $type, $no) = @_;
  304.     if (wantarray) {
  305.     my @res;
  306.     my $c;
  307.     for (@{$self->{'inputs'}}) {
  308.         if (defined $name) {
  309.         next unless exists $_->{name};
  310.         next if $name ne $_->{name};
  311.         }
  312.         next if $type && $type ne $_->{type};
  313.         $c++;
  314.         next if $no && $no != $c;
  315.         push(@res, $_);
  316.     }
  317.     return @res;
  318.     
  319.     }
  320.     else {
  321.     $no ||= 1;
  322.     for (@{$self->{'inputs'}}) {
  323.         if (defined $name) {
  324.         next unless exists $_->{name};
  325.         next if $name ne $_->{name};
  326.         }
  327.         next if $type && $type ne $_->{type};
  328.         next if --$no;
  329.         return $_;
  330.     }
  331.     return undef;
  332.     }
  333. }
  334.  
  335. sub fixup
  336. {
  337.     my $self = shift;
  338.     for (@{$self->{'inputs'}}) {
  339.     $_->fixup;
  340.     }
  341. }
  342.  
  343.  
  344. =item $value = $form->value( $name )
  345.  
  346. =item $form->value( $name, $new_value )
  347.  
  348. The value() method can be used to get/set the value of some input.  If
  349. no input has the indicated name, then this method will croak.
  350.  
  351. If multiple inputs have the same name, only the first one will be
  352. affected.
  353.  
  354. The call:
  355.  
  356.     $form->value('foo')
  357.  
  358. is a short-hand for:
  359.  
  360.     $form->find_input('foo')->value;
  361.  
  362. =cut
  363.  
  364. sub value
  365. {
  366.     my $self = shift;
  367.     my $key  = shift;
  368.     my $input = $self->find_input($key);
  369.     Carp::croak("No such field '$key'") unless $input;
  370.     local $Carp::CarpLevel = 1;
  371.     $input->value(@_);
  372. }
  373.  
  374. =item @names = $form->param
  375.  
  376. =item @values = $form->param( $name )
  377.  
  378. =item $form->param( $name, $value, ... )
  379.  
  380. =item $form->param( $name, \@values )
  381.  
  382. Alternative interface to examining and setting the values of the form.
  383.  
  384. If called without arguments then it returns the names of all the
  385. inputs in the form.  The names will not repeat even if multiple inputs
  386. have the same name.  In scalar context the number of different names
  387. is returned.
  388.  
  389. If called with a single argument then it returns the value or values
  390. of inputs with the given name.  If called in scalar context only the
  391. first value is returned.  If no input exists with the given name, then
  392. C<undef> is returned.
  393.  
  394. If called with 2 or more arguments then it will set values of the
  395. named inputs.  This form will croak if no inputs have the given name
  396. or if any of the values provided does not fit.  Values can also be
  397. provided as a reference to an array.  This form will allow unsetting
  398. all values with the given name as well.
  399.  
  400. This interface resembles that of the param() function of the CGI
  401. module.
  402.  
  403. =cut
  404.  
  405. sub param {
  406.     my $self = shift;
  407.     if (@_) {
  408.         my $name = shift;
  409.         my @inputs;
  410.         for ($self->inputs) {
  411.             my $n = $_->name;
  412.             next if !defined($n) || $n ne $name;
  413.             push(@inputs, $_);
  414.         }
  415.  
  416.         if (@_) {
  417.             # set
  418.             die "No '$name' parameter exists" unless @inputs;
  419.         my @v = @_;
  420.         @v = @{$v[0]} if @v == 1 && ref($v[0]);
  421.             while (@v) {
  422.                 my $v = shift @v;
  423.                 my $err;
  424.                 for my $i (0 .. @inputs-1) {
  425.                     eval {
  426.                         $inputs[$i]->value($v);
  427.                     };
  428.                     unless ($@) {
  429.                         undef($err);
  430.                         splice(@inputs, $i, 1);
  431.                         last;
  432.                     }
  433.                     $err ||= $@;
  434.                 }
  435.                 die $err if $err;
  436.             }
  437.  
  438.         # the rest of the input should be cleared
  439.         for (@inputs) {
  440.         $_->value(undef);
  441.         }
  442.         }
  443.         else {
  444.             # get
  445.             my @v;
  446.             for (@inputs) {
  447.         if (defined(my $v = $_->value)) {
  448.             push(@v, $v);
  449.         }
  450.             }
  451.             return wantarray ? @v : $v[0];
  452.         }
  453.     }
  454.     else {
  455.         # list parameter names
  456.         my @n;
  457.         my %seen;
  458.         for ($self->inputs) {
  459.             my $n = $_->name;
  460.             next if !defined($n) || $seen{$n}++;
  461.             push(@n, $n);
  462.         }
  463.         return @n;
  464.     }
  465. }
  466.  
  467.  
  468. =item $form->try_others( \&callback )
  469.  
  470. This method will iterate over all permutations of unvisited enumerated
  471. values (<select>, <radio>, <checkbox>) and invoke the callback for
  472. each.  The callback is passed the $form as argument.  The return value
  473. from the callback is ignored and the try_others() method itself does
  474. not return anything.
  475.  
  476. =cut
  477.  
  478. sub try_others
  479. {
  480.     my($self, $cb) = @_;
  481.     my @try;
  482.     for (@{$self->{'inputs'}}) {
  483.     my @not_tried_yet = $_->other_possible_values;
  484.     next unless @not_tried_yet;
  485.     push(@try, [\@not_tried_yet, $_]);
  486.     }
  487.     return unless @try;
  488.     $self->_try($cb, \@try, 0);
  489. }
  490.  
  491. sub _try
  492. {
  493.     my($self, $cb, $try, $i) = @_;
  494.     for (@{$try->[$i][0]}) {
  495.     $try->[$i][1]->value($_);
  496.     &$cb($self);
  497.     $self->_try($cb, $try, $i+1) if $i+1 < @$try;
  498.     }
  499. }
  500.  
  501.  
  502. =item $request = $form->make_request
  503.  
  504. Will return an C<HTTP::Request> object that reflects the current setting
  505. of the form.  You might want to use the click() method instead.
  506.  
  507. =cut
  508.  
  509. sub make_request
  510. {
  511.     my $self = shift;
  512.     my $method  = uc $self->{'method'};
  513.     my $uri     = $self->{'action'};
  514.     my $enctype = $self->{'enctype'};
  515.     my @form    = $self->form;
  516.  
  517.     if ($method eq "GET") {
  518.     require HTTP::Request;
  519.     $uri = URI->new($uri, "http");
  520.     $uri->query_form(@form);
  521.     return HTTP::Request->new(GET => $uri);
  522.     }
  523.     elsif ($method eq "POST") {
  524.     require HTTP::Request::Common;
  525.     return HTTP::Request::Common::POST($uri, \@form,
  526.                        Content_Type => $enctype);
  527.     }
  528.     else {
  529.     Carp::croak("Unknown method '$method'");
  530.     }
  531. }
  532.  
  533.  
  534. =item $request = $form->click
  535.  
  536. =item $request = $form->click( $name )
  537.  
  538. =item $request = $form->click( $x, $y )
  539.  
  540. =item $request = $form->click( $name, $x, $y )
  541.  
  542. Will "click" on the first clickable input (which will be of type
  543. C<submit> or C<image>).  The result of clicking is an C<HTTP::Request>
  544. object that can then be passed to C<LWP::UserAgent> if you want to
  545. obtain the server response.
  546.  
  547. If a $name is specified, we will click on the first clickable input
  548. with the given name, and the method will croak if no clickable input
  549. with the given name is found.  If $name is I<not> specified, then it
  550. is ok if the form contains no clickable inputs.  In this case the
  551. click() method returns the same request as the make_request() method
  552. would do.
  553.  
  554. If there are multiple clickable inputs with the same name, then there
  555. is no way to get the click() method of the C<HTML::Form> to click on
  556. any but the first.  If you need this you would have to locate the
  557. input with find_input() and invoke the click() method on the given
  558. input yourself.
  559.  
  560. A click coordinate pair can also be provided, but this only makes a
  561. difference if you clicked on an image.  The default coordinate is
  562. (1,1).  The upper-left corner of the image is (0,0), but some badly
  563. coded CGI scripts are known to not recognize this.  Therefore (1,1) was
  564. selected as a safer default.
  565.  
  566. =cut
  567.  
  568. sub click
  569. {
  570.     my $self = shift;
  571.     my $name;
  572.     $name = shift if (@_ % 2) == 1;  # odd number of arguments
  573.  
  574.     # try to find first submit button to activate
  575.     for (@{$self->{'inputs'}}) {
  576.         next unless $_->can("click");
  577.         next if $name && $_->name ne $name;
  578.     return $_->click($self, @_);
  579.     }
  580.     Carp::croak("No clickable input with name $name") if $name;
  581.     $self->make_request;
  582. }
  583.  
  584.  
  585. =item @kw = $form->form
  586.  
  587. Returns the current setting as a sequence of key/value pairs.  Note
  588. that keys might be repeated, which means that some values might be
  589. lost if the return values are assigned to a hash.
  590.  
  591. In scalar context this method returns the number of key/value pairs
  592. generated.
  593.  
  594. =cut
  595.  
  596. sub form
  597. {
  598.     my $self = shift;
  599.     map { $_->form_name_value($self) } @{$self->{'inputs'}};
  600. }
  601.  
  602.  
  603. =item $form->dump
  604.  
  605. Returns a textual representation of current state of the form.  Mainly
  606. useful for debugging.  If called in void context, then the dump is
  607. printed on STDERR.
  608.  
  609. =cut
  610.  
  611. sub dump
  612. {
  613.     my $self = shift;
  614.     my $method  = $self->{'method'};
  615.     my $uri     = $self->{'action'};
  616.     my $enctype = $self->{'enctype'};
  617.     my $dump = "$method $uri";
  618.     $dump .= " ($enctype)"
  619.     if $enctype ne "application/x-www-form-urlencoded";
  620.     $dump .= " [$self->{attr}{name}]"
  621.         if exists $self->{attr}{name};
  622.     $dump .= "\n";
  623.     for ($self->inputs) {
  624.     $dump .= "  " . $_->dump . "\n";
  625.     }
  626.     print STDERR $dump unless defined wantarray;
  627.     $dump;
  628. }
  629.  
  630.  
  631. #---------------------------------------------------
  632. package HTML::Form::Input;
  633.  
  634. =back
  635.  
  636. =head1 INPUTS
  637.  
  638. An C<HTML::Form> objects contains a sequence of I<inputs>.  References to
  639. the inputs can be obtained with the $form->inputs or $form->find_input
  640. methods.
  641.  
  642. Note that there is I<not> a one-to-one correspondence between input
  643. I<objects> and E<lt>inputE<gt> I<elements> in the HTML document.  An
  644. input object basically represents a name/value pair, so when multiple
  645. HTML elements contribute to the same name/value pair in the submitted
  646. form they are combined.
  647.  
  648. The input elements that are mapped one-to-one are "text", "textarea",
  649. "password", "hidden", "file", "image", "submit" and "checkbox".  For
  650. the "radio" and "option" inputs the story is not as simple: All
  651. E<lt>input type="radio"E<gt> elements with the same name will
  652. contribute to the same input radio object.  The number of radio input
  653. objects will be the same as the number of distinct names used for the
  654. E<lt>input type="radio"E<gt> elements.  For a E<lt>selectE<gt> element
  655. without the C<multiple> attribute there will be one input object of
  656. type of "option".  For a E<lt>select multipleE<gt> element there will
  657. be one input object for each contained E<lt>optionE<gt> element.  Each
  658. one of these option objects will have the same name.
  659.  
  660. The following methods are available for the I<input> objects:
  661.  
  662. =over 4
  663.  
  664. =cut
  665.  
  666. sub new
  667. {
  668.     my $class = shift;
  669.     my $self = bless {@_}, $class;
  670.     $self;
  671. }
  672.  
  673. sub add_to_form
  674. {
  675.     my($self, $form) = @_;
  676.     push(@{$form->{'inputs'}}, $self);
  677.     $self;
  678. }
  679.  
  680. sub fixup {}
  681.  
  682.  
  683. =item $input->type
  684.  
  685. Returns the type of this input.  The type is one of the following
  686. strings: "text", "password", "hidden", "textarea", "file", "image", "submit",
  687. "radio", "checkbox" or "option".
  688.  
  689. =cut
  690.  
  691. sub type
  692. {
  693.     shift->{type};
  694. }
  695.  
  696. =item $name = $input->name
  697.  
  698. =item $input->name( $new_name )
  699.  
  700. This method can be used to get/set the current name of the input.
  701.  
  702. =item $value = $input->value
  703.  
  704. =item $input->value( $new_value )
  705.  
  706. This method can be used to get/set the current value of an
  707. input.
  708.  
  709. If the input only can take an enumerated list of values, then it is an
  710. error to try to set it to something else and the method will croak if
  711. you try.
  712.  
  713. You will also be able to set the value of read-only inputs, but a
  714. warning will be generated if running under 'perl -w'.
  715.  
  716. =cut
  717.  
  718. sub name
  719. {
  720.     my $self = shift;
  721.     my $old = $self->{name};
  722.     $self->{name} = shift if @_;
  723.     $old;
  724. }
  725.  
  726. sub value
  727. {
  728.     my $self = shift;
  729.     my $old = $self->{value};
  730.     $self->{value} = shift if @_;
  731.     $old;
  732. }
  733.  
  734. =item $input->possible_values
  735.  
  736. Returns a list of all values that an input can take.  For inputs that
  737. do not have discrete values, this returns an empty list.
  738.  
  739. =cut
  740.  
  741. sub possible_values
  742. {
  743.     return;
  744. }
  745.  
  746. =item $input->other_possible_values
  747.  
  748. Returns a list of all values not tried yet.
  749.  
  750. =cut
  751.  
  752. sub other_possible_values
  753. {
  754.     return;
  755. }
  756.  
  757. =item $input->value_names
  758.  
  759. For some inputs the values can have names that are different from the
  760. values themselves.  The number of names returned by this method will
  761. match the number of values reported by $input->possible_values.
  762.  
  763. When setting values using the value() method it is also possible to
  764. use the value names in place of the value itself.
  765.  
  766. =cut
  767.  
  768. sub value_names {
  769.     return
  770. }
  771.  
  772. =item $input->form_name_value
  773.  
  774. Returns a (possible empty) list of key/value pairs that should be
  775. incorporated in the form value from this input.
  776.  
  777. =cut
  778.  
  779. sub form_name_value
  780. {
  781.     my $self = shift;
  782.     my $name = $self->{'name'};
  783.     return unless defined $name;
  784.     my $value = $self->value;
  785.     return unless defined $value;
  786.     return ($name => $value);
  787. }
  788.  
  789. sub dump
  790. {
  791.     my $self = shift;
  792.     my $name = $self->name;
  793.     $name = "<NONAME>" unless defined $name;
  794.     my $value = $self->value;
  795.     $value = "<UNDEF>" unless defined $value;
  796.     my $dump = "$name=$value";
  797.  
  798.     my $type = $self->type;
  799.     return $dump if $type eq "text";
  800.  
  801.     $type = ($type eq "text") ? "" : " ($type)";
  802.     my $menu = $self->{menu} || "";
  803.     my $value_names = $self->{value_names};
  804.     if ($menu) {
  805.     my @menu;
  806.     for (0 .. @$menu-1) {
  807.         my $opt = $menu->[$_];
  808.         $opt = "<UNDEF>" unless defined $opt;
  809.         substr($opt,0,0) = "*" if $self->{seen}[$_];
  810.         $opt .= "/$value_names->[$_]"
  811.         if $value_names && defined $value_names->[$_]
  812.             && $value_names->[$_] ne $opt;
  813.         push(@menu, $opt);
  814.     }
  815.     $menu = "[" . join("|", @menu) . "]";
  816.     }
  817.     sprintf "%-30s %-10s %s", $dump, $type, $menu;
  818. }
  819.  
  820.  
  821. #---------------------------------------------------
  822. package HTML::Form::TextInput;
  823. @HTML::Form::TextInput::ISA=qw(HTML::Form::Input);
  824.  
  825. #input/text
  826. #input/password
  827. #input/hidden
  828. #textarea
  829.  
  830. sub value
  831. {
  832.     my $self = shift;
  833.     my $old = $self->{value};
  834.     $old = "" unless defined $old;
  835.     if (@_) {
  836.     if (exists($self->{readonly}) || $self->{type} eq "hidden") {
  837.         Carp::carp("Input '$self->{name}' is readonly") if $^W;
  838.     }
  839.     $self->{value} = shift;
  840.     }
  841.     $old;
  842. }
  843.  
  844. #---------------------------------------------------
  845. package HTML::Form::IgnoreInput;
  846. @HTML::Form::IgnoreInput::ISA=qw(HTML::Form::Input);
  847.  
  848. #input/button
  849. #input/reset
  850.  
  851. sub value { return }
  852.  
  853.  
  854. #---------------------------------------------------
  855. package HTML::Form::ListInput;
  856. @HTML::Form::ListInput::ISA=qw(HTML::Form::Input);
  857.  
  858. #select/option   (val1, val2, ....)
  859. #input/radio     (undef, val1, val2,...)
  860. #input/checkbox  (undef, value)
  861. #select-multiple/option (undef, value)
  862.  
  863. sub new
  864. {
  865.     my $class = shift;
  866.     my $self = $class->SUPER::new(@_);
  867.  
  868.     my $value = delete $self->{value};
  869.     my $value_name = delete $self->{value_name};
  870.     
  871.     if ($self->type eq "checkbox") {
  872.     $value = "on" unless defined $value;
  873.     $self->{menu} = [undef, $value];
  874.     $self->{value_names} = ["off", $value_name];
  875.     $self->{current} = (exists $self->{checked}) ? 1 : 0;
  876.     delete $self->{checked};
  877.     }
  878.     else {
  879.     $self->{menu} = [$value];
  880.     my $checked = exists $self->{checked} || exists $self->{selected};
  881.     delete $self->{checked};
  882.     delete $self->{selected};
  883.     if (exists $self->{multiple}) {
  884.         unshift(@{$self->{menu}}, undef);
  885.         $self->{value_names} = ["off", $value_name];
  886.         $self->{current} = $checked ? 1 : 0;
  887.     }
  888.     else {
  889.         $self->{value_names} = [$value_name];
  890.         $self->{current} = 0 if $checked;
  891.     }
  892.     }
  893.     $self;
  894. }
  895.  
  896. sub add_to_form
  897. {
  898.     my($self, $form) = @_;
  899.     my $type = $self->type;
  900.     return $self->SUPER::add_to_form($form)
  901.     if $type eq "checkbox" ||
  902.        ($type eq "option" && exists $self->{multiple});
  903.  
  904.     my $prev = $form->find_input($self->{name}, $self->{type});
  905.     return $self->SUPER::add_to_form($form) unless $prev;
  906.  
  907.     # merge menues
  908.     push(@{$prev->{menu}}, @{$self->{menu}});
  909.     push(@{$prev->{value_names}}, @{$self->{value_names}});
  910.     $prev->{current} = @{$prev->{menu}} - 1 if exists $self->{current};
  911. }
  912.  
  913. sub fixup
  914. {
  915.     my $self = shift;
  916.     if ($self->{type} eq "option" && !(exists $self->{current})) {
  917.     $self->{current} = 0;
  918.     }
  919.     $self->{seen} = [(0) x @{$self->{menu}}];
  920.     $self->{seen}[$self->{current}] = 1 if exists $self->{current};
  921. }
  922.  
  923. sub value
  924. {
  925.     my $self = shift;
  926.     my $old;
  927.     $old = $self->{menu}[$self->{current}] if exists $self->{current};
  928.     if (@_) {
  929.     my $i = 0;
  930.     my $val = shift;
  931.     my $cur;
  932.     for (@{$self->{menu}}) {
  933.         if ((defined($val) && defined($_) && $val eq $_) ||
  934.         (!defined($val) && !defined($_))
  935.            )
  936.         {
  937.         $cur = $i;
  938.         last;
  939.         }
  940.         $i++;
  941.     }
  942.     unless (defined $cur) {
  943.         if (defined $val) {
  944.         # try to search among the alternative names as well
  945.         my $i = 0;
  946.         my $cur_ignorecase;
  947.         my $lc_val = lc($val);
  948.         for (@{$self->{value_names}}) {
  949.             if (defined $_) {
  950.             if ($val eq $_) {
  951.                 $cur = $i;
  952.                 last;
  953.             }
  954.             if (!defined($cur_ignorecase) && $lc_val eq lc($_)) {
  955.                 $cur_ignorecase = $i;
  956.             }
  957.             }
  958.             $i++;
  959.         }
  960.         unless (defined $cur) {
  961.             $cur = $cur_ignorecase;
  962.             unless (defined $cur) {
  963.             my $n = $self->name;
  964.                 Carp::croak("Illegal value '$val' for field '$n'");
  965.             }
  966.         }
  967.         }
  968.         else {
  969.         my $n = $self->name;
  970.             Carp::croak("The '$n' field can't be unchecked");
  971.         }
  972.     }
  973.     $self->{current} = $cur;
  974.     $self->{seen}[$cur] = 1;
  975.     }
  976.     $old;
  977. }
  978.  
  979. =item $input->check
  980.  
  981. Some input types represent toggles that can be turned on/off.  This
  982. includes "checkbox" and "option" inputs.  Calling this method turns
  983. this input on without having to know the value name.  If the input is
  984. already on, then nothing happens.
  985.  
  986. This has the same effect as:
  987.  
  988.     $input->value($input->possible_values[1]);
  989.  
  990. The input can be turned off with:
  991.  
  992.     $input->value(undef);
  993.  
  994. =cut
  995.  
  996. sub check
  997. {
  998.     my $self = shift;
  999.     $self->{current} = 1;
  1000.     $self->{seen}[1] = 1;
  1001. }
  1002.  
  1003. sub possible_values
  1004. {
  1005.     my $self = shift;
  1006.     @{$self->{menu}};
  1007. }
  1008.  
  1009. sub other_possible_values
  1010. {
  1011.     my $self = shift;
  1012.     map { $self->{menu}[$_] }
  1013.         grep {!$self->{seen}[$_]}
  1014.              0 .. (@{$self->{seen}} - 1);
  1015. }
  1016.  
  1017. sub value_names {
  1018.     my $self = shift;
  1019.     my @names;
  1020.     for my $i (0 .. @{$self->{menu}} - 1) {
  1021.     my $n = $self->{value_names}[$i];
  1022.     $n = $self->{menu}[$i] unless defined $n;
  1023.     push(@names, $n);
  1024.     }
  1025.     @names;
  1026. }
  1027.  
  1028.  
  1029. #---------------------------------------------------
  1030. package HTML::Form::SubmitInput;
  1031. @HTML::Form::SubmitInput::ISA=qw(HTML::Form::Input);
  1032.  
  1033. #input/image
  1034. #input/submit
  1035.  
  1036. =item $input->click($form, $x, $y)
  1037.  
  1038. Some input types (currently "submit" buttons and "images") can be
  1039. clicked to submit the form.  The click() method returns the
  1040. corresponding C<HTTP::Request> object.
  1041.  
  1042. =cut
  1043.  
  1044. sub click
  1045. {
  1046.     my($self,$form,$x,$y) = @_;
  1047.     for ($x, $y) { $_ = 1 unless defined; }
  1048.     local($self->{clicked}) = [$x,$y];
  1049.     return $form->make_request;
  1050. }
  1051.  
  1052. sub form_name_value
  1053. {
  1054.     my $self = shift;
  1055.     return unless $self->{clicked};
  1056.     return $self->SUPER::form_name_value(@_);
  1057. }
  1058.  
  1059.  
  1060. #---------------------------------------------------
  1061. package HTML::Form::ImageInput;
  1062. @HTML::Form::ImageInput::ISA=qw(HTML::Form::SubmitInput);
  1063.  
  1064. sub form_name_value
  1065. {
  1066.     my $self = shift;
  1067.     my $clicked = $self->{clicked};
  1068.     return unless $clicked;
  1069.     my $name = $self->{name};
  1070.     return unless defined $name;
  1071.     return ("$name.x" => $clicked->[0],
  1072.         "$name.y" => $clicked->[1]
  1073.        );
  1074. }
  1075.  
  1076. #---------------------------------------------------
  1077. package HTML::Form::FileInput;
  1078. @HTML::Form::FileInput::ISA=qw(HTML::Form::TextInput);
  1079.  
  1080. =back
  1081.  
  1082. If the input is of type C<file>, then it has these additional methods:
  1083.  
  1084. =over 4
  1085.  
  1086. =item $input->file
  1087.  
  1088. This is just an alias for the value() method.  It sets the filename to
  1089. read data from.
  1090.  
  1091. =cut
  1092.  
  1093. sub file {
  1094.     my $self = shift;
  1095.     $self->value(@_);
  1096. }
  1097.  
  1098. =item $filename = $input->filename
  1099.  
  1100. =item $input->filename( $new_filename )
  1101.  
  1102. This get/sets the filename reported to the server during file upload.
  1103. This attribute defaults to the value reported by the file() method.
  1104.  
  1105. =cut
  1106.  
  1107. sub filename {
  1108.     my $self = shift;
  1109.     my $old = $self->{filename};
  1110.     $self->{filename} = shift if @_;
  1111.     $old = $self->file unless defined $old;
  1112.     $old;
  1113. }
  1114.  
  1115. =item $content = $input->content
  1116.  
  1117. =item $input->content( $new_content )
  1118.  
  1119. This get/sets the file content provided to the server during file
  1120. upload.  This method can be used if you do not want the content to be
  1121. read from an actual file.
  1122.  
  1123. =cut
  1124.  
  1125. sub content {
  1126.     my $self = shift;
  1127.     my $old = $self->{content};
  1128.     $self->{content} = shift if @_;
  1129.     $old;
  1130. }
  1131.  
  1132. =item @headers = $input->headers
  1133.  
  1134. =item input->headers($key => $value, .... )
  1135.  
  1136. This get/set additional header fields describing the file uploaded.
  1137. This can for instance be used to set the C<Content-Type> reported for
  1138. the file.
  1139.  
  1140. =cut
  1141.  
  1142. sub headers {
  1143.     my $self = shift;
  1144.     my $old = $self->{headers} || [];
  1145.     $self->{headers} = [@_] if @_;
  1146.     @$old;
  1147. }
  1148.  
  1149. sub form_name_value {
  1150.     my($self, $form) = @_;
  1151.     return $self->SUPER::form_name_value($form)
  1152.     if $form->method ne "POST" ||
  1153.        $form->enctype ne "multipart/form-data";
  1154.  
  1155.     my $name = $self->name;
  1156.     return unless defined $name;
  1157.  
  1158.     my $file = $self->file;
  1159.     my $filename = $self->filename;
  1160.     my @headers = $self->headers;
  1161.     my $content = $self->content;
  1162.     if (defined $content) {
  1163.     $filename = $file unless defined $filename;
  1164.     $file = undef;
  1165.     unshift(@headers, "Content" => $content);
  1166.     }
  1167.     elsif (!defined($file) || length($file) == 0) {
  1168.     return;
  1169.     }
  1170.  
  1171.     # legacy (this used to be the way to do it)
  1172.     if (ref($file) eq "ARRAY") {
  1173.     my $f = shift @$file;
  1174.     my $fn = shift @$file;
  1175.     push(@headers, @$file);
  1176.     $file = $f;
  1177.     $filename = $fn unless defined $filename;
  1178.     }
  1179.  
  1180.     return ($name => [$file, $filename, @headers]);
  1181. }
  1182.  
  1183. 1;
  1184.  
  1185. __END__
  1186.  
  1187. =back
  1188.  
  1189. =head1 SEE ALSO
  1190.  
  1191. L<LWP>, L<LWP::UserAgent>, L<HTML::Parser>
  1192.  
  1193. =head1 COPYRIGHT
  1194.  
  1195. Copyright 1998-2003 Gisle Aas.
  1196.  
  1197. This library is free software; you can redistribute it and/or
  1198. modify it under the same terms as Perl itself.
  1199.  
  1200. =cut
  1201.