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