Debian Codegraph @

lib/WWW/Mechanize/Shell.pm

raw ◀ ▶
1 Debian patch touch this file
1 package WWW::Mechanize::Shell;
2
3 use strict;
4 use Carp;
5 use WWW::Mechanize;
6 use WWW::Mechanize::FormFiller;
7 use HTTP::Cookies;
8 use parent qw( Term::Shell );
9 use Exporter 'import';
10 use FindBin;
11 use File::Temp qw(tempfile);
12 use URI::URL;
13 use Hook::LexWrap;
14 use HTML::Display qw();
15 use HTML::TokeParser::Simple;
16 use B::Deparse;
17
18 our $VERSION = '0.63';
19 our @EXPORT = qw( &shell );
20
21 =head1 NAME
22
23 WWW::Mechanize::Shell - An interactive shell for WWW::Mechanize
24
25 =head1 SYNOPSIS
26
27 From the command line as
28
29 perl -MWWW::Mechanize::Shell -eshell
30
31 or alternatively as a custom shell program via :
32
33 =for example begin
34
35 #!/usr/bin/perl -w
36 use strict;
37 use WWW::Mechanize::Shell;
38
39 my $shell = WWW::Mechanize::Shell->new("shell");
40
41 if (@ARGV) {
42 $shell->source_file( @ARGV );
43 } else {
44 $shell->cmdloop;
45 };
46
47 =for example end
48
49 =for example_testing
50 BEGIN {
51 require WWW::Mechanize::Shell;
52 $ENV{PERL_RL} = 0;
53 $ENV{COLUMNS} = '80';
54 $ENV{LINES} = '24';
55 };
56 BEGIN {
57 no warnings 'once';
58 no warnings 'redefine';
59 *WWW::Mechanize::Shell::cmdloop = sub {};
60 *WWW::Mechanize::Shell::display_user_warning = sub {};
61 *WWW::Mechanize::Shell::source_file = sub {};
62 };
63 isa_ok( $shell, "WWW::Mechanize::Shell" );
64
65 =head1 DESCRIPTION
66
67 This module implements a www-like shell above WWW::Mechanize
68 and also has the capability to output crude Perl code that recreates
69 the recorded session. Its main use is as an interactive starting point
70 for automating a session through WWW::Mechanize.
71
72 The cookie support is there, but no cookies are read from your existing
73 browser sessions. See L<HTTP::Cookies> on how to implement reading/writing
74 your current browsers cookies.
75
76 =head2 C<WWW::Mechanize::Shell-E<gt>new %ARGS>
77
78 This is the constructor for a new shell instance. Some of the options
79 can be passed to the constructor as parameters.
80
81 By default, a file C<.mechanizerc> (respectively C<mechanizerc> under Windows)
82 in the users home directory is executed before the interactive shell loop is
83 entered. This can be used to set some defaults. If you want to supply a different
84 filename for the rcfile, the C<rcfile> parameter can be passed to the constructor :
85
86 rcfile => '.myapprc',
87
88 =over 4
89
90 =item B<agent>
91
92 my $shell = WWW::Mechanize::Shell->new(
93 agent => WWW::Mechanize::Chrome->new(),
94 );
95
96 Pass in a premade custom user agent. This object must be compatible to
97 L<WWW::Mechanize>. Use this feature from the command line as
98
99 perl -Ilib -MWWW::Mechanize::Chrome \
100 -MWWW::Mechanize::Shell \
101 -e"shell(agent => WWW::Mechanize::Chrome->new())"
102
103 =back
104
105 =cut
106
107 sub init {
108 my ($self) = @_;
109 my ($name,%args) = @{$self->{API}{args}};
110
111 $self->{agent} = $args{ agent };
112 if( ! $self->agent ) {
113 my $class = $args{ agent_class } || 'WWW::Mechanize';
114 my $args = $args{ agent_args } || [];
115 $self->{agent} = $class->new( @$args );
116 };
117
118 $self->{formfiller} = WWW::Mechanize::FormFiller->new(default => [ Ask => $self ]);
119
120 $self->{history} = [];
121
122 $self->{options} = {
123 autosync => 0,
124 warnings => (exists $args{warnings} ? $args{warnings} : 1),
125 autorestart => 0,
126 watchfiles => (exists $args{watchfiles} ? $args{watchfiles} : 1),
127 cookiefile => 'cookies.txt',
128 dumprequests => 0,
129 dumpresponses => 0,
130 verbose => 0,
131 };
132 # Install the request dumper :
133 $self->{request_wrapper} = wrap 'LWP::UserAgent::request',
134 #pre => sub { printf STDERR "Dumping? %s\n",$self->option("dumprequests"); $self->request_dumper($_[1]) if $self->option("dumprequests"); },
135 pre => sub { $self->request_dumper($_[1]) if $self->option("dumprequests"); },
136 post => sub {
137 $self->response_dumper($_[-1]) if $self->option("dumpresponses");
138 };
139
140 $self->{redirect_ok_wrapper} = wrap 'WWW::Mechanize::redirect_ok',
141 post => sub {
142 return unless $_[1];
143 $self->status( "\nRedirecting to ".$_[1]->uri."\n" );
144 $_[-1]
145 };
146
147 # Load the proxy settings from the environment
148 $self->agent->env_proxy()
149 if $self->agent->can('env_proxy');
150
151 # Read our .rc file :
•152 # I could use File::Homedir, but the docs claim it doesn't work on Win32. Maybe
153 # I should just release a patch for File::Homedir then... Not now.
154 my $sourcefile;
155 if (exists $args{rcfile}) {
156 $sourcefile = delete $args{rcfile};
157 } else {
158 my $userhome = $^O =~ /win32/i ? $ENV{'USERPROFILE'} || $ENV{'HOME'} : ((getpwuid($<))[7]);
159 $sourcefile = "$userhome/.mechanizerc"
160 if -f "$userhome/.mechanizerc";
161 };
162 $self->option('cookiefile', $args{cookiefile}) if (exists $args{cookiefile});
163 $self->source_file($sourcefile) if defined $sourcefile;
164 $self->{browser} = undef;
165
166 # Keep track of the files we consist of, to enable automatic reloading
167 $self->{files} = undef;
168 if ($self->option('watchfiles')) {
169 eval {
170 my @files = grep { -f && -r && $_ ne '-e' } values %INC;
171 local $, = ",";
172 require File::Modified;
173 $self->{files} = File::Modified->new(files=>[@files]);
174 };
175 $self->display_user_warning( "Module File::Modified not found. Automatic reloading disabled.\n" )
176 if ($@);
177 };
178 };
179
180 =head2 C<$shell-E<gt>release_agent>
181
182 Since the shell stores a reference back to itself within the
183 WWW::Mechanize instance, it is necessary to break this
184 circular reference. This method does this.
185
186 =cut
187
188 sub release_agent {
189 my ($self) = @_;
190 use Data::Dumper;
191 warn Dumper $self;
192 undef $self->{request_wrapper};
193 undef $self->{redirect_ok_wrapper};
194 $self->{agent} = undef;
195 };
196
197 =head2 C<$shell-E<gt>source_file FILENAME>
198
199 The C<source_file> method executes the lines of FILENAME
200 as if they were typed in.
201
202 $shell->source_file( $filename );
203
204 =cut
205
206 sub source_file {
207 my ($self,$filename) = @_;
208 local $_; # just to be on the safe side that we don't clobber outside users of $_
209 local *F;
210 open F, "< $filename"
211 or die "Couldn't open '$filename' : $!\n";
212 while (<F>) {
213 $self->cmd($_);
214 warn "cmd: $_"
215 if $self->{options}->{verbose};
216 };
217 close F;
218 };
219
220 sub add_history {
221 my ($self,@code) = @_;
222 push @{$self->{history}},[$self->line,join "",@code];
223 };
224
225 =head2 C<$shell-E<gt>display_user_warning>
226
227 All user warnings are routed through this routine
228 so they can be rerouted / disabled easily.
229
230 =cut
231
232 sub display_user_warning {
233 my ($self,@message) = @_;
234
235 warn @message
236 if $self->option('warnings');
237 };
238
239 =head2 C<$shell-E<gt>print_paged LIST>
240
241 Prints the text in LIST using C<$ENV{PAGER}>. If C<$ENV{PAGER}>
242 is empty, prints directly to C<STDOUT>. Most of this routine
243 comes from the C<perldoc> utility.
244
245 =cut
246
247 sub print_paged {
248 my $self = shift;
249
250 if ($ENV{PAGER} and -t STDOUT) {
251 my ($fh,$filename) = tempfile();
252 print $fh $_ for @_;
253 close $fh;
254
255 my @pagers = ($ENV{PAGER},qq{"$^X" -p});
256 foreach my $pager (@pagers) {
257 if ($^O eq 'VMS') {
258 last if system("$pager $filename") == 0; # quoting prevents logical expansion
259 } else {
260 last if system(qq{$pager "$filename"}) == 0;
261 }
262 };
263 unlink $filename
264 or $self->display_user_warning("Couldn't unlink tempfile $filename : $!\n");
265 } else {
266 print $_ for @_;
267 };
268 };
269
270 sub agent { $_[0]->{agent}; };
271
272 sub option {
273 my ($self,$option,$value) = @_;
274 if (exists $self->{options}->{$option}) {
275 my $result = $self->{options}->{$option};
276 if (scalar @_ == 3) {
277 $self->{options}->{$option} = $value;
278 };
279 $result;
280 } else {
281 Carp::carp "Unknown option '$option'";
282 undef;
283 };
284 };
285
286 sub restart_shell {
287 if ($0 ne '-e') {
288 print "Restarting $0\n";
289 exec $^X, $0, @ARGV;
290 };
291 };
292
293 sub precmd {
294 my $self = shift @_;
295 # We want to restart when any module was changed
296 if ($self->{files} and $self->{files}->changed()) {
297 print "One or more of the base files were changed\n";
298 $self->restart_shell if ($self->option('autorestart'));
299 };
300
301 $self->SUPER::precmd(@_);
302 };
303
304 sub browser {
305 my ($self) = @_;
306 $self->{browser} ||= HTML::Display->new();
307 $self->{browser};
308 };
309
310 sub sync_browser {
311 my ($self) = @_;
312
313 # We only can display html if we have any :
314 return unless $self->agent->res;
315
316 # Prepare the HTML for local display :
317 my $unclean = $self->agent->content;
318 my $html = '';
319
320 # ugly fix:
321 # strip all target='_blank' attributes from the HTML:
322 my $p = HTML::TokeParser::Simple->new(\$unclean);
323 while (my $token = $p->get_token) {
324 $token->delete_attr('target')
325 if $token->is_start_tag;
326 $html .= $token->as_is;
327 };
328
329 my $location = $self->agent->{uri};
330 my $browser = $self->browser;
331 $browser->display( html => $html, location => $location );
332 };
333
334 sub prompt_str {
335 my $self = shift;
336 if ($self->agent->response) {
337 return ($self->agent->uri || "") . ">"
338 } else {
339 return "(no url)>"
340 };
341 };
342
343 sub request_dumper { print $_[1]->as_string };
344 sub response_dumper {
345 if (ref $_[1] eq 'ARRAY') {
346 print $_[1]->[0]->as_string;
347 } else {
348 print $_[1]->as_string;
349 }
350 };
351
352 sub re_or_string {
353 my ($self,$arg) = @_;
354 if ($arg =~ m!^/(.*)/([imsx]*)$!) {
355 my ($re,$mode) = ($1,$2);
356 $re =~ s!([^\\])/!$1\\/!g;
357 $arg = eval "qr/$re/$mode";
358 };
359 $arg;
360 };
361
362 =head2 C<< $shell->link_text LINK >>
363
364 Returns a meaningful text from a WWW::Mechanize::Link object. This is (in order of
365 precedence) :
366
367 $link->text
368 $link->name
369 $link->url
370
371 =cut
372
373 sub link_text {
374 my ($self,$link) = @_;
375 my $result;
376 for (qw( text name url )) {
377 $result = $link->$_ and last;
378 };
379 $result;
380 };
381
382 =head2 C<$shell-E<gt>history>
383
384 Returns the (relevant) shell history, that is, all commands
385 that were not solely for the information of the user. The
386 lines are returned as a list.
387
388 print join "\n", $shell->history;
389
390 =cut
391
392 sub history {
393 my ($self) = @_;
394 map { $_->[0] } @{$self->{history}}
395 };
396
397 =head2 C<$shell-E<gt>script>
398
399 Returns the shell history as a Perl program. The
400 lines are returned as a list. The lines do not have
401 a one-by-one correspondence to the lines in the history.
402
403 print join "\n", $shell->script;
404
405 =cut
406
407 sub script {
408 my ($self,$prefix) = @_;
409 $prefix ||= "";
410
411 my @result = sprintf <<'HEADER', $^X;
412 #!%s -w
413 use strict;
414 use WWW::Mechanize;
415 use WWW::Mechanize::FormFiller;
416 use URI::URL;
417
418 my $agent = WWW::Mechanize->new( autocheck => 1 );
419 my $formfiller = WWW::Mechanize::FormFiller->new();
420 $agent->env_proxy();
421 HEADER
422
423 push @result, map { my $x = $_->[1]; $x =~ s/^/$prefix/mg; $x } @{$self->{history}};
424 @result;
425 };
426
427 =head2 C<$shell-E<gt>status>
428
429 C<status> is called for status updates.
430
431 =cut
432
433 sub status {
434 my $self = shift;
435 print join "", @_;
436 };
437
438 =head2 C<$shell-E<gt>display FILENAME LINES>
439
440 C<display> is called to output listings, currently from the
441 C<history> and C<script> commands. If the second parameter
442 is defined, it is the name of the file to be written,
443 otherwise the lines are displayed to the user.
444
445 =cut
446
447 sub display {
448 my ($self,$filename,@lines) = @_;
449 if (defined $filename) {
450 eval {
451 open my $f, ">", $filename
452 or die "Couldn't create $filename : $!";
453 binmode $f;
454 print $f join( "", map { "$_\n" } (@lines) );
455 close $f;
456 };
457 warn $@ if $@;
458 } else {
459 $self->print_paged( join( "", map { "$_\n" } (@lines) ));
460 };
461 };
462
463 # sub-classed from Term::Shell to handle all run_ requests that have no corresponding sub
464 # This is used for comments
465 sub catch_run {
466 my ($self) = shift;
467 my ($command) = @_;
468 if ($command =~ /^\s*#/) {
469 # Hey, it's a comment.
470 } else {
471 print $self->msg_unknown_cmd($command);
472 };
473 };
474
475 # sub-classed from Term::Shell to handle all smry requests
476 sub catch_smry {
477 my ($self,$command) = @_;
478
479 my $result = eval {
480 require Pod::Constants;
481
482 my @summary;
483 my $module = (ref $self ).".pm";
484 $module =~ s!::!/!g;
485 $module = $INC{$module};
486
487 Pod::Constants::import_from_file( $module, $command => \@summary );
488
489 $summary[0];
490 };
491 if ($@) {
492 return undef;
493 };
494 return $result;
495 };
496
497 # sub-classed from Term::Shell to handle all help requests
498 sub catch_help {
499 my ($self,$command) = @_;
500
501 my @result = eval {
502 require Pod::Constants;
503
504 my @summary;
505 my $module = (ref $self ).".pm";
506 $module =~ s!::!/!g;
507 $module = $INC{$module};
508
509 Pod::Constants::import_from_file( $module, $command => \@summary );
510
511 @summary;
512 };
513 if ($@) {
514 my $module = ref $self;
515 $self->display_user_warning( "Pod::Constants not available. Use perldoc $module for help.\n" );
516 return undef;
517 };
518 return join( "\n", @result) . "\n";
519 };
520
521 =head1 COMMANDS
522
523 The shell implements various commands :
524
525 =head2 exit
526
527 Leaves the shell.
528
529 =cut
530
531 sub alias_exit { qw(quit) };
532
533 =head2 restart
534
535 Restart the shell.
536
•537 This is mostly useful when you are modifying the shell itself. It doesn't
538 work if you use the shell in oneliner mode with C<-e>.
539
540 =cut
541
542 sub run_restart {
543 my ($self) = @_;
544 $self->restart_shell;
545 };
546
547 sub activate_first_form {
548 $_[0]->agent->form_number(1)
549 if $_[0]->agent->forms and scalar @{$_[0]->agent->forms};
550 };
551
552 =head2 get
553
554 Download a specific URL.
555
556 This is used as the entry point in all sessions
557
558 Syntax:
559
560 get URL
561
562 =cut
563
564 sub run_get {
565 my ($self,$url) = @_;
566 $self->status( "Retrieving $url" );
567 my $code;
568 eval { $self->agent->get($url) };
569 if ($@) {
570 print "\n$@\n" if $@;
571 $self->agent->back;
572 } else {
573 $code = $self->agent->res->code;
574 $self->status( "($code)\n" );
575 };
576
577 $self->activate_first_form;
578 $self->sync_browser if $self->option('autosync');
579 $self->add_history( sprintf q{$agent->get('%s');}."\n".q{ $agent->form_number(1) if $agent->forms and scalar @{$agent->forms};}, $url);
580 };
581
582 =head2 save
583
584 Download a link into a file.
585
586 If more than one link matches the RE, all matching links are
587 saved. The filename is taken from the last part of the
588 URL. Alternatively, the number of a link may also be given.
589
590 Syntax:
591
592 save RE
593
594 =cut
595
596 sub run_save {
597 my ($self,$user_link) = @_;
598
599 unless (defined $user_link) {
600 print "No link given to save\n";
601 return
602 };
603 my @history;
604
605 my @links = ();
606 my @all_links = $self->agent->links;
607 push @history, q{my @links;} . "\n";
608 push @history, q{my @all_links = $agent->links();} . "\n";
609
610 $user_link = $self->re_or_string($user_link);
611
612 if (ref $user_link) {
613 my $count = -1;
614 my $re = $user_link;
615 @links = map { $count++; ((defined $_->text && $_->text =~ /$re/)||(defined $_->url && $_->url =~ /$re/)) ? $count : () } @all_links;
616 if (@links == 0) {
617 print "No match for /$re/.\n";
618 };
619 push @history, q{my $count = -1;} . "\n";
620 push @history, sprintf q{@links = map { $count++; ((defined $_->text && $_->text =~ qr(%s))||(defined $_->url && $_->url =~ qr(%s))) ? $count : () } @all_links;} . "\n", $re, $re;
621 } else {
622 @links = $user_link;
623 push @history, sprintf q{@links = '%s';} . "\n", $user_link;
624 };
625
626 if (@links) {
627 $self->add_history( @history,<<'CODE' );
628 my $base = $agent->uri;
629 for my $link (@links) {
630 my $target = $all_links[$link]->url;
631 my $url = URI::URL->new($target,$base);
632 $target = $url->path;
633 $target =~ s!^(.*/)?([^/]+)$!$2!;
634 $url = $url->abs;
635
636 # use this line instead of the next in case you want to use smart mirroring
637 #$agent->mirror($url,$target);
638 $agent->get( $url, ':content_file' => $target );
639 };
640 CODE
641 my $base = $self->agent->uri;
642 for my $link (@links) {
643 my $target = $all_links[$link]->url;
644 my $url = URI::URL->new($target,$base);
645 $target = $url->path;
646 $target =~ s!^(.*/)?([^/]+)$!$2!;
647 $url = $url->abs;
648 eval {
649 $self->status( "$url => $target" );
650 $self->agent->get( $url, ':content_file' => $target );
651 };
652
653 warn $@ if $@;
654 };
655 }
656 };
657
658 =head2 content
659
660 Display the content for the current page.
661
662 Syntax: content [FILENAME]
663
664 If the FILENAME argument is provided, save the content to the file.
665
666 A trailing "\n" is added to the end of the content when using the
667 shell, so this might not be ideally suited to save binary files without
668 manual editing of the produced script.
669
670 =cut
671
672 sub run_content {
673 my ($self, $filename) = @_;
674 $self->display($filename, $self->agent->content);
675 if ($filename) {
676 $self->add_history( sprintf '{ my $filename = q{%s};
677 local *F;
678 open F, "> $filename" or die "$filename: $!";
679 binmode F;
680 print F $agent->content,"\n";
681 close F
682 };', $filename );
683 } else {
684 $self->add_history('print $agent->content,"\n";');
685 };
686 };
687
688 =head2 title
689
690 Display the current page title as found
691 in the C<< <TITLE> >> tag.
692
693 =cut
694
695 sub run_title {
696 my ($self) = @_;
697 my $title = $self->agent->title;
698 if (! defined $title) {
699 $title = "<missing title>"
700 } elsif ($title eq '') {
701 $title = "<empty title>"
702 };
703 print "$title\n";
704 };
705
706 =head2 headers
707
708 Prints all C<< <H1> >> through C<< <H5> >> strings found in the content,
709 indented accordingly. With an argument, prints only those
710 levels; e.g., C<headers 145> prints H1,H4,H5 strings only.
711
712 =cut
713
714 sub run_headers {
715 my ($self,$headers) = @_;
716 $headers ||= "12345";
717
718 my $content = $self->agent->content;
719
720 # Convert the $headers argument to a RE matching
721 # the header tags:
722 my $wanted = join "|", map { "H$_" } split //, $headers;
723 $wanted = qr/^$wanted$/i;
724 #warn $wanted;
725
726 my $p = HTML::TokeParser::Simple->new( \$content );
727 while ( my $token = $p->get_token ) {
728 # This prints all text in an HTML doc (i.e., it strips the HTML)
729 if ($token->is_start_tag($wanted)) {
730 my $tag = $token->get_tag;
731
732 # Indent with two spaces per level
733 my $indent;
734 $indent = $1
735 if ($tag =~ /(\d)/);
736 $indent ||= 1;
737 $indent--;
738 $indent *= 2;
739
740 # advance and print the first text tag we encounter
741 while ($token and not $token->is_text and not $token->is_end_tag($wanted)) {
742 $token = $p->get_token
743 };
744 my $text = "<no text>";
745 if ($token and $token->is_text) {
746 $text = $token->as_is;
747 if ($text !~ /\S/) {
748 $text = "<empty tag>";
749 };
750 };
751
752 # Clean up whitespace
753 $text =~ s/^\s+//g;
754 $text =~ s/\s+$//g;
755 $text =~ s/\s+/ /g;
756
757 printf "%s:%${indent}s%s\n", $tag, "", $text;
758 };
759 }
760 };
761
762 =head2 ua
763
764 Get/set the current user agent
765
766 Syntax:
767
768 # fake Internet Explorer
769 ua "Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)"
770
771 # fake QuickTime v5
772 ua "QuickTime (qtver=5.0.2;os=Windows NT 5.0Service Pack 2)"
773
774 # fake Mozilla/Gecko based
775 ua "Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101"
776
777 # set empty user agent :
778 ua ""
779
780 =cut
781
782 sub run_ua {
783 my ($self,$ua) = @_;
784 my ($result) = $self->agent->agent;
785 if (scalar @_ == 2) {
786 $self->agent->agent($ua);
787 $self->add_history( sprintf q{$agent->agent('%s');}, $ua);
788 } else {
789 print "Current user agent: $result\n";
790 };
791 };
792
793 =head2 links
794
795 Display all links on a page
796
797 The links numbers displayed can used by C<open> to directly
798 select a link to follow.
799
800 =cut
801
802 sub run_links {
803 my ($self) = @_;
804 my @links = $self->agent->links;
805 my $count = 0;
806 for my $link (@links) {
807 # print "[", $count++, "] ", $link->[1],"\n";
808 print sprintf "[%s] %s\n", $count++, $self->link_text($link);
809 };
810 };
811
812 =head2 images
813
814 Display images on a page
815
816 =cut
817
818 sub run_images {
819 my ($self) = @_;
820
821 my @images = $self->agent->images;
822 my $count = 0;
823
824 for my $image ( @images ) {
825 print sprintf("[%d] \"%s\" %s\n", $count++, $image->alt, $image->url);
826 }
827 }
828
829 =head2 parse
830
831 Dump the output of HTML::TokeParser of the current content
832
833 =cut
834
835 sub run_parse {
836 my ($self) = @_;
837 my $content = $self->agent->content;
838 my $p = HTML::TokeParser->new(\$content);
839
840 #$p->report_tags(qw(form input textarea select optgroup option));
841
842 while (my $token = $p->get_token()) {
843 #while (my $token = $p->get_tag("frame")) {
844 # print "<",$token->[0],":",ref $token->[1] ? $token->[1]->{src} : "",">";
845 print "<",$token->[0],":",$token->[1],">";
846 }
847 };
848
849 =head2 forms
850
851 Display all forms on the current page.
852
853 =cut
854
855 sub run_forms {
856 my ($self,$number) = @_;
857
858 my $count = 1;
859 my $agent = $self->agent;
860 my @forms = $agent->forms;
861 if (@forms) {
862 for (@forms) {
863 print "Form [",$count++,"]\n";
864 $_->dump;
865 };
866 } else {
867 print "No forms on current page.\n";
868 };
869 };
870
871 =head2 form
872
873 Select the form named NAME
874
875 If NAME matches C</^\d+$/>, it is assumed to be the (1-based) index
876 of the form to select. There is no way of selecting a numerically
877 named form by its name.
878
879 =cut
880
881 sub run_form {
882 my ($self,$name) = @_;
883 my $number;
884
885 unless ($self->agent->current_form) {
886 print "There is no form on this page.\n";
887 return;
888 };
889
890 if ($name) {
891 my ($method,$val);
892 $val = $name;
893 if ($name =~ /^\d+$/) {
894 $method = 'form_number';
895 } else {
896 $method = 'form_name';
897 $val = qq{'$name'};
898 };
899 eval {
900 $self->agent->$method($name);
901 $self->add_history(sprintf q{$agent->%s(%s);}, $method, $val);
902 $self->status($self->agent->current_form->dump);
903 };
904 $self->display_user_warning( $@ )
905 if ($@);
906 } else {
907 my $count = 1;
908 my @forms = $self->agent->forms;
909 if (@forms) {
910 for my $form (@forms) {
911 print sprintf "Form [%s] (%s)\n", $count++, ($form->attr('name') || "<no name>");
912 $form->dump;
913 };
914 } else {
915 print "No forms found on the current page.\n";
916 };
917 };
918 };
919
920 =head2 dump
921
922 Dump the values of the current form
923
924 =cut
925
926 sub run_dump {
927 my ($self) = @_;
928 my $form = $self->agent->current_form;
929 if ($form) {
930 $form->dump
931 } else {
932 warn "There is no form on the current page\n"
933 if $self->option('warnings');
934 };
935 };
936
937 =head2 value
938
939 Set a form value
940
941 Syntax:
942
943 value NAME [VALUE]
944
945 =cut
946
947 sub run_value {
948 my ($self,$key,@values) = @_;
949
950 # dwim on @values
951 my $value = join " ", @values;
952
953 # Look if we are filling a checkbox set:
954 #my $field = $self->agent->current_form->find_input($key);
955 #if ($field and ($field->type eq 'checkbox')) {
956 # # We want to explicitly multiple checkboxes. This means we
957 # # have to clear all checkboxes and then set them explicitly.
958 #
959 # for my $value (@values) {
960 # # Blatantly stolen from WWW::Mechanize::Ticky by
961 # # Mark Fowler E<lt>[email protected]<gt>
962 # my $input;
963 # my $index = 0;
964 # INPUT: while($input = $self->agent->current_form->find_input($name,"checkbox",$index)) {
965 # # can't guarentee that the first element will be undef and the second
966 # # element will be the right name
967 # foreach my $val ($input->possible_values()) {
968 # next unless defined $val;
969 # if ($val eq $value) {
970 # $input->value($set ? $value : undef);
971 # last INPUT;
972 # }
973 # }
974 #
975 # # move onto the next input
976 # $index++;
977 # }
978 # };
979 #};
980
981 eval {
982 local $^W;
983 $self->agent->current_form->value($key,$value);
984 # Hmm - neither $key nor $value may contain backslashes nor single quotes ...
985 $self->add_history( sprintf q{{ local $^W; $agent->current_form->value('%s', '%s'); };}, $key, $value);
986 };
987 warn $@ if $@;
988 };
989
990 =head2 tick
991
992 Set checkbox marks
993
994 Syntax:
995
996 tick NAME VALUE(s)
997
998 If no value is given, all boxes are checked.
999
1000 =cut
1001
1002 sub tick {
1003 my ($self,$tick,$key,@values) = @_;
1004 eval {
1005 local $^W;
1006 for my $value (@values) {
1007 $self->agent->$tick($key,$value);
1008 };
1009 # Hmm - neither $key nor $value may contain backslashes nor single quotes ...
1010 my $value_str = join ", ", map {qq{'$_'}} @values;
1011 $self->add_history( sprintf q{{ local $^W; for (%s) { $agent->%s('%s', $_); };}}, $value_str, $tick, $key);
1012 };
1013 warn $@ if $@;
1014 };
1015
1016 sub tick_all {
1017 my ($self,$tick,$name) = @_;
1018 eval {
1019 local $^W;
1020 my $index = 1;
1021 while(my $input = $self->agent->current_form->find_input($name,'checkbox',$index)) {
1022 my $value = (grep { defined $_ } ($input->possible_values()))[0];
1023 $self->agent->$tick($name,$value);
1024 $index++;
1025 };
1026 $self->add_history( sprintf q{
1027 { local $^W; my $index = 1;
1028 while(my $input = $agent->current_form->find_input('%s','checkbox',$index)) {
1029 my $value = (grep { defined $_ } ($input->possible_values()))[0];
1030 $agent->%s('%s',$value);
1031 $index++;
1032 };
1033 }}, $name, $tick, $name);
1034 };
1035 warn $@ if $@;
1036 };
1037
1038 sub run_tick {
1039 my ($self,$key,@values) = @_;
1040 if (scalar @values) {
1041 $self->tick( "tick", $key, @values )
1042 } else {
1043 $self->tick_all( "tick", $key )
1044 };
1045 };
1046
1047 =head2 untick
1048
1049 Remove checkbox marks
1050
1051 Syntax:
1052
1053 untick NAME VALUE(s)
1054
1055 If no value is given, all marks are removed.
1056
1057 =cut
1058
1059 sub run_untick {
1060 my ($self,$key,@values) = @_;
1061 if (scalar @values) {
1062 $self->tick( "untick", $key, @values )
1063 } else {
1064 $self->tick_all( "untick", $key )
1065 };
1066 };
1067
1068 =head2 submit
1069
1070 submits the form without clicking on any button
1071
1072 =cut
1073
1074 sub run_submit {
1075 my ($self) = @_;
1076 eval {
1077 my $res = $self->agent->submit;
1078 $self->status( $res->code."\n" );
1079 $self->add_history('$agent->submit();');
1080 $self->sync_browser if $self->option('autosync');
1081 };
1082 warn $@ if $@;
1083 };
1084
1085 =head2 click
1086
1087 Clicks on the button named NAME.
1088
1089 No regular expression expansion is done on NAME.
1090
1091 Syntax:
1092
1093 click NAME
1094
1095 If you have a button that has no name (displayed as NONAME),
1096 use
1097
1098 click ""
1099
1100 to click on it.
1101
1102 =cut
1103
1104 sub run_click {
1105 my ($self,$button) = @_;
1106 $button ||= "";
1107 eval {
1108 my $res = $self->agent->click($button);
1109 $self->status( "(".$res->code.")\n");
1110 $self->activate_first_form;
1111 $self->sync_browser if ($self->option('autosync'));
1112 $self->add_history( sprintf qq{\$agent->click('%s');}, $button );
1113 };
1114 warn $@ if $@;
1115 };
1116
1117 =head2 open
1118
1119 <open> accepts one argument, which can be a regular expression or the number
1120 of a link on the page, starting at zero. These numbers are displayed by the
1121 C<links> function. It goes directly to the page if a number is used
1122 or if the RE has one match. Otherwise, a list of links matching
1123 the regular expression is displayed.
1124
1125 The regular expression should start and end with "/".
1126
1127 Syntax:
1128
1129 open [ RE | # ]
1130
1131 =cut
1132
1133 sub run_open {
1134 my ($self,$user_link) = @_;
1135 $user_link = $self->re_or_string($user_link);
1136 my $link = $user_link;
1137 my $user_link_expr = ref $link ? qq{qr($link)} : qq{'$link'};
1138 unless (defined $link) {
1139 print "No link given\n";
1140 return
1141 };
1142
1143 if ($link =~ /\D/) { # looks like a name/re
1144 my $re = $link if ref $link;
1145 my $count = -1;
1146 my @possible_links = $self->agent->links();
1147 my @links = defined $re
1148 ? map { $count++; my $t = $_->text; defined $t && $t =~ /$re/ ? $count : () } @possible_links
1149 : map { $count++; my $t = $_->text; defined $t && $t eq $link ? $count : () } @possible_links;
1150 if (@links > 1) {
1151 $self->print_pairs([ @links ],[ map {$possible_links[$_]->[1]} @links ]);
1152 undef $link;
1153 } elsif (@links == 0) {
1154 print "No match.\n";
1155 undef $link;
1156 } else {
1157 $self->status( "Found $links[0]\n" );
1158 $link = $links[0];
1159 if ($possible_links[$count]->url =~ /^javascript:(.*)/i) {
1160 print "Can't follow javascript link $1\n";
1161 undef $link;
1162 };
1163 };
1164 };
1165
1166 if (defined $link) {
1167 eval {
1168 $self->agent->follow_link('n' => $link +1);
1169 my ( $hist_option, $hist_value ) =
1170 $user_link =~ /^\d+$/
1171 ? ('n', $user_link + 1 )
1172 : ref $user_link
1173 ? ( 'text_regex', $user_link_expr )
1174 : ( 'text' , $user_link_expr );
1175 $self->add_history(
1176 sprintf qq{\$agent->follow_link('%s' => %s);},
1177 $hist_option,
1178 $hist_value
1179 );
1180 $self->activate_first_form;
1181 if ($self->option('autosync')) {
1182 $self->sync_browser;
1183 };
1184 $self->status( "(".$self->agent->res->code.")\n" );
1185 };
1186 warn $@ if $@;
1187 };
1188 };
1189
1190 # Complete partially typed links :
1191 sub comp_open {
1192 my ($self,$word,$line,$start) = @_;
1193 my @completions = eval { grep {/^$word/} map { $self->link_text( $_ )} ($self->agent->find_all_links()) };
1194 $self->display_user_warning($@) if $@;
1195 return @completions;
1196 };
1197
1198 =head2 back
1199
1200 Go back one page in the browser page history.
1201
1202 =cut
1203
1204 sub run_back {
1205 my ($self) = @_;
1206 eval {
1207 $self->agent->back();
1208 $self->add_history('$agent->back();');
1209 $self->sync_browser
1210 if ($self->option('autosync'));
1211 };
1212 warn $@ if $@;
1213 };
1214
1215 =head2 reload
1216
1217 Repeat the last request, thus reloading the current page.
1218
1219 Note that also POST requests are blindly repeated, as this command
1220 is mostly intended to be used when testing server side code.
1221
1222 =cut
1223
1224 sub run_reload {
1225 my ($self) = @_;
1226 eval {
1227 $self->agent->reload();
1228 $self->add_history('$agent->reload;');
1229 $self->sync_browser
1230 if ($self->option('autosync'));
1231 };
1232 $self->display_user_warning($@)
1233 if $@;
1234 };
1235
1236 =head2 browse
1237
1238 Open the web browser with the current page
1239
1240 Displays the current page in the browser.
1241
1242 =cut
1243
1244 sub run_browse {
1245 my ($self) = @_;
1246 $self->sync_browser;
1247 };
1248
1249 =head2 set
1250
1251 Set a shell option
1252
1253 Syntax:
1254
1255 set OPTION [value]
1256
1257 The command lists all valid options. Here is a short overview over
1258 the different options available :
1259
1260 autosync - automatically synchronize the browser window
1261 autorestart - restart the shell when any required module changes
1262 This does not work with C<-e> oneliners.
1263 watchfiles - watch all required modules for changes
1264 cookiefile - the file where to store all cookies
1265 dumprequests - dump all requests to STDOUT
1266 dumpresponses - dump the headers of the responses to STDOUT
1267 verbose - print commands to STDERR as they are run,
1268 when sourcing from a file
1269
1270 =cut
1271
1272 sub run_set {
1273 my ($self,$option,$value) = @_;
1274 $option ||= "";
1275 if ($option && exists $self->{options}->{$option}) {
1276 if ($option and defined $value) {
1277 $self->option($option,$value);
1278 } else {
1279 $self->print_pairs( [$option], [$self->option($option)] );
1280 };
1281 } else {
1282 print "Unknown option '$option'\n" if $option;
1283 print "Valid options are :\n";
1284 $self->print_pairs( [keys %{$self->{options}}], [ map {$self->option($_)} (keys %{$self->{options}}) ] );
1285 };
1286 };
1287
1288 =head2 history
1289
1290 Display your current session history as the relevant commands.
1291
1292 Syntax:
1293
1294 history [FILENAME]
1295
1296 Commands that have no influence on the browser state are not added
1297 to the history. If a parameter is given to the C<history> command,
1298 the history is saved to that file instead of displayed onscreen.
1299
1300 =cut
1301
1302 sub run_history {
1303 my ($self,$filename) = @_;
1304 $self->display($filename,$self->history);
1305 };
1306
1307 =head2 script
1308
1309 Display your current session history as a Perl script using WWW::Mechanize.
1310
1311 Syntax:
1312
1313 script [FILENAME]
1314
1315 If a parameter is given to the C<script> command, the script is saved to
1316 that file instead of displayed on the console.
1317
1318 This command was formerly known as C<history>.
1319
1320 =cut
1321
1322 sub run_script {
1323 my ($self,$filename) = @_;
1324 $self->display($filename,$self->script(" "));
1325 };
1326
1327 =head2 comment
1328
1329 Adds a comment to the script and the history. The comment
1330 is prepended with a \n to increase readability.
1331
1332 =cut
1333
1334 sub run_comment {
1335 my $self = shift;
1336 if (@_)
1337 {
1338 $self->add_history("\n# @_ ");
1339 }
1340 }
1341
1342 =head2 fillout
1343
1344 Fill out the current form
1345
1346 Interactively asks the values hat have no preset
1347 value via the autofill command.
1348
1349 =cut
1350
1351 sub run_fillout {
1352 my ($self) = @_;
1353 my @interactive_values;
1354 eval {
1355 $self->{answers} = [];
1356 my $form = $self->agent->current_form;
1357 if ($form) {
1358 $self->{formfiller}->fill_form($self->agent->current_form);
1359 @interactive_values = @{$self->{answers}};
1360 } else {
1361 $self->display_user_warning( "No form found on the current page." )
1362 };
1363 };
1364 warn $@ if $@;
1365 $self->add_history( join( "\n",
1366 map { sprintf( q[$formfiller->add_filler( '%s' => Fixed => '%s' );], $_->[0], defined $_->[1] ? $_->[1] : '' ) } @interactive_values) . '$formfiller->fill_form($agent->current_form);');
1367 };
1368
1369 =head2 auth
1370
1371 Set basic authentication credentials.
1372
1373 Syntax:
1374
1375 auth [authority realm] user password
1376
1377 If you get back a 401, you can simply supply the matching
1378 user and password, as the authority and the realm are taken
1379 from the last response:
1380
1381 >get http://www.example.com
1382 Retrieving http://www.example.com(401)
1383 http://www.example.com>auth corion secret
1384 http://www.example.com>get http://www.example.com
1385 Retrieving http://www.example.com(200)
1386 http://www.example.com>
1387
1388 If you know the authority and the realm in advance, you can
1389 presupply the credentials, for example at the start of the script :
1390
1391 >auth www.example.com:80 secure_realm corion secret
1392 >get http://www.example.com
1393 Retrieving http://www.example.com(200)
1394 http://www.example.com>
1395
1396 =cut
1397
1398 sub run_auth {
1399 my ($self) = shift;
1400 my ($authority,$realm,$user,$password,$code);
1401 if (scalar @_ == 4) {
1402 ($authority,$realm,$user,$password) = @_;
1403
1404 $code = sub {
1405 $self->agent->credentials($authority,$realm,$user,$password);
1406 };
1407 } elsif (scalar @_ == 2) {
1408 ($user,$password) = @_;
1409 $password = "" if not defined $password;
1410
1411 if ($self->agent->res) {
1412 $code = sub {
1413 $realm = '';
1414 if (($self->agent->res->www_authenticate || '') =~ /\brealm=(['"]?)(.*?)\1/) {
1415 $realm = $2;
1416 };
1417 $authority = $self->agent->res->request->uri->host_port;
1418 $self->agent->credentials($authority,$realm,$user,$password);
1419 };
1420 } else {
1421 $self->display_user_warning("Cannot guess the authority and realm without a previous request. Use the four-argument form of auth instead.");
1422 $authority = $realm = '';
1423 $code = sub {
1424 $self->agent->credentials($user => $password);
1425 };
1426 }
1427 } else {
1428 $self->display_user_warning("Authentication needs two or four arguments");
1429 return;
1430 };
1431 $code->();
1432 my $body = $self->munge_code($code);
1433
1434 $self->add_history(
1435 sprintf( q{my ($authority,$realm,$user,$password) = ('%s','%s','%s','%s');},
1436 $authority, $realm, $user, $password),
1437 $body,
1438 );
1439 };
1440
1441 =head2 table
1442
1443 Display a table described by the columns COLUMNS.
1444
1445 Syntax:
1446
1447 table COLUMNS
1448
1449 Example:
1450
1451 table Product Price Description
1452
1453 If there is a table on the current page that has in its first row the three
1454 columns C<Product>, C<Price> and C<Description> (not necessarily in that order),
1455 the script will display these columns of the whole table.
1456
1457 The C<HTML::TableExtract> module is needed for this feature.
1458
1459 =cut
1460
1461 sub run_table {
1462 my ($self,@columns) = @_;
1463
1464 eval {
1465 require HTML::TableExtract;
1466 die "I need a HTML::TableExtract version of 2 or greater. I found '$HTML::TableExtract::VERSION'"
1467 if $HTML::TableExtract::VERSION < 2;
1468
1469 my $code = sub {
1470 my $table = HTML::TableExtract->new( headers => [ @columns ] );
1471 (my $content = $self->agent->content) =~ s/\&nbsp;?//g;
1472 $table->parse($content);
1473 my @lines;
1474 push @lines, join(", ", @columns),"\n";
1475 for my $ts ($table->table_states) {
1476 for my $row ($ts->rows) {
1477 push @lines, ">".join(", ", @$row)."<\n";
1478 };
1479 };
1480 $self->print_paged(@lines);
1481 };
1482 $code->();
1483 my $body = $self->munge_code($code);
1484
1485 $self->add_history(
1486 "require HTML::TableExtract;\n",
1487 sprintf( 'my @columns = ( %s );'."\n", join( ",", map( { s/(['\\])/\\$1/g; qq('$_') } @columns ))),
1488 $body
1489 );
1490 };
1491 $self->display_user_warning( "Couldn't load HTML::TableExtract: $@" )
1492 if ($@);
1493 };
1494
1495 =head2 tables
1496
1497 Display a list of tables.
1498
1499 Syntax:
1500
1501 tables
1502
1503 This command will display the top row for every
1504 table on the current page. This is convenient if you want
1505 to find out what the exact spellings for each column are.
1506
1507 The command does not always work nice, for example if a
1508 site uses tables for layout, it will be harder to guess
1509 what tables are irrelevant and what tables are relevant.
1510
1511 L<HTML::TableExtract> is needed for this feature.
1512
1513 =cut
1514
1515 sub run_tables {
1516 my ($self,@columns) = @_;
1517
1518 eval {
1519 require HTML::TableExtract;
1520 die "I need a HTML::TableExtract version of 2 or greater. I found '$HTML::TableExtract::VERSION'"
1521 if $HTML::TableExtract::VERSION < 2;
1522
1523 my $table = HTML::TableExtract->new( subtables => 1 );
1524 (my $content = $self->agent->content) =~ s/\&nbsp;?//g;
1525 $table->parse($content);
1526 my @lines;
1527 for my $ts ($table->table_states) {
1528 my ($row) = $ts->rows;
1529 if (grep { /\S/ } (@$row)) {
1530 push @lines, join( "", "Table ", join( ",",$ts->coords ), " : ", join(",", @$row),"\n" );
1531 };
1532 };
1533 $self->print_paged(@lines);
1534 };
1535 $self->display_user_warning( $@ )
1536 if $@;
1537 };
1538
1539 =head2 cookies
1540
1541 Set the cookie file name
1542
1543 Syntax:
1544
1545 cookies FILENAME
1546
1547 =cut
1548
1549 sub run_cookies {
1550 my ($self,$filename) = @_;
1551 $self->agent->cookie_jar(HTTP::Cookies->new(
1552 file => $filename,
1553 autosave => 1,
1554 ignore_discard => 1,
1555 ));
1556 };
1557
1558 sub run_ {
1559 # ignore empty lines
1560 };
1561
1562 =head2 autofill
1563
1564 Define an automatic value
1565
1566 Sets a form value to be filled automatically. The NAME parameter is
1567 the WWW::Mechanize::FormFiller::Value subclass you want to use. For
1568 session fields, C<Keep> is a good candidate, for interactive stuff,
1569 C<Ask> is a value implemented by the shell.
1570
1571 A field name starting and ending with a slash (C</>) is taken to be
1572 a regular expression and will be applied to all fields with their
1573 name matching the expression. A field with a matching name still
1574 takes precedence over the regular expression.
1575
1576 Syntax:
1577
1578 autofill NAME [PARAMETERS]
1579
1580 Examples:
1581
1582 autofill login Fixed corion
1583 autofill password Ask
1584 autofill selection Random red green orange
1585 autofill session Keep
1586 autofill "/date$/" Random::Date string "%m/%d/%Y"
1587
1588 =cut
1589
1590 sub run_autofill {
1591 my ($self,$name,$class,@args) = @_;
1592 @args = ($self)
1593 if ($class eq 'Ask');
1594 if ($class) {
1595 my $name_vis;
1596 $name = $self->re_or_string($name);
1597 if (ref $name) {
1598 $name_vis = qq{qr($name)};
1599 #warn "autofill RE detected $name";
1600 } else {
1601 $name_vis = qq{"$name"};
1602 };
1603 eval {
1604 $self->{formfiller}->add_filler($name,$class,@args);
1605 $self->add_history( sprintf qq{\$formfiller->add_filler( %s => "%s" => %s ); }, $name_vis, $class, join( ",", map {qq{'$_'}} @args));
1606 };
1607 warn $@
1608 if $@;
1609 } else {
1610 warn "No class for the autofiller given\n";
1611 };
1612 };
1613
1614 =head2 eval
1615
1616 Evaluate Perl code and print the result
1617
1618 Syntax:
1619
1620 eval CODE
1621
1622 For the generated scripts, anything matching the regular expression
1623 C</\$self-E<gt>agent\b/> is automatically
1624 replaced by C<$agent> in your eval code, to do the Right Thing.
1625
1626 Examples:
1627
1628 # Say hello
1629 eval "Hello World"
1630
1631 # And take a look at the current content type
1632 eval $self->agent->ct
1633
1634 =cut
1635
1636 sub run_eval {
1637 my ($self,@rest) = @_;
1638 my $code = $self->line;
1639 if ($code !~ /^eval\s+(.*)$/sm) {
1640 #warn "Don't know what to do with '$code'";
1641 $self->display_user_warning("Don't know what to make of '$code'");
1642 } else {
1643 my $str = $1;
1644 my $code = qq{ do { $str } };
1645 my @res = eval $code;
1646 if (my $err = $@) {
1647 #warn "Don't know what to do with '$str' ($err)";
1648 $self->display_user_warning($err);
1649 return
1650 };
1651 print join "", @res,"\n";
1652
1653
1654 my $script_code = $self->munge_code(qq{print $code, "\\n";});
1655 #warn "Script: $script_code<<";
1656 $self->add_history( $script_code );
1657 };
1658 };
1659
1660 =head2 source
1661
1662 Execute a batch of commands from a file
1663
1664 Syntax:
1665
1666 source FILENAME
1667
1668 =cut
1669
1670 sub run_source {
1671 my ($self,$file) = @_;
1672 if ($file) {
1673 eval { $self->source_file($file); };
1674 if ($@) {
1675 $self->display_user_warning( "Could not source file '$file' : $@" );
1676 };
1677 } else {
1678 print "Syntax: source FILENAME\n";
1679 };
1680 };
1681
1682 =head2 versions
1683
1684 Print the version numbers of important modules
1685
1686 Syntax:
1687
1688 versions
1689
1690 =cut
1691
1692 sub run_versions {
1693 my ($self) = @_;
1694 no strict 'refs';
1695 my @modules = qw( WWW::Mechanize::Shell WWW::Mechanize::FormFiller WWW::Mechanize
1696 Term::Shell
1697 HTML::Parser HTML::TableExtract HTML::Parser HTML::Display
1698 Pod::Constants
1699 File::Modified );
1700 eval "require $_" foreach @modules;
1701 $self->print_pairs( [@modules], [map { defined ${"${_}::VERSION"} ? ${"${_}::VERSION"} : "<undef>" } @modules]);
1702 };
1703
1704 =head2 timeout
1705
1706 Set new timeout value for the agent. Effects all subsequent
1707 requests. VALUE is in seconds.
1708
1709 Syntax:
1710
1711 timeout VALUE
1712
1713 =cut
1714
1715 sub run_timeout {
1716 my ($self, $timeout) = @_;
1717 if ($timeout) {
1718 eval { $self->agent->timeout($timeout); };
1719 if ($@) {
1720 print "Could not set new timeout value : $@";
1721 };
1722 $self->add_history( sprintf q{$agent->timeout(%s);}, $timeout);
1723 } else {
1724 print "Syntax: timeout VALUE\n";
1725 };
1726 };
1727
1728 =head2 ct
1729
1730 prints the content type of the most current response.
1731
1732 Syntax:
1733
1734 ct
1735
1736 =cut
1737
1738 sub run_ct {
1739 my ($self) = @_;
1740 if ($self->agent->content) {
1741 eval { print $self->agent->ct, "\n"; };
1742 if ($@) {
1743 print "Could not get content-type : $@";
1744 };
1745 $self->add_history('print $agent->ct, "\n";');
1746 } else {
1747 print "No content available yet!\n";
1748 }
1749 };
1750
1751 =head2 referrer
1752
1753 set the value of the Referer: header
1754
1755 Syntax:
1756
1757 referer URL
1758 referrer URL
1759
1760 =cut
1761
1762 sub run_referrer {
1763 my ($self, $referrer) = @_;
1764 if (defined $referrer) {
1765 eval { $self->agent->add_header(Referer => $referrer); };
1766 if ($@) {
1767 print "Could not set referrer : $@";
1768 };
1769 # warn "Added $referrer";
1770 $self->add_history( sprintf q{$agent->add_header('Referer', '%s');}, $referrer);
1771 } else {
1772 # print "syntax: referer|referrer URL\n";
1773 eval {
1774 print "Referer: ", $self->agent->{req}->header('Referer'),"\n";
1775 };
1776 }
1777 };
1778
1779 =head2 referer
1780
1781 Alias for referrer
1782
1783 =cut
1784
1785 sub run_referer {
1786 goto &WWW::Mechanize::Shell::run_referrer
1787 };
1788 # sub alias_referrer { qw(referer) };
1789
1790 =head2 response
1791
1792 display the last server response
1793
1794 =cut
1795
1796 sub run_response {
1797 my ($self) = @_;
1798 eval { $self->print_paged( $self->agent->res->as_string )};
1799 };
1800
1801 =head2 C<< $shell->munge_code( CODE ) >>
1802
1803 Munges a coderef to become code fit for
1804 output independent of WWW::Mechanize::Shell.
1805
1806 =cut
1807
1808 our %munge_map = (
1809 '^{' => '',
1810 '}$' => '',
1811 '\$self->print_paged' => 'print ',
1812 '\$self->agent' => '$agent',
1813 '\s*package ' . __PACKAGE__ . ';' => '',
1814 );
1815
1816 sub munge_code {
1817 my ($self, $code) = @_;
1818 my $body;
1819
1820 if (ref $code) {
1821 # Munge code
1822 my $d = B::Deparse->new('-sC');
1823 if ($d->can('ambient_pragmas')) {
1824 $d->ambient_pragmas(strict => 'all', warnings => 'all');
1825 };
1826 $body = $d->coderef2text($code);
1827 } else {
1828 $body = $code
1829 }
1830
1831 while (my ($key,$val) = each %munge_map) {
1832 $body =~ s/$key/$val/gs;
1833 };
1834
1835 $body
1836 };
1837
1838 =head2 C<< shell >>
1839
1840 This subroutine is exported by default as a convenience method
1841 so that the following oneliner invocation works:
1842
1843 perl -MWWW::Mechanize::Shell -eshell
1844
1845 You can pass constructor arguments to this
1846 routine as well. Any scripts given in C<< @ARGV >>
1847 will be run. If C<< @ARGV >> is empty,
1848 an interactive loop will be started.
1849
1850 =cut
1851
1852 sub shell {
1853 my @args = ("shell",@_);
1854 my $shell = WWW::Mechanize::Shell->new(@args);
1855
1856 if (@ARGV) {
1857 $shell->source_file( @ARGV );
1858 } else {
1859 $shell->cmdloop;
1860 };
1861 };
1862
1863 {
1864 package # hide from CPAN
1865 WWW::Mechanize::FormFiller::Value::Ask;
1866 use WWW::Mechanize::FormFiller;
1867 use base 'WWW::Mechanize::FormFiller::Value::Callback';
1868
1869 our $VERSION = '0.63';
1870
1871 sub new {
1872 my ($class,$name,$shell) = @_;
1873 # Using the name here to allow for late binding and overriding via eval()
1874 # from the shell command line
1875 #warn __PACKAGE__ . "::ask_value";
1876 my $self = $class->SUPER::new($name, __PACKAGE__ . '::ask_value');
1877 $self->{shell} = $shell;
1878 Carp::carp "WWW::Mechanize::FormFiller::Value::Ask->new called without a value for the shell" unless $self->{shell};
1879
1880 $self;
1881 };
1882
1883 sub ask_value {
1884 my ($self,$input) = @_;
1885 my @values;
1886 if ($input->possible_values) {
1887 @values = $input->possible_values;
1888 print join( "|", @values ), "\n";
1889 };
1890 my $value;
1891 $value = $input->value;
1892 #warn $value if $value;
1893 if ($input->type !~ /^(submit|hidden)$/) {
1894 $value = $self->{shell}->prompt("(" . $input->type . ")" . $input->name . "> [" . ($input->value || "") . "] ",
1895 ($input->value||''), @values );
1896 undef $value if ($value eq "" and $input->type eq "checkbox");
1897 push @{$self->{shell}->{answers}}, [ $input->name, $value ];
1898 };
1899 $value;
1900 };
1901 };
1902
1903 __END__
1904
1905 =head1 SAMPLE SESSIONS
1906
1907 =head2 Entering values
1908
1909 # Search for a term on Google
1910 get http://www.google.com
1911 value q "Corions Homepage"
1912 click btnG
1913 script
1914 # (yes, this is a bad example of automating, as Google
1915 # already has a Perl API. But other sites don't)
1916
1917 =head2 Retrieving a table
1918
1919 get http://www.perlmonks.org
1920 open "/Saints in/"
1921 table User Experience Level
1922 script
1923 # now you have a program that gives you a csv file of
1924 # that table.
1925
1926 =head2 Uploading a file
1927
1928 get http://aliens:xxxxx/
1929 value f path/to/file
1930 click "upload"
1931
1932 =head2 Batch download
1933
1934 # download prerelease versions of my modules
1935 get http://www.corion.net/perl-dev
1936 save /.tar.gz$/
1937
1938 =head1 REGULAR EXPRESSION SYNTAX
1939
1940 Some commands take regular expressions as parameters. A regular
1941 expression B<must> be a single parameter matching C<^/.*/([isxm]+)?$>, so
1942 you have to use quotes around it if the expression contains spaces :
1943
1944 /link_foo/ # will match as (?-xims:link_foo)
1945 "/link foo/" # will match as (?-xims:link foo)
1946
1947 Slashes do not need to be escaped, as the shell knows that a RE starts and
1948 ends with a slash :
1949
1950 /link/foo/ # will match as (?-xims:link/foo)
1951 "/link/ /foo/" # will match as (?-xims:link/\s/foo)
1952
1953 The C</i> modifier works as expected.
1954 If you desire more power over the regular expressions, consider dropping
1955 to Perl or recommend me a good parser module for regular expressions.
1956
1957 =head1 DISPLAYING HTML
1958
1959 WWW::Mechanize::Shell now uses the module HTML::Display
1960 to display the HTML of the current page in your browser.
1961 Have a look at the documentation of HTML::Display how to
1962 make it use your browser of choice in the case it does not
1963 already guess it correctly.
1964
1965 =head1 FILLING FORMS VIA CUSTOM CODE
1966
1967 If you want to stay within the confines of the shell, but still
1968 want to fill out forms using custom Perl code, here is a recipe
1969 how to achieve this :
1970
•1971 Code passed to the C<eval> command gets evaluated in the WWW::Mechanize::Shell
1972 namespace. You can inject new subroutines there and these get picked
1973 up by the Callback class of WWW::Mechanize::FormFiller :
1974
1975 # Fill in the "date" field with the current date/time as string
1976 eval sub &::custom_today { scalar localtime };
1977 autofill date Callback WWW::Mechanize::Shell::custom_today
1978 fillout
1979
1980 This method can also be used to retrieve data from shell scripts :
1981
1982 # Fill in the "date" field with the current date/time as string
1983 # works only if there is a program "date"
1984 eval sub &::custom_today { chomp `date` };
1985 autofill date Callback WWW::Mechanize::Shell::custom_today
1986 fillout
1987
1988 As the namespace is different between the shell and the generated
1989 script, make sure you always fully qualify your subroutine names,
1990 either in your own namespace or in the main namespace.
1991
1992 =head1 GENERATED SCRIPTS
1993
1994 The C<script> command outputs a skeleton script that reproduces
1995 your actions as done in the current session. It pulls in
1996 C<WWW::Mechanize::FormFiller>, which is possibly not needed. You
1997 should add some error and connection checking afterwards.
1998
1999 =head1 ADDING FIELDS TO HTML
2000
2001 If you are automating a JavaScript dependent site, you will encounter
2002 JavaScript like this :
2003
2004 <script>
2005 document.write( "<input type=submit name=submit>" );
2006 </script>
2007
2008 HTML::Form will not know about this and will not have provided a
2009 submit button for you (understandably). If you want to create such
2010 a submit button from within your automation script, use the following
2011 code :
2012
2013 $agent->current_form->push_input( submit => { name => "submit", value =>"submit" } );
2014
2015 This also works for other dynamically generated input fields.
2016
2017 To fake an input field from within a shell session, use the C<eval> command :
2018
2019 eval $self->agent->current_form->push_input(submit=>{name=>"submit",value=>"submit"});
2020
2021 And yes, the generated script should do the Right Thing for this eval as well.
2022
2023 =head1 LOCAL FILES
2024
2025 If you want to use the shell on a local file without setting up a C<http> server
2026 to serve the file, you can use the C<file:> URI scheme to load it into the "browser":
2027
2028 get file:local.html
2029 forms
2030
2031 =head1 PROXY SUPPORT
2032
2033 Currently, the proxy support is realized via a call to
2034 the C<env_proxy> method of the WWW::Mechanize object, which
2035 loads the proxies from the environment. There is no provision made
2036 to prevent using proxies (yet). The generated scripts also
2037 load their proxies from the environment.
2038
2039 =head1 ONLINE HELP
2040
2041 The online help feature is currently a bit broken in C<Term::Shell>,
2042 but a fix is in the works. Until then, you can re-enable the
2043 dynamic online help by patching C<Term::Shell> :
2044
2045 Remove the three lines
2046
2047 my $smry = exists $o->{handlers}{$h}{smry}
2048 ? $o->summary($h)
2049 : "undocumented";
2050
2051 in C<sub run_help> and replace them by
2052
2053 my $smry = $o->summary($h);
2054
2055 The shell works without this patch and the online help is still
2056 available through C<perldoc WWW::Mechanize::Shell>
2057
2058 =head1 BUGS
2059
2060 Bug reports are very welcome - please use the RT interface at
2061 https://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Mechanize-Shell or send a
2062 descriptive mail to [email protected] . Please
2063 try to include as much (relevant) information as possible - a test script
2064 that replicates the undesired behaviour is welcome every time!
2065
2066 =over 4
2067
2068 =item *
2069
2070 The two parameter version of the C<auth> command guesses the realm from
2071 the last received response. Currently a RE is used to extract the realm,
2072 but this fails with some servers resp. in some cases. Use the four
2073 parameter version of C<auth>, or if not possible, code the extraction
2074 in Perl, either in the final script or through C<eval> commands.
2075
2076 =item *
2077
2078 The shell currently detects when you want to follow a JavaScript link and tells you
2079 that this is not supported. It would be nicer if there was some callback mechanism
2080 to (automatically?) extract URLs from JavaScript-infected links.
2081
2082 =back
2083
2084 =head1 TODO
2085
2086 =over 4
2087
2088 =item *
2089
2090 Add XPath expressions (by moving C<WWW::Mechanize> from HTML::Parser to XML::XMLlib
2091 or maybe easier, by tacking Class::XPath onto an HTML tree)
2092
2093 =item *
2094
2095 Add C<head> as a command ?
2096
2097 =item *
2098
2099 Optionally silence the HTML::Parser / HTML::Forms warnings about invalid HTML.
2100
2101 =back
2102
2103 =head1 EXPORT
2104
2105 The routine C<shell> is exported into the importing namespace. This
2106 is mainly for convenience so you can use the following commandline
2107 invocation of the shell like with CPAN :
2108
2109 perl -MWWW::Mechanize::Shell -e"shell"
2110
2111 =head1 REPOSITORY
2112
2113 The public repository of this module is
2114 L<https://github.com/Corion/WWW-Mechanize-Shell>.
2115
2116 =head1 SUPPORT
2117
2118 The public support forum of this module is
2119 L<http://perlmonks.org/>.
2120
2121 =head1 COPYRIGHT AND LICENSE
2122
2123 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2124
2125 Copyright (C) 2002-2026 Max Maischein
2126
2127 =head1 AUTHOR
2128
2129 Max Maischein, E<lt>[email protected]<gt>
2130
2131 Please contact me if you find bugs or otherwise improve the module. More tests are also very welcome !
2132
2133 =head1 SEE ALSO
2134
2135 L<WWW::Mechanize>,L<WWW::Mechanize::FormFiller>,L<WWW::Mechanize::Firefox>
2136
2137 =cut