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