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