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