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