blib/lib/WWW/BrokenLinks.pm untested

filter: Statementstmt 0.0% 0 / 116 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 33 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 216 CC 20 SCAR 56.7
CC
20
Cov
0%
crawl
420.0
BEGIN
2.0
BEGIN
2.0
CRAP 290.3
1 package WWW::BrokenLinks;
2  
3 use 5.014;
4  
5 use strict;
6 use warnings;
7  
8 use Moose;
9 use namespace::autoclean;
10  
11 use WWW::Mechanize;
12 use URI;
13  
14 use Text::CSV;
15  
16 use IO::Handle;
17  
18 our $VERSION = '0.04';
19  
20 has 'base_url' => (
21 is => 'ro',
22 isa => 'Str',
23 required => 1,
24 );
25  
26 has 'debug' => (
27 is => 'ro',
28 isa => 'Bool',
29 required => 0,
30 default => 0,
31 );
32  
33 has 'request_gap' => (
34 is => 'ro',
35 isa => 'Int',
36 required => 0,
37 default => 1,
38 );
39  
40 has 'output_file' => (
41 is => 'ro',
42 isa => 'Str',
43 required => 0,
44 );
45  
46 has 'excluded_urls' => (
47 traits => ['Array'],
48 is => 'ro',
49 isa => 'ArrayRef[Str]',
50 required => 0,
51 default => sub { [] },
52 handles => {
53 all_excluded_urls => 'elements',
54 },
55 );
56  
57 sub crawl
58 {
59 my $self = shift;
60 my @crawl_queue = ();
61 my %scanned_urls = ();
62 my %broken_urls = ();
63 my $output_fh;
64 my @excluded_urls = $self->all_excluded_urls();
65
66 # Open either the specified output file for writing.
67 if ($self->output_file)
68 {
69 open $output_fh, '>', $self->output_file or die $self->output_file . ": $!";
70 }
71 else
72 {
73 die "No output file specified\n";
74 }
75
76 # Automatically flush STDOUT, otherwise we cannot monitor progress
77 STDOUT->autoflush(1);
78
79 my %csv_options = (
80 'always_quote' => 1,
81 'binary' => 1,
82 'eol' => "\n",
83 );
84
85 my $csv = Text::CSV->new(\%csv_options) or die 'Cannot use CSV: ' . Text::CSV->error_diag();
86
87 # CSV headers
88 $csv->print($output_fh, ['Error', 'Type', 'Source URL', 'Destination URL']);
89
90 # Don't take action when errors occur, otherwise encountering a broken
91 # link will cause the script to exit
92 my $mech = WWW::Mechanize->new(onerror => undef);
93
94 my $current_url = $self->base_url;
95 $scanned_urls{$current_url} = 1;
96
97 while ($current_url)
98 {
99 if ($self->debug) { print "Checking URL: $current_url\n"; }
100
101 my $response = $mech->get($current_url);
102 sleep $self->request_gap;
103
104 my @links = $mech->links();
105 my @images = $mech->images();
106
107 for my $link (@links)
108 {
109 my $abs_url = URI->new_abs($link->url, $current_url)->canonical;
110
111 # Remove the fragment of the URL
112 $abs_url->fragment(undef);
113
114 # Only check http(s) links - ignore mailto, javascript etc.
115 # Do not check URLs which we have previously scanned
116 if (($abs_url->scheme eq 'http' || $abs_url->scheme eq 'https') && !exists($scanned_urls{$abs_url}) && (!exists($broken_urls{$abs_url}) || $broken_urls{$abs_url} < 10))
117 {
118 if ($self->debug) { print "\tChecking link URL: $abs_url\n"; }
119
120 my $is_excluded = 0;
121
122 foreach my $excluded_url (@excluded_urls)
123 {
124 if (index($abs_url, $excluded_url) == 0)
125 {
126 $is_excluded = 1;
127 if ($self->debug) { print "\tMatched URL: $excluded_url\n"; }
128 last;
129 }
130 }
131
132 if (!$is_excluded)
133 {
134 # Issue a HEAD request initially, as we don't care about the body at this point
135 $response = $mech->head($abs_url);
136 sleep $self->request_gap;
137
138 my $final_url = $response->request()->uri();
139
140 if ($response->is_success)
141 {
142 if (index($final_url, $self->base_url) != -1 && $response->content_type eq 'text/html' && !exists($scanned_urls{$abs_url}) && !exists($scanned_urls{$final_url}))
143 {
144 # Local link which we haven't checked, so add to the crawl queue
145 push(@crawl_queue, $final_url);
146
147 if ($self->debug) { print "\tQueued link URL: $abs_url\n"; }
148 }
149 else
150 {
151 if ($self->debug) { print "\tSkipping link URL: $abs_url\n"; }
152 }
153
154 # Always mark a successful URL as scanned, even if it is not local
155 $scanned_urls{$abs_url} = 1;
156 $scanned_urls{$final_url} = 1;
157 }
158 else
159 {
160 # Increment broken list entry for this URL, or set to 1 if this is the
161 # first time we have seen it
162 if (exists($broken_urls{$abs_url}))
163 {
164 $broken_urls{$abs_url} += 1;
165 }
166 else
167 {
168 $broken_urls{$abs_url} = 1;
169 }
170
171 if ($self->debug) { print "\tBroken link URL: $abs_url\n"; }
172
173 $csv->print($output_fh, [$response->status_line, 'Broken Link', $current_url, $abs_url]);
174 }
175 }
176 else
177 {
178 if ($self->debug) { print "\tExcluded URL: $abs_url\n"; }
179 }
180 }
181 else
182 {
183 if ($self->debug) { print "\tSkipping link URL: $abs_url\n"; }
184 }
185 }
186
187 for my $image (@images)
188 {
189 my $abs_url = URI->new_abs($image->url, $current_url)->canonical;
190
191 # Only check http(s) images.
192 # Do not check URLs which we have previously scanned
193 if (($abs_url->scheme eq 'http' || $abs_url->scheme eq 'https') && !exists($scanned_urls{$abs_url}))
194 {
195 if ($self->debug) { print "\tChecking image URL: $abs_url\n"; }
196
197 # Issue a HEAD request initially, as we don't care about the body at this point
198 $response = $mech->head($abs_url);
199 sleep $self->request_gap;
200
201 $abs_url = $response->request()->uri();
202
203 if ($response->is_success)
204 {
205 # We've checked this image, so no need to fetch it again
206 $scanned_urls{$abs_url} = 1;
207 }
208 else
209 {
210 if ($self->debug) { print "\tBroken image URL: $abs_url\n"; }
211
212 $csv->print($output_fh, [$response->status_line, 'Broken image', $current_url, $abs_url]);
213 }
214 }
215 }
216
217 $current_url = pop(@crawl_queue);
218 }
219
220 close $output_fh or die "Could not close output file: $!";
221 }
222  
223 __PACKAGE__->meta->make_immutable;
224  
225 1; # Magic true value required at end of module
226  
227 =pod
228  
229 =encoding UTF-8
230  
231 =head1 NAME
232  
233 WWW::BrokenLinks - Finds broken links (including images) on a website.
234  
235 =head1 VERSION
236  
237 version 0.04
238  
239 =head1 DESCRIPTION
240  
241 This module crawls a given website for broken links, including
242 images, and outputs a report in CSV format.
243  
244 The following functions are provided:
245  
246 =over
247  
248 =item new(\%options)
249  
250 Provided automatically by Moose, thsi is the constructor for the class.
251  
252 The following parameters can be provided as a hash reference.
253  
254 =over
255  
256 =item C<base_url> (required): The base URL to crawl. The module will not crawl above the depth specified.
257  
258 =item C<debug> (optional): Set to 1 to enable debugging messages (off by default).
259  
260 =item C<request_gap> (optional): Number of seconds to wait between requests. Defaults to 1 second.
261  
262 =item C<output_file> (required): Path to file where report shoud be saved.
263  
264 =item C<excluded_urls> (optional): Array reference of URLs to excluded. Defaults to an empty array.
265  
266 =back
267  
268 =item crawl()
269  
270 Crawl the given website for broken links.
271  
272 =back
273  
274 =head1 DEPENDENCIES
275  
276 Perl 5.14 or later is required. This module may work with earlier versions
277 of Perl, but this is neither tested nor supported.
278  
279 =head1 AUTHOR
280  
281 Paul Waring <paul.waring@manchester.ac.uk>
282  
283 =head1 COPYRIGHT AND LICENSE
284  
285 This software is Copyright (c) 2014 by University of Manchester.
286  
287 This is free software, licensed under:
288  
289 The GNU Lesser General Public License, Version 2.1, February 1999
290  
291 =cut
292  
293 __END__