| 1 | # -*- mode: Perl; -*- | ||
| 2 | package NewsClipper::AcquisitionFunctions; | ||
| 3 | |||
| 4 | # This package contains a set of useful functions for grabbing data from the | ||
| 5 | # internet. It is used by the handlers' Get functions. | ||
| 6 | |||
| 7 | use strict; | ||
| 8 | # For some HTML manipulation functions | ||
| 9 | use NewsClipper::HTMLTools; | ||
| 10 | # For UserAgent | ||
| 11 | use LWP::UserAgent; | ||
| 12 | # For exporting of functions | ||
| 13 | use Exporter; | ||
| 14 | |||
| 15 | use vars qw( @ISA @EXPORT $VERSION ); | ||
| 16 | |||
| 17 | @ISA = qw( Exporter ); | ||
| 18 | @EXPORT = qw(GetUrl GetHtml GetImages GetLinks GetText); | ||
| 19 | |||
| 20 | $VERSION = 0.67; | ||
| 21 | |||
| 22 | use NewsClipper::Globals; | ||
| 23 | |||
| 24 | my $userAgent = new LWP::UserAgent; | ||
| 25 | |||
| 26 | # ------------------------------------------------------------------------------ | ||
| 27 | |||
| 28 | # Gets the entire contents from a URL. This function *does not* escape & < and | ||
| 29 | # >. Use "GetHtml($url,'^','$')" if you want this behavior. | ||
| 30 | |||
| 31 | sub GetUrl($) | ||
| 32 | { | ||
| 33 | my $url = shift; | ||
| 34 | |||
| 35 | unless (defined($url) && ($url ne '')) | ||
| 36 | { | ||
| 37 | dprint "GetUrl couldn't get data. Proper URL not supplied."; | ||
| 38 | $errors{'acquisition'} .= | ||
| 39 | "GetUrl couldn't get data. Proper URL not supplied.\n"; | ||
| 40 | return undef; | ||
| 41 | } | ||
| 42 | |||
| 43 | dprint "GetUrl is getting URL:\n $url"; | ||
| 44 | |||
| 45 | # Try to get the cached data if it's available and still valid. First try to | ||
| 46 | # get the update times for the handler. | ||
| 47 | my @updateTimes = @NewsClipper::Interpreter::update_times; | ||
| 48 | |||
| 49 | # If the user specified "always", there's no need to check the time. | ||
| 50 | if (lc($updateTimes[0]) eq 'always') | ||
| 51 | { | ||
| 52 | dprint "\"Always\" specified. Skipping cache check" | ||
| 53 | } | ||
| 54 | # See if we can just return the current cached data. | ||
| 55 | else | ||
| 56 | { | ||
| 57 | my ($cachedData,$cacheStatus) = | ||
| 58 | $NewsClipper::Globals::cache->get($url,@updateTimes); | ||
| 59 | |||
| 60 | # If the data is still valid for the @updateTimes, we can return it | ||
| 61 | # immediately (There's no need to bless this since it's just a SCALAR) | ||
| 62 | return \$cachedData if $cacheStatus eq 'valid'; | ||
| 63 | |||
| 64 | # Now see if the remote content hasn't changed. If it hasn't, we can | ||
| 65 | # just return the cached data. | ||
| 66 | if ($cacheStatus eq 'stale') | ||
| 67 | { | ||
| 68 | my $last_modified = _GetLastModifiedTime($url); | ||
| 69 | my $cached_time = $NewsClipper::Globals::cache->GetTimeCached($url); | ||
| 70 | if (defined $last_modified && defined $cached_time && | ||
| 71 | $cached_time > $last_modified) | ||
| 72 | { | ||
| 73 | return \$cachedData | ||
| 74 | } | ||
| 75 | } | ||
| 76 | } | ||
| 77 | |||
| 78 | # Otherwise we'll have to fetch it. | ||
| 79 | $userAgent->timeout($config{socket_timeout}); | ||
| 80 | $userAgent->proxy(['http', 'ftp'], $config{proxy}) | ||
| 81 | if $config{proxy} ne ''; | ||
| 82 | my $request = new HTTP::Request GET => "$url"; | ||
| 83 | |||
| 84 | # We'll look like Netscape to the servers. Some servers return different | ||
| 85 | # information depending on whether you are a browser or not. | ||
| 86 | # $userAgent->agent('Mozilla/4.03'); | ||
| 87 | |||
| 88 | # Reload content if the user wants it | ||
| 89 | $request->push_header("Pragma" => "no-cache") if exists $opts{r}; | ||
| 90 | |||
| 91 | if ($config{proxy_username} ne '') | ||
| 92 | { | ||
| 93 | $request->proxy_authorization_basic($config{proxy_username}, | ||
| 94 | $config{proxy_password}); | ||
| 95 | } | ||
| 96 | |||
| 97 | # Tell the server not to send the data if it hasn't been modified. This is | ||
| 98 | # an extra check in addition to the last modified check above. | ||
| 99 | { | ||
| 100 | my $cached_time = $NewsClipper::Globals::cache->GetTimeCached($url); | ||
| 101 | $request->if_modified_since($cached_time); | ||
| 102 | } | ||
| 103 | |||
| 104 | my $result; | ||
| 105 | my $numTriesLeft = $config{socket_tries}; | ||
| 106 | |||
| 107 | do | ||
| 108 | { | ||
| 109 | $result = $userAgent->request($request); | ||
| 110 | $numTriesLeft--; | ||
| 111 | } until ($numTriesLeft == 0 || $result->is_success); | ||
| 112 | |||
| 113 | # If the server reports that the data hasn't changed | ||
| 114 | if (!$result->is_success && $result->code == 304) | ||
| 115 | { | ||
| 116 | dprint "Server reports data hasn't changed."; | ||
| 117 | |||
| 118 | my ($cachedData,$cacheStatus) = | ||
| 119 | $NewsClipper::Globals::cache->get($url,@updateTimes); | ||
| 120 | |||
| 121 | # Use the cached data if there is any available | ||
| 122 | if ($cacheStatus eq 'stale') | ||
| 123 | { | ||
| 124 | dprint "Using cached data."; | ||
| 125 | # No need to bless this since it's just a SCALAR | ||
| 126 | return \$cachedData; | ||
| 127 | } | ||
| 128 | else | ||
| 129 | { | ||
| 130 | dprint "There is no cached data available"; | ||
| 131 | |||
| 132 | return undef; | ||
| 133 | } | ||
| 134 | } | ||
| 135 | elsif (!$result->is_success) | ||
| 136 | { | ||
| 137 | dprint "Couldn't get data. Error on HTTP request: \"" . $result->message . | ||
| 138 | "\""; | ||
| 139 | $errors{'acquisition'} .= "Error on HTTP request: \"" . | ||
| 140 | $result->message . "\".\n" | ||
| 141 | if defined $result; | ||
| 142 | |||
| 143 | my ($cachedData,$cacheStatus) = | ||
| 144 | $NewsClipper::Globals::cache->get($url,@updateTimes); | ||
| 145 | |||
| 146 | # Use the cached data if there is any available | ||
| 147 | if ($cacheStatus eq 'stale') | ||
| 148 | { | ||
| 149 | dprint "HTTP request failed, but there is cached data available."; | ||
| 150 | $errors{'acquisition'} .= "Using cached data.\n"; | ||
| 151 | # No need to bless this since it's just a SCALAR | ||
| 152 | return \$cachedData; | ||
| 153 | } | ||
| 154 | else | ||
| 155 | { | ||
| 156 | dprint "HTTP request failed, and there is no cached data available"; | ||
| 157 | $errors{'acquisition'} .= "There is no cached data.\n"; | ||
| 158 | |||
| 159 | return undef; | ||
| 160 | } | ||
| 161 | } | ||
| 162 | |||
| 163 | my $content = $result->content; | ||
| 164 | |||
| 165 | # Strip linefeeds off the lines if the content looks non-binary | ||
| 166 | $content =~ s/\r//gs if $content !~ /\000/; | ||
| 167 | |||
| 168 | # Cache it for later use, even if "always" was specified. (We use the cached | ||
| 169 | # data to determine when the info was last fetched. Also, the person may | ||
| 170 | # change the handler to something other than "always".) | ||
| 171 | $NewsClipper::Globals::cache->set($url,$content); | ||
| 172 | |||
| 173 | # No need to bless this since it's just a SCALAR | ||
| 174 | return \$content; | ||
| 175 | } | ||
| 176 | |||
| 177 | # ------------------------------------------------------------------------------ | ||
| 178 | |||
| 179 | # Contacts a remote server and determines when the content at the URL was last | ||
| 180 | # modified. Returns undef if it can't determine the time. | ||
| 181 | |||
| 182 | sub _GetLastModifiedTime | ||
| 183 | { | ||
| 184 | my $url = shift; | ||
| 185 | |||
| 186 | # Tell the server to return just 1 byte of content, so we can analyze the | ||
| 187 | # headers. We do a GET here instead of HEAD because I heard that Apache | ||
| 188 | # doesn't return the size for HEAD requests by default. | ||
| 189 | |||
| 190 | # Some FTP servers try to send the whole thing no matter what we tell them. | ||
| 191 | # In that case, we set the timeout small to abort after the headers are | ||
| 192 | # received but before a lot of data comes down the pipe. | ||
| 193 | my $old_timeout = $userAgent->timeout(5); | ||
| 194 | |||
| 195 | my $result; | ||
| 196 | my $numTriesLeft = $config{socket_tries}; | ||
| 197 | |||
| 198 | do | ||
| 199 | { | ||
| 200 | $result = $userAgent->request(HTTP::Request->new('GET', $url),sub{die},1); | ||
| 201 | $numTriesLeft--; | ||
| 202 | } until ($numTriesLeft == 0 || $result->is_success); | ||
| 203 | |||
| 204 | $userAgent->timeout($old_timeout); | ||
| 205 | |||
| 206 | return $result->last_modified; | ||
| 207 | } | ||
| 208 | |||
| 209 | # ------------------------------------------------------------------------------ | ||
| 210 | |||
| 211 | # Gets all the text from a URL, stripping out all HTML tags between the | ||
| 212 | # starting pattern and the ending pattern. This function escapes & < >. | ||
| 213 | |||
| 214 | sub GetText($$$) | ||
| 215 | { | ||
| 216 | my $url = shift; | ||
| 217 | my $startPattern = shift; | ||
| 218 | my $endPattern = shift; | ||
| 219 | |||
| 220 | my $html = GetUrl($url); | ||
| 221 | |||
| 222 | return unless | ||
| 223 | defined $html && defined $startPattern && defined $endPattern; | ||
| 224 | |||
| 225 | $html = $$html; | ||
| 226 | |||
| 227 | # Strip off all the stuff before and after the start and end patterns | ||
| 228 | $html = &ExtractText($html,$startPattern,$endPattern); | ||
| 229 | |||
| 230 | unless (defined $html) | ||
| 231 | { | ||
| 232 | dprint reformat (70,dequote <<" EOF"); | ||
| 233 | Remote content was acquired, but GetText could not extract the | ||
| 234 | interesting part using the start pattern "$startPattern" and the end | ||
| 235 | pattern "$endPattern". | ||
| 236 | EOF | ||
| 237 | |||
| 238 | return undef; | ||
| 239 | } | ||
| 240 | |||
| 241 | # Remove pieces of tags at the ends | ||
| 242 | $html =~ s/^[^<]*>//s; | ||
| 243 | $html =~ s/<[^>]*$//s; | ||
| 244 | |||
| 245 | # Wrap in HTML to help TreeBuilder. | ||
| 246 | $html = "<body>$html" unless $html =~ /<body/i; | ||
| 247 | $html = "$html</body>" unless $html =~ /<\/body>/i; | ||
| 248 | $html = "</head>$html" unless $html =~ /<\/head>/i; | ||
| 249 | $html = "<head>$html" unless $html =~ /<head/i; | ||
| 250 | $html = "<html>$html" unless $html =~ /<html/i; | ||
| 251 | $html = "$html</html>" unless $html =~ /<\/html>/i; | ||
| 252 | |||
| 253 | # FormatText seems to have a problem with | ||
| 254 | $html =~ s/ / /sg; | ||
| 255 | |||
| 256 | # Convert to text | ||
| 257 | require HTML::FormatText; | ||
| 258 | require HTML::TreeBuilder; | ||
| 259 | |||
| 260 | my $f = HTML::FormatText->new(leftmargin=>0); | ||
| 261 | $html = $f->format(HTML::TreeBuilder->new->parse($html)); | ||
| 262 | $html =~ s/\n*$//sg; | ||
| 263 | |||
| 264 | # Escape HTML characters | ||
| 265 | $html = EscapeHTMLChars($html); | ||
| 266 | |||
| 267 | if ($html ne '') | ||
| 268 | { | ||
| 269 | # No need to bless this since it's just a SCALAR | ||
| 270 | return \$html; | ||
| 271 | } | ||
| 272 | else | ||
| 273 | { | ||
| 274 | return undef; | ||
| 275 | } | ||
| 276 | } | ||
| 277 | |||
| 278 | # ------------------------------------------------------------------------------ | ||
| 279 | |||
| 280 | # Extracts HTML between startPattern and endPattern. | ||
| 281 | |||
| 282 | # startPattern and endPattern can be '^' or '$' to match the beginning of the | ||
| 283 | # file or the end of the file, and understands <base href=...> | ||
| 284 | |||
| 285 | sub GetHtml($$$) | ||
| 286 | { | ||
| 287 | my $url = shift; | ||
| 288 | my $startPattern = shift; | ||
| 289 | my $endPattern = shift; | ||
| 290 | |||
| 291 | my $html = &GetUrl($url); | ||
| 292 | |||
| 293 | return unless | ||
| 294 | defined $html && defined $startPattern && defined $endPattern; | ||
| 295 | |||
| 296 | $html = $$html; | ||
| 297 | |||
| 298 | { | ||
| 299 | my $base_href = GetAttributeValue($html,'base','href'); | ||
| 300 | $url = $base_href if defined $base_href; | ||
| 301 | } | ||
| 302 | |||
| 303 | # Strip off all the stuff before and after the start and end patterns | ||
| 304 | $html = &ExtractText($html,$startPattern,$endPattern); | ||
| 305 | return unless defined $html; | ||
| 306 | |||
| 307 | unless (defined $html) | ||
| 308 | { | ||
| 309 | dprint reformat (70,dequote <<" EOF"); | ||
| 310 | Remote content was acquired, but GetHtml could not extract the | ||
| 311 | interesting part using the start pattern "$startPattern" and the end | ||
| 312 | pattern "$endPattern". | ||
| 313 | EOF | ||
| 314 | |||
| 315 | return undef; | ||
| 316 | } | ||
| 317 | |||
| 318 | $html = &MakeLinksAbsolute($url,$html); | ||
| 319 | return unless defined $html; | ||
| 320 | |||
| 321 | if ($html ne '') | ||
| 322 | { | ||
| 323 | # No need to bless this since it's just a SCALAR | ||
| 324 | return \$html; | ||
| 325 | } | ||
| 326 | else | ||
| 327 | { | ||
| 328 | return undef; | ||
| 329 | } | ||
| 330 | } | ||
| 331 | |||
| 332 | #------------------------------------------------------------------------------- | ||
| 333 | |||
| 334 | # Extracts all <img...> tags at a given url between startPattern | ||
| 335 | # and endPattern. | ||
| 336 | # Handles '^' and '$' to signify start and end of file, and understands <base | ||
| 337 | # href=...> | ||
| 338 | |||
| 339 | sub GetImages($$$) | ||
| 340 | { | ||
| 341 | my $url = shift; | ||
| 342 | my $startPattern = shift; | ||
| 343 | my $endPattern = shift; | ||
| 344 | |||
| 345 | my $html = &GetUrl($url); | ||
| 346 | |||
| 347 | return unless | ||
| 348 | defined $html && defined $startPattern && defined $endPattern; | ||
| 349 | |||
| 350 | $html = $$html; | ||
| 351 | |||
| 352 | { | ||
| 353 | my $base_href = GetAttributeValue($html,'base','href'); | ||
| 354 | $url = $base_href if defined $base_href; | ||
| 355 | } | ||
| 356 | |||
| 357 | # Strip off all the stuff before and after the start and end patterns | ||
| 358 | $html = &ExtractText($html,$startPattern,$endPattern); | ||
| 359 | |||
| 360 | unless (defined $html) | ||
| 361 | { | ||
| 362 | dprint reformat (70,dequote <<" EOF"); | ||
| 363 | Remote content was acquired, but GetImages could not extract the | ||
| 364 | interesting part using the start pattern "$startPattern" and the end | ||
| 365 | pattern "$endPattern". | ||
| 366 | EOF | ||
| 367 | |||
| 368 | return undef; | ||
| 369 | } | ||
| 370 | |||
| 371 | # Remove any formatting | ||
| 372 | $html = StripTags($html); | ||
| 373 | |||
| 374 | require HTML::TreeBuilder; | ||
| 375 | my $tree = HTML::TreeBuilder->new; | ||
| 376 | $tree->parse($html); | ||
| 377 | |||
| 378 | my @imgTags; | ||
| 379 | |||
| 380 | foreach my $linkpair (@{$tree->extract_links('img')}) | ||
| 381 | { | ||
| 382 | # Extract the link from the HTML element. | ||
| 383 | my $elem = ${$linkpair}[1]; | ||
| 384 | my $link = $elem->as_HTML(); | ||
| 385 | chomp $link; | ||
| 386 | |||
| 387 | # Repair brain-dead & to & in URLs | ||
| 388 | $link =~ s! | ||
| 389 | # First look for an a, img, or area, followed later by an href or src | ||
| 390 | (<\s*(?:a|img|area)\b[^>]*(?:href|src)\s*=\s* | ||
| 391 | # Then an optional quote | ||
| 392 | ['"]?) | ||
| 393 | # Then the interesting part | ||
| 394 | ([^'"> ]+) | ||
| 395 | # Then another optional quote | ||
| 396 | (['"]? | ||
| 397 | # And the left-overs | ||
| 398 | [^>]*>) | ||
| 399 | ! | ||
| 400 | my $front = $1; | ||
| 401 | my $url = $2; | ||
| 402 | my $back = $3; | ||
| 403 | |||
| 404 | $url =~ s/\&/\&/g; | ||
| 405 | |||
| 406 | # Then construct the new link from the prefix and suffix | ||
| 407 | $_ = $front.$url.$back; | ||
| 408 | !segix; | ||
| 409 | |||
| 410 | # change relative tags to absolute | ||
| 411 | $link = &MakeLinksAbsolute($url,$link); | ||
| 412 | bless \$link,'Image'; | ||
| 413 | push @imgTags, \$link; | ||
| 414 | } | ||
| 415 | |||
| 416 | if ($#imgTags != -1) | ||
| 417 | { | ||
| 418 | return \@imgTags; | ||
| 419 | } | ||
| 420 | else | ||
| 421 | { | ||
| 422 | return undef; | ||
| 423 | } | ||
| 424 | } | ||
| 425 | |||
| 426 | # ------------------------------------------------------------------------------ | ||
| 427 | |||
| 428 | # Extracts all <a href...>...</a> links at a given url between startPattern | ||
| 429 | # and endPattern. Removes all text formatting, and makes relative links | ||
| 430 | # absolute. Puts quotes around attribute values in stuff like <a href=blah> and | ||
| 431 | # <img src=blah>. | ||
| 432 | |||
| 433 | # Handles '^' and '$' to signify start and end of file, and understands <base | ||
| 434 | # href=...> | ||
| 435 | |||
| 436 | sub GetLinks($$$) | ||
| 437 | { | ||
| 438 | my $url = shift; | ||
| 439 | my $startPattern = shift; | ||
| 440 | my $endPattern = shift; | ||
| 441 | |||
| 442 | my $html = &GetUrl($url); | ||
| 443 | |||
| 444 | return unless | ||
| 445 | defined $html && defined $startPattern && defined $endPattern; | ||
| 446 | |||
| 447 | $html = $$html; | ||
| 448 | |||
| 449 | { | ||
| 450 | my $base_href = GetAttributeValue($html,'base','href'); | ||
| 451 | $url = $base_href if defined $base_href; | ||
| 452 | } | ||
| 453 | |||
| 454 | # Strip off all the stuff before and after the start and end patterns | ||
| 455 | $html = &ExtractText($html,$startPattern,$endPattern); | ||
| 456 | |||
| 457 | unless (defined $html) | ||
| 458 | { | ||
| 459 | dprint reformat (70,dequote <<" EOF"); | ||
| 460 | Remote content was acquired, but GetLinks could not extract the | ||
| 461 | interesting part using the start pattern "$startPattern" and the end | ||
| 462 | pattern "$endPattern". | ||
| 463 | EOF | ||
| 464 | |||
| 465 | return undef; | ||
| 466 | } | ||
| 467 | |||
| 468 | # Remove any formatting | ||
| 469 | $html = StripTags($html); | ||
| 470 | |||
| 471 | return undef unless defined $html; | ||
| 472 | |||
| 473 | require HTML::TreeBuilder; | ||
| 474 | my $tree = HTML::TreeBuilder->new; | ||
| 475 | $tree->parse($html); | ||
| 476 | |||
| 477 | my @links; | ||
| 478 | |||
| 479 | foreach my $linkpair (@{$tree->extract_links('a')}) | ||
| 480 | { | ||
| 481 | # Extract the link from the HTML element. | ||
| 482 | my $elem = ${$linkpair}[1]; | ||
| 483 | my $link = $elem->as_HTML(); | ||
| 484 | chomp $link; | ||
| 485 | |||
| 486 | # Repair brain-dead & to & in URLs | ||
| 487 | $link =~ s! | ||
| 488 | # First look for an a, img, or area, followed later by an href or src | ||
| 489 | (<\s*(?:a|img|area)\b[^>]*(?:href|src)\s*=\s* | ||
| 490 | # Then an optional quote | ||
| 491 | ['"]?) | ||
| 492 | # Then the interesting part | ||
| 493 | ([^'"> ]+) | ||
| 494 | # Then another optional quote | ||
| 495 | (['"]? | ||
| 496 | # And the left-overs | ||
| 497 | [^>]*>) | ||
| 498 | ! | ||
| 499 | my $front = $1; | ||
| 500 | my $url = $2; | ||
| 501 | my $back = $3; | ||
| 502 | |||
| 503 | $url =~ s/\&/\&/g; | ||
| 504 | |||
| 505 | # Then construct the new link from the prefix and suffix | ||
| 506 | $_ = $front.$url.$back; | ||
| 507 | !segix; | ||
| 508 | |||
| 509 | # change relative tags to absolute | ||
| 510 | $link = &MakeLinksAbsolute($url,$link); | ||
| 511 | bless \$link,'Link'; | ||
| 512 | push @links, \$link; | ||
| 513 | } | ||
| 514 | |||
| 515 | if ($#links != -1) | ||
| 516 | { | ||
| 517 | return \@links; | ||
| 518 | } | ||
| 519 | else | ||
| 520 | { | ||
| 521 | return undef; | ||
| 522 | } | ||
| 523 | } | ||
| 524 | |||
| 525 | 1; |