From http://www.jwz.org/xscreensaver/xscreensaver-5.29.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.165 $' =~ 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?q=";
1498
1499
1500 # bingimgs
1501 sub pick_from_bing_images($;$$) {
1502   my ($timeout, $words, $max_page) = @_;
1503
1504   if (!defined($words)) {
1505     $words = random_word();   # only one word for Bing
1506   }
1507
1508   my $off = int(rand(300));
1509   my $search_url = $bing_images_url . $words . "&first=" . $off;
1510
1511   my ($search_hit_count, @subpages) =
1512     pick_from_search_engine ($timeout, $search_url, $words);
1513
1514   my @candidates = ();
1515   my %referers;
1516   foreach my $u (@subpages) {
1517     my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1518     next unless $img;
1519     LOG ($verbose_filter, "  candidate: $ref");
1520     push @candidates, $img;
1521     $referers{$img} = $ref;
1522   }
1523
1524   @candidates = depoison (@candidates);
1525   return () if ($#candidates < 0);
1526   my $i = int(rand($#candidates+1));
1527   my $img = $candidates[$i];
1528   my $ref = $referers{$img};
1529
1530   LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1531   return ($ref, $img);
1532 }
1533
1534
1535
1536 \f
1537 ############################################################################
1538 #
1539 # Pick images by feeding random numbers into Bing Image Search.
1540 #
1541 ############################################################################
1542
1543 # bingnums
1544 sub pick_from_bing_image_numbers($) {
1545   my ($timeout) = @_;
1546
1547   my $max = 9999;
1548   my $number = int(rand($max));
1549
1550   $number = sprintf("%04d", $number)
1551     if (rand() < 0.3);
1552
1553   pick_from_bing_images ($timeout, "$number");
1554 }
1555
1556 \f
1557 ############################################################################
1558 #
1559 # Pick images by feeding random numbers into Bing Image Search.
1560 #
1561 ############################################################################
1562
1563 # bingphotos
1564 sub pick_from_bing_image_photos($) {
1565   my ($timeout) = @_;
1566
1567   my $i = int(rand($#photomakers + 1));
1568   my $fn = $photomakers[$i];
1569   my $file = &$fn;
1570
1571   pick_from_bing_images ($timeout, $file);
1572 }
1573
1574 \f
1575 ############################################################################
1576 #
1577 # Pick images by feeding random words into Alta Vista Text Search
1578 #
1579 ############################################################################
1580
1581
1582 my $alta_vista_url = "http://www.altavista.com/web/results" .
1583                      "?pg=aq" .
1584                      "&aqmode=s" .
1585                      "&filetype=html" .
1586                      "&sc=on" .        # "site collapse"
1587                      "&nbq=50" .
1588                      "&aqo=";
1589
1590 # avtext
1591 sub pick_from_alta_vista_text($) {
1592   my ($timeout) = @_;
1593
1594   my $words = random_words('%20');
1595   my $page = (int(rand(9)) + 1);
1596   my $search_url = $alta_vista_url . $words;
1597
1598   if ($page > 1) {
1599     $search_url .= "&pgno=" . $page;
1600     $search_url .= "&stq=" . (($page-1) * 10);
1601   }
1602
1603   my ($search_hit_count, @subpages) =
1604     pick_from_search_engine ($timeout, $search_url, $words);
1605
1606   my @candidates = ();
1607   foreach my $u (@subpages) {
1608
1609     # Those altavista fuckers are playing really nasty redirection games
1610     # these days: the filter your clicks through their site, but use
1611     # onMouseOver to make it look like they're not!  Well, it makes it
1612     # easier for us to identify search results...
1613     #
1614     next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1615     $u = url_unquote($u);
1616
1617     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1618     next if ($u =~ m@[/.]altavista\.com\b@i);     # skip altavista builtins
1619     next if ($u =~ m@[/.]yahoo\.com\b@i);         # yahoo and av in cahoots?
1620
1621     LOG ($verbose_filter, "  candidate: $u");
1622     push @candidates, $u;
1623   }
1624
1625   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1626                                 $timeout, @candidates);
1627 }
1628
1629
1630 \f
1631 ############################################################################
1632 #
1633 # Pick images by feeding random words into Hotbot
1634 #
1635 ############################################################################
1636
1637 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1638                         "?ca=w" .
1639                         "&descriptiontype=0" .
1640                         "&imagetoggle=1" .
1641                         "&matchmode=any" .
1642                         "&nummod=2" .
1643                         "&recordcount=50" .
1644                         "&sitegroup=1" .
1645                         "&stem=1" .
1646                         "&cobrand=undefined" .
1647                         "&query=");
1648
1649 sub pick_from_hotbot_text($) {
1650   my ($timeout) = @_;
1651
1652   $last_search = $hotbot_search_url;   # for warnings
1653
1654   # lycos seems to always give us back dictionaries and word lists if
1655   # we search for more than one word...
1656   #
1657   my $words = random_word();
1658
1659   my $start = int(rand(8)) * 10 + 1;
1660   my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1661
1662   my ($search_hit_count, @subpages) =
1663     pick_from_search_engine ($timeout, $search_url, $words);
1664
1665   my @candidates = ();
1666   foreach my $u (@subpages) {
1667
1668     # Hotbot plays redirection games too
1669     # (not any more?)
1670 #    next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1671 #    $u = url_decode($1);
1672
1673     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1674     next if ($u =~ m@[/.]hotbot\.com\b@i);     # skip hotbot builtins
1675     next if ($u =~ m@[/.]lycos\.com\b@i);      # skip hotbot builtins
1676     next if ($u =~ m@[/.]inktomi\.com\b@i);    # skip hotbot builtins
1677
1678     LOG ($verbose_filter, "  candidate: $u");
1679     push @candidates, $u;
1680   }
1681
1682   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1683                                 $timeout, @candidates);
1684 }
1685
1686
1687 \f
1688 ############################################################################
1689 #
1690 # Pick images by feeding random words into Lycos
1691 #
1692 ############################################################################
1693
1694 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1695                        "?lpv=1" .
1696                        "&loc=searchhp" .
1697                        "&tab=web" .
1698                        "&query=";
1699
1700 sub pick_from_lycos_text($) {
1701   my ($timeout) = @_;
1702
1703   $last_search = $lycos_search_url;   # for warnings
1704
1705   # lycos seems to always give us back dictionaries and word lists if
1706   # we search for more than one word...
1707   #
1708   my $words = random_word();
1709
1710   my $start = int(rand(8)) * 10 + 1;
1711   my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1712
1713   my ($search_hit_count, @subpages) =
1714     pick_from_search_engine ($timeout, $search_url, $words);
1715
1716   my @candidates = ();
1717   foreach my $u (@subpages) {
1718
1719     # Lycos plays redirection games.
1720     # (not any more?)
1721 #    next unless ($u =~ m@^http://click.lycos.com/director.asp
1722 #                         .*
1723 #                         \btarget=([^&]+)
1724 #                         .*
1725 #                        @x);
1726 #    $u = url_decode($1);
1727
1728     next unless ($u =~ m@^http://@i);    #  skip non-HTTP or relative URLs
1729     next if ($u =~ m@[/.]hotbot\.com\b@i);     # skip lycos builtins
1730     next if ($u =~ m@[/.]lycos\.com\b@i);      # skip lycos builtins
1731     next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1732     next if ($u =~ m@[/.]inktomi\.com\b@i);    # skip lycos builtins
1733
1734
1735     LOG ($verbose_filter, "  candidate: $u");
1736     push @candidates, $u;
1737   }
1738
1739   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1740                                 $timeout, @candidates);
1741 }
1742
1743
1744 \f
1745 ############################################################################
1746 #
1747 # Pick images by feeding random words into news.yahoo.com
1748 #
1749 ############################################################################
1750
1751 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1752                      "?c=news_photos" .
1753                      "&p=";
1754
1755 # yahoonews
1756 sub pick_from_yahoo_news_text($) {
1757   my ($timeout) = @_;
1758
1759   $last_search = $yahoo_news_url;   # for warnings
1760
1761   my $words = random_word();
1762   my $search_url = $yahoo_news_url . $words;
1763
1764   my ($search_hit_count, @subpages) =
1765     pick_from_search_engine ($timeout, $search_url, $words);
1766
1767   my @candidates = ();
1768   foreach my $u (@subpages) {
1769
1770     # de-redirectize the URLs
1771     $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1772
1773     # only accept URLs on Yahoo's news site
1774     next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1775                  $u =~ m@^http://story\.news\.yahoo\.com/@i);
1776     next unless ($u =~ m@&u=/@);
1777
1778     LOG ($verbose_filter, "  candidate: $u");
1779     push @candidates, $u;
1780   }
1781
1782   return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1783                                 $timeout, @candidates);
1784 }
1785
1786
1787 \f
1788 ############################################################################
1789 #
1790 # Pick images from LiveJournal's list of recently-posted images.
1791 #
1792 ############################################################################
1793
1794 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1795
1796 # With most of our image sources, we get a random page and then select
1797 # from the images on it.  However, in the case of LiveJournal, the page
1798 # of images tends to update slowly; so we'll remember the last N entries
1799 # on it and randomly select from those, to get a wider variety each time.
1800
1801 my $lj_cache_size = 1000;
1802 my @lj_cache = (); # fifo, for ordering by age
1803 my %lj_cache = (); # hash, for detecting dups
1804
1805 # livejournal
1806 sub pick_from_livejournal_images($) {
1807   my ($timeout) = @_;
1808
1809   $last_search = $livejournal_img_url;   # for warnings
1810
1811   my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1812   return () unless $body;
1813
1814   $body =~ s/\n/ /gs;
1815   $body =~ s/(<recent-image)\b/\n$1/gsi;
1816
1817   foreach (split (/\n/, $body)) {
1818     next unless (m/^<recent-image\b/);
1819     next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1820     my $img = html_unquote ($1);
1821
1822     next if ($lj_cache{$img}); # already have it
1823
1824     next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1825     my $page = html_unquote ($1);
1826     my @pair = ($img, $page);
1827     LOG ($verbose_filter, "  candidate: $img");
1828     push @lj_cache, \@pair;
1829     $lj_cache{$img} = \@pair;
1830   }
1831
1832   return () if ($#lj_cache == -1);
1833
1834   my $n = $#lj_cache+1;
1835   my $i = int(rand($n));
1836   my ($img, $page) = @{$lj_cache[$i]};
1837
1838   # delete this one from @lj_cache and from %lj_cache.
1839   #
1840   @lj_cache = ( @lj_cache[0 .. $i-1],
1841                 @lj_cache[$i+1 .. $#lj_cache] );
1842   delete $lj_cache{$img};
1843
1844   # Keep the size of the cache under the limit by nuking older entries
1845   #
1846   while ($#lj_cache >= $lj_cache_size) {
1847     my $pairP = shift @lj_cache;
1848     my $img = $pairP->[0];
1849     delete $lj_cache{$img};
1850   }
1851
1852   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1853
1854   return ($page, $img);
1855 }
1856
1857 \f
1858 ############################################################################
1859 #
1860 # Pick images from ircimages.com (images that have been in the /topic of
1861 # various IRC channels.)
1862 #
1863 ############################################################################
1864
1865 my $ircimages_url = "http://ircimages.com/";
1866
1867 # ircimages
1868 sub pick_from_ircimages($) {
1869   my ($timeout) = @_;
1870
1871   $last_search = $ircimages_url;   # for warnings
1872
1873   my $n = int(rand(2900));
1874   my $search_url = $ircimages_url . "page-$n";
1875
1876   my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1877   return () unless $body;
1878
1879   my @candidates = ();
1880
1881   $body =~ s/\n/ /gs;
1882   $body =~ s/(<A)\b/\n$1/gsi;
1883
1884   foreach (split (/\n/, $body)) {
1885
1886     my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1887     next unless $u;
1888
1889     if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; }   # quoted string
1890     elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; }  # or token
1891
1892     next unless ($u =~ m/^http:/i);
1893     next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1894     next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1895
1896     LOG ($verbose_http, "    HREF: $u");
1897     push @candidates, $u;
1898   }
1899
1900   LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1901
1902   return () if ($#candidates == -1);
1903
1904   my $i = int(rand($#candidates+1));
1905   my $img = $candidates[$i];
1906
1907   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1908        ": $img");
1909
1910   $search_url = $img;  # hmm...
1911   return ($search_url, $img);
1912 }
1913
1914 \f
1915 ############################################################################
1916 #
1917 # Pick images from Twitpic's list of recently-posted images.
1918 #
1919 ############################################################################
1920
1921 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1922
1923 # With most of our image sources, we get a random page and then select
1924 # from the images on it.  However, in the case of Twitpic, the page
1925 # of images tends to update slowly; so we'll remember the last N entries
1926 # on it and randomly select from those, to get a wider variety each time.
1927
1928 my $twitpic_cache_size = 1000;
1929 my @twitpic_cache = (); # fifo, for ordering by age
1930 my %twitpic_cache = (); # hash, for detecting dups
1931
1932 # twitpic
1933 sub pick_from_twitpic_images($) {
1934   my ($timeout) = @_;
1935
1936   $last_search = $twitpic_img_url;   # for warnings
1937
1938   my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1939
1940   # Update the cache.
1941
1942   if ($body) {
1943     $body =~ s/\n/ /gs;
1944     $body =~ s/(<item)\b/\n$1/gsi;
1945
1946     my @items = split (/\n/, $body);
1947     shift @items;
1948     foreach (@items) {
1949       next unless (m@<link>([^<>]*)</link>@si);
1950       my $page = html_unquote ($1);
1951
1952       $page =~ s@/$@@s;
1953       $page .= '/full';
1954
1955       next if ($twitpic_cache{$page}); # already have it
1956
1957       LOG ($verbose_filter, "  candidate: $page");
1958       push @twitpic_cache, $page;
1959       $twitpic_cache{$page} = $page;
1960     }
1961   }
1962
1963   # Pull from the cache.
1964
1965   return () if ($#twitpic_cache == -1);
1966
1967   my $n = $#twitpic_cache+1;
1968   my $i = int(rand($n));
1969   my $page = $twitpic_cache[$i];
1970
1971   # delete this one from @twitpic_cache and from %twitpic_cache.
1972   #
1973   @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1974                      @twitpic_cache[$i+1 .. $#twitpic_cache] );
1975   delete $twitpic_cache{$page};
1976
1977   # Keep the size of the cache under the limit by nuking older entries
1978   #
1979   while ($#twitpic_cache >= $twitpic_cache_size) {
1980     my $page = shift @twitpic_cache;
1981     delete $twitpic_cache{$page};
1982   }
1983
1984   ( $base, $body ) = get_document ($page, undef, $timeout);
1985   my $img = undef;
1986   $body = '' unless defined($body);
1987
1988   foreach (split (/<img\s+/, $body)) {
1989     my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1990     next unless $src;
1991     next if m@/js/@s;
1992     next if m@/images/@s;
1993
1994     $img = $src;
1995
1996     $img = "http:$img" if ($img =~ m@^//@s);  # Oh come on
1997
1998     # Sometimes these images are hosted on twitpic, sometimes on Amazon.
1999     if ($img =~ m@^/@) {
2000       $base =~ s@^(https?://[^/]+)/.*@$1@s;
2001       $img = $base . $img;
2002     }
2003     last;
2004   }
2005
2006   if (!$img) {
2007     LOG ($verbose_load, "no matching images on $page\n");
2008     return ();
2009   }
2010
2011   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2012
2013   return ($page, $img);
2014 }
2015
2016 \f
2017 ############################################################################
2018 #
2019 # Pick images from Twitter's list of recently-posted updates.
2020 #
2021 ############################################################################
2022
2023 # With most of our image sources, we get a random page and then select
2024 # from the images on it.  However, in the case of Twitter, the page
2025 # of images only updates once a minute; so we'll remember the last N entries
2026 # on it and randomly select from those, to get a wider variety each time.
2027
2028 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2029                       "public_timeline.json" .
2030                       "?include_entities=true" .
2031                       "&include_rts=true" .
2032                       "&count=200";
2033
2034 my $twitter_cache_size = 1000;
2035
2036 my @twitter_cache = (); # fifo, for ordering by age
2037 my %twitter_cache = (); # hash, for detecting dups
2038
2039
2040 # twitter
2041 sub pick_from_twitter_images($) {
2042   my ($timeout) = @_;
2043
2044   $last_search = $twitter_img_url;   # for warnings
2045
2046   my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2047   # Update the cache.
2048
2049   if ($body) {
2050     $body =~ s/[\r\n]+/ /gs;
2051
2052     # Parsing JSON is a pain in the ass.  So we halfass it as usual.
2053     $body =~ s/^\[|\]$//s;
2054     $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2055     my @items = split (/},{/, $body);
2056     foreach (@items) {
2057       my ($name) = m@"screen_name":"([^\"]+)"@si;
2058       my ($img)  = m@"media_url":"([^\"]+)"@si;
2059       my ($page) = m@"display_url":"([^\"]+)"@si;
2060       next unless ($name && $img && $page);
2061       foreach ($img, $page) {
2062         s/\\//gs;
2063         $_ = "http://$_" unless (m/^http/si);
2064       }
2065
2066       next if ($twitter_cache{$page}); # already have it
2067
2068       LOG ($verbose_filter, "  candidate: $page - $img");
2069       push @twitter_cache, $page;
2070       $twitter_cache{$page} = $img;
2071     }
2072   }
2073
2074   # Pull from the cache.
2075
2076   return () if ($#twitter_cache == -1);
2077
2078   my $n = $#twitter_cache+1;
2079   my $i = int(rand($n));
2080   my $page = $twitter_cache[$i];
2081   my $url  = $twitter_cache{$page};
2082
2083   # delete this one from @twitter_cache and from %twitter_cache.
2084   #
2085   @twitter_cache = ( @twitter_cache[0 .. $i-1],
2086                      @twitter_cache[$i+1 .. $#twitter_cache] );
2087   delete $twitter_cache{$page};
2088
2089   # Keep the size of the cache under the limit by nuking older entries
2090   #
2091   while ($#twitter_cache >= $twitter_cache_size) {
2092     my $page = shift @twitter_cache;
2093     delete $twitter_cache{$page};
2094   }
2095
2096   LOG ($verbose_load, "picked page $url");
2097
2098   $suppress_audit = 1;
2099
2100   return ($page, $url);
2101 }
2102
2103 \f
2104 ############################################################################
2105 #
2106 # Pick images from Flickr's page of recently-posted photos.
2107 #
2108 ############################################################################
2109
2110 my $flickr_img_url = "http://www.flickr.com/explore/";
2111
2112 # Like LiveJournal, the Flickr page of images tends to update slowly,
2113 # so remember the last N entries on it and randomly select from those.
2114
2115 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2116 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2117
2118 my $flickr_cache_size = 1000;
2119 my @flickr_cache = (); # fifo, for ordering by age
2120 my %flickr_cache = (); # hash, for detecting dups
2121
2122
2123 # flickr_recent
2124 sub pick_from_flickr_recent($) {
2125   my ($timeout) = @_;
2126
2127   my $start = 16 * int(rand(100));
2128
2129   $last_search = $flickr_img_url;   # for warnings
2130   $last_search .= "?start=$start" if ($start > 0);
2131
2132   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2133   return () unless $body;
2134
2135   $body =~ s/[\r\n]/ /gs;
2136   $body =~ s/(<a)\b/\n$1/gsi;
2137
2138   my $count = 0;
2139   my $count2 = 0;
2140   foreach (split (/\n/, $body)) {
2141
2142     my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2143                            <IMG \s [^<>]* \b
2144                                 data-defer-src = \"([^<>\"]+)\" @xsi;
2145     next unless defined ($thumb);
2146     $page = html_unquote ($page);
2147     $thumb = html_unquote ($thumb);
2148
2149     next unless ($thumb =~ m@^https?://[^/.]+\d*\.static\.?flickr\.com/@);
2150
2151     my $base = "http://www.flickr.com/";
2152     $page  =~ s@^/@$base@;
2153     $thumb =~ s@^/@$base@;
2154
2155     my $img = $thumb;
2156     $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si;  # take off "thumb" suffix
2157
2158     $count++;
2159     next if ($flickr_cache{$img}); # already have it
2160
2161     my @pair = ($img, $page, $start);
2162     LOG ($verbose_filter, "  candidate: $img");
2163     push @flickr_cache, \@pair;
2164     $flickr_cache{$img} = \@pair;
2165     $count2++;
2166   }
2167
2168   return () if ($#flickr_cache == -1);
2169
2170   my $n = $#flickr_cache+1;
2171   my $i = int(rand($n));
2172   my ($img, $page) = @{$flickr_cache[$i]};
2173
2174   # delete this one from @flickr_cache and from %flickr_cache.
2175   #
2176   @flickr_cache = ( @flickr_cache[0 .. $i-1],
2177                     @flickr_cache[$i+1 .. $#flickr_cache] );
2178   delete $flickr_cache{$img};
2179
2180   # Keep the size of the cache under the limit by nuking older entries
2181   #
2182   while ($#flickr_cache >= $flickr_cache_size) {
2183     my $pairP = shift @flickr_cache;
2184     my $img = $pairP->[0];
2185     delete $flickr_cache{$img};
2186   }
2187
2188   LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2189
2190   return ($page, $img);
2191 }
2192
2193 \f
2194 ############################################################################
2195 #
2196 # Pick images from a random RSS feed on Flickr.
2197 #
2198 ############################################################################
2199
2200 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2201                        "?format=rss_200_enc&tagmode=any&tags=");
2202
2203 # Picks a random RSS feed; picks a random image from that feed;
2204 # returns 2 URLs: the page containing the image, and the image.
2205 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2206 #
2207 # flickr_random
2208 sub pick_from_flickr_random($) {
2209   my $timeout = shift;
2210
2211   my $words = random_words(',');
2212   my $rss = $flickr_rss_base . $words;
2213   $last_search = $rss;
2214
2215   $_ = $words;
2216   s/,/ /g;
2217
2218   print STDERR "\n\n" if ($verbose_load);
2219   LOG ($verbose_load, "words: $_");
2220   LOG ($verbose_load, "URL: $last_search");
2221
2222   $suppress_audit = 1;
2223
2224   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2225   if (!$base || !$body) {
2226     $body = undef;
2227     return;
2228   }
2229
2230   my $img;
2231   ($base, $img) = pick_image_from_rss ($base, $body);
2232   $body = undef;
2233   return () unless defined ($img);
2234
2235   LOG ($verbose_load, "redirected to: $base");
2236   return ($base, $img);
2237 }
2238
2239 \f
2240 ############################################################################
2241 #
2242 # Pick random images from Instagram, via gramfeed.com's key.
2243 #
2244 ############################################################################
2245
2246 my $instagram_url_base = "https://api.instagram.com/v1/media/popular" .
2247                          "?client_id=b59fbe4563944b6c88cced13495c0f49";
2248
2249 # instagram_random
2250 sub pick_from_instagram($) {
2251   my $timeout = shift;
2252
2253   $last_search = $instagram_url_base;
2254
2255   print STDERR "\n\n" if ($verbose_load);
2256   LOG ($verbose_load, "URL: $last_search");
2257
2258   my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2259   if (!$base || !$body) {
2260     $body = undef;
2261     return;
2262   }
2263
2264   $body =~ s/("link")/\001$1/gs;
2265   my @chunks = split(/\001/, $body);
2266   shift @chunks;
2267   my @urls = ();
2268   foreach (@chunks) {
2269     s/\\//gs;
2270     my ($url) = m/"link":\s*"(.*?)"/s;
2271     my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2272        ($img) = m/"url":\s*"(.*?)"/s unless $url;
2273     next unless ($url && $img);
2274     push @urls, [ $url, $img ];
2275   }
2276
2277   if ($#urls < 0) {
2278     LOG ($verbose_load, "no images on $last_search");
2279     return ();
2280   }
2281
2282   my $i = int(rand($#urls+1));
2283   my ($url, $img) = @{$urls[$i]};
2284
2285   LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2286   return ($url, $img);
2287 }
2288
2289 \f
2290 ############################################################################
2291 #
2292 # Pick images by waiting for driftnet to populate a temp dir with files.
2293 # Requires driftnet version 0.1.5 or later.
2294 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2295 # for images being downloaded by others.)
2296 # Driftnet/webcollage integration by jwz.
2297 #
2298 ############################################################################
2299
2300 # driftnet
2301 sub pick_from_driftnet($) {
2302   my ($timeout) = @_;
2303
2304   my $id = $driftnet_magic;
2305   my $dir = $driftnet_dir;
2306   my $start = time;
2307   my $now;
2308
2309   error ("\$driftnet_dir unset?") unless ($dir);
2310   $dir =~ s@/+$@@;
2311
2312   error ("$dir unreadable") unless (-d "$dir/.");
2313
2314   $timeout = $http_timeout unless ($timeout);
2315   $last_search = $id;
2316
2317   while ($now = time, $now < $start + $timeout) {
2318     opendir (my $dir, $dir) || error ("$dir: $!");
2319     while (my $file = readdir($dir)) {
2320       next if ($file =~ m/^\./);
2321       $file = "$dir/$file";
2322       closedir ($dir);
2323       LOG ($verbose_load, "picked file $file ($id)");
2324       return ($id, $file);
2325     }
2326     closedir ($dir);
2327   }
2328   LOG (($verbose_net || $verbose_load), "timed out for $id");
2329   return ();
2330 }
2331
2332
2333 sub get_driftnet_file($) {
2334   my ($file) = @_;
2335
2336   error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2337
2338   my $id = $driftnet_magic;
2339   error ("$id: $file not in $driftnet_dir?")
2340     unless ($file =~ m@^\Q$driftnet_dir@o);
2341
2342   open (my $in, '<', $file) || error ("$id: $file: $!");
2343   my $body = '';
2344   local $/ = undef;  # read entire file
2345   $body = <$in>;
2346   close ($in) || error ("$id: $file: $!");
2347   unlink ($file) || error ("$id: $file: rm: $!");
2348   return ($id, $body);
2349 }
2350
2351
2352 sub spawn_driftnet($) {
2353   my ($cmd) = @_;
2354
2355   # make a directory to use.
2356   while (1) {
2357     my $tmp = $ENV{TEMPDIR} || "/tmp";
2358     $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2359     LOG ($verbose_exec, "mkdir $driftnet_dir");
2360     last if mkdir ($driftnet_dir, 0700);
2361   }
2362
2363   if (! ($cmd =~ m/\s/)) {
2364     # if the command didn't have any arguments in it, then it must be just
2365     # a pointer to the executable.  Append the default args to it.
2366     my $dargs = $default_driftnet_cmd;
2367     $dargs =~ s/^[^\s]+//;
2368     $cmd .= $dargs;
2369   }
2370
2371   # point the driftnet command at our newly-minted private directory.
2372   #
2373   $cmd .= " -d $driftnet_dir";
2374   $cmd .= ">/dev/null" unless ($verbose_exec);
2375
2376   my $pid = fork();
2377   if ($pid < 0) { error ("fork: $!\n"); }
2378   if ($pid) {
2379     # parent fork
2380     push @pids_to_kill, $pid;
2381     LOG ($verbose_exec, "forked for \"$cmd\"");
2382   } else {
2383     # child fork
2384     nontrapping_system ($cmd) || error ("exec: $!");
2385   }
2386
2387   # wait a bit, then make sure the process actually started up.
2388   #
2389   sleep (1);
2390   error ("pid $pid failed to start \"$cmd\"")
2391     unless (1 == kill (0, $pid));
2392 }
2393
2394 # local-directory
2395 sub pick_from_local_dir($) {
2396   my ($timeout) = @_;
2397
2398   my $id = $local_magic;
2399   $last_search = $id;
2400
2401   my $dir = $local_dir;
2402   error ("\$local_dir unset?") unless ($dir);
2403   $dir =~ s@/+$@@;
2404
2405   error ("$dir unreadable") unless (-d "$dir/.");
2406
2407   my $v = ($verbose_exec ? "-v" : "");
2408   my $pick = `xscreensaver-getimage-file $v "$dir"`;
2409   $pick =~ s/\s+$//s;
2410   $pick = "$dir/$pick" unless ($pick =~ m@^/@s);       # relative path
2411
2412   LOG ($verbose_load, "picked file $pick ($id)");
2413   return ($id, $pick);
2414 }
2415
2416
2417 sub get_local_file($) {
2418   my ($file) = @_;
2419
2420   error ("\$local_dir unset?") unless ($local_dir);
2421
2422   my $id = $local_magic;
2423   error ("$id: $file not in $local_dir?")
2424     unless ($file =~ m@^\Q$local_dir@o);
2425
2426   open (my $in, '<', $file) || error ("$id: $file: $!");
2427   local $/ = undef;  # read entire file
2428   my $body = <$in>;
2429   close ($in) || error ("$id: $file: $!");
2430   return ($id, $body);
2431 }
2432
2433
2434 \f
2435 ############################################################################
2436 #
2437 # Pick a random image in a random way
2438 #
2439 ############################################################################
2440
2441
2442 # Picks a random image on a random page, and returns two URLs:
2443 # the page containing the image, and the image.
2444 # Returns () if nothing found this time.
2445 #
2446
2447 sub pick_image(;$) {
2448   my ($timeout) = @_;
2449
2450   $current_state = "select";
2451   $load_method = "none";
2452
2453   my $n = int(rand(100));
2454   my $fn = undef;
2455   my $total = 0;
2456   my @rest = @search_methods;
2457
2458   while (@rest) {
2459     my $pct  = shift @rest;
2460     my $name = shift @rest;
2461     my $tfn  = shift @rest;
2462     $total += $pct;
2463     if ($total > $n && !defined($fn)) {
2464       $fn = $tfn;
2465       $current_state = $name;
2466       $load_method = $current_state;
2467     }
2468   }
2469
2470   if ($total != 100) {
2471     error ("internal error: \@search_methods totals to $total%!");
2472   }
2473
2474   record_attempt ($current_state);
2475   return $fn->($timeout);
2476 }
2477
2478
2479 \f
2480 ############################################################################
2481 #
2482 # Statistics and logging
2483 #
2484 ############################################################################
2485
2486 sub timestr() {
2487   return strftime ("%H:%M:%S: ", localtime);
2488 }
2489
2490 sub blurb() {
2491   return "$progname: " . timestr() . "$current_state: ";
2492 }
2493
2494 sub error($) {
2495   my ($err) = @_;
2496   print STDERR blurb() . "$err\n";
2497   exit 1;
2498 }
2499
2500 sub stacktrace() {
2501   my $i = 1;
2502   print STDERR "$progname: stack trace:\n";
2503   while (1) {
2504     my ($package, $filename, $line, $subroutine) = caller($i++);
2505     last unless defined($package);
2506     $filename =~ s@^.*/@@;
2507     print STDERR "  $filename#$line, $subroutine\n";
2508   }
2509 }
2510
2511
2512 my $lastlog = "";
2513
2514 sub clearlog() {
2515   $lastlog = "";
2516 }
2517
2518 sub showlog() {
2519   my $head = "$progname: DEBUG: ";
2520   foreach (split (/\n/, $lastlog)) {
2521     print STDERR "$head$_\n";
2522   }
2523   $lastlog = "";
2524 }
2525
2526 sub LOG($$) {
2527   my ($print, $msg) = @_;
2528   my $blurb = timestr() . "$current_state: ";
2529   $lastlog .= "$blurb$msg\n";
2530   print STDERR "$progname: $blurb$msg\n" if $print;
2531 }
2532
2533
2534 my %stats_attempts;
2535 my %stats_successes;
2536 my %stats_elapsed;
2537
2538 my $last_state = undef;
2539 sub record_attempt($) {
2540   my ($name) = @_;
2541
2542   if ($last_state) {
2543     record_failure($last_state) unless ($image_succeeded > 0);
2544   }
2545   $last_state = $name;
2546
2547   clearlog();
2548   report_performance();
2549
2550   start_timer($name);
2551   $image_succeeded = 0;
2552   $suppress_audit = 0;
2553 }
2554
2555 sub record_success($$$) {
2556   my ($name, $url, $base) = @_;
2557   if (defined($stats_successes{$name})) {
2558     $stats_successes{$name}++;
2559   } else {
2560     $stats_successes{$name} = 1;
2561   }
2562
2563   stop_timer ($name, 1);
2564   my $o = $current_state;
2565   $current_state = $name;
2566   save_recent_url ($url, $base);
2567   $current_state = $o;
2568   $image_succeeded = 1;
2569   clearlog();
2570 }
2571
2572
2573 sub record_failure($) {
2574   my ($name) = @_;
2575
2576   return if $image_succeeded;
2577
2578   stop_timer ($name, 0);
2579   if ($verbose_load && !$verbose_exec) {
2580
2581     if ($suppress_audit) {
2582       print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2583       return;
2584     }
2585
2586     my $o = $current_state;
2587     $current_state = "DEBUG";
2588
2589     my $line =  "#" x 78;
2590     print STDERR "\n\n\n";
2591     print STDERR ("#" x 78) . "\n";
2592     print STDERR blurb() . "failed to get an image.  Full audit log:\n";
2593     print STDERR "\n";
2594     showlog();
2595     print STDERR ("-" x 78) . "\n";
2596     print STDERR "\n\n";
2597
2598     $current_state = $o;
2599   }
2600   $image_succeeded = 0;
2601 }
2602
2603
2604
2605 sub stats_of($) {
2606   my ($name) = @_;
2607   my $i = $stats_successes{$name};
2608   my $j = $stats_attempts{$name};
2609   $i = 0 unless $i;
2610   $j = 0 unless $j;
2611   return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2612 }
2613
2614
2615 my $current_start_time = 0;
2616
2617 sub start_timer($) {
2618   my ($name) = @_;
2619   $current_start_time = time;
2620
2621   if (defined($stats_attempts{$name})) {
2622     $stats_attempts{$name}++;
2623   } else {
2624     $stats_attempts{$name} = 1;
2625   }
2626   if (!defined($stats_elapsed{$name})) {
2627     $stats_elapsed{$name} = 0;
2628   }
2629 }
2630
2631 sub stop_timer($$) {
2632   my ($name, $success) = @_;
2633   $stats_elapsed{$name} += time - $current_start_time;
2634 }
2635
2636
2637 my $last_report_time = 0;
2638 sub report_performance() {
2639
2640   return unless $verbose_warnings;
2641
2642   my $now = time;
2643   return unless ($now >= $last_report_time + $report_performance_interval);
2644   my $ot = $last_report_time;
2645   $last_report_time = $now;
2646
2647   return if ($ot == 0);
2648
2649   my $blurb = "$progname: " . timestr();
2650
2651   print STDERR "\n";
2652   print STDERR "${blurb}Current standings:\n";
2653
2654   foreach my $name (sort keys (%stats_attempts)) {
2655     my $try = $stats_attempts{$name};
2656     my $suc = $stats_successes{$name} || 0;
2657     my $pct = int($suc * 100 / $try);
2658     my $secs = $stats_elapsed{$name};
2659     my $secs_link = $secs / $try;
2660     print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2661                           "       \t %.1f secs/link\n",
2662                           "$name:", "$pct%", $suc, $try, $secs_link);
2663   }
2664 }
2665
2666
2667
2668 my $max_recent_images = 400;
2669 my $max_recent_sites  = 20;
2670 my @recent_images = ();
2671 my @recent_sites = ();
2672
2673 sub save_recent_url($$) {
2674   my ($url, $base) = @_;
2675
2676   return unless ($verbose_warnings);
2677
2678   $_ = $url;
2679   my ($site) = m@^http://([^ \t\n\r/:]+)@;
2680   return unless defined ($site);
2681
2682   if ($base eq $driftnet_magic || $base eq $local_magic) {
2683     $site = $base;
2684     @recent_images = ();
2685   }
2686
2687   my $done = 0;
2688   foreach (@recent_images) {
2689     if ($_ eq $url) {
2690       print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2691         " (on $base via $last_search)\n";
2692       $done = 1;
2693       last;
2694     }
2695   }
2696
2697   # suppress "duplicate site" warning via %warningless_sites.
2698   #
2699   if ($warningless_sites{$site}) {
2700     $done = 1;
2701   } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2702            $warningless_sites{$1}) {
2703     $done = 1;
2704   } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2705            $warningless_sites{$1}) {
2706     $done = 1;
2707   }
2708
2709   if (!$done) {
2710     foreach (@recent_sites) {
2711       if ($_ eq $site) {
2712         print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2713         " ($url on $base via $last_search)\n";
2714         last;
2715       }
2716     }
2717   }
2718
2719   push @recent_images, $url;
2720   push @recent_sites,  $site;
2721   shift @recent_images if ($#recent_images >= $max_recent_images);
2722   shift @recent_sites  if ($#recent_sites  >= $max_recent_sites);
2723 }
2724
2725
2726 \f
2727 ##############################################################################
2728 #
2729 # other utilities
2730 #
2731 ##############################################################################
2732
2733 # Does %-decoding.
2734 #
2735 sub url_decode($) {
2736   ($_) = @_;
2737   tr/+/ /;
2738   s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2739   return $_;
2740 }
2741
2742
2743 # Given the raw body of a GIF document, returns the dimensions of the image.
2744 #
2745 sub gif_size($) {
2746   my ($body) = @_;
2747   my $type = substr($body, 0, 6);
2748   my $s;
2749   return () unless ($type =~ /GIF8[7,9]a/);
2750   $s = substr ($body, 6, 10);
2751   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2752   return () unless defined ($d);
2753   return (($b<<8|$a), ($d<<8|$c));
2754 }
2755
2756 # Given the raw body of a JPEG document, returns the dimensions of the image.
2757 #
2758 sub jpeg_size($) {
2759   my ($body) = @_;
2760   my $i = 0;
2761   my $L = length($body);
2762
2763   my $c1 = substr($body, $i, 1); $i++;
2764   my $c2 = substr($body, $i, 1); $i++;
2765   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2766
2767   my $ch = "0";
2768   while (ord($ch) != 0xDA && $i < $L) {
2769     # Find next marker, beginning with 0xFF.
2770     while (ord($ch) != 0xFF) {
2771       return () if (length($body) <= $i);
2772       $ch = substr($body, $i, 1); $i++;
2773     }
2774     # markers can be padded with any number of 0xFF.
2775     while (ord($ch) == 0xFF) {
2776       return () if (length($body) <= $i);
2777       $ch = substr($body, $i, 1); $i++;
2778     }
2779
2780     # $ch contains the value of the marker.
2781     my $marker = ord($ch);
2782
2783     if (($marker >= 0xC0) &&
2784         ($marker <= 0xCF) &&
2785         ($marker != 0xC4) &&
2786         ($marker != 0xCC)) {  # it's a SOFn marker
2787       $i += 3;
2788       return () if (length($body) <= $i);
2789       my $s = substr($body, $i, 4); $i += 4;
2790       my ($a,$b,$c,$d) = unpack("C"x4, $s);
2791       return (($c<<8|$d), ($a<<8|$b));
2792
2793     } else {
2794       # We must skip variables, since FFs in variable names aren't
2795       # valid JPEG markers.
2796       return () if (length($body) <= $i);
2797       my $s = substr($body, $i, 2); $i += 2;
2798       my ($c1, $c2) = unpack ("C"x2, $s);
2799       my $length = ($c1 << 8) | $c2;
2800       return () if ($length < 2);
2801       $i += $length-2;
2802     }
2803   }
2804   return ();
2805 }
2806
2807 # Given the raw body of a PNG document, returns the dimensions of the image.
2808 #
2809 sub png_size($) {
2810   my ($body) = @_;
2811   return () unless ($body =~ m/^\211PNG\r/);
2812   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2813   return () unless defined ($bits);
2814   return () unless ($bits =~ /^IHDR/);
2815   my ($ign, $w, $h) = unpack("a4N2", $bits);
2816   return ($w, $h);
2817 }
2818
2819
2820 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2821 # of the image.
2822 #
2823 sub image_size($) {
2824   my ($body) = @_;
2825   my ($w, $h) = gif_size ($body);
2826   if ($w && $h) { return ($w, $h); }
2827   ($w, $h) = jpeg_size ($body);
2828   if ($w && $h) { return ($w, $h); }
2829   return png_size ($body);
2830 }
2831
2832
2833 # returns the full path of the named program, or undef.
2834 #
2835 sub which($) {
2836   my ($prog) = @_;
2837   foreach (split (/:/, $ENV{PATH})) {
2838     if (-x "$_/$prog") {
2839       return $prog;
2840     }
2841   }
2842   return undef;
2843 }
2844
2845
2846 # Like rand(), but chooses numbers with a bell curve distribution.
2847 sub bellrand(;$) {
2848   ($_) = @_;
2849   $_ = 1.0 unless defined($_);
2850   $_ /= 3.0;
2851   return (rand($_) + rand($_) + rand($_));
2852 }
2853
2854
2855 sub exit_cleanup() {
2856   x_cleanup();
2857   print STDERR "$progname: exiting\n" if ($verbose_warnings);
2858   if (@pids_to_kill) {
2859     print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2860     kill ('TERM', @pids_to_kill);
2861   }
2862 }
2863
2864 sub signal_cleanup($) {
2865   my ($sig) = @_;
2866   print STDERR blurb() . (defined($sig)
2867                           ? "caught signal $sig."
2868                           : "exiting.")
2869                        . "\n"
2870     if ($verbose_exec || $verbose_warnings);
2871   exit 1;
2872 }
2873
2874
2875
2876 ##############################################################################
2877 #
2878 # Generating a list of urls only
2879 #
2880 ##############################################################################
2881
2882 sub url_only_output() {
2883   do {
2884     my ($base, $img) = pick_image;
2885     if ($img) {
2886       $base =~ s/ /%20/g;
2887       $img  =~ s/ /%20/g;
2888       print "$img $base\n";
2889     }
2890   } while (1);
2891 }
2892
2893 ##############################################################################
2894 #
2895 # Running as an xscreensaver module, or as a web page imagemap
2896 #
2897 ##############################################################################
2898
2899 my $image_ppm   = sprintf ("%s/webcollage-%08x.ppm",
2900                            ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2901                            rand(0xFFFFFFFF));
2902 my $image_tmp1  = sprintf ("%s/webcollage-1-%08x.ppm",
2903                            ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2904                            rand(0xFFFFFFFF));
2905 my $image_tmp2  = sprintf ("%s/webcollage-2-%08x.ppm",
2906                            ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2907                            rand(0xFFFFFFFF));
2908
2909 my $filter_cmd = undef;
2910 my $post_filter_cmd = undef;
2911 my $background = undef;
2912
2913 my @imagemap_areas = ();
2914 my $imagemap_html_tmp = undef;
2915 my $imagemap_jpg_tmp = undef;
2916
2917
2918 my $img_width;            # size of the image being generated.
2919 my $img_height;
2920
2921 my $delay = 2;
2922
2923 sub x_cleanup() {
2924   unlink $image_ppm, $image_tmp1, $image_tmp2;
2925   unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2926     if (defined ($imagemap_html_tmp));
2927 }
2928
2929
2930 # Like system, but prints status about exit codes, and kills this process
2931 # with whatever signal killed the sub-process, if any.
2932 #
2933 sub nontrapping_system(@) {
2934   $! = 0;
2935
2936   $_ = join(" ", @_);
2937   s/\"[^\"]+\"/\"...\"/g;
2938
2939   LOG ($verbose_exec, "executing \"$_\"");
2940
2941   my $rc = system @_;
2942
2943   if ($rc == 0) {
2944     LOG ($verbose_exec, "subproc exited normally.");
2945   } elsif (($rc & 0xff) == 0) {
2946     $rc >>= 8;
2947     LOG ($verbose_exec, "subproc exited with status $rc.");
2948   } else {
2949     if ($rc & 0x80) {
2950       LOG ($verbose_exec, "subproc dumped core.");
2951       $rc &= ~0x80;
2952     }
2953     LOG ($verbose_exec, "subproc died with signal $rc.");
2954     # die that way ourselves.
2955     kill $rc, $$;
2956   }
2957
2958   return $rc;
2959 }
2960
2961
2962 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2963 # writes a PPM to the given output file.  Returns the width/height of the
2964 # image if successful.
2965 #
2966 sub image_to_pnm($$$) {
2967   my ($url, $body, $output) = @_;
2968   my ($cmd, $cmd2, $w, $h);
2969
2970   if ((@_ = gif_size ($body))) {
2971     ($w, $h) = @_;
2972     $cmd = "giftopnm";
2973   } elsif ((@_ = jpeg_size ($body))) {
2974     ($w, $h) = @_;
2975     $cmd = "djpeg";
2976   } elsif ((@_ = png_size ($body))) {
2977     ($w, $h) = @_;
2978     $cmd = "pngtopnm";
2979   } else {
2980     LOG (($verbose_pbm || $verbose_load),
2981          "not a GIF, JPG, or PNG" .
2982          (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2983           ? " (looks like HTML)" : "") .
2984          ": $url");
2985     $suppress_audit = 1;
2986     return ();
2987   }
2988
2989   $cmd2 = "exec $cmd";        # yes, this really is necessary.  if we don't
2990                               # do this, the process doesn't die properly.
2991   if (!$verbose_pbm) {
2992     #
2993     # We get a "giftopnm: got a 'Application Extension' extension"
2994     # warning any time it's an animgif.
2995     #
2996     # Note that "giftopnm: EOF / read error on image data" is not
2997     # always a fatal error -- sometimes the image looks fine anyway.
2998     #
2999     $cmd2 .= " 2>/dev/null";
3000   }
3001
3002   # There exist corrupted GIF and JPEG files that can make giftopnm and
3003   # djpeg lose their minds and go into a loop.  So this gives those programs
3004   # a small timeout -- if they don't complete in time, kill them.
3005   #
3006   my $pid;
3007   @_ = eval {
3008     my $timed_out;
3009
3010     local $SIG{ALRM}  = sub {
3011       LOG ($verbose_pbm,
3012            "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3013       kill ('TERM', $pid) if ($pid);
3014       $timed_out = 1;
3015       $body = undef;
3016     };
3017
3018     if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3019       $timed_out = 0;
3020       alarm $cvt_timeout;
3021       print $pipe $body;
3022       $body = undef;
3023       close $pipe;
3024
3025       LOG ($verbose_exec, "awaiting $pid");
3026       waitpid ($pid, 0);
3027       LOG ($verbose_exec, "$pid completed");
3028
3029       my $size = (stat($output))[7];
3030       $size = -1 unless defined($size);
3031       if ($size < 5) {
3032         LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3033         return ();
3034       }
3035
3036       LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3037       return ($w, $h);
3038     } else {
3039       print STDERR blurb() . "$cmd failed: $!\n";
3040       return ();
3041     }
3042   };
3043   die if ($@ && $@ ne "alarm\n");       # propagate errors
3044   if ($@) {
3045     # timed out
3046     $body = undef;
3047     return ();
3048   } else {
3049     # didn't
3050     alarm 0;
3051     $body = undef;
3052     return @_;
3053   }
3054 }
3055
3056
3057 # Same as the "ppmmake" command: creates a solid-colored PPM.
3058 # Does not understand the rgb.txt color names except "black" and "white".
3059 #
3060 sub ppmmake($$$$) {
3061   my ($outfile, $bgcolor, $w, $h) = @_;
3062
3063   my ($r, $g, $b);
3064   if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3065       $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3066     ($r, $g, $b) = (hex($1), hex($2), hex($3));
3067   } elsif ($bgcolor =~ m/^black$/i) {
3068     ($r, $g, $b) = (0, 0, 0);
3069   } elsif ($bgcolor =~ m/^white$/i) {
3070     ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3071   } else {
3072     error ("unparsable color name: $bgcolor");
3073   }
3074
3075   my $pixel = pack('CCC', $r, $g, $b);
3076   my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3077
3078   open (my $out, '>', $outfile) || error ("$outfile: $!");
3079   print $out $bits;
3080   close $out;
3081 }
3082
3083
3084 sub pick_root_displayer() {
3085   my @names = ();
3086
3087   if ($cocoa_p) {
3088     # see "xscreensaver/hacks/webcollage-cocoa.m"
3089     return "echo COCOA LOAD ";
3090   }
3091
3092   foreach my $cmd (@root_displayers) {
3093     $_ = $cmd;
3094     my ($name) = m/^([^ ]+)/;
3095     push @names, "\"$name\"";
3096     LOG ($verbose_exec, "looking for $name...");
3097     foreach my $dir (split (/:/, $ENV{PATH})) {
3098       LOG ($verbose_exec, "  checking $dir/$name");
3099       return $cmd if (-x "$dir/$name");
3100     }
3101   }
3102
3103   $names[$#names] = "or " . $names[$#names];
3104   error "none of: " . join (", ", @names) . " were found on \$PATH.";
3105 }
3106
3107
3108 my $ppm_to_root_window_cmd = undef;
3109
3110
3111 sub x_or_pbm_output($) {
3112   my ($window_id) = @_;
3113
3114   # Check for our helper program, to see whether we need to use PPM pipelines.
3115   #
3116   $_ = "webcollage-helper";
3117   if (defined ($webcollage_helper) || which ($_)) {
3118     $webcollage_helper = $_ unless (defined($webcollage_helper));
3119     LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3120     $webcollage_helper .= " -v";
3121   } else {
3122     LOG (($verbose_pbm || $verbose_load), "no $_ program");
3123   }
3124
3125   if ($cocoa_p && !defined ($webcollage_helper)) {
3126     error ("webcollage-helper not found in Cocoa-mode!");
3127   }
3128
3129
3130   # make sure the various programs we execute exist, right up front.
3131   #
3132   my @progs = ();
3133
3134   if (!defined($webcollage_helper)) {
3135     # Only need these others if we don't have the helper.
3136     @progs = (@progs,
3137               "giftopnm", "pngtopnm", "djpeg",
3138               "pnmpaste", "pnmscale", "pnmcut");
3139   }
3140
3141   foreach (@progs) {
3142     which ($_) || error "$_ not found on \$PATH.";
3143   }
3144
3145   # find a root-window displayer program.
3146   #
3147   if (!$no_output_p) {
3148     $ppm_to_root_window_cmd = pick_root_displayer();
3149   }
3150
3151   if (defined ($window_id)) {
3152     error ("-window-id only works if xscreensaver-getimage is installed")
3153       unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3154
3155     error ("unparsable window id: $window_id")
3156       unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3157     $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3158       error ("unable to munge displayer: $ppm_to_root_window_cmd");
3159   }
3160
3161   if (!$img_width || !$img_height) {
3162
3163     if (!defined ($window_id) &&
3164         defined ($ENV{XSCREENSAVER_WINDOW})) {
3165       $window_id = $ENV{XSCREENSAVER_WINDOW};
3166     }
3167
3168     if (!defined ($window_id)) {
3169       $_ = "xdpyinfo";
3170       which ($_) || error "$_ not found on \$PATH.";
3171       $_ = `$_`;
3172       ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3173       if (!defined($img_height)) {
3174         error "xdpyinfo failed.";
3175       }
3176     } else {  # we have a window id
3177       $_ = "xwininfo";
3178       which ($_) || error "$_ not found on \$PATH.";
3179       $_ .= " -id $window_id";
3180       $_ = `$_`;
3181       ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3182
3183       if (!defined($img_height)) {
3184         error "xwininfo failed.";
3185       }
3186     }
3187   }
3188
3189   my $bgcolor = "#000000";
3190   my $bgimage = undef;
3191
3192   if ($background) {
3193     if ($background =~ m/^\#[0-9a-f]+$/i) {
3194       $bgcolor = $background;
3195
3196     } elsif (-r $background) {
3197       $bgimage = $background;
3198
3199     } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3200       error "not a color or readable file: $background";
3201
3202     } else {
3203       # default to assuming it's a color
3204       $bgcolor = $background;
3205     }
3206   }
3207
3208   # Create the sold-colored base image.
3209   #
3210   LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3211   $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3212
3213   # Paste the default background image in the middle of it.
3214   #
3215   if ($bgimage) {
3216     my ($iw, $ih);
3217
3218     my $body = "";
3219     open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3220     local $/ = undef;  # read entire file
3221     $body = <$imgf>;
3222     close ($imgf);
3223
3224     my $cmd;
3225     if ((@_ = gif_size ($body))) {
3226       ($iw, $ih) = @_;
3227       $cmd = "giftopnm |";
3228
3229     } elsif ((@_ = jpeg_size ($body))) {
3230       ($iw, $ih) = @_;
3231       $cmd = "djpeg |";
3232
3233     } elsif ((@_ = png_size ($body))) {
3234       ($iw, $ih) = @_;
3235       $cmd = "pngtopnm |";
3236
3237     } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3238       $iw = $1;
3239       $ih = $2;
3240       $cmd = "";
3241
3242     } else {
3243       error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3244     }
3245
3246     my $x = int (($img_width  - $iw) / 2);
3247     my $y = int (($img_height - $ih) / 2);
3248     LOG ($verbose_pbm,
3249          "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3250
3251     $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3252     open ($imgf, "| $cmd") || error "running $cmd: $!";
3253     print $imgf $body;
3254     $body = undef;
3255     close ($imgf);
3256     LOG ($verbose_exec, "subproc exited normally.");
3257     rename ($image_tmp1, $image_ppm) ||
3258       error "renaming $image_tmp1 to $image_ppm: $!";
3259   }
3260
3261   clearlog();
3262
3263   while (1) {
3264     my ($base, $img) = pick_image();
3265     my $source = $current_state;
3266     $current_state = "loadimage";
3267     if ($img) {
3268       my ($headers, $body) = get_document ($img, $base);
3269       if ($body) {
3270         paste_image ($base, $img, $body, $source);
3271         $body = undef;
3272       }
3273     }
3274     $current_state = "idle";
3275     $load_method = "none";
3276
3277     unlink $image_tmp1, $image_tmp2;
3278     sleep $delay;
3279   }
3280 }
3281
3282 sub paste_image($$$$) {
3283   my ($base, $img, $body, $source) = @_;
3284
3285   $current_state = "paste";
3286
3287   $suppress_audit = 0;
3288
3289   LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3290
3291   my ($iw, $ih);
3292
3293   # If we are using the webcollage-helper, then we do not need to convert this
3294   # image to a PPM.  But, if we're using a filter command, we still must, since
3295   # that's what the filters expect (webcollage-helper can read PPMs, so that's
3296   # fine.)
3297   #
3298   if (defined ($webcollage_helper) &&
3299       !defined ($filter_cmd)) {
3300
3301     ($iw, $ih) = image_size ($body);
3302     if (!$iw || !$ih) {
3303       LOG (($verbose_pbm || $verbose_load),
3304            "not a GIF, JPG, or PNG" .
3305            (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3306             ? " (looks like HTML)" : "") .
3307            ": $img");
3308       $suppress_audit = 1;
3309       $body = undef;
3310       return 0;
3311     }
3312
3313     open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3314     (print $out $body) || error ("writing $image_tmp1: $!");
3315     close ($out) || error ("writing $image_tmp1: $!");
3316
3317   } else {
3318     ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3319     $body = undef;
3320     if (!$iw || !$ih) {
3321       LOG ($verbose_pbm, "unable to make PBM from $img");
3322       return 0;
3323     }
3324   }
3325
3326   record_success ($load_method, $img, $base);
3327
3328
3329   my $ow = $iw;  # used only for error messages
3330   my $oh = $ih;
3331
3332   # don't just tack this onto the front of the pipeline -- we want it to
3333   # be able to change the size of the input image.
3334   #
3335   if ($filter_cmd) {
3336     LOG ($verbose_pbm, "running $filter_cmd");
3337
3338     my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3339     if ($rc != 0) {
3340       LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3341       LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3342       return;
3343     }
3344     rename ($image_tmp2, $image_tmp1);
3345
3346     # re-get the width/height in case the filter resized it.
3347     open (my $imgf, '<', $image_tmp1) || return 0;
3348     $_ = <$imgf>;
3349     $_ = <$imgf>;
3350     ($iw, $ih) = m/^(\d+) (\d+)$/;
3351     close ($imgf);
3352     return 0 unless ($iw && $ih);
3353   }
3354
3355   my $target_w = $img_width;   # max rectangle into which the image must fit
3356   my $target_h = $img_height;
3357
3358   my $cmd = "";
3359   my $scale = 1.0;
3360
3361
3362   # Usually scale the image to fit on the screen -- but sometimes scale it
3363   # to fit on half or a quarter of the screen.  (We do this by reducing the
3364   # size of the target rectangle.)  Note that the image is not merely scaled
3365   # to fit; we instead cut the image in half repeatedly until it fits in the
3366   # target rectangle -- that gives a wider distribution of sizes.
3367   #
3368   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3369   if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3370
3371   if ($iw > $target_w || $ih > $target_h) {
3372     while ($iw > $target_w ||
3373            $ih > $target_h) {
3374       $iw = int($iw / 2);
3375       $ih = int($ih / 2);
3376       $scale /= 2;
3377     }
3378     if ($iw <= 10 || $ih <= 10) {
3379       LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3380       return 0;
3381     }
3382
3383     LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3384
3385     $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3386   }
3387
3388
3389   my $src = $image_tmp1;
3390
3391   my $crop_x = 0;     # the sub-rectangle of the image
3392   my $crop_y = 0;     # that we will actually paste.
3393   my $crop_w = $iw;
3394   my $crop_h = $ih;
3395
3396   # The chance that we will randomly crop out a section of an image starts
3397   # out fairly low, but goes up for images that are very large, or images
3398   # that have ratios that make them look like banners (we try to avoid
3399   # banner images entirely, but they slip through when the IMG tags didn't
3400   # have WIDTH and HEIGHT specified.)
3401   #
3402   my $crop_chance = 0.2;
3403   if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3404     $crop_chance += 0.2;
3405   }
3406   if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3407     $crop_chance += 0.2;
3408   }
3409   if ($min_ratio && ($iw * $min_ratio) > $ih) {
3410     $crop_chance += 0.7;
3411   }
3412
3413   if ($crop_chance > 0.1) {
3414     LOG ($verbose_pbm, "crop chance: $crop_chance");
3415   }
3416
3417   if (rand() < $crop_chance) {
3418
3419     my $ow = $crop_w;
3420     my $oh = $crop_h;
3421
3422     if ($crop_w > $min_width) {
3423       # if it's a banner, select the width linearly.
3424       # otherwise, select a bell.
3425       my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3426                ? rand()
3427                : bellrand());
3428       $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3429       $crop_x = int (rand() * ($ow - $crop_w));
3430     }
3431     if ($crop_h > $min_height) {
3432       # height always selects as a bell.
3433       $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3434       $crop_y = int (rand() * ($oh - $crop_h));
3435     }
3436
3437     if ($crop_x != 0   || $crop_y != 0 ||
3438         $crop_w != $iw || $crop_h != $ih) {
3439       LOG ($verbose_pbm,
3440            "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3441     }
3442   }
3443
3444   # Where the image should logically land -- this might be negative.
3445   #
3446   my $x = int((rand() * ($img_width  + $crop_w/2)) - $crop_w*3/4);
3447   my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3448
3449   # if we have chosen to paste the image outside of the rectangle of the
3450   # screen, then we need to crop it.
3451   #
3452   if ($x < 0 ||
3453       $y < 0 ||
3454       $x + $crop_w > $img_width ||
3455       $y + $crop_h > $img_height) {
3456
3457     LOG ($verbose_pbm,
3458          "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3459
3460     if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3461     if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3462
3463     if ($x + $crop_w >= $img_width)  { $crop_w = $img_width  - $x - 1; }
3464     if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3465   }
3466
3467   # If any cropping needs to happen, add pnmcut.
3468   #
3469   if ($crop_x != 0   || $crop_y != 0 ||
3470       $crop_w != $iw || $crop_h != $ih) {
3471     $iw = $crop_w;
3472     $ih = $crop_h;
3473     $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3474     LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3475   }
3476
3477   LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3478
3479   $cmd .= " | pnmpaste - $x $y $image_ppm";
3480
3481   $cmd =~ s@^ *\| *@@;
3482
3483   if (defined ($webcollage_helper)) {
3484     $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3485                               "$scale $opacity " .
3486                               "$crop_x $crop_y $x $y " .
3487                               "$iw $ih";
3488     $_ = $cmd;
3489
3490   } else {
3491     # use a PPM pipeline
3492     $_ = "($cmd)";
3493     $_ .= " < $image_tmp1 > $image_tmp2";
3494   }
3495
3496   if ($verbose_pbm) {
3497     $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3498   } else {
3499     $_ .= " 2> /dev/null";
3500   }
3501
3502   my $rc = nontrapping_system ($_);
3503
3504   if (defined ($webcollage_helper) && -z $image_ppm) {
3505     LOG (1, "failed command: \"$cmd\"");
3506     print STDERR "\naudit log:\n\n\n";
3507     print STDERR ("#" x 78) . "\n";
3508     print STDERR blurb() . "$image_ppm has zero size\n";
3509     showlog();
3510     print STDERR "\n\n";
3511     exit (1);
3512   }
3513
3514   if ($rc != 0) {
3515     LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3516     LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3517     return;
3518   }
3519
3520   if (!defined ($webcollage_helper)) {
3521     rename ($image_tmp2, $image_ppm) || return;
3522   }
3523
3524   my $target = "$image_ppm";
3525
3526   # don't just tack this onto the end of the pipeline -- we don't want it
3527   # to end up in $image_ppm, because we don't want the results to be
3528   # cumulative.
3529   #
3530   if ($post_filter_cmd) {
3531
3532     my $cmd;
3533
3534     $target = $image_tmp1;
3535     if (!defined ($webcollage_helper)) {
3536       $cmd = "($post_filter_cmd) < $image_ppm > $target";
3537     } else {
3538       # Blah, my scripts need the JPEG data, but some other folks need
3539       # the PPM data -- what to do?  Ignore the problem, that's what!
3540 #     $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3541       $cmd = "($post_filter_cmd) < $image_ppm > $target";
3542     }
3543
3544     $rc = nontrapping_system ($cmd);
3545     if ($rc != 0) {
3546       LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3547       return;
3548     }
3549   }
3550
3551   if (!$no_output_p) {
3552     my $tsize = (stat($target))[7];
3553     if ($tsize > 200) {
3554       $cmd = "$ppm_to_root_window_cmd $target";
3555
3556       # xv seems to hate being killed.  it tends to forget to clean
3557       # up after itself, and leaves windows around and colors allocated.
3558       # I had this same problem with vidwhacker, and I'm not entirely
3559       # sure what I did to fix it.  But, let's try this: launch xv
3560       # in the background, so that killing this process doesn't kill it.
3561       # it will die of its own accord soon enough.  So this means we
3562       # start pumping bits to the root window in parallel with starting
3563       # the next network retrieval, which is probably a better thing
3564       # to do anyway.
3565       #
3566       $cmd .= " &" unless ($cocoa_p);
3567
3568       $rc = nontrapping_system ($cmd);
3569
3570       if ($rc != 0) {
3571         LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3572         return;
3573       }
3574
3575     } else {
3576       LOG ($verbose_pbm, "$target size is $tsize");
3577     }
3578   }
3579
3580   $source .= "-" . stats_of($source);
3581   print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3582     if ($verbose_imgmap);
3583   if ($imagemap_base) {
3584     update_imagemap ($base, $x, $y, $iw, $ih,
3585                      $image_ppm, $img_width, $img_height);
3586   }
3587
3588   clearlog();
3589
3590   return 1;
3591 }
3592
3593
3594 sub update_imagemap($$$$$$$$) {
3595   my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3596
3597   $current_state = "imagemap";
3598
3599   my $max_areas = 200;
3600
3601   $url = html_quote ($url);
3602   my $x2 = $x + $w;
3603   my $y2 = $y + $h;
3604   my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3605   unshift @imagemap_areas, $area;       # put one on the front
3606   if ($#imagemap_areas >= $max_areas) {
3607     pop @imagemap_areas;                # take one off the back.
3608   }
3609
3610   LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3611
3612   my $map_name = $imagemap_base;
3613   $map_name =~ s@^.*/@@;
3614   $map_name = 'collage' if ($map_name eq '');
3615
3616   my $imagemap_html = $imagemap_base . ".html";
3617   my $imagemap_jpg  = $imagemap_base . ".jpg";
3618   my $imagemap_jpg2 = $imagemap_jpg;
3619   $imagemap_jpg2 =~ s@^.*/@@gs;
3620
3621   if (!defined ($imagemap_html_tmp)) {
3622     $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3623     $imagemap_jpg_tmp  = $imagemap_jpg  . sprintf (".%08x", rand(0xffffffff));
3624   }
3625
3626   # Read the imagemap html file (if any) to get a template.
3627   #
3628   my $template_html = '';
3629   {
3630     if (open (my $in, '<', $imagemap_html)) {
3631       local $/ = undef;  # read entire file
3632       $template_html = <$in>;
3633       close $in;
3634       LOG ($verbose_pbm, "read template $imagemap_html");
3635     }
3636
3637     if ($template_html =~ m/^\s*$/s) {
3638       $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3639                         "<IMG SRC=\"$imagemap_jpg2\"" .
3640                         " USEMAP=\"$map_name\">\n");
3641       LOG ($verbose_pbm, "created dummy template");
3642     }
3643   }
3644
3645   # Write the jpg to a tmp file
3646   #
3647   {
3648     my $cmd;
3649     if (defined ($webcollage_helper)) {
3650       $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3651     } else {
3652       $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3653     }
3654     my $rc = nontrapping_system ($cmd);
3655     if ($rc != 0) {
3656       error ("imagemap jpeg failed: \"$cmd\"\n");
3657     }
3658   }
3659
3660   # Write the html to a tmp file
3661   #
3662   {
3663     my $body = $template_html;
3664     my $areas = join ("\n\t", @imagemap_areas);
3665     my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3666     my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3667                "BORDER=0 " .
3668                "WIDTH=$image_width HEIGHT=$image_height " .
3669                "USEMAP=\"#$map_name\">");
3670     $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3671     $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3672
3673     # if there are magic webcollage spans in the html, update those too.
3674     #
3675     {
3676       my @st = stat ($imagemap_jpg_tmp);
3677       my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3678       my $size = int(($st[7] / 1024) + 0.5) . "K";
3679       $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3680       $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3681     }
3682
3683     open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3684     (print $out $body)                      || error ("$imagemap_html_tmp: $!");
3685     close ($out)                            || error ("$imagemap_html_tmp: $!");
3686     LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3687   }
3688
3689   # Rename the two tmp files to the real files
3690   #
3691   rename ($imagemap_html_tmp, $imagemap_html) ||
3692     error "renaming $imagemap_html_tmp to $imagemap_html";
3693   LOG ($verbose_pbm, "wrote $imagemap_html");
3694   rename ($imagemap_jpg_tmp,  $imagemap_jpg) ||
3695     error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3696   LOG ($verbose_pbm, "wrote $imagemap_jpg");
3697 }
3698
3699
3700 # Figure out what the proxy server should be, either from environment
3701 # variables or by parsing the output of the (MacOS) program "scutil",
3702 # which tells us what the system-wide proxy settings are.
3703 #
3704 sub set_proxy() {
3705
3706   if (! $http_proxy) {
3707     # historical suckage: the environment variable name is lower case.
3708     $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3709   }
3710
3711   if (defined ($http_proxy)) {
3712     if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3713       # historical suckage: allow "http://host:port" as well as "host:port".
3714       $http_proxy = $1;
3715     }
3716
3717   } else {
3718     my $proxy_data = `scutil --proxy 2>/dev/null`;
3719     my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3720     my ($port)   = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3721     # Note: this ignores the "ExceptionsList".
3722     if ($server) {
3723       $http_proxy = $server;
3724       $http_proxy .= ":$port" if $port;
3725     }
3726   }
3727
3728   if ($http_proxy) {
3729     LOG ($verbose_net, "proxy server: $http_proxy");
3730   }
3731 }
3732
3733
3734 sub init_signals() {
3735
3736   $SIG{HUP}  = \&signal_cleanup;
3737   $SIG{INT}  = \&signal_cleanup;
3738   $SIG{QUIT} = \&signal_cleanup;
3739   $SIG{ABRT} = \&signal_cleanup;
3740   $SIG{KILL} = \&signal_cleanup;
3741   $SIG{TERM} = \&signal_cleanup;
3742
3743   # Need this so that if giftopnm dies, we don't die.
3744   $SIG{PIPE} = 'IGNORE';
3745 }
3746
3747 END { exit_cleanup(); }
3748
3749
3750 sub main() {
3751   $| = 1;
3752   srand(time ^ $$);
3753
3754   my $verbose = 0;
3755   my $dict;
3756   my $driftnet_cmd = 0;
3757
3758   $current_state = "init";
3759   $load_method = "none";
3760
3761   my $root_p = 0;
3762   my $window_id = undef;
3763
3764   while ($_ = $ARGV[0]) {
3765     shift @ARGV;
3766     if ($_ eq "-display" ||
3767         $_ eq "-displ" ||
3768         $_ eq "-disp" ||
3769         $_ eq "-dis" ||
3770         $_ eq "-dpy" ||
3771         $_ eq "-d") {
3772       $ENV{DISPLAY} = shift @ARGV;
3773     } elsif ($_ eq "-root") {
3774       $root_p = 1;
3775     } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3776       $window_id = shift @ARGV;
3777       $root_p = 1;
3778     } elsif ($_ eq "-no-output") {
3779       $no_output_p = 1;
3780     } elsif ($_ eq "-urls-only") {
3781       $urls_only_p = 1;
3782       $no_output_p = 1;
3783     } elsif ($_ eq "-cocoa") {
3784       $cocoa_p = 1;
3785     } elsif ($_ eq "-imagemap") {
3786       $imagemap_base = shift @ARGV;
3787       $no_output_p = 1;
3788     } elsif ($_ eq "-verbose") {
3789       $verbose++;
3790     } elsif (m/^-v+$/) {
3791       $verbose += length($_)-1;
3792     } elsif ($_ eq "-delay") {
3793       $delay = shift @ARGV;
3794     } elsif ($_ eq "-timeout") {
3795       $http_timeout = shift @ARGV;
3796     } elsif ($_ eq "-filter") {
3797       $filter_cmd = shift @ARGV;
3798     } elsif ($_ eq "-filter2") {
3799       $post_filter_cmd = shift @ARGV;
3800     } elsif ($_ eq "-background" || $_ eq "-bg") {
3801       $background = shift @ARGV;
3802     } elsif ($_ eq "-size") {
3803       $_ = shift @ARGV;
3804       if (m@^(\d+)x(\d+)$@) {
3805         $img_width = $1;
3806         $img_height = $2;
3807       } else {
3808         error "argument to \"-size\" must be of the form \"640x400\"";
3809       }
3810     } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3811       $http_proxy = shift @ARGV;
3812     } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3813       $dict = shift @ARGV;
3814     } elsif ($_ eq "-opacity") {
3815       $opacity = shift @ARGV;
3816       error ("opacity must be between 0.0 and 1.0")
3817         if ($opacity <= 0 || $opacity > 1);
3818     } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3819       @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3820       if (! ($ARGV[0] =~ m/^-/)) {
3821         $driftnet_cmd = shift @ARGV;
3822       } else {
3823         $driftnet_cmd = $default_driftnet_cmd;
3824       }
3825     } elsif ($_ eq "-directory" || $_ eq "--directory") {
3826       @search_methods = ( 100, "local", \&pick_from_local_dir );
3827       if (! ($ARGV[0] =~ m/^-/)) {
3828         $local_dir = shift @ARGV;
3829       } else {
3830         error ("local directory path must be set")
3831       }
3832     } elsif ($_ eq "-fps") {
3833       # -fps only works on MacOS, via "webcollage-cocoa.m".
3834       # Ignore it if passed to this script in an X11 context.
3835     } elsif ($_ eq "-debug" || $_ eq "--debug") {
3836       my $which = shift @ARGV;
3837       my @rest = @search_methods;
3838       my $ok = 0;
3839       while (@rest) {
3840         my $pct  = shift @rest;
3841         my $name = shift @rest;
3842         my $tfn  = shift @rest;
3843
3844         if ($name eq $which) {
3845           @search_methods = (100, $name, $tfn);
3846           $ok = 1;
3847           last;
3848         }
3849       }
3850       error "no such search method as \"$which\"" unless ($ok);
3851       LOG (1, "DEBUG: using only \"$which\"");
3852
3853     } else {
3854       print STDERR "$copyright\nusage: $progname " .
3855               "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3856         "\t\t  [-timeout secs] [-delay secs] [-size WxH]\n" .
3857         "\t\t  [-no-output] [-urls-only] [-imagemap filename]\n" .
3858         "\t\t  [-background color] [-opacity f]\n" .
3859         "\t\t  [-filter cmd] [-filter2 cmd]\n" .
3860         "\t\t  [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3861         "\t\t  [-driftnet [driftnet-program-and-args]]\n" .
3862         "\t\t  [-directory local-image-directory]\n" .
3863         "\n";
3864       exit 1;
3865     }
3866   }
3867
3868   if (!$root_p && !$no_output_p && !$cocoa_p) {
3869     print STDERR $copyright;
3870     error "the -root argument is mandatory (for now.)";
3871   }
3872
3873   if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3874     error "\$DISPLAY is not set.";
3875   }
3876
3877
3878   if ($verbose == 1) {
3879     $verbose_imgmap   = 1;
3880     $verbose_warnings = 1;
3881
3882   } elsif ($verbose == 2) {
3883     $verbose_imgmap   = 1;
3884     $verbose_warnings = 1;
3885     $verbose_load     = 1;
3886
3887   } elsif ($verbose == 3) {
3888     $verbose_imgmap   = 1;
3889     $verbose_warnings = 1;
3890     $verbose_load     = 1;
3891     $verbose_filter   = 1;
3892
3893   } elsif ($verbose == 4) {
3894     $verbose_imgmap   = 1;
3895     $verbose_warnings = 1;
3896     $verbose_load     = 1;
3897     $verbose_filter   = 1;
3898     $verbose_net      = 1;
3899
3900   } elsif ($verbose == 5) {
3901     $verbose_imgmap   = 1;
3902     $verbose_warnings = 1;
3903     $verbose_load     = 1;
3904     $verbose_filter   = 1;
3905     $verbose_net      = 1;
3906     $verbose_pbm      = 1;
3907
3908   } elsif ($verbose == 6) {
3909     $verbose_imgmap   = 1;
3910     $verbose_warnings = 1;
3911     $verbose_load     = 1;
3912     $verbose_filter   = 1;
3913     $verbose_net      = 1;
3914     $verbose_pbm      = 1;
3915     $verbose_http     = 1;
3916
3917   } elsif ($verbose >= 7) {
3918     $verbose_imgmap   = 1;
3919     $verbose_warnings = 1;
3920     $verbose_load     = 1;
3921     $verbose_filter   = 1;
3922     $verbose_net      = 1;
3923     $verbose_pbm      = 1;
3924     $verbose_http     = 1;
3925     $verbose_exec     = 1;
3926   }
3927
3928   if ($dict) {
3929     error ("$dict does not exist") unless (-f $dict);
3930     $wordlist = $dict;
3931   } else {
3932     pick_dictionary();
3933   }
3934
3935   if ($imagemap_base && !($img_width && $img_height)) {
3936     error ("-size WxH is required with -imagemap");
3937   }
3938
3939   if (defined ($local_dir)) {
3940     $_ = "xscreensaver-getimage-file";
3941     which ($_) || error "$_ not found on \$PATH.";
3942   }
3943
3944   init_signals();
3945   set_proxy();
3946
3947   spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3948
3949   if ($urls_only_p) {
3950     url_only_output ();
3951   } else {
3952     x_or_pbm_output ($window_id);
3953   }
3954 }
3955
3956 main();
3957 exit (0);