home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _5d05288bac5579cce37290807fab6dd0 < prev    next >
Encoding:
Text File  |  2004-06-01  |  30.0 KB  |  1,239 lines

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