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