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