From http://www.jwz.org/xscreensaver/xscreensaver-5.33.tar.gz
[xscreensaver] / hacks / webcollage
1 #!/usr/bin/perl -w
2 #
3 # webcollage, Copyright © 1999-2015 by Jamie Zawinski <jwz@jwz.org>
4 # This program decorates the screen with random images from the web.
5 # One satisfied customer described it as "a nonstop pop culture brainbath."
6 #
7 # Permission to use, copy, modify, distribute, and sell this software and its
8 # documentation for any purpose is hereby granted without fee, provided that
9 # the above copyright notice appear in all copies and that both that
10 # copyright notice and this permission notice appear in supporting
11 # documentation.  No representations are made about the suitability of this
12 # software for any purpose.  It is provided "as is" without express or
13 # implied warranty.
14
15
16 # To run this as a display mode with xscreensaver, add this to `programs':
17 #
18 #     webcollage --root
19 #     webcollage --root --filter 'vidwhacker --stdin --stdout'
20 #
21 #
22 # You can see this in action at http://www.jwz.org/webcollage/ --
23 # it auto-reloads about once a minute.  To make a page similar to
24 # that on your own system, do this:
25 #
26 #     webcollage --size '800x600' --imagemap $HOME/www/webcollage/index
27 #
28 #
29 # If you have the "driftnet" program installed, webcollage can display a
30 # collage of images sniffed off your local ethernet, instead of pulled out
31 # of search engines: in that way, your screensaver can display the images
32 # that your co-workers are downloading!
33 #
34 # Driftnet is available here: http://www.ex-parrot.com/~chris/driftnet/
35 # Use it like so:
36 #
37 #     webcollage --root --driftnet
38 #
39 # Driftnet is the Unix implementation of the MacOS "EtherPEG" program.
40
41
42 require 5;
43 use strict;
44
45 # We can't "use diagnostics" here, because that library malfunctions if
46 # you signal and catch alarms: it says "Uncaught exception from user code"
47 # and exits, even though I damned well AM catching it!
48 #use diagnostics;
49
50
51 require Time::Local;
52 require POSIX;
53 use Fcntl ':flock'; # import LOCK_* constants
54 use POSIX qw(strftime);
55 use LWP::UserAgent;
56 use bytes;
57
58
59 my $progname = $0; $progname =~ s@.*/@@g;
60 my ($version) = ('$Revision: 1.171 $' =~ m/\s(\d[.\d]+)\s/s);
61 my $copyright = "WebCollage $version, Copyright (c) 1999-2015" .
62     " Jamie Zawinski <jwz\@jwz.org>\n" .
63     "                  http://www.jwz.org/webcollage/\n";
64
65
66
67 my @search_methods = (
68                       # Google is rate-limiting us now, so this works ok from
69                       # a short-running screen saver, but not as a batch job.
70                       # I haven't found a workaround.
71                       #
72                         7, "googlephotos",  \&pick_from_google_image_photos,
73                         5, "googleimgs",    \&pick_from_google_images,
74                         5, "googlenums",    \&pick_from_google_image_numbers,
75
76                       # So let's try Bing instead. No rate limiting yet!
77                       #
78                         7, "bingphotos",    \&pick_from_bing_image_photos,
79                         6, "bingimgs",      \&pick_from_bing_images,
80                         6, "bingnums",      \&pick_from_bing_image_numbers,
81
82                        21, "flickr_recent", \&pick_from_flickr_recent,
83                        16, "flickr_random", \&pick_from_flickr_random,
84                        23, "instagram",     \&pick_from_instagram,
85                         4, "livejournal",   \&pick_from_livejournal_images,
86
87                      # No longer exists, as of Apr 2014
88                      #  4, "yahoorand",     \&pick_from_yahoo_random_link,
89
90                      # Twitter destroyed their whole API in 2013.
91                      #  0, "twitpic",       \&pick_from_twitpic_images,
92                      #  0, "twitter",       \&pick_from_twitter_images,
93
94                      # This is a cute way to search for a certain webcams.
95                      # Not included in default methods, since these images
96                      # aren't terribly interesting by themselves.
97                      # See also "SurveillanceSaver".
98                      #
99                         0, "securitycam",   \&pick_from_security_camera,
100
101                      # Nonfunctional as of June 2011.
102                      #  0, "altavista",     \&pick_from_alta_vista_random_link,
103
104                      # In Apr 2002, Google asked me to stop searching them.
105                      # I asked them to add a "random link" url.  They said
106                      # "that would be easy, we'll think about it" and then
107                      # never wrote back.  Booo Google!  Booooo!  So, screw
108                      # those turkeys, I've turned Google searching back on.
109                      # I'm sure they can take it.  (Jan 2005.)
110
111                      # Jan 2005: Yahoo fucked up their search form so that
112                      # it's no longer possible to do "or" searches on news
113                      # images, so we rarely get any hits there any more.
114                      # 
115                      #  0, "yahoonews",     \&pick_from_yahoo_news_text,
116
117                      # Dec 2004: the ircimages guy's server can't take the
118                      # heat, so he started banning the webcollage user agent.
119                      # I tried to convince him to add a lighter-weight page to
120                      # support webcollage better, but he doesn't care.
121                      #
122                      #  0, "ircimages",     \&pick_from_ircimages,
123
124                      # Dec 2002: Alta Vista has a new "random link" URL now.
125                      # They added it specifically to better support webcollage!
126                      # That was super cool of them.  This is how we used to do
127                      # it, before:
128                      #
129                      #  0, "avimages",      \&pick_from_alta_vista_images,
130                      #  0, "avtext",        \&pick_from_alta_vista_text,
131
132                      # This broke in 2004.  Eh, Lycos sucks anyway.
133                      #
134                      #  0, "lycos",         \&pick_from_lycos_text,
135
136                      # This broke in 2003, I think.  I suspect Hotbot is
137                      # actually the same search engine data as Lycos.
138                      #
139                      #  0, "hotbot",        \&pick_from_hotbot_text,
140                       );
141
142 # programs we can use to write to the root window (tried in ascending order.)
143 #
144 my @root_displayers = (
145   "xscreensaver-getimage -root -file",
146   "chbg       -once -xscreensaver -max_size 100",
147   "xv         -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
148   "           -rfg black -rbg black",
149   "xli        -quiet -onroot -center -border black",
150   "xloadimage -quiet -onroot -center -border black",
151
152 # this lame program wasn't built with vroot.h:
153 # "xsri       -scale -keep-aspect -center-horizontal -center-vertical",
154 );
155
156
157 # Some sites need cookies to work properly.   These are they.
158 #
159 my %cookies = (
160   "www.altavista.com"  =>  "AV_ALL=1",   # request uncensored searches
161   "web.altavista.com"  =>  "AV_ALL=1",
162
163                                          # log in as "cipherpunk"
164   "www.nytimes.com"    =>  'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
165                            'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
166                            '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
167
168   "ircimages.com"      =>  'disclaimer=1',
169 );
170
171
172 # If this is set, it's a helper program to use for pasting images together:
173 # this is a lot faster and more efficient than using PPM pipelines, which is
174 # what we do if this program doesn't exist.  (We check for "webcollage-helper"
175 # on $PATH at startup, and set this variable appropriately.)
176 #
177 my $webcollage_helper = undef;
178
179
180 # If we have the webcollage-helper program, then it will paste the images
181 # together with transparency!  0.0 is invisible, 1.0 is totally opaque.
182 #
183 my $opacity = 0.85;
184
185
186 # Some sites have  managed to poison the search engines.  These are they.
187 # (We auto-detect sites that have poisoned the search engines via excessive
188 # keywords or dictionary words,  but these are ones that slip through
189 # anyway.)
190 #
191 # This can contain full host names, or 2 or 3 component domains.
192 #
193 my %poisoners = (
194   "die.net"                 => 1,  # 'l33t h4ck3r d00dz.
195   "genforum.genealogy.com"  => 1,  # Cluttering avtext with human names.
196   "rootsweb.com"            => 1,  # Cluttering avtext with human names.
197   "akamai.net"              => 1,  # Lots of sites have their images on Akamai.
198   "akamaitech.net"          => 1,  # But those are pretty much all banners.
199                                    # Since Akamai is super-expensive, let's
200                                    # go out on a limb and assume that all of
201                                    # their customers are rich-and-boring.
202   "bartleby.com"            => 1,  # Dictionary, cluttering avtext.
203   "encyclopedia.com"        => 1,  # Dictionary, cluttering avtext.
204   "onlinedictionary.datasegment.com" => 1,  # Dictionary, cluttering avtext.
205   "hotlinkpics.com"         => 1,  # Porn site that has poisoned avimages
206                                    # (I don't see how they did it, though!)
207   "alwayshotels.com"        => 1,  # Poisoned Lycos pretty heavily.
208   "nextag.com"              => 1,  # Poisoned Alta Vista real good.
209   "ghettodriveby.com"       => 1,  # Poisoned Google Images.
210   "crosswordsolver.org"     => 1,  # Poisoned Google Images.
211   "xona.com"                => 1,  # Poisoned Google Images.
212   "freepatentsonline.com"   => 1,  # Poisoned Google Images.
213   "herbdatanz.com"          => 1,  # Poisoned Google Images.
214 );
215
216
217 # When verbosity is turned on, we warn about sites that we seem to be hitting
218 # a lot: usually this means some new poisoner has made it into the search
219 # engines.  But sometimes, the warning is just because that site has a lot
220 # of stuff on it.  So these are the sites that are immune to the "frequent
221 # site" diagnostic message.
222 #
223 my %warningless_sites = (
224   "home.earthlink.net"      => 1,
225   "www.angelfire.com"       => 1,
226   "members.aol.com"         => 1,
227   "img.photobucket.com"     => 1,
228   "pics.livejournal.com"    => 1,
229   "tinypic.com"             => 1,
230   "flickr.com"              => 1,
231   "staticflickr.com"        => 1,
232   "pbase.com"               => 1,
233   "blogger.com"             => 1,
234   "multiply.com"            => 1,
235   "wikimedia.org"           => 1,
236   "twitpic.com"             => 1,
237   "amazonaws.com"           => 1,
238   "blogspot.com"            => 1,
239   "photoshelter.com"        => 1,
240   "myspacecdn.com"          => 1,
241   "feedburner.com"          => 1,
242   "wikia.com"               => 1,
243   "ljplus.ru"               => 1,
244   "yandex.ru"               => 1,
245   "imgur.com"               => 1,
246   "yfrog.com"               => 1,
247   "cdninstagram.com"        => 1,
248
249   "yimg.com"                => 1,  # This is where dailynews.yahoo.com stores
250   "eimg.com"                => 1,  # its images, so pick_from_yahoo_news_text()
251                                    # hits this every time.
252
253   "images.quizfarm.com"     => 1,  # damn those LJ quizzes...
254   "images.quizilla.com"     => 1,
255   "images.quizdiva.net"     => 1,
256
257   "driftnet"                => 1,  # builtin...
258   "local-directory"         => 1,  # builtin...
259 );
260
261
262 # For decoding HTML-encoded character entities to URLs.
263 #
264 my %entity_table = (
265    "apos"   => '\'',
266    "quot"   => '"',    "amp"    => '&',    "lt"     => '<',
267    "gt"     => '>',    "nbsp"   => ' ',    "iexcl"  => '',
268    "cent"   => "\xA2", "pound"  => "\xA3", "curren" => "\xA4",
269    "yen"    => "\xA5", "brvbar" => "\xA6", "sect"   => "\xA7",
270    "uml"    => "\xA8", "copy"   => "\xA9", "ordf"   => "\xAA",
271    "laquo"  => "\xAB", "not"    => "\xAC", "shy"    => "\xAD",
272    "reg"    => "\xAE", "macr"   => "\xAF", "deg"    => "\xB0",
273    "plusmn" => "\xB1", "sup2"   => "\xB2", "sup3"   => "\xB3",
274    "acute"  => "\xB4", "micro"  => "\xB5", "para"   => "\xB6",
275    "middot" => "\xB7", "cedil"  => "\xB8", "sup1"   => "\xB9",
276    "ordm"   => "\xBA", "raquo"  => "\xBB", "frac14" => "\xBC",
277    "frac12" => "\xBD", "frac34" => "\xBE", "iquest" => "\xBF",
278    "Agrave" => "\xC0", "Aacute" => "\xC1", "Acirc"  => "\xC2",
279    "Atilde" => "\xC3", "Auml"   => "\xC4", "Aring"  => "\xC5",
280    "AElig"  => "\xC6", "Ccedil" => "\xC7", "Egrave" => "\xC8",
281    "Eacute" => "\xC9", "Ecirc"  => "\xCA", "Euml"   => "\xCB",
282    "Igrave" => "\xCC", "Iacute" => "\xCD", "Icirc"  => "\xCE",
283    "Iuml"   => "\xCF", "ETH"    => "\xD0", "Ntilde" => "\xD1",
284    "Ograve" => "\xD2", "Oacute" => "\xD3", "Ocirc"  => "\xD4",
285    "Otilde" => "\xD5", "Ouml"   => "\xD6", "times"  => "\xD7",
286    "Oslash" => "\xD8", "Ugrave" => "\xD9", "Uacute" => "\xDA",
287    "Ucirc"  => "\xDB", "Uuml"   => "\xDC", "Yacute" => "\xDD",
288    "THORN"  => "\xDE", "szlig"  => "\xDF", "agrave" => "\xE0",
289    "aacute" => "\xE1", "acirc"  => "\xE2", "atilde" => "\xE3",
290    "auml"   => "\xE4", "aring"  => "\xE5", "aelig"  => "\xE6",
291    "ccedil" => "\xE7", "egrave" => "\xE8", "eacute" => "\xE9",
292    "ecirc"  => "\xEA", "euml"   => "\xEB", "igrave" => "\xEC",
293    "iacute" => "\xED", "icirc"  => "\xEE", "iuml"   => "\xEF",
294    "eth"    => "\xF0", "ntilde" => "\xF1", "ograve" => "\xF2",
295    "oacute" => "\xF3", "ocirc"  => "\xF4", "otilde" => "\xF5",
296    "ouml"   => "\xF6", "divide" => "\xF7", "oslash" => "\xF8",
297    "ugrave" => "\xF9", "uacute" => "\xFA", "ucirc"  => "\xFB",
298    "uuml"   => "\xFC", "yacute" => "\xFD", "thorn"  => "\xFE",
299    "yuml"   => "\xFF",
300
301    # HTML 4 entities that do not have 1:1 Latin1 mappings.
302    "bull"  => "*",    "hellip"=> "...",  "prime" => "'",  "Prime" => "\"",
303    "frasl" => "/",    "trade" => "[tm]", "larr"  => "<-", "rarr"  => "->",
304    "harr"  => "<->",  "lArr"  => "<=",   "rArr"  => "=>", "hArr"  => "<=>",
305    "empty" => "\xD8", "minus" => "-",    "lowast"=> "*",  "sim"   => "~",
306    "cong"  => "=~",   "asymp" => "~",    "ne"    => "!=", "equiv" => "==",
307    "le"    => "<=",   "ge"    => ">=",   "lang"  => "<",  "rang"  => ">",
308    "loz"   => "<>",   "OElig" => "OE",   "oelig" => "oe", "Yuml"  => "Y",
309    "circ"  => "^",    "tilde" => "~",    "ensp"  => " ",  "emsp"  => " ",
310    "thinsp"=> " ",    "ndash" => "-",    "mdash" => "--", "lsquo" => "`",
311    "rsquo" => "'",    "sbquo" => "'",    "ldquo" => "\"", "rdquo" => "\"",
312    "bdquo" => "\"",   "lsaquo"=> "<",    "rsaquo"=> ">",
313 );
314
315
316 ##############################################################################
317 #
318 # Various global flags set by command line parameters, or computed
319 #
320 ##############################################################################
321
322
323 my $current_state = "???";      # for diagnostics
324 my $load_method;
325 my $last_search;
326 my $image_succeeded = -1;
327 my $suppress_audit = 0;
328
329 my $verbose_imgmap = 0;         # print out rectangles and URLs only (stdout)
330 my $verbose_warnings = 0;       # print out warnings when things go wrong
331 my $verbose_load = 0;           # diagnostics about loading of URLs
332 my $verbose_filter = 0;         # diagnostics about page selection/rejection
333 my $verbose_net = 0;            # diagnostics about network I/O
334 my $verbose_pbm = 0;            # diagnostics about PBM pipelines
335 my $verbose_http = 0;           # diagnostics about all HTTP activity
336 my $verbose_exec = 0;           # diagnostics about executing programs
337
338 my $report_performance_interval = 60 * 15;  # print some stats every 15 minutes
339
340 my $http_proxy = undef;
341 my $http_timeout = 20;
342 my $cvt_timeout = 10;
343
344 my $min_width = 50;
345 my $min_height = 50;
346 my $min_ratio = 1/5;
347
348 my $min_gif_area = (120 * 120);
349
350
351 my $no_output_p = 0;
352 my $urls_only_p = 0;
353 my $cocoa_p = 0;
354 my $imagemap_base = undef;
355
356 my @pids_to_kill = ();  # forked pids we should kill when we exit, if any.
357
358 my $driftnet_magic = 'driftnet';
359 my $driftnet_dir = undef;
360 my $default_driftnet_cmd = "driftnet -a -m 100";
361
362 my $local_magic = 'local-directory';
363 my $local_dir = undef;
364
365 my $wordlist;
366
367 my %rejected_urls;
368 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
369                       "arrhenius", "arteriole", "blanket", "brainchild",
370                       "burdensome", "carnival", "cherub", "chord", "clever",
371                       "dedicate", "dilogarithm", "dolan", "dryden",
372                       "eggplant");
373
374
375 ##############################################################################
376 #
377 # Retrieving URLs
378 #
379 ##############################################################################
380
381 # returns three values: the HTTP response line; the document headers;
382 # and the document body.
383 #
384 sub get_document_1($$$) {
385   my ($url, $referer, $timeout) = @_;
386
387   if (!defined($timeout)) { $timeout = $http_timeout; }
388   if ($timeout > $http_timeout) { $timeout = $http_timeout; }
389
390   my $user_agent = "$progname/$version";
391
392   if ($url =~ m@^https?://www\.altavista\.com/@s ||
393       $url =~ m@^https?://random\.yahoo\.com/@s  ||
394       $url =~ m@^https?://[^./]+\.google\.com/@s ||
395       $url =~ m@^https?://www\.livejournal\.com/@s) {
396     # block this, you turkeys.
397     $user_agent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)' .
398                   ' Gecko/20070914 Firefox/2.0.0.7';
399   }
400
401   my $ua = LWP::UserAgent->new ( agent => $user_agent,
402                                  keep_alive => 0,
403                                  env_proxy => 0,
404                                );
405   $ua->proxy ('http', $http_proxy) if $http_proxy;
406   $ua->default_header ('Referer' => $referer) if $referer;
407   $ua->default_header ('Accept' => '*/*');
408   $ua->timeout($timeout) if $timeout;
409
410   if (0) {
411     $ua->add_handler ("request_send",
412                       sub($$$) {
413                         my ($req, $ua, $h) = @_;
414                         print "\n>>[[\n"; $req->dump; print "\n]]\n";
415                         return;
416                       });
417     $ua->add_handler ("response_data",
418                       sub($$$$) {
419                         my ($req, $ua, $h, $data) = @_;
420                         #print "\n<<[[\n"; print $data; print "\n]]\n";
421                         return 1;
422                       });
423     $ua->add_handler ("request_done",
424                       sub($$$) {
425                         my ($req, $ua, $h) = @_;
426                         print "\n<<[[\n"; $req->dump; print "\n]]\n";
427                         return;
428                       });
429   }
430
431   if ($verbose_http) {
432     LOG (1, "  ==> GET $url");
433     LOG (1, "  ==> User-Agent: $user_agent");
434     LOG (1, "  ==> Referer: $referer") if $referer;
435   }
436
437   my $res = $ua->get ($url);
438
439   my $http = ($res ? $res->status_line : '') || '';
440   my $head = ($res ? $res->headers()->as_string : '') || '';
441   my $body = ($res && $res->is_success ? $res->decoded_content : '') || '';
442
443   LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
444
445   $head =~ s/\r\n/\n/gs;
446   $head =~ s/\r/\n/gs;
447   if ($verbose_http) {
448     foreach (split (/\n/, $head)) {
449       LOG ($verbose_http, "  <== $_");
450     }
451   }
452
453   my @L = split(/\r\n|\r|\n/, $body);
454   my $lines = @L;
455   LOG ($verbose_http,
456        "  <== [ body ]: $lines lines, " . length($body) . " bytes");
457
458   if (!$http) {
459     LOG (($verbose_net || $verbose_load), "null response: $url");
460     return ();
461   }
462
463   return ( $http, $head, $body );
464 }
465
466
467 # returns two values: the document headers; and the document body.
468 # if the given URL did a redirect, returns the redirected-to document.
469 #
470 sub get_document($$;$) {
471   my ($url, $referer, $timeout) = @_;
472   my $start = time;
473
474   if (defined($referer) && $referer eq $driftnet_magic) {
475     return get_driftnet_file ($url);
476   }
477
478   if (defined($referer) && $referer eq $local_magic) {
479     return get_local_file ($url);
480   }
481
482   my $orig_url = $url;
483   my $loop_count = 0;
484   my $max_loop_count = 4;
485
486   do {
487     if (defined($timeout) && $timeout <= 0) {
488       LOG (($verbose_net || $verbose_load), "timed out for $url");
489       $suppress_audit = 1;
490       return ();
491     }
492
493     my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
494
495     if (defined ($timeout)) {
496       my $now = time;
497       my $elapsed = $now - $start;
498       $timeout -= $elapsed;
499       $start = $now;
500     }
501
502     return () unless $http; # error message already printed
503
504     $http =~ s/[\r\n]+$//s;
505
506     if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
507       $_ = $head;
508
509       my ( $location ) = m@^location:[ \t]*(.*)$@im;
510       if ( $location ) {
511         $location =~ s/[\r\n]$//;
512
513         LOG ($verbose_net, "redirect from $url to $location");
514         $referer = $url;
515         $url = $location;
516
517         if ($url =~ m@^/@) {
518           $referer =~ m@^(https?://[^/]+)@i;
519           $url = $1 . $url;
520         } elsif (! ($url =~ m@^[a-z]+:@i)) {
521           $_ = $referer;
522           s@[^/]+$@@g if m@^https?://[^/]+/@i;
523           $_ .= "/" if m@^https?://[^/]+$@i;
524           $url = $_ . $url;
525         }
526
527       } else {
528         LOG ($verbose_net, "no Location with \"$http\"");
529         return ( $url, $body );
530       }
531
532       if ($loop_count++ > $max_loop_count) {
533         LOG ($verbose_net,
534              "too many redirects ($max_loop_count) from $orig_url");
535         $body = undef;
536         return ();
537       }
538
539     } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
540
541       LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
542
543       # http errors -- return nothing.
544       $body = undef;
545       return ();
546
547     } elsif (!$body) {
548
549       LOG (($verbose_net || $verbose_load), "document contains no data: $url");
550       return ();
551
552     } else {
553
554       # ok!
555       return ( $url, $body );
556     }
557
558   } while (1);
559 }
560
561 # If we already have a cookie defined for this site, and the site is trying
562 # to overwrite that very same cookie, let it do so.  This is because nytimes
563 # expires its cookies - it lets you upgrade to a new cookie without logging
564 # in again, but you have to present the old cookie to get the new cookie.
565 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
566 #
567 sub set_cookie($$) {
568   my ($host, $cookie) = @_;
569   my $oc = $cookies{$host};
570   return unless $oc;
571   $_ = $oc;
572   my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
573   $_ = $cookie;
574   my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
575
576   if ($oc_name eq $nc_name &&
577       $oc_value ne $nc_value) {
578     $cookies{$host} = $cookie;
579     LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
580   }
581 }
582
583
584 ############################################################################
585 #
586 # Extracting image URLs from HTML
587 #
588 ############################################################################
589
590 # given a URL and the body text at that URL, selects and returns a random
591 # image from it.  returns () if no suitable images found.
592 #
593 sub pick_image_from_body($$) {
594   my ($url, $body) = @_;
595
596   my $base = $url;
597   $_ = $url;
598
599   # if there's at least one slash after the host, take off the last
600   # pathname component
601   if ( m@^https?://[^/]+/@io ) {
602     $base =~ s@[^/]+$@@go;
603   }
604
605   # if there are no slashes after the host at all, put one on the end.
606   if ( m@^https?://[^/]+$@io ) {
607     $base .= "/";
608   }
609
610   $_ = $body;
611
612   # strip out newlines, compress whitespace
613   s/[\r\n\t ]+/ /go;
614
615   # nuke comments
616   s/<!--.*?-->//go;
617
618
619   # There are certain web sites that list huge numbers of dictionary
620   # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
621   # Porn sites tend not to be reputable!)
622   #
623   # I do not want webcollage to filter on content: I want it to select
624   # randomly from the set of images on the web.  All the logic here for
625   # rejecting some images is really a set of heuristics for rejecting
626   # images that are not really images: for rejecting *text* that is in
627   # GIF/JPEG/PNG form.  I don't want text, I want pictures, and I want
628   # the content of the pictures to be randomly selected from among all
629   # the available content.
630   #
631   # So, filtering out "dirty" pictures by looking for "dirty" keywords
632   # would be wrong: dirty pictures exist, like it or not, so webcollage
633   # should be able to select them.
634   #
635   # However, picking a random URL is a hard thing to do.  The mechanism I'm
636   # using is to search for a selection of random words.  This is not
637   # perfect, but works ok most of the time.  The way it breaks down is when
638   # some URLs get precedence because their pages list *every word* as
639   # related -- those URLs come up more often than others.
640   #
641   # So, after we've retrieved a URL, if it has too many keywords, reject
642   # it.  We reject it not on the basis of what those keywords are, but on
643   # the basis that by having so many, the page has gotten an unfair
644   # advantage against our randomizer.
645   #
646   my $trip_count = 0;
647   foreach my $trip (@tripwire_words) {
648     $trip_count++ if m/$trip/i;
649   }
650
651   if ($trip_count >= $#tripwire_words - 2) {
652     LOG (($verbose_filter || $verbose_load),
653          "there is probably a dictionary in \"$url\": rejecting.");
654     $rejected_urls{$url} = -1;
655     $body = undef;
656     $_ = undef;
657     return ();
658   }
659
660
661   my @urls;
662   my %unique_urls;
663
664   foreach (split(/ *</)) {
665     if ( m/^meta.*["']keywords["']/i ) {
666
667       # Likewise, reject any web pages that have a KEYWORDS meta tag
668       # that is too long.
669       #
670       my $L = length($_);
671       if ($L > 1000) {
672         LOG (($verbose_filter || $verbose_load),
673              "excessive keywords ($L bytes) in $url: rejecting.");
674         $rejected_urls{$url} = $L;
675         $body = undef;
676         $_ = undef;
677         return ();
678       } else {
679         LOG ($verbose_filter, "  keywords ($L bytes) in $url (ok)");
680       }
681
682     } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
683              m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
684                  ["']? (image_src|og:image) ["']? /six) {
685
686       my $was_inline = (lc($1) eq 'img');
687       my $was_meta   = (lc($1) eq 'link' || lc($1) eq 'meta');
688       my $link = $3;
689
690       # For <link rel="image_src" href="...">
691       # and <meta property="og:image" content="...">
692       #
693       if ($was_meta) {
694         next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
695         $link = $2;
696       }
697
698       my ( $width )  = m/width ?=[ \"]*(\d+)/oi;
699       my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
700       $_ = $link;
701
702       if ( m@^/@o ) {
703         my $site;
704         ( $site = $base ) =~ s@^(https?://[^/]*).*@$1@gio;
705         $_ = "$site$link";
706       } elsif ( ! m@^[^/:?]+:@ ) {
707         $_ = "$base$link";
708         s@/\./@/@g;
709         1 while (s@/[^/]+/\.\./@/@g);
710       }
711
712       # skip non-http
713       if ( ! m@^https?://@io ) {
714         next;
715       }
716
717       # skip non-image
718       if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
719         next;
720       }
721
722       # skip really short or really narrow images
723       if ( $width && $width < $min_width) {
724         if (!$height) { $height = "?"; }
725         LOG ($verbose_filter, "  skip narrow image $_ (${width}x$height)");
726         next;
727       }
728
729       if ( $height && $height < $min_height) {
730         if (!$width) { $width = "?"; }
731         LOG ($verbose_filter, "  skip short image $_ (${width}x$height)");
732         next;
733       }
734
735       # skip images with ratios that make them look like banners.
736       if ($min_ratio && $width && $height &&
737           ($width * $min_ratio ) > $height) {
738         if (!$height) { $height = "?"; }
739         LOG ($verbose_filter, "  skip bad ratio $_ (${width}x$height)");
740         next;
741       }
742
743       # skip GIFs with a small number of pixels -- those usually suck.
744       if ($width && $height &&
745           m/\.gif$/io &&
746           ($width * $height) < $min_gif_area) {
747         LOG ($verbose_filter, "  skip small GIF $_ (${width}x$height)");
748         next;
749       }
750       
751       # skip images with a URL that indicates a Yahoo thumbnail.
752       if (m@\.yimg\.com/.*/t/@) {
753         if (!$width)  { $width  = "?"; }
754         if (!$height) { $height = "?"; }
755         LOG ($verbose_filter, "  skip yahoo thumb $_ (${width}x$height)");
756         next;
757       }
758
759       my $url = $_;
760
761       if ($unique_urls{$url}) {
762         LOG ($verbose_filter, "  skip duplicate image $_");
763         next;
764       }
765
766       LOG ($verbose_filter,
767            "  image $url" .
768            ($width && $height ? " (${width}x${height})" : "") .
769            ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
770
771
772       my $weight = 1;
773
774       if ($was_meta) {
775         $weight = 20;    # meta tag images are far preferable to inline images.
776       } else {
777         if ($url !~ m@[.](gif|png)$@io ) {
778           $weight += 2;  # JPEGs are preferable to GIFs and PNGs.
779         }
780         if (! $was_inline) {
781           $weight += 4;  # pointers to images are preferable to inlined images.
782         }
783       }
784
785       $unique_urls{$url}++;
786       for (my $i = 0; $i < $weight; $i++) {
787         $urls[++$#urls] = $url;
788       }
789     }
790   }
791
792   my $fsp = ($body =~ m@<frameset@i);
793
794   $_ = undef;
795   $body = undef;
796
797   @urls = depoison (@urls);
798
799   if ( $#urls < 0 ) {
800     LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
801     return ();
802   }
803
804   # pick a random element of the table
805   my $i = int(rand($#urls+1));
806   $url = $urls[$i];
807
808   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
809
810   return $url;
811 }
812
813
814 # Given a URL and the RSS feed from that URL, pick a random image from
815 # the feed.  This is a lot simpler than extracting images out of a page:
816 # we already know we have reasonable images, so we just pick one.
817 # Returns: the real URL of the page (preferably not the RSS version),
818 # and the image.
819
820 sub pick_image_from_rss($$) {
821   my ( $url, $body ) = @_;
822   my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
823
824   my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
825   $base = $url unless $base;
826
827   # pick a random element of the table
828   if (@suitable) {
829     my $i = int(rand(scalar @suitable));
830     my $url = $suitable[$i];
831     LOG ($verbose_load, "picked image " .($i+1) . "/" . 
832                         ($#suitable+1) . ": $url");
833     return ($base, $url);
834   }
835   return;
836 }
837
838 \f
839 ############################################################################
840 #
841 # Subroutines for getting pages and images out of search engines
842 #
843 ############################################################################
844
845
846 sub pick_dictionary() {
847   my @dicts = ("/usr/dict/words",
848                "/usr/share/dict/words",
849                "/usr/share/lib/dict/words",
850                "/usr/share/dict/cracklib-small",
851                "/usr/share/dict/cracklib-words"
852                );
853   foreach my $f (@dicts) {
854     if (-f $f) {
855       $wordlist = $f;
856       last;
857     }
858   }
859   error ("$dicts[0] does not exist") unless defined($wordlist);
860 }
861
862 # returns a random word from the dictionary
863 #
864 sub random_word() {
865
866   return undef unless open (my $in, '<', $wordlist);
867
868   my $size = (stat($in))[7];
869   my $word = undef;
870   my $count = 0;
871
872   while (1) {
873     error ("looping ($count) while reading $wordlist")
874       if (++$count > 100);
875
876     my $pos = int (rand ($size));
877     if (seek ($in, $pos, 0)) {
878       $word = <$in>;   # toss partial line
879       $word = <$in>;   # keep next line
880     }
881
882     next unless ($word);
883     next if ($word =~ m/^[-\']/);
884
885     $word = lc($word);
886     $word =~ s/^.*-//s;
887     $word =~ s/^[^a-z]+//s;
888     $word =~ s/[^a-z]+$//s;
889     $word =~ s/\'s$//s;
890     $word =~ s/ys$/y/s;
891     $word =~ s/ally$//s;
892     $word =~ s/ly$//s;
893     $word =~ s/ies$/y/s;
894     $word =~ s/ally$/al/s;
895     $word =~ s/izes$/ize/s;
896     $word =~ s/esses$/ess/s;
897     $word =~ s/(.{5})ing$/$1/s;
898
899     next if (length ($word) > 14);
900     last if ($word);
901   }
902
903   close ($in);
904
905   if ( $word =~ s/\s/\+/gs ) {  # convert intra-word spaces to "+".
906     $word = "\%22$word\%22";    # And put quotes (%22) around it.
907   }
908
909   return $word;
910 }
911
912
913 sub random_words($) {
914   my ($sep) = @_;
915   return (random_word() . $sep .
916           random_word() . $sep .
917           random_word() . $sep .
918           random_word() . $sep .
919           random_word());
920 }
921
922
923 sub url_quote($) {
924   my ($s) = @_;
925   $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
926   return $s;
927 }
928
929 sub url_unquote($) {
930   my ($s) = @_;
931   $s =~ s/[+]/ /g;
932   $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
933   return $s;
934 }
935
936 sub html_quote($) {
937   my ($s) = @_;
938   $s =~ s/&/&amp;/gi;
939   $s =~ s/</&lt;/gi;
940   $s =~ s/>/&gt;/gi;
941   $s =~ s/\"/&quot;/gi;
942   return $s;
943 }
944
945 sub html_unquote($) {
946   my ($s) = @_;
947   $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi;  # e.g., &apos;
948   $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi;                    # e.g., &#39;
949   return $s;
950 }
951
952
953 # Loads the given URL (a search on some search engine) and returns:
954 # - the total number of hits the search engine claimed it had;
955 # - a list of URLs from the page that the search engine returned;
956 # Note that this list contains all kinds of internal search engine
957 # junk URLs too -- caller must prune them.
958 #
959 sub pick_from_search_engine($$$) {
960   my ( $timeout, $search_url, $words ) = @_;
961
962   $_ = $words;
963   s/%20/ /g;
964
965   print STDERR "\n\n" if ($verbose_load);
966
967   LOG ($verbose_load, "words: $_");
968   LOG ($verbose_load, "URL: $search_url");
969
970   $last_search = $search_url;   # for warnings
971
972   my $start = time;
973   my ( $base, $body ) = get_document ($search_url, undef, $timeout);
974   if (defined ($timeout)) {
975     $timeout -= (time - $start);
976     if ($timeout <= 0) {
977       $body = undef;
978       LOG (($verbose_net || $verbose_load),
979            "timed out (late) for $search_url");
980       $suppress_audit = 1;
981       return ();
982     }
983   }
984
985   return () if (! $body);
986
987
988   my @subpages;
989
990   if ($body =~ m/^\{\"/s) {                     # Google AJAX JSON response.
991
992     my @chunks = split (/"GsearchResultClass"/, $body);
993     shift @chunks;
994     my $body2 = '';
995     my $n = 1;
996     foreach (@chunks) {
997       my ($img) = m/"unescapedUrl":"(.*?)"/si;
998       my ($url) = m/"originalContextUrl":"(.*?)"/si;
999       next unless ($img && $url);
1000       $url = ("/imgres" .
1001               "?imgurl="    . url_quote($img) .
1002               "&imgrefurl=" . url_quote($url) .
1003               "&...");
1004       $body2 .= "<A HREF=\"" . html_quote($url) . "\">$n</A>\n";
1005       $n++;
1006     }
1007     $body = $body2 if $body2;
1008   }
1009
1010   my $search_count = "?";
1011   if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
1012     $search_count = $3;
1013   } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*)&nbsp;@i) {
1014     $search_count = $1;
1015   } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
1016     $search_count = $1;
1017   } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1018     $search_count = $1;
1019   } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1020     $search_count = $1;
1021   } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1022     $search_count = $1;
1023   } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1024     $search_count = $1;
1025   } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1026     $search_count = $1;
1027   } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1028     $search_count = $1;    # lycos
1029   } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1030     $search_count = $1;                          # hotbot
1031   } elsif ($body =~ m@no photos were found containing@i) { # avimages
1032     $search_count = "0";
1033   } elsif ($body =~ m@found no document matching@i) { # avtext
1034     $search_count = "0";
1035   }
1036   1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1037
1038 #  if ($search_count eq "?" || $search_count eq "0") {
1039 #    my $file = "/tmp/wc.html";
1040 #    open (my $out, '>', $file) || error ("writing $file: $!");
1041 #    print $out $body;
1042 #    close $out;
1043 #    print STDERR  blurb() . "###### wrote $file\n";
1044 #  }
1045
1046
1047   my $length = length($body);
1048   my $href_count = 0;
1049
1050   $_ = $body;
1051
1052   s/[\r\n\t ]+/ /g;
1053
1054
1055   s/(<A )/\n$1/gi;
1056   foreach (split(/\n/)) {
1057     $href_count++;
1058     my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1059     next unless $u;
1060
1061     if (m/\bm="{(.*?)}"/s) {            # Bing info is inside JSON crud
1062       my $json = html_unquote($1);
1063       my ($href) = ($json =~ m/\bsurl:"(.*?)"/s);
1064       my ($img)  = ($json =~ m/\bimgurl:"(.*?)"/s);
1065       $u = "$img\t$href" if ($img && $href);
1066
1067     } elsif ($u =~ m/^\"([^\"]*)\"/) { $u = $1   # quoted string
1068     } elsif ($u =~ m/^([^\s]*)\s/) { $u = $1;    # or token
1069     }
1070
1071     if ( $rejected_urls{$u} ) {
1072       LOG ($verbose_filter, "  pre-rejecting candidate: $u");
1073       next;
1074     }
1075
1076     LOG ($verbose_http, "    HREF: $u");
1077
1078     $subpages[++$#subpages] = $u;
1079   }
1080
1081   if ( $#subpages < 0 ) {
1082     LOG ($verbose_filter,
1083          "found nothing on $base ($length bytes, $href_count links).");
1084     return ();
1085   }
1086
1087   LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1088
1089   return ($search_count, @subpages);
1090 }
1091
1092
1093 sub depoison(@) {
1094   my (@urls) = @_;
1095   my @urls2 = ();
1096   foreach (@urls) {
1097     my ($h) = m@^https?://([^/: \t\r\n]+)@i;
1098
1099     next unless defined($h);
1100
1101     if ($poisoners{$h}) {
1102       LOG (($verbose_filter), "  rejecting poisoner: $_");
1103       next;
1104     }
1105     if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1106         $poisoners{$1}) {
1107       LOG (($verbose_filter), "  rejecting poisoner: $_");
1108       next;
1109     }
1110     if ($h =~ m@([^.]+\.[^.]+)$@ &&
1111         $poisoners{$1}) {
1112       LOG (($verbose_filter), "  rejecting poisoner: $_");
1113       next;
1114     }
1115
1116     push @urls2, $_;
1117   }
1118   return @urls2;
1119 }
1120
1121
1122 # given a list of URLs, picks one at random; loads it; and returns a
1123 # random image from it.
1124 # returns the url of the page loaded; the url of the image chosen.
1125 #
1126 sub pick_image_from_pages($$$$@) {
1127   my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1128
1129   $total_hit_count = "?" unless defined($total_hit_count);
1130
1131   @pages = depoison (@pages);
1132   LOG ($verbose_load,
1133        "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1134        " ($total_hit_count total)");
1135
1136   return () if ($#pages < 0);
1137
1138   my $i = int(rand($#pages+1));
1139   my $page = $pages[$i];
1140
1141   LOG ($verbose_load, "picked page $page");
1142
1143   $suppress_audit = 1;
1144
1145   my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1146
1147   if (!$base2 || !$body2) {
1148     $body2 = undef;
1149     return ();
1150   }
1151
1152   my $img = pick_image_from_body ($base2, $body2);
1153   $body2 = undef;
1154
1155   if ($img) {
1156     return ($base2, $img);
1157   } else {
1158     return ();
1159   }
1160 }
1161
1162 \f
1163 #############################################################################
1164 ##
1165 ## Pick images from random pages returned by the Yahoo Random Link
1166 ##
1167 #############################################################################
1168 #
1169 ## yahoorand
1170 #my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1171 #
1172 #
1173 # Picks a random page; picks a random image on that page;
1174 # returns two URLs: the page containing the image, and the image.
1175 # Returns () if nothing found this time.
1176 #
1177 #sub pick_from_yahoo_random_link($) {
1178 #  my ($timeout) = @_;
1179 #
1180 #  print STDERR "\n\n" if ($verbose_load);
1181 #  LOG ($verbose_load, "URL: $yahoo_random_link");
1182 #
1183 #  $last_search = $yahoo_random_link;   # for warnings
1184 #
1185 #  $suppress_audit = 1;
1186 #
1187 #  my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1188 #  if (!$base || !$body) {
1189 #    $body = undef;
1190 #    return;
1191 #  }
1192 #
1193 #  LOG ($verbose_load, "redirected to: $base");
1194 #
1195 #  my $img = pick_image_from_body ($base, $body);
1196 #  $body = undef;
1197 #
1198 #  if ($img) {
1199 #    return ($base, $img);
1200 #  } else {
1201 #    return ();
1202 #  }
1203 #}
1204
1205 \f
1206 ############################################################################
1207 #
1208 # Pick images from random pages returned by the Alta Vista Random Link
1209 # Note: this seems to have gotten a *lot* less random lately (2007).
1210 #
1211 ############################################################################
1212
1213 # altavista
1214 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1215
1216
1217 # Picks a random page; picks a random image on that page;
1218 # returns two URLs: the page containing the image, and the image.
1219 # Returns () if nothing found this time.
1220 #
1221 sub pick_from_alta_vista_random_link($) {
1222   my ($timeout) = @_;
1223
1224   print STDERR "\n\n" if ($verbose_load);
1225   LOG ($verbose_load, "URL: $alta_vista_random_link");
1226
1227   $last_search = $alta_vista_random_link;   # for warnings
1228
1229   $suppress_audit = 1;
1230
1231   my ( $base, $body ) = get_document ($alta_vista_random_link,
1232                                       undef, $timeout);
1233   if (!$base || !$body) {
1234     $body = undef;
1235     return;
1236   }
1237
1238   LOG ($verbose_load, "redirected to: $base");
1239
1240   my $img = pick_image_from_body ($base, $body);
1241   $body = undef;
1242
1243   if ($img) {
1244     return ($base, $img);
1245   } else {
1246     return ();
1247   }
1248 }
1249
1250 \f
1251 ############################################################################
1252 #
1253 # Pick images by feeding random words into Alta Vista Image Search
1254 #
1255 ############################################################################
1256
1257
1258 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1259                             "?ipht=1" .       # photos
1260                             "&igrph=1" .      # graphics
1261                             "&iclr=1" .       # color
1262                             "&ibw=1" .        # b&w
1263                             "&micat=1" .      # no partner sites
1264                             "&sc=on" .        # "site collapse"
1265                             "&q=";
1266
1267 # avimages
1268 sub pick_from_alta_vista_images($) {
1269   my ($timeout) = @_;
1270
1271   my $words = random_word();
1272   my $page = (int(rand(9)) + 1);
1273   my $search_url = $alta_vista_images_url . $words;
1274
1275   if ($page > 1) {
1276     $search_url .= "&pgno=" . $page;            # page number
1277     $search_url .= "&stq=" . (($page-1) * 12);  # first hit result on page
1278   }
1279
1280   my ($search_hit_count, @subpages) =
1281     pick_from_search_engine ($timeout, $search_url, $words);
1282
1283   my @candidates = ();
1284   foreach my $u (@subpages) {
1285
1286     # avimages is encoding their URLs now.
1287     next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1288     $u = url_unquote($u);
1289
1290     next unless ($u =~ m@^https?://@i);    #  skip non-HTTP or relative URLs
1291     next if ($u =~ m@[/.]altavista\.com\b@i);     # skip altavista builtins
1292     next if ($u =~ m@[/.]yahoo\.com\b@i);         # yahoo and av in cahoots?
1293     next if ($u =~ m@[/.]doubleclick\.net\b@i);   # you cretins
1294     next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1295
1296     next if ($u =~ m@[/.]viewimages\.com\b@i);    # stacked deck
1297     next if ($u =~ m@[/.]gettyimages\.com\b@i);
1298
1299     LOG ($verbose_filter, "  candidate: $u");
1300     push @candidates, $u;
1301   }
1302
1303   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1304                                 $timeout, @candidates);
1305 }
1306
1307
1308 \f
1309 ############################################################################
1310 #
1311 # Pick images from Aptix security cameras
1312 # Cribbed liberally from google image search code.
1313 # By Jason Sullivan <jasonsul@us.ibm.com>
1314 #
1315 ############################################################################
1316
1317 my $aptix_images_url = ("http://www.google.com/search" .
1318                         "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1319
1320 # securitycam
1321 sub pick_from_security_camera($) {
1322   my ($timeout) = @_;
1323
1324   my $page = (int(rand(9)) + 1);
1325   my $num = 20;                                 # 20 images per page
1326   my $search_url = $aptix_images_url;
1327
1328   if ($page > 1) {
1329     $search_url .= "&start=" . $page*$num;      # page number
1330     $search_url .= "&num="   . $num;            #images per page
1331   }
1332
1333   my ($search_hit_count, @subpages) =
1334     pick_from_search_engine ($timeout, $search_url, '');
1335
1336   my @candidates = ();
1337   my %referers;
1338   foreach my $u (@subpages) {
1339     next if ($u =~ m@[/.]google\.com\b@i);        # skip google builtins (most links)
1340     next unless ($u =~ m@jpg/image.jpg\?r=@i);    #  All pics contain this
1341
1342     LOG ($verbose_filter, "  candidate: $u");
1343     push @candidates, $u;
1344     $referers{$u} = $u;
1345     }
1346
1347   @candidates = depoison (@candidates);
1348   return () if ($#candidates < 0);
1349   my $i = int(rand($#candidates+1));
1350   my $img = $candidates[$i];
1351   my $ref = $referers{$img};
1352
1353   LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1354   return ($ref, $img);
1355 }
1356
1357 \f
1358 ############################################################################
1359 #
1360 # Pick images by feeding random words into Google Image Search.
1361 # By Charles Gales <gales@us.ibm.com>
1362 #
1363 ############################################################################
1364
1365
1366 my $google_images_url =     "http://ajax.googleapis.com/ajax/services/" .
1367                             "search/images" .
1368                             "?v=1.0" .
1369                             "&rsz=large" .
1370                             "&q=";
1371
1372 # googleimgs
1373 sub pick_from_google_images($;$$) {
1374   my ($timeout, $words, $max_page) = @_;
1375
1376   if (!defined($words)) {
1377     $words = random_word();   # only one word for Google
1378   }
1379
1380   my $off = int(rand(40));
1381   my $search_url = $google_images_url . $words . "&start=" . $off;
1382
1383   my ($search_hit_count, @subpages) =
1384     pick_from_search_engine ($timeout, $search_url, $words);
1385
1386   my @candidates = ();
1387   my %referers;
1388   foreach my $u (@subpages) {
1389     next unless ($u =~ m@imgres\?imgurl@i);    #  All pics start with this
1390     next if ($u =~ m@[/.]google\.com\b@i);     # skip google builtins
1391
1392     $u = html_unquote($u);
1393     if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1394       my $ref = $2;
1395       my $img = $1;
1396       $ref = url_decode($ref);
1397       $img = url_decode($img);
1398
1399       $img = "http://$img" unless ($img =~ m/^https?:/i);
1400
1401       LOG ($verbose_filter, "  candidate: $ref");
1402       push @candidates, $img;
1403       $referers{$img} = $ref;
1404     }
1405   }
1406
1407   @candidates = depoison (@candidates);
1408   return () if ($#candidates < 0);
1409   my $i = int(rand($#candidates+1));
1410   my $img = $candidates[$i];
1411   my $ref = $referers{$img};
1412
1413   LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1414   return ($ref, $img);
1415 }
1416
1417
1418 \f
1419 ############################################################################
1420 #
1421 # Pick images by feeding random numbers into Google Image Search.
1422 # By jwz, suggested by Ian O'Donnell.
1423 #
1424 ############################################################################
1425
1426
1427 # googlenums
1428 sub pick_from_google_image_numbers($) {
1429   my ($timeout) = @_;
1430
1431   my $max = 9999;
1432   my $number = int(rand($max));
1433
1434   $number = sprintf("%04d", $number)
1435     if (rand() < 0.3);
1436
1437   pick_from_google_images ($timeout, "$number");
1438 }
1439
1440
1441 \f
1442 ############################################################################
1443 #
1444 # Pick images by feeding random digital camera file names into 
1445 # Google Image Search.
1446 # By jwz, inspired by the excellent Random Personal Picture Finder
1447 # at http://www.diddly.com/random/
1448 #
1449 ############################################################################
1450
1451 my @photomakers = (
1452   #
1453   # Common digital camera file name formats, as described at
1454   # http://www.diddly.com/random/about.html
1455   #
1456   sub { sprintf ("dcp%05d.jpg",  int(rand(4000))); },   # Kodak
1457   sub { sprintf ("dsc%05d.jpg",  int(rand(4000))); },   # Nikon
1458   sub { sprintf ("dscn%04d.jpg", int(rand(4000))); },   # Nikon
1459   sub { sprintf ("mvc-%03d.jpg", int(rand(999)));  },   # Sony Mavica
1460   sub { sprintf ("mvc%05d.jpg",  int(rand(9999))); },   # Sony Mavica
1461   sub { sprintf ("P101%04d.jpg", int(rand(9999))); },   # Olympus w/ date=101
1462   sub { sprintf ("P%x%02d%04d.jpg",                     # Olympus
1463                  int(rand(0xC)), int(rand(30))+1,
1464                  rand(9999)); },
1465   sub { sprintf ("IMG_%03d.jpg",  int(rand(999))); },   # ?
1466   sub { sprintf ("IMAG%04d.jpg",  int(rand(9999))); },  # RCA and Samsung
1467   sub { my $n = int(rand(9999));                        # Canon
1468           sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1469   sub { my $n = int(rand(9999));                        # Canon
1470           sprintf ("1%02d-%04d_IMG.jpg",
1471                    int($n/100), $n); },
1472   sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); },   # Canon
1473   sub { sprintf ("dscf%04d.jpg", int(rand(9999))); },   # Fuji Finepix
1474   sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); },   # Toshiba PDR
1475   sub { sprintf ("IM%06d.jpg", int(rand(9999))); },     # HP Photosmart
1476   sub { sprintf ("EX%06d.jpg", int(rand(9999))); },     # HP Photosmart
1477 #  sub { my $n = int(rand(3));                          # Kodak DC-40,50,120
1478 #        sprintf ("DC%04d%s.jpg", int(rand(9999)),
1479 #                 $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1480   sub { sprintf ("pict%04d.jpg", int(rand(9999))); },   # Minolta Dimage
1481   sub { sprintf ("P%07d.jpg", int(rand(9999))); },      # Kodak DC290
1482 #  sub { sprintf ("%02d%02d%04d.jpg",                   # Casio QV3000, QV4000
1483 #                 int(rand(12))+1, int(rand(31))+1,
1484 #                 int(rand(999))); },
1485 #  sub { sprintf ("%02d%x%02d%04d.jpg",                 # Casio QV7000
1486 #                 int(rand(6)), # year
1487 #                 int(rand(12))+1, int(rand(31))+1,
1488 #                 int(rand(999))); },
1489   sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); },   # Pentax Optio S
1490   sub { sprintf ("PANA%04d.jpg", int(rand(9999))); },   # Panasonic vid still
1491   sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); },   # HP Photosmart
1492   sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); },   # ?
1493  );
1494
1495
1496 # googlephotos
1497 sub pick_from_google_image_photos($) {
1498   my ($timeout) = @_;
1499
1500   my $i = int(rand($#photomakers + 1));
1501   my $fn = $photomakers[$i];
1502   my $file = &$fn;
1503   #$file .= "%20filetype:jpg";
1504
1505   pick_from_google_images ($timeout, $file);
1506 }
1507
1508 \f
1509 ############################################################################
1510 #
1511 # Pick images by feeding random words into Google Image Search.
1512 # By the way: fuck Microsoft.
1513 #
1514 ############################################################################
1515
1516 my $bing_images_url =   "http://www.bing.com/images/async?q=";
1517
1518
1519 # bingimgs
1520 sub pick_from_bing_images($;$$) {
1521   my ($timeout, $words, $max_page) = @_;
1522
1523   if (!defined($words)) {
1524     $words = random_word();   # only one word for Bing
1525   }
1526
1527   my $off = int(rand(300));
1528   my $search_url = $bing_images_url . $words . "&first=" . $off;
1529
1530   my ($search_hit_count, @subpages) =
1531     pick_from_search_engine ($timeout, $search_url, $words);
1532
1533   my @candidates = ();
1534   my %referers;
1535   foreach my $u (@subpages) {
1536     my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1537     next unless $img;
1538     LOG ($verbose_filter, "  candidate: $ref");
1539     push @candidates, $img;
1540     $referers{$img} = $ref;
1541   }
1542
1543   @candidates = depoison (@candidates);
1544   return () if ($#candidates < 0);
1545   my $i = int(rand($#candidates+1));
1546   my $img = $candidates[$i];
1547   my $ref = $referers{$img};
1548
1549   LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1550   return ($ref, $img);
1551 }
1552
1553
1554
1555 \f
1556 ############################################################################
1557 #
1558 # Pick images by feeding random numbers into Bing Image Search.
1559 #
1560 ############################################################################
1561
1562 # bingnums
1563 sub pick_from_bing_image_numbers($) {
1564   my ($timeout) = @_;
1565
1566   my $max = 9999;
1567   my $number = int(rand($max));
1568
1569   $number = sprintf("%04d", $number)
1570     if (rand() < 0.3);
1571
1572   pick_from_bing_images ($timeout, "$number");
1573 }
1574
1575 \f
1576 ############################################################################
1577 #
1578 # Pick images by feeding random numbers into Bing Image Search.
1579 #
1580 ############################################################################
1581
1582 # bingphotos
1583 sub pick_from_bing_image_photos($) {
1584   my ($timeout) = @_;
1585
1586   my $i = int(rand($#photomakers + 1));
1587   my $fn = $photomakers[$i];
1588   my $file = &$fn;
1589
1590   pick_from_bing_images ($timeout, $file);
1591 }
1592
1593 \f
1594 ############################################################################
1595 #
1596 # Pick images by feeding random words into Alta Vista Text Search
1597 #
1598 ############################################################################
1599
1600
1601 my $alta_vista_url = "http://www.altavista.com/web/results" .
1602                      "?pg=aq" .
1603                      "&aqmode=s" .
1604                      "&filetype=html" .
1605                      "&sc=on" .        # "site collapse"
1606                      "&nbq=50" .
1607                      "&aqo=";
1608
1609 # avtext
1610 sub pick_from_alta_vista_text($) {
1611   my ($timeout) = @_;
1612
1613   my $words = random_words('%20');
1614   my $page = (int(rand(9)) + 1);
1615   my $search_url = $alta_vista_url . $words;
1616
1617   if ($page > 1) {
1618     $search_url .= "&pgno=" . $page;
1619     $search_url .= "&stq=" . (($page-1) * 10);
1620   }
1621
1622   my ($search_hit_count, @subpages) =
1623     pick_from_search_engine ($timeout, $search_url, $words);
1624
1625   my @candidates = ();
1626   foreach my $u (@subpages) {
1627
1628     # Those altavista fuckers are playing really nasty redirection games
1629     # these days: the filter your clicks through their site, but use
1630     # onMouseOver to make it look like they're not!  Well, it makes it
1631     # easier for us to identify search results...
1632     #
1633     next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1634     $u = url_unquote($u);
1635
1636     next unless ($u =~ m@^https?://@i);    #  skip non-HTTP or relative URLs
1637     next if ($u =~ m@[/.]altavista\.com\b@i);     # skip altavista builtins
1638     next if ($u =~ m@[/.]yahoo\.com\b@i);         # yahoo and av in cahoots?
1639
1640     LOG ($verbose_filter, "  candidate: $u");
1641     push @candidates, $u;
1642   }
1643
1644   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1645                                 $timeout, @candidates);
1646 }
1647
1648
1649 \f
1650 ############################################################################
1651 #
1652 # Pick images by feeding random words into Hotbot
1653 #
1654 ############################################################################
1655
1656 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1657                         "?ca=w" .
1658                         "&descriptiontype=0" .
1659                         "&imagetoggle=1" .
1660                         "&matchmode=any" .
1661                         "&nummod=2" .
1662                         "&recordcount=50" .
1663                         "&sitegroup=1" .
1664                         "&stem=1" .
1665                         "&cobrand=undefined" .
1666                         "&query=");
1667
1668 sub pick_from_hotbot_text($) {
1669   my ($timeout) = @_;
1670
1671   $last_search = $hotbot_search_url;   # for warnings
1672
1673   # lycos seems to always give us back dictionaries and word lists if
1674   # we search for more than one word...
1675   #
1676   my $words = random_word();
1677
1678   my $start = int(rand(8)) * 10 + 1;
1679   my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1680
1681   my ($search_hit_count, @subpages) =
1682     pick_from_search_engine ($timeout, $search_url, $words);
1683
1684   my @candidates = ();
1685   foreach my $u (@subpages) {
1686
1687     # Hotbot plays redirection games too
1688     # (not any more?)
1689 #    next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1690 #    $u = url_decode($1);
1691
1692     next unless ($u =~ m@^https?://@i);    #  skip non-HTTP or relative URLs
1693     next if ($u =~ m@[/.]hotbot\.com\b@i);     # skip hotbot builtins
1694     next if ($u =~ m@[/.]lycos\.com\b@i);      # skip hotbot builtins
1695     next if ($u =~ m@[/.]inktomi\.com\b@i);    # skip hotbot builtins
1696
1697     LOG ($verbose_filter, "  candidate: $u");
1698     push @candidates, $u;
1699   }
1700
1701   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1702                                 $timeout, @candidates);
1703 }
1704
1705
1706 \f
1707 ############################################################################
1708 #
1709 # Pick images by feeding random words into Lycos
1710 #
1711 ############################################################################
1712
1713 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1714                        "?lpv=1" .
1715                        "&loc=searchhp" .
1716                        "&tab=web" .
1717                        "&query=";
1718
1719 sub pick_from_lycos_text($) {
1720   my ($timeout) = @_;
1721
1722   $last_search = $lycos_search_url;   # for warnings
1723
1724   # lycos seems to always give us back dictionaries and word lists if
1725   # we search for more than one word...
1726   #
1727   my $words = random_word();
1728
1729   my $start = int(rand(8)) * 10 + 1;
1730   my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1731
1732   my ($search_hit_count, @subpages) =
1733     pick_from_search_engine ($timeout, $search_url, $words);
1734
1735   my @candidates = ();
1736   foreach my $u (@subpages) {
1737
1738     # Lycos plays redirection games.
1739     # (not any more?)
1740 #    next unless ($u =~ m@^https?://click.lycos.com/director.asp
1741 #                         .*
1742 #                         \btarget=([^&]+)
1743 #                         .*
1744 #                        @x);
1745 #    $u = url_decode($1);
1746
1747     next unless ($u =~ m@^https?://@i);    #  skip non-HTTP or relative URLs
1748     next if ($u =~ m@[/.]hotbot\.com\b@i);     # skip lycos builtins
1749     next if ($u =~ m@[/.]lycos\.com\b@i);      # skip lycos builtins
1750     next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1751     next if ($u =~ m@[/.]inktomi\.com\b@i);    # skip lycos builtins
1752
1753
1754     LOG ($verbose_filter, "  candidate: $u");
1755     push @candidates, $u;
1756   }
1757
1758   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1759                                 $timeout, @candidates);
1760 }
1761
1762
1763 \f
1764 ############################################################################
1765 #
1766 # Pick images by feeding random words into news.yahoo.com
1767 #
1768 ############################################################################
1769
1770 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1771                      "?c=news_photos" .
1772                      "&p=";
1773
1774 # yahoonews
1775 sub pick_from_yahoo_news_text($) {
1776   my ($timeout) = @_;
1777
1778   $last_search = $yahoo_news_url;   # for warnings
1779
1780   my $words = random_word();
1781   my $search_url = $yahoo_news_url . $words;
1782
1783   my ($search_hit_count, @subpages) =
1784     pick_from_search_engine ($timeout, $search_url, $words);
1785
1786   my @candidates = ();
1787   foreach my $u (@subpages) {
1788
1789     # de-redirectize the URLs
1790     $u =~ s@^https?://rds\.yahoo\.com/.*-http%3A@http:@s;
1791
1792     # only accept URLs on Yahoo's news site
1793     next unless ($u =~ m@^https?://dailynews\.yahoo\.com/@i ||
1794                  $u =~ m@^https?://story\.news\.yahoo\.com/@i);
1795     next unless ($u =~ m@&u=/@);
1796
1797     LOG ($verbose_filter, "  candidate: $u");
1798     push @candidates, $u;
1799   }
1800
1801   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1802                                 $timeout, @candidates);
1803 }
1804
1805
1806 \f
1807 ############################################################################
1808 #
1809 # Pick images from LiveJournal's list of recently-posted images.
1810 #
1811 ############################################################################
1812
1813 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1814
1815 # With most of our image sources, we get a random page and then select
1816 # from the images on it.  However, in the case of LiveJournal, the page
1817 # of images tends to update slowly; so we'll remember the last N entries
1818 # on it and randomly select from those, to get a wider variety each time.
1819
1820 my $lj_cache_size = 1000;
1821 my @lj_cache = (); # fifo, for ordering by age
1822 my %lj_cache = (); # hash, for detecting dups
1823
1824 # livejournal
1825 sub pick_from_livejournal_images($) {
1826   my ($timeout) = @_;
1827
1828   $last_search = $livejournal_img_url;   # for warnings
1829
1830   my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1831
1832   # Often the document comes back empty. If so, just use the cache.
1833   # return () unless $body;
1834   $body = '' unless defined($body);
1835
1836   $body =~ s/\n/ /gs;
1837   $body =~ s/(<recent-image)\b/\n$1/gsi;
1838
1839   foreach (split (/\n/, $body)) {
1840     next unless (m/^<recent-image\b/);
1841     next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1842     my $img = html_unquote ($1);
1843
1844     next if ($lj_cache{$img}); # already have it
1845
1846     next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1847     my $page = html_unquote ($1);
1848     my @pair = ($img, $page);
1849     LOG ($verbose_filter, "  candidate: $img");
1850     push @lj_cache, \@pair;
1851     $lj_cache{$img} = \@pair;
1852   }
1853
1854   return () if ($#lj_cache == -1);
1855
1856   my $n = $#lj_cache+1;
1857   my $i = int(rand($n));
1858   my ($img, $page) = @{$lj_cache[$i]};
1859
1860   # delete this one from @lj_cache and from %lj_cache.
1861   #
1862   @lj_cache = ( @lj_cache[0 .. $i-1],
1863                 @lj_cache[$i+1 .. $#lj_cache] );
1864   delete $lj_cache{$img};
1865
1866   # Keep the size of the cache under the limit by nuking older entries
1867   #
1868   while ($#lj_cache >= $lj_cache_size) {
1869     my $pairP = shift @lj_cache;
1870     my $img = $pairP->[0];
1871     delete $lj_cache{$img};
1872   }
1873
1874   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1875
1876   return ($page, $img);
1877 }
1878
1879 \f
1880 ############################################################################
1881 #
1882 # Pick images from ircimages.com (images that have been in the /topic of
1883 # various IRC channels.)
1884 #
1885 ############################################################################
1886
1887 my $ircimages_url = "http://ircimages.com/";
1888
1889 # ircimages
1890 sub pick_from_ircimages($) {
1891   my ($timeout) = @_;
1892
1893   $last_search = $ircimages_url;   # for warnings
1894
1895   my $n = int(rand(2900));
1896   my $search_url = $ircimages_url . "page-$n";
1897
1898   my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1899   return () unless $body;
1900
1901   my @candidates = ();
1902
1903   $body =~ s/\n/ /gs;
1904   $body =~ s/(<A)\b/\n$1/gsi;
1905
1906   foreach (split (/\n/, $body)) {
1907
1908     my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1909     next unless $u;
1910
1911     if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; }   # quoted string
1912     elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; }  # or token
1913
1914     next unless ($u =~ m/^https?:/i);
1915     next if ($u =~ m@^https?://(searchirc\.com\|ircimages\.com)@i);
1916     next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1917
1918     LOG ($verbose_http, "    HREF: $u");
1919     push @candidates, $u;
1920   }
1921
1922   LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1923
1924   return () if ($#candidates == -1);
1925
1926   my $i = int(rand($#candidates+1));
1927   my $img = $candidates[$i];
1928
1929   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1930        ": $img");
1931
1932   $search_url = $img;  # hmm...
1933   return ($search_url, $img);
1934 }
1935
1936 \f
1937 ############################################################################
1938 #
1939 # Pick images from Twitpic's list of recently-posted images.
1940 #
1941 ############################################################################
1942
1943 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1944
1945 # With most of our image sources, we get a random page and then select
1946 # from the images on it.  However, in the case of Twitpic, the page
1947 # of images tends to update slowly; so we'll remember the last N entries
1948 # on it and randomly select from those, to get a wider variety each time.
1949
1950 my $twitpic_cache_size = 1000;
1951 my @twitpic_cache = (); # fifo, for ordering by age
1952 my %twitpic_cache = (); # hash, for detecting dups
1953
1954 # twitpic
1955 sub pick_from_twitpic_images($) {
1956   my ($timeout) = @_;
1957
1958   $last_search = $twitpic_img_url;   # for warnings
1959
1960   my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1961
1962   # Update the cache.
1963
1964   if ($body) {
1965     $body =~ s/\n/ /gs;
1966     $body =~ s/(<item)\b/\n$1/gsi;
1967
1968     my @items = split (/\n/, $body);
1969     shift @items;
1970     foreach (@items) {
1971       next unless (m@<link>([^<>]*)</link>@si);
1972       my $page = html_unquote ($1);
1973
1974       $page =~ s@/$@@s;
1975       $page .= '/full';
1976
1977       next if ($twitpic_cache{$page}); # already have it
1978
1979       LOG ($verbose_filter, "  candidate: $page");
1980       push @twitpic_cache, $page;
1981       $twitpic_cache{$page} = $page;
1982     }
1983   }
1984
1985   # Pull from the cache.
1986
1987   return () if ($#twitpic_cache == -1);
1988
1989   my $n = $#twitpic_cache+1;
1990   my $i = int(rand($n));
1991   my $page = $twitpic_cache[$i];
1992
1993   # delete this one from @twitpic_cache and from %twitpic_cache.
1994   #
1995   @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1996                      @twitpic_cache[$i+1 .. $#twitpic_cache] );
1997   delete $twitpic_cache{$page};
1998
1999   # Keep the size of the cache under the limit by nuking older entries
2000   #
2001   while ($#twitpic_cache >= $twitpic_cache_size) {
2002     my $page = shift @twitpic_cache;
2003     delete $twitpic_cache{$page};
2004   }
2005
2006   ( $base, $body ) = get_document ($page, undef, $timeout);
2007   my $img = undef;
2008   $body = '' unless defined($body);
2009
2010   foreach (split (/<img\s+/, $body)) {
2011     my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
2012     next unless $src;
2013     next if m@/js/@s;
2014     next if m@/images/@s;
2015
2016     $img = $src;
2017
2018     $img = "http:$img" if ($img =~ m@^//@s);  # Oh come on
2019
2020     # Sometimes these images are hosted on twitpic, sometimes on Amazon.
2021     if ($img =~ m@^/@) {
2022       $base =~ s@^(https?://[^/]+)/.*@$1@s;
2023       $img = $base . $img;
2024     }
2025     last;
2026   }
2027
2028   if (!$img) {
2029     LOG ($verbose_load, "no matching images on $page\n");
2030     return ();
2031   }
2032
2033   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2034
2035   return ($page, $img);
2036 }
2037
2038 \f
2039 ############################################################################
2040 #
2041 # Pick images from Twitter's list of recently-posted updates.
2042 #
2043 ############################################################################
2044
2045 # With most of our image sources, we get a random page and then select
2046 # from the images on it.  However, in the case of Twitter, the page
2047 # of images only updates once a minute; so we'll remember the last N entries
2048 # on it and randomly select from those, to get a wider variety each time.
2049
2050 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2051                       "public_timeline.json" .
2052                       "?include_entities=true" .
2053                       "&include_rts=true" .
2054                       "&count=200";
2055
2056 my $twitter_cache_size = 1000;
2057
2058 my @twitter_cache = (); # fifo, for ordering by age
2059 my %twitter_cache = (); # hash, for detecting dups
2060
2061
2062 # twitter
2063 sub pick_from_twitter_images($) {
2064   my ($timeout) = @_;
2065
2066   $last_search = $twitter_img_url;   # for warnings
2067
2068   my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2069   # Update the cache.
2070
2071   if ($body) {
2072     $body =~ s/[\r\n]+/ /gs;
2073
2074     # Parsing JSON is a pain in the ass.  So we halfass it as usual.
2075     $body =~ s/^\[|\]$//s;
2076     $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2077     my @items = split (/},{/, $body);
2078     foreach (@items) {
2079       my ($name) = m@"screen_name":"([^\"]+)"@si;
2080       my ($img)  = m@"media_url":"([^\"]+)"@si;
2081       my ($page) = m@"display_url":"([^\"]+)"@si;
2082       next unless ($name && $img && $page);
2083       foreach ($img, $page) {
2084         s/\\//gs;
2085         $_ = "http://$_" unless (m/^http/si);
2086       }
2087
2088       next if ($twitter_cache{$page}); # already have it
2089
2090       LOG ($verbose_filter, "  candidate: $page - $img");
2091       push @twitter_cache, $page;
2092       $twitter_cache{$page} = $img;
2093     }
2094   }
2095
2096   # Pull from the cache.
2097
2098   return () if ($#twitter_cache == -1);
2099
2100   my $n = $#twitter_cache+1;
2101   my $i = int(rand($n));
2102   my $page = $twitter_cache[$i];
2103   my $url  = $twitter_cache{$page};
2104
2105   # delete this one from @twitter_cache and from %twitter_cache.
2106   #
2107   @twitter_cache = ( @twitter_cache[0 .. $i-1],
2108                      @twitter_cache[$i+1 .. $#twitter_cache] );
2109   delete $twitter_cache{$page};
2110
2111   # Keep the size of the cache under the limit by nuking older entries
2112   #
2113   while ($#twitter_cache >= $twitter_cache_size) {
2114     my $page = shift @twitter_cache;
2115     delete $twitter_cache{$page};
2116   }
2117
2118   LOG ($verbose_load, "picked page $url");
2119
2120   $suppress_audit = 1;
2121
2122   return ($page, $url);
2123 }
2124
2125 \f
2126 ############################################################################
2127 #
2128 # Pick images from Flickr's page of recently-posted photos.
2129 #
2130 ############################################################################
2131
2132 my $flickr_img_url = "http://www.flickr.com/explore/";
2133
2134 # Like LiveJournal, the Flickr page of images tends to update slowly,
2135 # so remember the last N entries on it and randomly select from those.
2136
2137 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2138 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2139
2140 my $flickr_cache_size = 1000;
2141 my @flickr_cache = (); # fifo, for ordering by age
2142 my %flickr_cache = (); # hash, for detecting dups
2143
2144
2145 # flickr_recent
2146 sub pick_from_flickr_recent($) {
2147   my ($timeout) = @_;
2148
2149   my $start = 16 * int(rand(100));
2150
2151   $last_search = $flickr_img_url;   # for warnings
2152   $last_search .= "?start=$start" if ($start > 0);
2153
2154   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2155
2156   # If the document comes back empty. just use the cache.
2157   # return () unless $body;
2158   $body = '' unless defined($body);
2159
2160   my $count = 0;
2161   my $count2 = 0;
2162
2163   if ($body =~ m@{ *"_data": \[ ( .*? \} ) \]@six) {
2164     $body = $1;
2165   } else {
2166     LOG ($verbose_load, "flickr unparsable: $last_search");
2167     return ();
2168   }
2169
2170   $body =~ s/[\r\n]/ /gs;
2171   $body =~ s/(\},) *(\{)/$1\n$2/gs;     # "_flickrModelRegistry"
2172
2173   foreach my $chunk (split (/\n/, $body)) {
2174     my ($img) = ($chunk =~ m@"displayUrl": *"(.*?)"@six);
2175     next unless defined ($img);
2176     $img =~ s/\\//gs;
2177     $img = "//" unless ($img =~ m@^/@s);
2178     $img = "http:$img" unless ($img =~ m/^http/s);
2179
2180     my ($user) = ($chunk =~ m/"pathAlias": *"(.*?)"/si);
2181     next unless defined ($user);
2182
2183     my ($id) = ($img =~ m@/\d+/(\d+)_([\da-f]+)_@si);
2184     my ($page) = "https://www.flickr.com/photos/$user/$id/";
2185
2186     # $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si;  # take off "thumb" suffix
2187
2188     $count++;
2189     next if ($flickr_cache{$img}); # already have it
2190
2191     my @pair = ($img, $page, $start);
2192     LOG ($verbose_filter, "  candidate: $img");
2193     push @flickr_cache, \@pair;
2194     $flickr_cache{$img} = \@pair;
2195     $count2++;
2196   }
2197
2198   return () if ($#flickr_cache == -1);
2199
2200   my $n = $#flickr_cache+1;
2201   my $i = int(rand($n));
2202   my ($img, $page) = @{$flickr_cache[$i]};
2203
2204   # delete this one from @flickr_cache and from %flickr_cache.
2205   #
2206   @flickr_cache = ( @flickr_cache[0 .. $i-1],
2207                     @flickr_cache[$i+1 .. $#flickr_cache] );
2208   delete $flickr_cache{$img};
2209
2210   # Keep the size of the cache under the limit by nuking older entries
2211   #
2212   while ($#flickr_cache >= $flickr_cache_size) {
2213     my $pairP = shift @flickr_cache;
2214     my $img = $pairP->[0];
2215     delete $flickr_cache{$img};
2216   }
2217
2218   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2219
2220   return ($page, $img);
2221 }
2222
2223 \f
2224 ############################################################################
2225 #
2226 # Pick images from a random RSS feed on Flickr.
2227 #
2228 ############################################################################
2229
2230 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2231                        "?format=rss_200_enc&tagmode=any&tags=");
2232
2233 # Picks a random RSS feed; picks a random image from that feed;
2234 # returns 2 URLs: the page containing the image, and the image.
2235 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2236 #
2237 # flickr_random
2238 sub pick_from_flickr_random($) {
2239   my $timeout = shift;
2240
2241   my $words = random_words(',');
2242   my $rss = $flickr_rss_base . $words;
2243   $last_search = $rss;
2244
2245   $_ = $words;
2246   s/,/ /g;
2247
2248   print STDERR "\n\n" if ($verbose_load);
2249   LOG ($verbose_load, "words: $_");
2250   LOG ($verbose_load, "URL: $last_search");
2251
2252   $suppress_audit = 1;
2253
2254   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2255   if (!$base || !$body) {
2256     $body = undef;
2257     return;
2258   }
2259
2260   my $img;
2261   ($base, $img) = pick_image_from_rss ($base, $body);
2262   $body = undef;
2263   return () unless defined ($img);
2264
2265   LOG ($verbose_load, "redirected to: $base");
2266   return ($base, $img);
2267 }
2268
2269 \f
2270 ############################################################################
2271 #
2272 # Pick random images from Instagram.
2273 #
2274 ############################################################################
2275
2276 my $instagram_url_base = "https://api.instagram.com/v1/media/popular";
2277
2278 # instagram_random
2279 sub pick_from_instagram($) {
2280   my $timeout = shift;
2281
2282   # Liberated access tokens.
2283   # jsdo.it search for: instagram client_id
2284   # Google search for: instagram "&client_id=" site:jsfiddle.net
2285   my @tokens = ('b59fbe4563944b6c88cced13495c0f49', # gramfeed.com
2286                 'fa26679250df49c48a33fbcf30aae989', # instac.at
2287                 'd9494686198d4dfeb954979a3e270e5e', # iconosquare.com
2288                 '793ef48bb18e4197b61afce2d799b81c', # jsdo.it
2289                 '67b8a3e0073449bba70600d0fc68e6cb', # jsdo.it
2290                 '26a098e0df4d4b9ea8b4ce6c505b7742', # jsdo.it
2291                 '2437cbcd906a4c10940f990d283d3cd5', # jsdo.it
2292                 '191c7d7d5312464cbd92134f36ffdab5', # jsdo.it
2293                 'acfec809437b4340b2c38f66503af774', # jsdo.it
2294                 'e9f77604a3a24beba949c12d18130988', # jsdo.it
2295                 '2cd7bcf68ae346529770073d311575b3', # jsdo.it
2296                 '830c600fe8d742e2ab3f3b94f9bb22b7', # jsdo.it
2297                 '55865a0397ad41e5997dd95ef4df8da1', # jsdo.it
2298                 '192a5742f3644ea8bed1d25e439286a8', # jsdo.it
2299                 '38ed1477e7a44595861b8842cdb8ba23', # jsdo.it
2300                 'e52f79f645f54488ad0cc47f6f55ade6', # jsfiddle.net
2301                 );
2302
2303   my $tok = $tokens[int(rand($#tokens+1))];
2304   $last_search = $instagram_url_base . "?client_id=" . $tok;
2305
2306   print STDERR "\n\n" if ($verbose_load);
2307   LOG ($verbose_load, "URL: $last_search");
2308
2309   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2310   if (!$base || !$body) {
2311     $body = undef;
2312     return;
2313   }
2314
2315   $body =~ s/("link")/\001$1/gs;
2316   my @chunks = split(/\001/, $body);
2317   shift @chunks;
2318   my @urls = ();
2319   foreach (@chunks) {
2320     s/\\//gs;
2321     my ($url) = m/"link":\s*"(.*?)"/s;
2322     my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2323        ($img) = m/"url":\s*"(.*?)"/s unless $url;
2324     next unless ($url && $img);
2325     push @urls, [ $url, $img ];
2326   }
2327
2328   if ($#urls < 0) {
2329     LOG ($verbose_load, "no images on $last_search");
2330     return ();
2331   }
2332
2333   my $i = int(rand($#urls+1));
2334   my ($url, $img) = @{$urls[$i]};
2335
2336   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2337   return ($url, $img);
2338 }
2339
2340 \f
2341 ############################################################################
2342 #
2343 # Pick images by waiting for driftnet to populate a temp dir with files.
2344 # Requires driftnet version 0.1.5 or later.
2345 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2346 # for images being downloaded by others.)
2347 # Driftnet/webcollage integration by jwz.
2348 #
2349 ############################################################################
2350
2351 # driftnet
2352 sub pick_from_driftnet($) {
2353   my ($timeout) = @_;
2354
2355   my $id = $driftnet_magic;
2356   my $dir = $driftnet_dir;
2357   my $start = time;
2358   my $now;
2359
2360   error ("\$driftnet_dir unset?") unless ($dir);
2361   $dir =~ s@/+$@@;
2362
2363   error ("$dir unreadable") unless (-d "$dir/.");
2364
2365   $timeout = $http_timeout unless ($timeout);
2366   $last_search = $id;
2367
2368   while ($now = time, $now < $start + $timeout) {
2369     opendir (my $dir, $dir) || error ("$dir: $!");
2370     while (my $file = readdir($dir)) {
2371       next if ($file =~ m/^\./);
2372       $file = "$dir/$file";
2373       closedir ($dir);
2374       LOG ($verbose_load, "picked file $file ($id)");
2375       return ($id, $file);
2376     }
2377     closedir ($dir);
2378   }
2379   LOG (($verbose_net || $verbose_load), "timed out for $id");
2380   return ();
2381 }
2382
2383
2384 sub get_driftnet_file($) {
2385   my ($file) = @_;
2386
2387   error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2388
2389   my $id = $driftnet_magic;
2390   error ("$id: $file not in $driftnet_dir?")
2391     unless ($file =~ m@^\Q$driftnet_dir@o);
2392
2393   open (my $in, '<', $file) || error ("$id: $file: $!");
2394   my $body = '';
2395   local $/ = undef;  # read entire file
2396   $body = <$in>;
2397   close ($in) || error ("$id: $file: $!");
2398   unlink ($file) || error ("$id: $file: rm: $!");
2399   return ($id, $body);
2400 }
2401
2402
2403 sub spawn_driftnet($) {
2404   my ($cmd) = @_;
2405
2406   # make a directory to use.
2407   while (1) {
2408     my $tmp = $ENV{TEMPDIR} || "/tmp";
2409     $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2410     LOG ($verbose_exec, "mkdir $driftnet_dir");
2411     last if mkdir ($driftnet_dir, 0700);
2412   }
2413
2414   if (! ($cmd =~ m/\s/)) {
2415     # if the command didn't have any arguments in it, then it must be just
2416     # a pointer to the executable.  Append the default args to it.
2417     my $dargs = $default_driftnet_cmd;
2418     $dargs =~ s/^[^\s]+//;
2419     $cmd .= $dargs;
2420   }
2421
2422   # point the driftnet command at our newly-minted private directory.
2423   #
2424   $cmd .= " -d $driftnet_dir";
2425   $cmd .= ">/dev/null" unless ($verbose_exec);
2426
2427   my $pid = fork();
2428   if ($pid < 0) { error ("fork: $!\n"); }
2429   if ($pid) {
2430     # parent fork
2431     push @pids_to_kill, $pid;
2432     LOG ($verbose_exec, "forked for \"$cmd\"");
2433   } else {
2434     # child fork
2435     nontrapping_system ($cmd) || error ("exec: $!");
2436   }
2437
2438   # wait a bit, then make sure the process actually started up.
2439   #
2440   sleep (1);
2441   error ("pid $pid failed to start \"$cmd\"")
2442     unless (1 == kill (0, $pid));
2443 }
2444
2445 # local-directory
2446 sub pick_from_local_dir($) {
2447   my ($timeout) = @_;
2448
2449   my $id = $local_magic;
2450   $last_search = $id;
2451
2452   my $dir = $local_dir;
2453   error ("\$local_dir unset?") unless ($dir);
2454   $dir =~ s@/+$@@;
2455
2456   error ("$dir unreadable") unless (-d "$dir/.");
2457
2458   my $v = ($verbose_exec ? "-v" : "");
2459   my $pick = `xscreensaver-getimage-file $v "$dir"`;
2460   $pick =~ s/\s+$//s;
2461   $pick = "$dir/$pick" unless ($pick =~ m@^/@s);       # relative path
2462
2463   LOG ($verbose_load, "picked file $pick ($id)");
2464   return ($id, $pick);
2465 }
2466
2467
2468 sub get_local_file($) {
2469   my ($file) = @_;
2470
2471   error ("\$local_dir unset?") unless ($local_dir);
2472
2473   my $id = $local_magic;
2474   error ("$id: $file not in $local_dir?")
2475     unless ($file =~ m@^\Q$local_dir@o);
2476
2477   open (my $in, '<', $file) || error ("$id: $file: $!");
2478   local $/ = undef;  # read entire file
2479   my $body = <$in>;
2480   close ($in) || error ("$id: $file: $!");
2481   return ($id, $body);
2482 }
2483
2484
2485 \f
2486 ############################################################################
2487 #
2488 # Pick a random image in a random way
2489 #
2490 ############################################################################
2491
2492
2493 # Picks a random image on a random page, and returns two URLs:
2494 # the page containing the image, and the image.
2495 # Returns () if nothing found this time.
2496 #
2497
2498 sub pick_image(;$) {
2499   my ($timeout) = @_;
2500
2501   $current_state = "select";
2502   $load_method = "none";
2503
2504   my $n = int(rand(100));
2505   my $fn = undef;
2506   my $total = 0;
2507   my @rest = @search_methods;
2508
2509   while (@rest) {
2510     my $pct  = shift @rest;
2511     my $name = shift @rest;
2512     my $tfn  = shift @rest;
2513     $total += $pct;
2514     if ($total > $n && !defined($fn)) {
2515       $fn = $tfn;
2516       $current_state = $name;
2517       $load_method = $current_state;
2518     }
2519   }
2520
2521   if ($total != 100) {
2522     error ("internal error: \@search_methods totals to $total%!");
2523   }
2524
2525   record_attempt ($current_state);
2526   return $fn->($timeout);
2527 }
2528
2529
2530 \f
2531 ############################################################################
2532 #
2533 # Statistics and logging
2534 #
2535 ############################################################################
2536
2537 sub timestr() {
2538   return strftime ("%H:%M:%S: ", localtime);
2539 }
2540
2541 sub blurb() {
2542   return "$progname: " . timestr() . "$current_state: ";
2543 }
2544
2545 sub error($) {
2546   my ($err) = @_;
2547   print STDERR blurb() . "$err\n";
2548   exit 1;
2549 }
2550
2551 sub stacktrace() {
2552   my $i = 1;
2553   print STDERR "$progname: stack trace:\n";
2554   while (1) {
2555     my ($package, $filename, $line, $subroutine) = caller($i++);
2556     last unless defined($package);
2557     $filename =~ s@^.*/@@;
2558     print STDERR "  $filename#$line, $subroutine\n";
2559   }
2560 }
2561
2562
2563 my $lastlog = "";
2564
2565 sub clearlog() {
2566   $lastlog = "";
2567 }
2568
2569 sub showlog() {
2570   my $head = "$progname: DEBUG: ";
2571   foreach (split (/\n/, $lastlog)) {
2572     print STDERR "$head$_\n";
2573   }
2574   $lastlog = "";
2575 }
2576
2577 sub LOG($$) {
2578   my ($print, $msg) = @_;
2579   my $blurb = timestr() . "$current_state: ";
2580   $lastlog .= "$blurb$msg\n";
2581   print STDERR "$progname: $blurb$msg\n" if $print;
2582 }
2583
2584
2585 my %stats_attempts;
2586 my %stats_successes;
2587 my %stats_elapsed;
2588
2589 my $last_state = undef;
2590 sub record_attempt($) {
2591   my ($name) = @_;
2592
2593   if ($last_state) {
2594     record_failure($last_state) unless ($image_succeeded > 0);
2595   }
2596   $last_state = $name;
2597
2598   clearlog();
2599   report_performance();
2600
2601   start_timer($name);
2602   $image_succeeded = 0;
2603   $suppress_audit = 0;
2604 }
2605
2606 sub record_success($$$) {
2607   my ($name, $url, $base) = @_;
2608   if (defined($stats_successes{$name})) {
2609     $stats_successes{$name}++;
2610   } else {
2611     $stats_successes{$name} = 1;
2612   }
2613
2614   stop_timer ($name, 1);
2615   my $o = $current_state;
2616   $current_state = $name;
2617   save_recent_url ($url, $base);
2618   $current_state = $o;
2619   $image_succeeded = 1;
2620   clearlog();
2621 }
2622
2623
2624 sub record_failure($) {
2625   my ($name) = @_;
2626
2627   return if $image_succeeded;
2628
2629   stop_timer ($name, 0);
2630   if ($verbose_load && !$verbose_exec) {
2631
2632     if ($suppress_audit) {
2633       print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2634       return;
2635     }
2636
2637     my $o = $current_state;
2638     $current_state = "DEBUG";
2639
2640     my $line =  "#" x 78;
2641     print STDERR "\n\n\n";
2642     print STDERR ("#" x 78) . "\n";
2643     print STDERR blurb() . "failed to get an image.  Full audit log:\n";
2644     print STDERR "\n";
2645     showlog();
2646     print STDERR ("-" x 78) . "\n";
2647     print STDERR "\n\n";
2648
2649     $current_state = $o;
2650   }
2651   $image_succeeded = 0;
2652 }
2653
2654
2655
2656 sub stats_of($) {
2657   my ($name) = @_;
2658   my $i = $stats_successes{$name};
2659   my $j = $stats_attempts{$name};
2660   $i = 0 unless $i;
2661   $j = 0 unless $j;
2662   return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2663 }
2664
2665
2666 my $current_start_time = 0;
2667
2668 sub start_timer($) {
2669   my ($name) = @_;
2670   $current_start_time = time;
2671
2672   if (defined($stats_attempts{$name})) {
2673     $stats_attempts{$name}++;
2674   } else {
2675     $stats_attempts{$name} = 1;
2676   }
2677   if (!defined($stats_elapsed{$name})) {
2678     $stats_elapsed{$name} = 0;
2679   }
2680 }
2681
2682 sub stop_timer($$) {
2683   my ($name, $success) = @_;
2684   $stats_elapsed{$name} += time - $current_start_time;
2685 }
2686
2687
2688 my $last_report_time = 0;
2689 sub report_performance() {
2690
2691   return unless $verbose_warnings;
2692
2693   my $now = time;
2694   return unless ($now >= $last_report_time + $report_performance_interval);
2695   my $ot = $last_report_time;
2696   $last_report_time = $now;
2697
2698   return if ($ot == 0);
2699
2700   my $blurb = "$progname: " . timestr();
2701
2702   print STDERR "\n";
2703   print STDERR "${blurb}Current standings:\n";
2704
2705   foreach my $name (sort keys (%stats_attempts)) {
2706     my $try = $stats_attempts{$name};
2707     my $suc = $stats_successes{$name} || 0;
2708     my $pct = int($suc * 100 / $try);
2709     my $secs = $stats_elapsed{$name};
2710     my $secs_link = $secs / $try;
2711     print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2712                           "       \t %.1f secs/link\n",
2713                           "$name:", "$pct%", $suc, $try, $secs_link);
2714   }
2715 }
2716
2717
2718
2719 my $max_recent_images = 400;
2720 my $max_recent_sites  = 20;
2721 my @recent_images = ();
2722 my @recent_sites = ();
2723
2724 sub save_recent_url($$) {
2725   my ($url, $base) = @_;
2726
2727   return unless ($verbose_warnings);
2728
2729   $_ = $url;
2730   my ($site) = m@^https?://([^ \t\n\r/:]+)@;
2731   return unless defined ($site);
2732
2733   if ($base eq $driftnet_magic || $base eq $local_magic) {
2734     $site = $base;
2735     @recent_images = ();
2736   }
2737
2738   my $done = 0;
2739   foreach (@recent_images) {
2740     if ($_ eq $url) {
2741       print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2742         " (on $base via $last_search)\n";
2743       $done = 1;
2744       last;
2745     }
2746   }
2747
2748   # suppress "duplicate site" warning via %warningless_sites.
2749   #
2750   if ($warningless_sites{$site}) {
2751     $done = 1;
2752   } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2753            $warningless_sites{$1}) {
2754     $done = 1;
2755   } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2756            $warningless_sites{$1}) {
2757     $done = 1;
2758   }
2759
2760   if (!$done) {
2761     foreach (@recent_sites) {
2762       if ($_ eq $site) {
2763         print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2764         " ($url on $base via $last_search)\n";
2765         last;
2766       }
2767     }
2768   }
2769
2770   push @recent_images, $url;
2771   push @recent_sites,  $site;
2772   shift @recent_images if ($#recent_images >= $max_recent_images);
2773   shift @recent_sites  if ($#recent_sites  >= $max_recent_sites);
2774 }
2775
2776
2777 \f
2778 ##############################################################################
2779 #
2780 # other utilities
2781 #
2782 ##############################################################################
2783
2784 # Does %-decoding.
2785 #
2786 sub url_decode($) {
2787   ($_) = @_;
2788   tr/+/ /;
2789   s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2790   return $_;
2791 }
2792
2793
2794 # Given the raw body of a GIF document, returns the dimensions of the image.
2795 #
2796 sub gif_size($) {
2797   my ($body) = @_;
2798   my $type = substr($body, 0, 6);
2799   my $s;
2800   return () unless ($type =~ /GIF8[7,9]a/);
2801   $s = substr ($body, 6, 10);
2802   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2803   return () unless defined ($d);
2804   return (($b<<8|$a), ($d<<8|$c));
2805 }
2806
2807 # Given the raw body of a JPEG document, returns the dimensions of the image.
2808 #
2809 sub jpeg_size($) {
2810   my ($body) = @_;
2811   my $i = 0;
2812   my $L = length($body);
2813
2814   my $c1 = substr($body, $i, 1); $i++;
2815   my $c2 = substr($body, $i, 1); $i++;
2816   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2817
2818   my $ch = "0";
2819   while (ord($ch) != 0xDA && $i < $L) {
2820     # Find next marker, beginning with 0xFF.
2821     while (ord($ch) != 0xFF) {
2822       return () if (length($body) <= $i);
2823       $ch = substr($body, $i, 1); $i++;
2824     }
2825     # markers can be padded with any number of 0xFF.
2826     while (ord($ch) == 0xFF) {
2827       return () if (length($body) <= $i);
2828       $ch = substr($body, $i, 1); $i++;
2829     }
2830
2831     # $ch contains the value of the marker.
2832     my $marker = ord($ch);
2833
2834     if (($marker >= 0xC0) &&
2835         ($marker <= 0xCF) &&
2836         ($marker != 0xC4) &&
2837         ($marker != 0xCC)) {  # it's a SOFn marker
2838       $i += 3;
2839       return () if (length($body) <= $i);
2840       my $s = substr($body, $i, 4); $i += 4;
2841       my ($a,$b,$c,$d) = unpack("C"x4, $s);
2842       return (($c<<8|$d), ($a<<8|$b));
2843
2844     } else {
2845       # We must skip variables, since FFs in variable names aren't
2846       # valid JPEG markers.
2847       return () if (length($body) <= $i);
2848       my $s = substr($body, $i, 2); $i += 2;
2849       my ($c1, $c2) = unpack ("C"x2, $s);
2850       my $length = ($c1 << 8) | $c2;
2851       return () if ($length < 2);
2852       $i += $length-2;
2853     }
2854   }
2855   return ();
2856 }
2857
2858 # Given the raw body of a PNG document, returns the dimensions of the image.
2859 #
2860 sub png_size($) {
2861   my ($body) = @_;
2862   return () unless ($body =~ m/^\211PNG\r/);
2863   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2864   return () unless defined ($bits);
2865   return () unless ($bits =~ /^IHDR/);
2866   my ($ign, $w, $h) = unpack("a4N2", $bits);
2867   return ($w, $h);
2868 }
2869
2870
2871 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2872 # of the image.
2873 #
2874 sub image_size($) {
2875   my ($body) = @_;
2876   my ($w, $h) = gif_size ($body);
2877   if ($w && $h) { return ($w, $h); }
2878   ($w, $h) = jpeg_size ($body);
2879   if ($w && $h) { return ($w, $h); }
2880   return png_size ($body);
2881 }
2882
2883
2884 # returns the full path of the named program, or undef.
2885 #
2886 sub which($) {
2887   my ($prog) = @_;
2888   foreach (split (/:/, $ENV{PATH})) {
2889     my $path = "$_/$prog";
2890     if (-x $path) {
2891       return $path;
2892     }
2893   }
2894   return undef;
2895 }
2896
2897
2898 # Like rand(), but chooses numbers with a bell curve distribution.
2899 sub bellrand(;$) {
2900   ($_) = @_;
2901   $_ = 1.0 unless defined($_);
2902   $_ /= 3.0;
2903   return (rand($_) + rand($_) + rand($_));
2904 }
2905
2906
2907 sub exit_cleanup() {
2908   x_cleanup();
2909   print STDERR "$progname: exiting\n" if ($verbose_warnings);
2910   if (@pids_to_kill) {
2911     print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2912     kill ('TERM', @pids_to_kill);
2913   }
2914 }
2915
2916 sub signal_cleanup($) {
2917   my ($sig) = @_;
2918   print STDERR blurb() . (defined($sig)
2919                           ? "caught signal $sig."
2920                           : "exiting.")
2921                        . "\n"
2922     if ($verbose_exec || $verbose_warnings);
2923   exit 1;
2924 }
2925
2926
2927
2928 ##############################################################################
2929 #
2930 # Generating a list of urls only
2931 #
2932 ##############################################################################
2933
2934 sub url_only_output() {
2935   do {
2936     my ($base, $img) = pick_image;
2937     if ($img) {
2938       $base =~ s/ /%20/g;
2939       $img  =~ s/ /%20/g;
2940       print "$img $base\n";
2941     }
2942   } while (1);
2943 }
2944
2945 ##############################################################################
2946 #
2947 # Running as an xscreensaver module, or as a web page imagemap
2948 #
2949 ##############################################################################
2950
2951 my ($image_ppm, $image_tmp1, $image_tmp2);
2952 {
2953   my $seed = rand(0xFFFFFFFF);
2954   $image_ppm = sprintf ("%s/webcollage-%08x",
2955                         ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2956                         $seed);
2957   $image_tmp1 = $image_ppm . '-1.ppm';
2958   $image_tmp2 = $image_ppm . '-2.ppm';
2959   $image_ppm .= '.ppm';
2960 }
2961
2962
2963 my $filter_cmd = undef;
2964 my $post_filter_cmd = undef;
2965 my $background = undef;
2966
2967 my @imagemap_areas = ();
2968 my $imagemap_html_tmp = undef;
2969 my $imagemap_jpg_tmp = undef;
2970
2971
2972 my $img_width;            # size of the image being generated.
2973 my $img_height;
2974
2975 my $delay = 2;
2976
2977 sub x_cleanup() {
2978   unlink $image_ppm, $image_tmp1, $image_tmp2;
2979   unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2980     if (defined ($imagemap_html_tmp));
2981 }
2982
2983
2984 # Like system, but prints status about exit codes, and kills this process
2985 # with whatever signal killed the sub-process, if any.
2986 #
2987 sub nontrapping_system(@) {
2988   $! = 0;
2989
2990   $_ = join(" ", @_);
2991   s/\"[^\"]+\"/\"...\"/g;
2992
2993   LOG ($verbose_exec, "executing \"$_\"");
2994
2995   my $rc = system @_;
2996
2997   if ($rc == 0) {
2998     LOG ($verbose_exec, "subproc exited normally.");
2999   } elsif (($rc & 0xff) == 0) {
3000     $rc >>= 8;
3001     LOG ($verbose_exec, "subproc exited with status $rc.");
3002   } else {
3003     if ($rc & 0x80) {
3004       LOG ($verbose_exec, "subproc dumped core.");
3005       $rc &= ~0x80;
3006     }
3007     LOG ($verbose_exec, "subproc died with signal $rc.");
3008     # die that way ourselves.
3009     kill $rc, $$;
3010   }
3011
3012   return $rc;
3013 }
3014
3015
3016 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
3017 # writes a PPM to the given output file.  Returns the width/height of the
3018 # image if successful.
3019 #
3020 sub image_to_pnm($$$) {
3021   my ($url, $body, $output) = @_;
3022   my ($cmd, $cmd2, $w, $h);
3023
3024   if ((@_ = gif_size ($body))) {
3025     ($w, $h) = @_;
3026     $cmd = "giftopnm";
3027   } elsif ((@_ = jpeg_size ($body))) {
3028     ($w, $h) = @_;
3029     $cmd = "djpeg";
3030   } elsif ((@_ = png_size ($body))) {
3031     ($w, $h) = @_;
3032     $cmd = "pngtopnm";
3033   } else {
3034     LOG (($verbose_pbm || $verbose_load),
3035          "not a GIF, JPG, or PNG" .
3036          (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
3037           ? " (looks like HTML)" : "") .
3038          ": $url");
3039     $suppress_audit = 1;
3040     return ();
3041   }
3042
3043   $cmd2 = "exec $cmd";        # yes, this really is necessary.  if we don't
3044                               # do this, the process doesn't die properly.
3045   if (!$verbose_pbm) {
3046     #
3047     # We get a "giftopnm: got a 'Application Extension' extension"
3048     # warning any time it's an animgif.
3049     #
3050     # Note that "giftopnm: EOF / read error on image data" is not
3051     # always a fatal error -- sometimes the image looks fine anyway.
3052     #
3053     $cmd2 .= " 2>/dev/null";
3054   }
3055
3056   # There exist corrupted GIF and JPEG files that can make giftopnm and
3057   # djpeg lose their minds and go into a loop.  So this gives those programs
3058   # a small timeout -- if they don't complete in time, kill them.
3059   #
3060   my $pid;
3061   @_ = eval {
3062     my $timed_out;
3063
3064     local $SIG{ALRM}  = sub {
3065       LOG ($verbose_pbm,
3066            "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3067       kill ('TERM', $pid) if ($pid);
3068       $timed_out = 1;
3069       $body = undef;
3070     };
3071
3072     if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3073       $timed_out = 0;
3074       alarm $cvt_timeout;
3075       print $pipe $body;
3076       $body = undef;
3077       close $pipe;
3078
3079       LOG ($verbose_exec, "awaiting $pid");
3080       waitpid ($pid, 0);
3081       LOG ($verbose_exec, "$pid completed");
3082
3083       my $size = (stat($output))[7];
3084       $size = -1 unless defined($size);
3085       if ($size < 5) {
3086         LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3087         return ();
3088       }
3089
3090       LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3091       return ($w, $h);
3092     } else {
3093       print STDERR blurb() . "$cmd failed: $!\n";
3094       return ();
3095     }
3096   };
3097   die if ($@ && $@ ne "alarm\n");       # propagate errors
3098   if ($@) {
3099     # timed out
3100     $body = undef;
3101     return ();
3102   } else {
3103     # didn't
3104     alarm 0;
3105     $body = undef;
3106     return @_;
3107   }
3108 }
3109
3110
3111 # Same as the "ppmmake" command: creates a solid-colored PPM.
3112 # Does not understand the rgb.txt color names except "black" and "white".
3113 #
3114 sub ppmmake($$$$) {
3115   my ($outfile, $bgcolor, $w, $h) = @_;
3116
3117   my ($r, $g, $b);
3118   if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3119       $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3120     ($r, $g, $b) = (hex($1), hex($2), hex($3));
3121   } elsif ($bgcolor =~ m/^black$/i) {
3122     ($r, $g, $b) = (0, 0, 0);
3123   } elsif ($bgcolor =~ m/^white$/i) {
3124     ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3125   } else {
3126     error ("unparsable color name: $bgcolor");
3127   }
3128
3129   my $pixel = pack('CCC', $r, $g, $b);
3130   my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3131
3132   open (my $out, '>', $outfile) || error ("$outfile: $!");
3133   print $out $bits;
3134   close $out;
3135 }
3136
3137
3138 sub pick_root_displayer() {
3139   my @names = ();
3140
3141   if ($cocoa_p) {
3142     # see "xscreensaver/hacks/webcollage-cocoa.m"
3143     return "echo COCOA LOAD ";
3144   }
3145
3146   foreach my $cmd (@root_displayers) {
3147     $_ = $cmd;
3148     my ($name) = m/^([^ ]+)/;
3149     push @names, "\"$name\"";
3150     LOG ($verbose_exec, "looking for $name...");
3151     foreach my $dir (split (/:/, $ENV{PATH})) {
3152       LOG ($verbose_exec, "  checking $dir/$name");
3153       return $cmd if (-x "$dir/$name");
3154     }
3155   }
3156
3157   $names[$#names] = "or " . $names[$#names];
3158   error "none of: " . join (", ", @names) . " were found on \$PATH.";
3159 }
3160
3161
3162 my $ppm_to_root_window_cmd = undef;
3163
3164
3165 sub x_or_pbm_output($) {
3166   my ($window_id) = @_;
3167
3168   # Adjust the PATH for OS X 10.10.
3169   #
3170   $_ = $0;
3171   s:/[^/]*$::;
3172   s/([^a-zA-Z0-9._\-+\/])/\\$1/g;
3173   $ENV{PATH} = "$_:$ENV{PATH}";
3174
3175   # Check for our helper program, to see whether we need to use PPM pipelines.
3176   #
3177   $_ = "webcollage-helper";
3178
3179   if (! defined ($webcollage_helper)) {
3180     $webcollage_helper = which ($_);
3181   }
3182
3183   if (defined ($webcollage_helper)) {
3184     LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3185     $webcollage_helper = "'$webcollage_helper' -v";
3186   } else {
3187     LOG (($verbose_pbm || $verbose_load), "no $_ program");
3188   }
3189
3190   if ($cocoa_p && !defined ($webcollage_helper)) {
3191     error ("webcollage-helper not found in Cocoa-mode!");
3192   }
3193
3194
3195   # make sure the various programs we execute exist, right up front.
3196   #
3197   my @progs = ();
3198
3199   if (!defined($webcollage_helper)) {
3200     # Only need these others if we don't have the helper.
3201     @progs = (@progs,
3202               "giftopnm", "pngtopnm", "djpeg",
3203               "pnmpaste", "pnmscale", "pnmcut");
3204   }
3205
3206   foreach (@progs) {
3207     which ($_) || error "$_ not found on \$PATH.";
3208   }
3209
3210   # If we're using webcollage-helper and not a filter, then the tmp files
3211   # are JPEGs, not PPMs.
3212   #
3213   if (defined ($webcollage_helper) && !defined ($filter_cmd)) {
3214     foreach ($image_ppm, $image_tmp1, $image_tmp2) {
3215       s/\.ppm$/.jpg/s;
3216     }
3217   }
3218
3219
3220   # find a root-window displayer program.
3221   #
3222   if (!$no_output_p) {
3223     $ppm_to_root_window_cmd = pick_root_displayer();
3224   }
3225
3226   if (defined ($window_id)) {
3227     error ("-window-id only works if xscreensaver-getimage is installed")
3228       unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3229
3230     error ("unparsable window id: $window_id")
3231       unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3232     $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3233       error ("unable to munge displayer: $ppm_to_root_window_cmd");
3234   }
3235
3236   if (!$img_width || !$img_height) {
3237
3238     if (!defined ($window_id) &&
3239         defined ($ENV{XSCREENSAVER_WINDOW})) {
3240       $window_id = $ENV{XSCREENSAVER_WINDOW};
3241     }
3242
3243     if (!defined ($window_id)) {
3244       $_ = "xdpyinfo";
3245       which ($_) || error "$_ not found on \$PATH.";
3246       $_ = `$_`;
3247       ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3248       if (!defined($img_height)) {
3249         error "xdpyinfo failed.";
3250       }
3251     } else {  # we have a window id
3252       $_ = "xwininfo";
3253       which ($_) || error "$_ not found on \$PATH.";
3254       $_ .= " -id $window_id";
3255       $_ = `$_`;
3256       ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3257
3258       if (!defined($img_height)) {
3259         error "xwininfo failed.";
3260       }
3261     }
3262   }
3263
3264   my $bgcolor = "#000000";
3265   my $bgimage = undef;
3266
3267   if ($background) {
3268     if ($background =~ m/^\#[0-9a-f]+$/i) {
3269       $bgcolor = $background;
3270
3271     } elsif (-r $background) {
3272       $bgimage = $background;
3273
3274     } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3275       error "not a color or readable file: $background";
3276
3277     } else {
3278       # default to assuming it's a color
3279       $bgcolor = $background;
3280     }
3281   }
3282
3283   # Create the sold-colored base image.
3284   #
3285   LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3286   $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3287
3288   # Paste the default background image in the middle of it.
3289   #
3290   if ($bgimage) {
3291     my ($iw, $ih);
3292
3293     my $body = "";
3294     open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3295     local $/ = undef;  # read entire file
3296     $body = <$imgf>;
3297     close ($imgf);
3298
3299     my $cmd;
3300     if ((@_ = gif_size ($body))) {
3301       ($iw, $ih) = @_;
3302       $cmd = "giftopnm |";
3303
3304     } elsif ((@_ = jpeg_size ($body))) {
3305       ($iw, $ih) = @_;
3306       $cmd = "djpeg |";
3307
3308     } elsif ((@_ = png_size ($body))) {
3309       ($iw, $ih) = @_;
3310       $cmd = "pngtopnm |";
3311
3312     } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3313       $iw = $1;
3314       $ih = $2;
3315       $cmd = "";
3316
3317     } else {
3318       error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3319     }
3320
3321     my $x = int (($img_width  - $iw) / 2);
3322     my $y = int (($img_height - $ih) / 2);
3323     LOG ($verbose_pbm,
3324          "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3325
3326     $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3327     open ($imgf, "| $cmd") || error "running $cmd: $!";
3328     print $imgf $body;
3329     $body = undef;
3330     close ($imgf);
3331     LOG ($verbose_exec, "subproc exited normally.");
3332     rename ($image_tmp1, $image_ppm) ||
3333       error "renaming $image_tmp1 to $image_ppm: $!";
3334   }
3335
3336   clearlog();
3337
3338   while (1) {
3339     my ($base, $img) = pick_image();
3340     my $source = $current_state;
3341     $current_state = "loadimage";
3342     if ($img) {
3343       my ($headers, $body) = get_document ($img, $base);
3344       if ($body) {
3345         paste_image ($base, $img, $body, $source);
3346         $body = undef;
3347       }
3348     }
3349     $current_state = "idle";
3350     $load_method = "none";
3351
3352     unlink $image_tmp1, $image_tmp2;
3353     sleep $delay;
3354   }
3355 }
3356
3357 sub paste_image($$$$) {
3358   my ($base, $img, $body, $source) = @_;
3359
3360   $current_state = "paste";
3361
3362   $suppress_audit = 0;
3363
3364   LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3365
3366   my ($iw, $ih);
3367
3368   # If we are using the webcollage-helper, then we do not need to convert this
3369   # image to a PPM.  But, if we're using a filter command, we still must, since
3370   # that's what the filters expect (webcollage-helper can read PPMs, so that's
3371   # fine.)
3372   #
3373   if (defined ($webcollage_helper) &&
3374       !defined ($filter_cmd)) {
3375
3376     ($iw, $ih) = image_size ($body);
3377     if (!$iw || !$ih) {
3378       LOG (($verbose_pbm || $verbose_load),
3379            "not a GIF, JPG, or PNG" .
3380            (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3381             ? " (looks like HTML)" : "") .
3382            ": $img");
3383       $suppress_audit = 1;
3384       $body = undef;
3385       return 0;
3386     }
3387
3388     if ($iw <= 0 || $ih <= 0 || $iw > 9999 || $ih > 9999) {
3389       LOG (($verbose_pbm || $verbose_load),
3390            "ludicrous image dimensions: $iw x $ih (" . length($body) .
3391            "): $img");
3392       $body = undef;
3393       return 0;
3394     }
3395
3396     open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3397     (print $out $body) || error ("writing $image_tmp1: $!");
3398     close ($out) || error ("writing $image_tmp1: $!");
3399
3400   } else {
3401     ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3402     $body = undef;
3403     if (!$iw || !$ih) {
3404       LOG ($verbose_pbm, "unable to make PBM from $img");
3405       return 0;
3406     }
3407   }
3408
3409   record_success ($load_method, $img, $base);
3410
3411
3412   my $ow = $iw;  # used only for error messages
3413   my $oh = $ih;
3414
3415   # don't just tack this onto the front of the pipeline -- we want it to
3416   # be able to change the size of the input image.
3417   #
3418   if ($filter_cmd) {
3419     LOG ($verbose_pbm, "running $filter_cmd");
3420
3421     my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3422     if ($rc != 0) {
3423       LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3424       LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3425       return;
3426     }
3427     rename ($image_tmp2, $image_tmp1);
3428
3429     # re-get the width/height in case the filter resized it.
3430     open (my $imgf, '<', $image_tmp1) || return 0;
3431     $_ = <$imgf>;
3432     $_ = <$imgf>;
3433     ($iw, $ih) = m/^(\d+) (\d+)$/;
3434     close ($imgf);
3435     return 0 unless ($iw && $ih);
3436   }
3437
3438   my $target_w = $img_width;   # max rectangle into which the image must fit
3439   my $target_h = $img_height;
3440
3441   my $cmd = "";
3442   my $scale = 1.0;
3443
3444
3445   # Usually scale the image to fit on the screen -- but sometimes scale it
3446   # to fit on half or a quarter of the screen.  (We do this by reducing the
3447   # size of the target rectangle.)  Note that the image is not merely scaled
3448   # to fit; we instead cut the image in half repeatedly until it fits in the
3449   # target rectangle -- that gives a wider distribution of sizes.
3450   #
3451   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3452   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3453
3454   if ($iw > $target_w || $ih > $target_h) {
3455     while ($iw > $target_w ||
3456            $ih > $target_h) {
3457       $iw = int($iw / 2);
3458       $ih = int($ih / 2);
3459       $scale /= 2;
3460     }
3461     if ($iw <= 10 || $ih <= 10) {
3462       LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3463       return 0;
3464     }
3465
3466     LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3467
3468     $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3469   }
3470
3471
3472   my $src = $image_tmp1;
3473
3474   my $crop_x = 0;     # the sub-rectangle of the image
3475   my $crop_y = 0;     # that we will actually paste.
3476   my $crop_w = $iw;
3477   my $crop_h = $ih;
3478
3479   # The chance that we will randomly crop out a section of an image starts
3480   # out fairly low, but goes up for images that are very large, or images
3481   # that have ratios that make them look like banners (we try to avoid
3482   # banner images entirely, but they slip through when the IMG tags didn't
3483   # have WIDTH and HEIGHT specified.)
3484   #
3485   my $crop_chance = 0.2;
3486   if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3487     $crop_chance += 0.2;
3488   }
3489   if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3490     $crop_chance += 0.2;
3491   }
3492   if ($min_ratio && ($iw * $min_ratio) > $ih) {
3493     $crop_chance += 0.7;
3494   }
3495
3496   if ($crop_chance > 0.1) {
3497     LOG ($verbose_pbm, "crop chance: $crop_chance");
3498   }
3499
3500   if (rand() < $crop_chance) {
3501
3502     my $ow = $crop_w;
3503     my $oh = $crop_h;
3504
3505     if ($crop_w > $min_width) {
3506       # if it's a banner, select the width linearly.
3507       # otherwise, select a bell.
3508       my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3509                ? rand()
3510                : bellrand());
3511       $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3512       $crop_x = int (rand() * ($ow - $crop_w));
3513     }
3514     if ($crop_h > $min_height) {
3515       # height always selects as a bell.
3516       $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3517       $crop_y = int (rand() * ($oh - $crop_h));
3518     }
3519
3520     if ($crop_x != 0   || $crop_y != 0 ||
3521         $crop_w != $iw || $crop_h != $ih) {
3522       LOG ($verbose_pbm,
3523            "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3524     }
3525   }
3526
3527   # Where the image should logically land -- this might be negative.
3528   #
3529   my $x = int((rand() * ($img_width  + $crop_w/2)) - $crop_w*3/4);
3530   my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3531
3532   # if we have chosen to paste the image outside of the rectangle of the
3533   # screen, then we need to crop it.
3534   #
3535   if ($x < 0 ||
3536       $y < 0 ||
3537       $x + $crop_w > $img_width ||
3538       $y + $crop_h > $img_height) {
3539
3540     LOG ($verbose_pbm,
3541          "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3542
3543     if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3544     if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3545
3546     if ($x + $crop_w >= $img_width)  { $crop_w = $img_width  - $x - 1; }
3547     if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3548   }
3549
3550   # If any cropping needs to happen, add pnmcut.
3551   #
3552   if ($crop_x != 0   || $crop_y != 0 ||
3553       $crop_w != $iw || $crop_h != $ih) {
3554     $iw = $crop_w;
3555     $ih = $crop_h;
3556     $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3557     LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3558   }
3559
3560   LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3561
3562   $cmd .= " | pnmpaste - $x $y $image_ppm";
3563
3564   $cmd =~ s@^ *\| *@@;
3565
3566   if (defined ($webcollage_helper)) {
3567     $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3568                               "$scale $opacity " .
3569                               "$crop_x $crop_y $x $y " .
3570                               "$iw $ih";
3571     $_ = $cmd;
3572
3573   } else {
3574     # use a PPM pipeline
3575     $_ = "($cmd)";
3576     $_ .= " < $image_tmp1 > $image_tmp2";
3577   }
3578
3579   if ($verbose_pbm) {
3580     $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3581   } else {
3582     $_ .= " 2> /dev/null";
3583   }
3584
3585   my $rc = nontrapping_system ($_);
3586
3587   if (defined ($webcollage_helper) && -z $image_ppm) {
3588     LOG (1, "failed command: \"$cmd\"");
3589     print STDERR "\naudit log:\n\n\n";
3590     print STDERR ("#" x 78) . "\n";
3591     print STDERR blurb() . "$image_ppm has zero size\n";
3592     showlog();
3593     print STDERR "\n\n";
3594     exit (1);
3595   }
3596
3597   if ($rc != 0) {
3598     LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3599     LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3600     return;
3601   }
3602
3603   if (!defined ($webcollage_helper)) {
3604     rename ($image_tmp2, $image_ppm) || return;
3605   }
3606
3607   my $target = "$image_ppm";
3608
3609   # don't just tack this onto the end of the pipeline -- we don't want it
3610   # to end up in $image_ppm, because we don't want the results to be
3611   # cumulative.
3612   #
3613   if ($post_filter_cmd) {
3614
3615     my $cmd;
3616
3617     $target = $image_tmp1;
3618     if (!defined ($webcollage_helper)) {
3619       $cmd = "($post_filter_cmd) < $image_ppm > $target";
3620     } else {
3621       # Blah, my scripts need the JPEG data, but some other folks need
3622       # the PPM data -- what to do?  Ignore the problem, that's what!
3623 #     $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3624       $cmd = "($post_filter_cmd) < $image_ppm > $target";
3625     }
3626
3627     $rc = nontrapping_system ($cmd);
3628     if ($rc != 0) {
3629       LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3630       return;
3631     }
3632   }
3633
3634   if (!$no_output_p) {
3635     my $tsize = (stat($target))[7];
3636     if ($tsize > 200) {
3637       $cmd = "$ppm_to_root_window_cmd $target";
3638
3639       # xv seems to hate being killed.  it tends to forget to clean
3640       # up after itself, and leaves windows around and colors allocated.
3641       # I had this same problem with vidwhacker, and I'm not entirely
3642       # sure what I did to fix it.  But, let's try this: launch xv
3643       # in the background, so that killing this process doesn't kill it.
3644       # it will die of its own accord soon enough.  So this means we
3645       # start pumping bits to the root window in parallel with starting
3646       # the next network retrieval, which is probably a better thing
3647       # to do anyway.
3648       #
3649       $cmd .= " &" unless ($cocoa_p);
3650
3651       $rc = nontrapping_system ($cmd);
3652
3653       if ($rc != 0) {
3654         LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3655         return;
3656       }
3657
3658     } else {
3659       LOG ($verbose_pbm, "$target size is $tsize");
3660     }
3661   }
3662
3663   $source .= "-" . stats_of($source);
3664   print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3665     if ($verbose_imgmap);
3666   if ($imagemap_base) {
3667     update_imagemap ($base, $x, $y, $iw, $ih,
3668                      $image_ppm, $img_width, $img_height);
3669   }
3670
3671   clearlog();
3672
3673   return 1;
3674 }
3675
3676
3677 sub update_imagemap($$$$$$$$) {
3678   my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3679
3680   $current_state = "imagemap";
3681
3682   my $max_areas = 200;
3683
3684   $url = html_quote ($url);
3685   my $x2 = $x + $w;
3686   my $y2 = $y + $h;
3687   my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3688   unshift @imagemap_areas, $area;       # put one on the front
3689   if ($#imagemap_areas >= $max_areas) {
3690     pop @imagemap_areas;                # take one off the back.
3691   }
3692
3693   LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3694
3695   my $map_name = $imagemap_base;
3696   $map_name =~ s@^.*/@@;
3697   $map_name = 'collage' if ($map_name eq '');
3698
3699   my $imagemap_html = $imagemap_base . ".html";
3700   my $imagemap_jpg  = $imagemap_base . ".jpg";
3701   my $imagemap_jpg2 = $imagemap_jpg;
3702   $imagemap_jpg2 =~ s@^.*/@@gs;
3703
3704   if (!defined ($imagemap_html_tmp)) {
3705     $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3706     $imagemap_jpg_tmp  = $imagemap_jpg  . sprintf (".%08x", rand(0xffffffff));
3707   }
3708
3709   # Read the imagemap html file (if any) to get a template.
3710   #
3711   my $template_html = '';
3712   {
3713     if (open (my $in, '<', $imagemap_html)) {
3714       local $/ = undef;  # read entire file
3715       $template_html = <$in>;
3716       close $in;
3717       LOG ($verbose_pbm, "read template $imagemap_html");
3718     }
3719
3720     if ($template_html =~ m/^\s*$/s) {
3721       $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3722                         "<IMG SRC=\"$imagemap_jpg2\"" .
3723                         " USEMAP=\"$map_name\">\n");
3724       LOG ($verbose_pbm, "created dummy template");
3725     }
3726   }
3727
3728   # Write the jpg to a tmp file
3729   #
3730   {
3731     my $cmd;
3732     if (defined ($webcollage_helper)) {
3733       $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3734     } else {
3735       $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3736     }
3737     my $rc = nontrapping_system ($cmd);
3738     if ($rc != 0) {
3739       error ("imagemap jpeg failed: \"$cmd\"\n");
3740     }
3741   }
3742
3743   # Write the html to a tmp file
3744   #
3745   {
3746     my $body = $template_html;
3747     my $areas = join ("\n\t", @imagemap_areas);
3748     my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3749     my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3750                "BORDER=0 " .
3751                "WIDTH=$image_width HEIGHT=$image_height " .
3752                "USEMAP=\"#$map_name\">");
3753     $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3754     $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3755
3756     # if there are magic webcollage spans in the html, update those too.
3757     #
3758     {
3759       my @st = stat ($imagemap_jpg_tmp);
3760       my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3761       my $size = int(($st[7] / 1024) + 0.5) . "K";
3762       $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3763       $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3764     }
3765
3766     open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3767     (print $out $body)                      || error ("$imagemap_html_tmp: $!");
3768     close ($out)                            || error ("$imagemap_html_tmp: $!");
3769     LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3770   }
3771
3772   # Rename the two tmp files to the real files
3773   #
3774   rename ($imagemap_html_tmp, $imagemap_html) ||
3775     error "renaming $imagemap_html_tmp to $imagemap_html";
3776   LOG ($verbose_pbm, "wrote $imagemap_html");
3777   rename ($imagemap_jpg_tmp,  $imagemap_jpg) ||
3778     error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3779   LOG ($verbose_pbm, "wrote $imagemap_jpg");
3780 }
3781
3782
3783 # Figure out what the proxy server should be, either from environment
3784 # variables or by parsing the output of the (MacOS) program "scutil",
3785 # which tells us what the system-wide proxy settings are.
3786 #
3787 sub set_proxy() {
3788
3789   if (! defined($http_proxy)) {
3790     # historical suckage: the environment variable name is lower case.
3791     $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3792   }
3793
3794   if (defined ($http_proxy)) {
3795     if ($http_proxy && $http_proxy =~ m@^https?://([^/]*)/?$@ ) {
3796       # historical suckage: allow "http://host:port" as well as "host:port".
3797       $http_proxy = $1;
3798     }
3799
3800   } else {
3801     my $proxy_data = `scutil --proxy 2>/dev/null`;
3802     my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3803     my ($port)   = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3804     # Note: this ignores the "ExceptionsList".
3805     if ($server) {
3806       $http_proxy = $server;
3807       $http_proxy .= ":$port" if $port;
3808     }
3809   }
3810
3811   delete $ENV{http_proxy};
3812   delete $ENV{HTTP_PROXY};
3813   delete $ENV{https_proxy};
3814   delete $ENV{HTTPS_PROXY};
3815   delete $ENV{PERL_LWP_ENV_PROXY};
3816
3817   if ($http_proxy) {
3818     $http_proxy = 'http://' . $http_proxy;
3819     LOG ($verbose_net, "proxy server: $http_proxy");
3820   } else {
3821     $http_proxy = undef;  # for --proxy ''
3822   }
3823 }
3824
3825
3826 sub init_signals() {
3827
3828   $SIG{HUP}  = \&signal_cleanup;
3829   $SIG{INT}  = \&signal_cleanup;
3830   $SIG{QUIT} = \&signal_cleanup;
3831   $SIG{ABRT} = \&signal_cleanup;
3832   $SIG{KILL} = \&signal_cleanup;
3833   $SIG{TERM} = \&signal_cleanup;
3834
3835   # Need this so that if giftopnm dies, we don't die.
3836   $SIG{PIPE} = 'IGNORE';
3837 }
3838
3839 END { exit_cleanup(); }
3840
3841
3842 sub main() {
3843   $| = 1;
3844   srand(time ^ $$);
3845
3846   my $verbose = 0;
3847   my $dict;
3848   my $driftnet_cmd = 0;
3849
3850   $current_state = "init";
3851   $load_method = "none";
3852
3853   my $root_p = 0;
3854   my $window_id = undef;
3855
3856   while ($#ARGV >= 0) {
3857     $_ = shift @ARGV;
3858     if (m/^--?d(i(s(p(l(a(y)?)?)?)?)?)?$/s) {
3859       $ENV{DISPLAY} = shift @ARGV;
3860     } elsif (m/^--?root$/s) {
3861       $root_p = 1;
3862     } elsif (m/^--?window-id$/s) {
3863       $window_id = shift @ARGV;
3864       $root_p = 1;
3865     } elsif (m/^--?no-output$/s) {
3866       $no_output_p = 1;
3867     } elsif (m/^--?urls(-only)?$/s) {
3868       $urls_only_p = 1;
3869       $no_output_p = 1;
3870     } elsif (m/^--?cocoa$/s) {
3871       $cocoa_p = 1;
3872     } elsif (m/^--?imagemap$/s) {
3873       $imagemap_base = shift @ARGV;
3874       $no_output_p = 1;
3875     } elsif (m/^--?verbose$/s) {
3876       $verbose++;
3877     } elsif (m/^-v+$/) {
3878       $verbose += length($_)-1;
3879     } elsif (m/^--?delay$/s) {
3880       $delay = shift @ARGV;
3881     } elsif (m/^--?timeout$/s) {
3882       $http_timeout = shift @ARGV;
3883     } elsif (m/^--?filter$/s) {
3884       $filter_cmd = shift @ARGV;
3885     } elsif (m/^--?filter2$/s) {
3886       $post_filter_cmd = shift @ARGV;
3887     } elsif (m/^--?(background|bg)$/s) {
3888       $background = shift @ARGV;
3889     } elsif (m/^--?size$/s) {
3890       $_ = shift @ARGV;
3891       if (m@^(\d+)x(\d+)$@) {
3892         $img_width = $1;
3893         $img_height = $2;
3894       } else {
3895         error "argument to \"--size\" must be of the form \"640x400\"";
3896       }
3897     } elsif (m/^--?(http-)?proxy$/s) {
3898       $http_proxy = shift @ARGV;
3899     } elsif (m/^--?dict(ionary)?$/s) {
3900       $dict = shift @ARGV;
3901     } elsif (m/^--?opacity$/s) {
3902       $opacity = shift @ARGV;
3903       error ("opacity must be between 0.0 and 1.0")
3904         if ($opacity <= 0 || $opacity > 1);
3905     } elsif (m/^--?driftnet$/s) {
3906       @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3907       if (! ($ARGV[0] =~ m/^-/)) {
3908         $driftnet_cmd = shift @ARGV;
3909       } else {
3910         $driftnet_cmd = $default_driftnet_cmd;
3911       }
3912     } elsif (m/^--?dir(ectory)?$/s) {
3913       @search_methods = ( 100, "local", \&pick_from_local_dir );
3914       if (! ($ARGV[0] =~ m/^-/)) {
3915         $local_dir = shift @ARGV;
3916       } else {
3917         error ("local directory path must be set")
3918       }
3919     } elsif (m/^--?fps$/s) {
3920       # -fps only works on MacOS, via "webcollage-cocoa.m".
3921       # Ignore it if passed to this script in an X11 context.
3922     } elsif (m/^--?debug$/s) {
3923       my $which = shift @ARGV;
3924       my @rest = @search_methods;
3925       my $ok = 0;
3926       while (@rest) {
3927         my $pct  = shift @rest;
3928         my $name = shift @rest;
3929         my $tfn  = shift @rest;
3930
3931         if ($name eq $which) {
3932           @search_methods = (100, $name, $tfn);
3933           $ok = 1;
3934           last;
3935         }
3936       }
3937       error "no such search method as \"$which\"" unless ($ok);
3938       LOG (1, "DEBUG: using only \"$which\"");
3939       $report_performance_interval = 30;
3940
3941     } else {
3942       print STDERR "unknown option: $_\n\n";
3943       print STDERR "$copyright\nusage: $progname " .
3944               "[--root] [--display dpy] [--verbose] [--debug which]\n" .
3945         "\t\t  [--timeout secs] [--delay secs] [--size WxH]\n" .
3946         "\t\t  [--no-output] [--urls-only] [--imagemap filename]\n" .
3947         "\t\t  [--background color] [--opacity f]\n" .
3948         "\t\t  [--filter cmd] [--filter2 cmd]\n" .
3949         "\t\t  [--dictionary dictionary-file] [--http-proxy host[:port]]\n" .
3950         "\t\t  [--driftnet [driftnet-program-and-args]]\n" .
3951         "\t\t  [--directory local-image-directory]\n" .
3952         "\n";
3953       exit 1;
3954     }
3955   }
3956
3957   if (!$root_p && !$no_output_p && !$cocoa_p) {
3958     print STDERR $copyright;
3959     error "the --root argument is mandatory (for now.)";
3960   }
3961
3962   if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3963     error "\$DISPLAY is not set.";
3964   }
3965
3966
3967   if ($verbose == 1) {
3968     $verbose_imgmap   = 1;
3969     $verbose_warnings = 1;
3970
3971   } elsif ($verbose == 2) {
3972     $verbose_imgmap   = 1;
3973     $verbose_warnings = 1;
3974     $verbose_load     = 1;
3975
3976   } elsif ($verbose == 3) {
3977     $verbose_imgmap   = 1;
3978     $verbose_warnings = 1;
3979     $verbose_load     = 1;
3980     $verbose_filter   = 1;
3981
3982   } elsif ($verbose == 4) {
3983     $verbose_imgmap   = 1;
3984     $verbose_warnings = 1;
3985     $verbose_load     = 1;
3986     $verbose_filter   = 1;
3987     $verbose_net      = 1;
3988
3989   } elsif ($verbose == 5) {
3990     $verbose_imgmap   = 1;
3991     $verbose_warnings = 1;
3992     $verbose_load     = 1;
3993     $verbose_filter   = 1;
3994     $verbose_net      = 1;
3995     $verbose_pbm      = 1;
3996
3997   } elsif ($verbose == 6) {
3998     $verbose_imgmap   = 1;
3999     $verbose_warnings = 1;
4000     $verbose_load     = 1;
4001     $verbose_filter   = 1;
4002     $verbose_net      = 1;
4003     $verbose_pbm      = 1;
4004     $verbose_http     = 1;
4005
4006   } elsif ($verbose >= 7) {
4007     $verbose_imgmap   = 1;
4008     $verbose_warnings = 1;
4009     $verbose_load     = 1;
4010     $verbose_filter   = 1;
4011     $verbose_net      = 1;
4012     $verbose_pbm      = 1;
4013     $verbose_http     = 1;
4014     $verbose_exec     = 1;
4015   }
4016
4017   if ($dict) {
4018     error ("$dict does not exist") unless (-f $dict);
4019     $wordlist = $dict;
4020   } else {
4021     pick_dictionary();
4022   }
4023
4024   if ($imagemap_base && !($img_width && $img_height)) {
4025     error ("--size WxH is required with --imagemap");
4026   }
4027
4028   if (defined ($local_dir)) {
4029     $_ = "xscreensaver-getimage-file";
4030     which ($_) || error "$_ not found on \$PATH.";
4031   }
4032
4033   init_signals();
4034   set_proxy();
4035
4036   spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
4037
4038   if ($urls_only_p) {
4039     url_only_output ();
4040   } else {
4041     x_or_pbm_output ($window_id);
4042   }
4043 }
4044
4045 main();
4046 exit (0);