home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / perl5 / HTML / Form.pm < prev    next >
Encoding:
Perl POD Document  |  2005-12-07  |  32.4 KB  |  1,387 lines

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