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