3 # webcollage, Copyright (c) 1999-2008 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."
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
16 # To run this as a display mode with xscreensaver, add this to `programs':
19 # webcollage -root -filter 'vidwhacker -stdin -stdout'
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:
26 # webcollage -size '800x600' -imagemap $HOME/www/webcollage/index
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!
34 # Driftnet is available here: http://www.ex-parrot.com/~chris/driftnet/
37 # webcollage -root -driftnet
39 # Driftnet is the Unix implementation of the MacOS "EtherPEG" program.
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!
54 use Fcntl ':flock'; # import LOCK_* constants
55 use POSIX qw(strftime);
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.
62 my $progname = $0; $progname =~ s@.*/@@g;
63 my $version = q{ $Revision: 1.150 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
64 my $copyright = "WebCollage $version, Copyright (c) 1999-2008" .
65 " Jamie Zawinski <jwz\@jwz.org>\n" .
66 " http://www.jwz.org/webcollage/\n";
70 my @search_methods = ( 20, "googlephotos", \&pick_from_google_image_photos,
71 10, "googleimgs", \&pick_from_google_images,
72 10, "googlenums", \&pick_from_google_image_numbers,
74 19, "altavista", \&pick_from_alta_vista_random_link,
75 12, "flickr_recent", \&pick_from_flickr_recent,
76 10, "flickr_random", \&pick_from_flickr_random,
77 10, "livejournal", \&pick_from_livejournal_images,
78 5, "twitter", \&pick_from_twitter_images,
79 4, "yahoorand", \&pick_from_yahoo_random_link,
82 # This is a cute way to search for a certain webcams.
83 # Not included in default methods, since these images
84 # aren't terribly interesting by themselves.
85 # See also "SurveillanceSaver".
87 0, "securitycam", \&pick_from_security_camera,
89 # In Apr 2002, Google asked me to stop searching them.
90 # I asked them to add a "random link" url. They said
91 # "that would be easy, we'll think about it" and then
92 # never wrote back. Booo Google! Booooo! So, screw
93 # those turkeys, I've turned Google searching back on.
94 # I'm sure they can take it. (Jan 2005.)
96 # Jan 2005: Yahoo fucked up their search form so that
97 # it's no longer possible to do "or" searches on news
98 # images, so we rarely get any hits there any more.
100 # 0, "yahoonews", \&pick_from_yahoo_news_text,
102 # Dec 2004: the ircimages guy's server can't take the
103 # heat, so he started banning the webcollage user agent.
104 # I tried to convince him to add a lighter-weight page to
105 # support webcollage better, but he doesn't care.
107 # 0, "ircimages", \&pick_from_ircimages,
109 # Dec 2002: Alta Vista has a new "random link" URL now.
110 # They added it specifically to better support webcollage!
111 # That was super cool of them. This is how we used to do
114 # 0, "avimages", \&pick_from_alta_vista_images,
115 # 0, "avtext", \&pick_from_alta_vista_text,
117 # This broke in 2004. Eh, Lycos sucks anyway.
119 # 0, "lycos", \&pick_from_lycos_text,
121 # This broke in 2003, I think. I suspect Hotbot is
122 # actually the same search engine data as Lycos.
124 # 0, "hotbot", \&pick_from_hotbot_text,
127 # programs we can use to write to the root window (tried in ascending order.)
129 my @root_displayers = (
130 "xscreensaver-getimage -root -file",
131 "chbg -once -xscreensaver -max_size 100",
132 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
133 " -rfg black -rbg black",
134 "xli -quiet -onroot -center -border black",
135 "xloadimage -quiet -onroot -center -border black",
137 # this lame program wasn't built with vroot.h:
138 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
142 # Some sites need cookies to work properly. These are they.
145 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
146 "web.altavista.com" => "AV_ALL=1",
148 # log in as "cipherpunk"
149 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
150 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
151 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
153 "ircimages.com" => 'disclaimer=1',
157 # If this is set, it's a helper program to use for pasting images together:
158 # this is a lot faster and more efficient than using PPM pipelines, which is
159 # what we do if this program doesn't exist. (We check for "webcollage-helper"
160 # on $PATH at startup, and set this variable appropriately.)
162 my $webcollage_helper = undef;
165 # If we have the webcollage-helper program, then it will paste the images
166 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
171 # Some sites have managed to poison the search engines. These are they.
172 # (We auto-detect sites that have poisoned the search engines via excessive
173 # keywords or dictionary words, but these are ones that slip through
176 # This can contain full host names, or 2 or 3 component domains.
179 "die.net" => 1, # 'l33t h4ck3r d00dz.
180 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
181 "rootsweb.com" => 1, # Cluttering avtext with human names.
182 "akamai.net" => 1, # Lots of sites have their images on Akamai.
183 "akamaitech.net" => 1, # But those are pretty much all banners.
184 # Since Akamai is super-expensive, let's
185 # go out on a limb and assume that all of
186 # their customers are rich-and-boring.
187 "bartleby.com" => 1, # Dictionary, cluttering avtext.
188 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
189 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
190 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
191 # (I don't see how they did it, though!)
192 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
193 "nextag.com" => 1, # Poisoned Alta Vista real good.
194 "ghettodriveby.com" => 1, # Poisoned Google Images.
195 "crosswordsolver.org" => 1, # Poisoned Google Images.
196 "xona.com" => 1, # Poisoned Google Images.
197 "freepatentsonline.com" => 1, # Poisoned Google Images.
198 "herbdatanz.com" => 1, # Poisoned Google Images.
202 # When verbosity is turned on, we warn about sites that we seem to be hitting
203 # a lot: usually this means some new poisoner has made it into the search
204 # engines. But sometimes, the warning is just because that site has a lot
205 # of stuff on it. So these are the sites that are immune to the "frequent
206 # site" diagnostic message.
208 my %warningless_sites = (
209 "home.earthlink.net" => 1, # Lots of home pages here.
210 "www.geocities.com" => 1,
211 "www.angelfire.com" => 1,
212 "members.aol.com" => 1,
213 "img.photobucket.com" => 1,
214 "pics.livejournal.com" => 1,
220 "wikimedia.org" => 1,
222 "amazonaws.com" => 1, # used by twitpic.com
224 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
225 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
226 # hits this every time.
228 "images.quizfarm.com" => 1, # damn those LJ quizzes...
229 "images.quizilla.com" => 1,
230 "images.quizdiva.net" => 1,
232 "driftnet" => 1, # builtin...
233 "local-directory" => 1, # builtin...
237 # For decoding HTML-encoded character entities to URLs.
241 "quot" => '"', "amp" => '&', "lt" => '<', "gt" => '>',
242 "nbsp" => ' ', "iexcl" => '¡', "cent" => '¢', "pound" => '£',
243 "curren" => '¤', "yen" => '¥', "brvbar" => '¦', "sect" => '§',
244 "uml" => '¨', "copy" => '©', "ordf" => 'ª', "laquo" => '«',
245 "not" => '¬', "shy" => '', "reg" => '®', "macr" => '¯',
246 "deg" => '°', "plusmn" => '±', "sup2" => '²', "sup3" => '³',
247 "acute" => '´', "micro" => 'µ', "para" => '¶', "middot" => '·',
248 "cedil" => '¸', "sup1" => '¹', "ordm" => 'º', "raquo" => '»',
249 "frac14" => '¼', "frac12" => '½', "frac34" => '¾', "iquest" => '¿',
250 "Agrave" => 'À', "Aacute" => 'Á', "Acirc" => 'Â', "Atilde" => 'Ã',
251 "Auml" => 'Ä', "Aring" => 'Å', "AElig" => 'Æ', "Ccedil" => 'Ç',
252 "Egrave" => 'È', "Eacute" => 'É', "Ecirc" => 'Ê', "Euml" => 'Ë',
253 "Igrave" => 'Ì', "Iacute" => 'Í', "Icirc" => 'Î', "Iuml" => 'Ï',
254 "ETH" => 'Ð', "Ntilde" => 'Ñ', "Ograve" => 'Ò', "Oacute" => 'Ó',
255 "Ocirc" => 'Ô', "Otilde" => 'Õ', "Ouml" => 'Ö', "times" => '×',
256 "Oslash" => 'Ø', "Ugrave" => 'Ù', "Uacute" => 'Ú', "Ucirc" => 'Û',
257 "Uuml" => 'Ü', "Yacute" => 'Ý', "THORN" => 'Þ', "szlig" => 'ß',
258 "agrave" => 'à', "aacute" => 'á', "acirc" => 'â', "atilde" => 'ã',
259 "auml" => 'ä', "aring" => 'å', "aelig" => 'æ', "ccedil" => 'ç',
260 "egrave" => 'è', "eacute" => 'é', "ecirc" => 'ê', "euml" => 'ë',
261 "igrave" => 'ì', "iacute" => 'í', "icirc" => 'î', "iuml" => 'ï',
262 "eth" => 'ð', "ntilde" => 'ñ', "ograve" => 'ò', "oacute" => 'ó',
263 "ocirc" => 'ô', "otilde" => 'õ', "ouml" => 'ö', "divide" => '÷',
264 "oslash" => 'ø', "ugrave" => 'ù', "uacute" => 'ú', "ucirc" => 'û',
265 "uuml" => 'ü', "yacute" => 'ý', "thorn" => 'þ', "yuml" => 'ÿ',
267 # HTML 4 entities that do not have 1:1 Latin1 mappings.
268 "bull" => "*", "hellip"=> "...", "prime" => "'", "Prime" => "\"",
269 "frasl" => "/", "trade" => "[tm]", "larr" => "<-", "rarr" => "->",
270 "harr" => "<->", "lArr" => "<=", "rArr" => "=>", "hArr" => "<=>",
271 "empty" => "Ø", "minus" => "-", "lowast"=> "*", "sim" => "~",
272 "cong" => "=~", "asymp" => "~", "ne" => "!=", "equiv" => "==",
273 "le" => "<=", "ge" => ">=", "lang" => "<", "rang" => ">",
274 "loz" => "<>", "OElig" => "OE", "oelig" => "oe", "Yuml" => "Y",
275 "circ" => "^", "tilde" => "~", "ensp" => " ", "emsp" => " ",
276 "thinsp"=> " ", "ndash" => "-", "mdash" => "--", "lsquo" => "`",
277 "rsquo" => "'", "sbquo" => "'", "ldquo" => "\"", "rdquo" => "\"",
278 "bdquo" => "\"", "lsaquo"=> "<", "rsaquo"=> ">",
282 ##############################################################################
284 # Various global flags set by command line parameters, or computed
286 ##############################################################################
289 my $current_state = "???"; # for diagnostics
292 my $image_succeeded = -1;
293 my $suppress_audit = 0;
295 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
296 my $verbose_warnings = 0; # print out warnings when things go wrong
297 my $verbose_load = 0; # diagnostics about loading of URLs
298 my $verbose_filter = 0; # diagnostics about page selection/rejection
299 my $verbose_net = 0; # diagnostics about network I/O
300 my $verbose_pbm = 0; # diagnostics about PBM pipelines
301 my $verbose_http = 0; # diagnostics about all HTTP activity
302 my $verbose_exec = 0; # diagnostics about executing programs
304 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
306 my $http_proxy = undef;
307 my $http_timeout = 20;
308 my $cvt_timeout = 10;
314 my $min_gif_area = (120 * 120);
320 my $imagemap_base = undef;
322 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
324 my $driftnet_magic = 'driftnet';
325 my $driftnet_dir = undef;
326 my $default_driftnet_cmd = "driftnet -a -m 100";
328 my $local_magic = 'local-directory';
329 my $local_dir = undef;
334 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
335 "arrhenius", "arteriole", "blanket", "brainchild",
336 "burdensome", "carnival", "cherub", "chord", "clever",
337 "dedicate", "dilogarithm", "dolan", "dryden",
341 ##############################################################################
345 ##############################################################################
347 # returns three values: the HTTP response line; the document headers;
348 # and the document body.
350 sub get_document_1($$$) {
351 my ($url, $referer, $timeout) = @_;
353 if (!defined($timeout)) { $timeout = $http_timeout; }
354 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
357 LOG (($verbose_net || $verbose_load), "timed out for $url");
361 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
363 if (! ($url =~ m@^http://@i)) {
364 LOG ($verbose_net, "not an HTTP URL: $url");
368 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
369 $path = "" unless $path;
371 if (!$url_proto || !$serverstring) {
372 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
376 my ($them,$port) = split(/:/, $serverstring);
377 $port = 80 unless $port;
382 $serverstring = $http_proxy if $http_proxy;
383 $serverstring =~ s@^[a-z]+://@@;
384 ($them2,$port2) = split(/:/, $serverstring);
385 $port2 = 80 unless $port2;
388 my ($remote, $iaddr, $paddr, $proto, $line);
390 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
392 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
395 $iaddr = inet_aton($remote);
397 LOG (($verbose_net || $verbose_load), "host not found: $remote");
400 $paddr = sockaddr_in($port2, $iaddr);
408 local $SIG{ALRM} = sub {
409 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
414 $proto = getprotobyname('tcp');
415 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
416 LOG (($verbose_net || $verbose_load), "socket: $!");
419 if (!connect(S, $paddr)) {
420 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
424 select(S); $| = 1; select(STDOUT);
426 my $cookie = $cookies{$them};
428 my $user_agent = "$progname/$version";
430 if ($url =~ m@^http://www\.altavista\.com/@ ||
431 $url =~ m@^http://random\.yahoo\.com/@ ||
432 $url =~ m@^http://images\.google\.com/@ ||
433 $url =~ m@^http://www\.google\.com/@) {
434 # block this, you turkeys.
435 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)" .
436 " Gecko/20070914 Firefox/2.0.0.7";
438 # 28-Jun-2007: Google Images now emits the entire page in JS if
439 # you claim to be Gecko. They also still block "webcollage".
440 # They serve non-JS for unrecognised agents, so let's try this...
441 $user_agent = "NoJavascriptPlease/1.0"
442 if ($url =~ m@^http://[a-z]+\.google\.com/@);
445 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
447 "User-Agent: $user_agent\r\n";
449 $hdrs .= "Referer: $referer\r\n";
452 my @cc = split(/\r?\n/, $cookie);
453 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
457 foreach (split('\r?\n', $hdrs)) {
458 LOG ($verbose_http, " ==> $_");
461 my $http = <S> || "";
463 # Kludge: the Yahoo Random Link is now returning as its first
464 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
466 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
470 LOG ($verbose_http, " <== $_");
476 LOG ($verbose_http, " <== $_");
478 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
479 set_cookie($them, $1)
490 " <== [ body ]: $lines lines, " . length($body) . " bytes");
495 LOG (($verbose_net || $verbose_load), "null response: $url");
499 $SIG{ALRM} = 'DEFAULT'; # seem to be suffering a race?
500 return ( $http, $head, $body );
502 die if ($@ && $@ ne "alarm\n"); # propagate errors
504 if ($@ && $@ ne "alarm\n") {
505 print STDERR blurb() . "DIE " . join(" ", $@) . "\n";
523 # returns two values: the document headers; and the document body.
524 # if the given URL did a redirect, returns the redirected-to document.
526 sub get_document($$;$) {
527 my ($url, $referer, $timeout) = @_;
530 if (defined($referer) && $referer eq $driftnet_magic) {
531 return get_driftnet_file ($url);
534 if (defined($referer) && $referer eq $local_magic) {
535 return get_local_file ($url);
540 my $max_loop_count = 4;
543 if (defined($timeout) && $timeout <= 0) {
544 LOG (($verbose_net || $verbose_load), "timed out for $url");
549 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
551 if (defined ($timeout)) {
553 my $elapsed = $now - $start;
554 $timeout -= $elapsed;
558 return () unless $http; # error message already printed
560 $http =~ s/[\r\n]+$//s;
562 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
565 my ( $location ) = m@^location:[ \t]*(.*)$@im;
567 $location =~ s/[\r\n]$//;
569 LOG ($verbose_net, "redirect from $url to $location");
574 $referer =~ m@^(http://[^/]+)@i;
576 } elsif (! ($url =~ m@^[a-z]+:@i)) {
578 s@[^/]+$@@g if m@^http://[^/]+/@i;
579 $_ .= "/" if m@^http://[^/]+$@i;
584 LOG ($verbose_net, "no Location with \"$http\"");
585 return ( $url, $body );
588 if ($loop_count++ > $max_loop_count) {
590 "too many redirects ($max_loop_count) from $orig_url");
595 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
597 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
599 # http errors -- return nothing.
605 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
611 return ( $url, $body );
617 # If we already have a cookie defined for this site, and the site is trying
618 # to overwrite that very same cookie, let it do so. This is because nytimes
619 # expires its cookies - it lets you upgrade to a new cookie without logging
620 # in again, but you have to present the old cookie to get the new cookie.
621 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
624 my ($host, $cookie) = @_;
625 my $oc = $cookies{$host};
628 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
630 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
632 if ($oc_name eq $nc_name &&
633 $oc_value ne $nc_value) {
634 $cookies{$host} = $cookie;
635 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
640 ############################################################################
642 # Extracting image URLs from HTML
644 ############################################################################
646 # given a URL and the body text at that URL, selects and returns a random
647 # image from it. returns () if no suitable images found.
649 sub pick_image_from_body($$) {
650 my ($url, $body) = @_;
655 # if there's at least one slash after the host, take off the last
657 if ( m@^http://[^/]+/@io ) {
658 $base =~ s@[^/]+$@@go;
661 # if there are no slashes after the host at all, put one on the end.
662 if ( m@^http://[^/]+$@io ) {
668 # strip out newlines, compress whitespace
675 # There are certain web sites that list huge numbers of dictionary
676 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
677 # Porn sites tend not to be reputable!)
679 # I do not want webcollage to filter on content: I want it to select
680 # randomly from the set of images on the web. All the logic here for
681 # rejecting some images is really a set of heuristics for rejecting
682 # images that are not really images: for rejecting *text* that is in
683 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
684 # the content of the pictures to be randomly selected from among all
685 # the available content.
687 # So, filtering out "dirty" pictures by looking for "dirty" keywords
688 # would be wrong: dirty pictures exist, like it or not, so webcollage
689 # should be able to select them.
691 # However, picking a random URL is a hard thing to do. The mechanism I'm
692 # using is to search for a selection of random words. This is not
693 # perfect, but works ok most of the time. The way it breaks down is when
694 # some URLs get precedence because their pages list *every word* as
695 # related -- those URLs come up more often than others.
697 # So, after we've retrieved a URL, if it has too many keywords, reject
698 # it. We reject it not on the basis of what those keywords are, but on
699 # the basis that by having so many, the page has gotten an unfair
700 # advantage against our randomizer.
703 foreach my $trip (@tripwire_words) {
704 $trip_count++ if m/$trip/i;
707 if ($trip_count >= $#tripwire_words - 2) {
708 LOG (($verbose_filter || $verbose_load),
709 "there is probably a dictionary in \"$url\": rejecting.");
710 $rejected_urls{$url} = -1;
720 foreach (split(/ *</)) {
723 # Likewise, reject any web pages that have a KEYWORDS meta tag
726 if (m/name ?= ?\"?keywords\"?/i &&
727 m/content ?= ?\"([^\"]+)\"/) {
730 LOG (($verbose_filter || $verbose_load),
731 "excessive keywords ($L bytes) in $url: rejecting.");
732 $rejected_urls{$url} = $L;
737 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
741 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
743 my $was_inline = (! ( "$1" eq "a" || "$1" eq "A" ));
745 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
746 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
751 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
753 } elsif ( ! m@^[^/:?]+:@ ) {
756 1 while (s@/[^/]+/\.\./@/@g);
760 if ( ! m@^http://@io ) {
765 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
769 # skip really short or really narrow images
770 if ( $width && $width < $min_width) {
771 if (!$height) { $height = "?"; }
772 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
776 if ( $height && $height < $min_height) {
777 if (!$width) { $width = "?"; }
778 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
782 # skip images with ratios that make them look like banners.
783 if ($min_ratio && $width && $height &&
784 ($width * $min_ratio ) > $height) {
785 if (!$height) { $height = "?"; }
786 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
790 # skip GIFs with a small number of pixels -- those usually suck.
791 if ($width && $height &&
793 ($width * $height) < $min_gif_area) {
794 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
798 # skip images with a URL that indicates a Yahoo thumbnail.
799 if (m@\.yimg\.com/.*/t/@) {
800 if (!$width) { $width = "?"; }
801 if (!$height) { $height = "?"; }
802 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
808 if ($unique_urls{$url}) {
809 LOG ($verbose_filter, " skip duplicate image $_");
813 LOG ($verbose_filter,
815 ($width && $height ? " (${width}x${height})" : "") .
816 ($was_inline ? " (inline)" : ""));
818 $urls[++$#urls] = $url;
819 $unique_urls{$url}++;
821 # JPEGs are preferable to GIFs and PNGs.
823 if ( ! m@[.](gif|png)$@io ) {
824 $urls[++$#urls] = $url;
827 # pointers to images are preferable to inlined images.
828 if ( ! $was_inline ) {
829 $urls[++$#urls] = $url;
830 $urls[++$#urls] = $url;
835 my $fsp = ($body =~ m@<frameset@i);
840 @urls = depoison (@urls);
843 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
847 # pick a random element of the table
848 my $i = int(rand($#urls+1));
851 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
856 # Given a URL and the RSS feed from that URL, pick a random image from
857 # the feed. This is a lot simpler than extracting images out of a page:
858 # we already know we have reasonable images, so we just pick one.
859 # Returns: the real URL of the page (preferably not the RSS version),
862 sub pick_image_from_rss($$) {
863 my ( $url, $body ) = @_;
864 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
866 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
867 $base = $url unless $base;
869 # pick a random element of the table
871 my $i = int(rand(scalar @suitable));
872 my $url = $suitable[$i];
873 LOG ($verbose_load, "picked image " .($i+1) . "/" .
874 ($#suitable+1) . ": $url");
875 return ($base, $url);
881 ############################################################################
883 # Subroutines for getting pages and images out of search engines
885 ############################################################################
888 sub pick_dictionary() {
889 my @dicts = ("/usr/dict/words",
890 "/usr/share/dict/words",
891 "/usr/share/lib/dict/words",
892 "/usr/share/dict/cracklib-small",
893 "/usr/share/dict/cracklib-words"
895 foreach my $f (@dicts) {
901 error ("$dicts[0] does not exist") unless defined($wordlist);
904 # returns a random word from the dictionary
909 if (! open (IN, "<$wordlist")) {
913 my $size = (stat(IN))[7];
918 error ("looping ($count) while reading $wordlist")
921 my $pos = int (rand ($size));
922 if (seek (IN, $pos, 0)) {
923 $word = <IN>; # toss partial line
924 $word = <IN>; # keep next line
928 next if ($word =~ m/^[-\']/);
932 $word =~ s/^[^a-z]+//s;
933 $word =~ s/[^a-z]+$//s;
939 $word =~ s/ally$/al/s;
940 $word =~ s/izes$/ize/s;
941 $word =~ s/esses$/ess/s;
942 $word =~ s/(.{5})ing$/$1/s;
944 next if (length ($word) > 14);
950 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
951 $word = "\%22$word\%22"; # And put quotes (%22) around it.
958 sub random_words($) {
960 my $sep = ($or_p ? "%20OR%20" : "%20");
961 return (random_word . $sep .
971 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
978 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
987 $s =~ s/\"/"/gi;
991 sub html_unquote($) {
993 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
994 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
999 # Loads the given URL (a search on some search engine) and returns:
1000 # - the total number of hits the search engine claimed it had;
1001 # - a list of URLs from the page that the search engine returned;
1002 # Note that this list contains all kinds of internal search engine
1003 # junk URLs too -- caller must prune them.
1005 sub pick_from_search_engine($$$) {
1006 my ( $timeout, $search_url, $words ) = @_;
1011 print STDERR "\n\n" if ($verbose_load);
1013 LOG ($verbose_load, "words: $_");
1014 LOG ($verbose_load, "URL: $search_url");
1016 $last_search = $search_url; # for warnings
1019 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1020 if (defined ($timeout)) {
1021 $timeout -= (time - $start);
1022 if ($timeout <= 0) {
1024 LOG (($verbose_net || $verbose_load),
1025 "timed out (late) for $search_url");
1026 $suppress_audit = 1;
1031 return () if (! $body);
1036 my $search_count = "?";
1037 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
1039 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
1041 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
1043 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1045 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1047 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1049 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1051 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1053 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1054 $search_count = $1; # lycos
1055 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1056 $search_count = $1; # hotbot
1057 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1058 $search_count = "0";
1059 } elsif ($body =~ m@found no document matching@i) { # avtext
1060 $search_count = "0";
1062 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1064 # if ($search_count eq "?" || $search_count eq "0") {
1066 # my $file = "/tmp/wc.html";
1067 # open(OUT, ">$file") || error ("writing $file: $!");
1070 # print STDERR blurb() . "###### wrote $file\n";
1074 my $length = length($body);
1083 foreach (split(/\n/)) {
1085 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1088 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1089 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1091 if ( $rejected_urls{$u} ) {
1092 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1096 LOG ($verbose_http, " HREF: $u");
1098 $subpages[++$#subpages] = $u;
1101 if ( $#subpages < 0 ) {
1102 LOG ($verbose_filter,
1103 "found nothing on $base ($length bytes, $href_count links).");
1107 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1109 return ($search_count, @subpages);
1117 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1119 next unless defined($h);
1121 if ($poisoners{$h}) {
1122 LOG (($verbose_filter), " rejecting poisoner: $_");
1125 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1127 LOG (($verbose_filter), " rejecting poisoner: $_");
1130 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1132 LOG (($verbose_filter), " rejecting poisoner: $_");
1142 # given a list of URLs, picks one at random; loads it; and returns a
1143 # random image from it.
1144 # returns the url of the page loaded; the url of the image chosen.
1146 sub pick_image_from_pages($$$$@) {
1147 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1149 $total_hit_count = "?" unless defined($total_hit_count);
1151 @pages = depoison (@pages);
1153 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1154 " ($total_hit_count total)");
1156 return () if ($#pages < 0);
1158 my $i = int(rand($#pages+1));
1159 my $page = $pages[$i];
1161 LOG ($verbose_load, "picked page $page");
1163 $suppress_audit = 1;
1165 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1167 if (!$base2 || !$body2) {
1172 my $img = pick_image_from_body ($base2, $body2);
1176 return ($base2, $img);
1183 ############################################################################
1185 # Pick images from random pages returned by the Yahoo Random Link
1187 ############################################################################
1190 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1193 # Picks a random page; picks a random image on that page;
1194 # returns two URLs: the page containing the image, and the image.
1195 # Returns () if nothing found this time.
1197 sub pick_from_yahoo_random_link($) {
1200 print STDERR "\n\n" if ($verbose_load);
1201 LOG ($verbose_load, "URL: $yahoo_random_link");
1203 $last_search = $yahoo_random_link; # for warnings
1205 $suppress_audit = 1;
1207 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1208 if (!$base || !$body) {
1213 LOG ($verbose_load, "redirected to: $base");
1215 my $img = pick_image_from_body ($base, $body);
1219 return ($base, $img);
1226 ############################################################################
1228 # Pick images from random pages returned by the Alta Vista Random Link
1229 # Note: this seems to have gotten a *lot* less random lately (2007).
1231 ############################################################################
1234 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1237 # Picks a random page; picks a random image on that page;
1238 # returns two URLs: the page containing the image, and the image.
1239 # Returns () if nothing found this time.
1241 sub pick_from_alta_vista_random_link($) {
1244 print STDERR "\n\n" if ($verbose_load);
1245 LOG ($verbose_load, "URL: $alta_vista_random_link");
1247 $last_search = $alta_vista_random_link; # for warnings
1249 $suppress_audit = 1;
1251 my ( $base, $body ) = get_document ($alta_vista_random_link,
1253 if (!$base || !$body) {
1258 LOG ($verbose_load, "redirected to: $base");
1260 my $img = pick_image_from_body ($base, $body);
1264 return ($base, $img);
1271 ############################################################################
1273 # Pick images by feeding random words into Alta Vista Image Search
1275 ############################################################################
1278 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1279 "?ipht=1" . # photos
1280 "&igrph=1" . # graphics
1283 "&micat=1" . # no partner sites
1284 "&sc=on" . # "site collapse"
1288 sub pick_from_alta_vista_images($) {
1291 my $words = random_word();
1292 my $page = (int(rand(9)) + 1);
1293 my $search_url = $alta_vista_images_url . $words;
1296 $search_url .= "&pgno=" . $page; # page number
1297 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1300 my ($search_hit_count, @subpages) =
1301 pick_from_search_engine ($timeout, $search_url, $words);
1303 my @candidates = ();
1304 foreach my $u (@subpages) {
1306 # avimages is encoding their URLs now.
1307 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1308 $u = url_unquote($u);
1310 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1311 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1312 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1313 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1314 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1316 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1317 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1319 LOG ($verbose_filter, " candidate: $u");
1320 push @candidates, $u;
1323 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1324 $timeout, @candidates);
1329 ############################################################################
1331 # Pick images from Aptix security cameras
1332 # Cribbed liberally from google image search code.
1333 # By Jason Sullivan <jasonsul@us.ibm.com>
1335 ############################################################################
1337 my $aptix_images_url = ("http://www.google.com/search" .
1338 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1341 sub pick_from_security_camera($) {
1344 my $page = (int(rand(9)) + 1);
1345 my $num = 20; # 20 images per page
1346 my $search_url = $aptix_images_url;
1349 $search_url .= "&start=" . $page*$num; # page number
1350 $search_url .= "&num=" . $num; #images per page
1353 my ($search_hit_count, @subpages) =
1354 pick_from_search_engine ($timeout, $search_url, '');
1356 my @candidates = ();
1358 foreach my $u (@subpages) {
1359 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1360 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1362 LOG ($verbose_filter, " candidate: $u");
1363 push @candidates, $u;
1367 @candidates = depoison (@candidates);
1368 return () if ($#candidates < 0);
1369 my $i = int(rand($#candidates+1));
1370 my $img = $candidates[$i];
1371 my $ref = $referers{$img};
1373 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1374 return ($ref, $img);
1378 ############################################################################
1380 # Pick images by feeding random words into Google Image Search.
1381 # By Charles Gales <gales@us.ibm.com>
1383 ############################################################################
1386 my $google_images_url = "http://images.google.com/images" .
1387 "?site=images" . # photos
1388 "&btnG=Search" . # graphics
1389 "&safe=off" . # no screening
1394 sub pick_from_google_images($;$$) {
1395 my ($timeout, $words, $max_page) = @_;
1397 if (!defined($words)) {
1398 $words = random_word; # only one word for Google
1401 my $page = (int(rand(9)) + 1);
1402 my $num = 20; # 20 images per page
1403 my $search_url = $google_images_url . $words;
1406 $search_url .= "&start=" . $page*$num; # page number
1407 $search_url .= "&num=" . $num; #images per page
1410 my ($search_hit_count, @subpages) =
1411 pick_from_search_engine ($timeout, $search_url, $words);
1413 my @candidates = ();
1415 foreach my $u (@subpages) {
1416 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1417 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1419 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1422 $img = "http://$img" unless ($img =~ m/^http:/i);
1424 LOG ($verbose_filter, " candidate: $ref");
1425 push @candidates, $img;
1426 $referers{$img} = $ref;
1430 @candidates = depoison (@candidates);
1431 return () if ($#candidates < 0);
1432 my $i = int(rand($#candidates+1));
1433 my $img = $candidates[$i];
1434 my $ref = $referers{$img};
1436 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1437 return ($ref, $img);
1442 ############################################################################
1444 # Pick images by feeding random numbers into Google Image Search.
1445 # By jwz, suggested by Ian O'Donnell.
1447 ############################################################################
1451 sub pick_from_google_image_numbers($) {
1455 my $number = int(rand($max));
1457 $number = sprintf("%04d", $number)
1460 pick_from_google_images ($timeout, "$number");
1465 ############################################################################
1467 # Pick images by feeding random digital camera file names into
1468 # Google Image Search.
1469 # By jwz, inspired by the excellent Random Personal Picture Finder
1470 # at http://www.diddly.com/random/
1472 ############################################################################
1476 # Common digital camera file name formats, as described at
1477 # http://www.diddly.com/random/about.html
1479 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1480 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1481 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1482 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1483 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1484 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1485 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1486 int(rand(0xC)), int(rand(30))+1,
1488 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1489 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1490 sub { my $n = int(rand(9999)); # Canon
1491 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1492 sub { my $n = int(rand(9999)); # Canon
1493 sprintf ("1%02d-%04d_IMG.jpg",
1494 int($n/100), $n); },
1495 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1496 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1497 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1498 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1499 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1500 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1501 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1502 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1503 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1504 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1505 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1506 # int(rand(12))+1, int(rand(31))+1,
1507 # int(rand(999))); },
1508 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1509 # int(rand(6)), # year
1510 # int(rand(12))+1, int(rand(31))+1,
1511 # int(rand(999))); },
1512 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1513 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1514 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1515 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1520 sub pick_from_google_image_photos($) {
1523 my $i = int(rand($#photomakers + 1));
1524 my $fn = $photomakers[$i];
1526 my $words .= $file . "%20filetype:jpg";
1528 pick_from_google_images ($timeout, $words);
1533 ############################################################################
1535 # Pick images by feeding random words into Alta Vista Text Search
1537 ############################################################################
1540 my $alta_vista_url = "http://www.altavista.com/web/results" .
1544 "&sc=on" . # "site collapse"
1549 sub pick_from_alta_vista_text($) {
1552 my $words = random_words(0);
1553 my $page = (int(rand(9)) + 1);
1554 my $search_url = $alta_vista_url . $words;
1557 $search_url .= "&pgno=" . $page;
1558 $search_url .= "&stq=" . (($page-1) * 10);
1561 my ($search_hit_count, @subpages) =
1562 pick_from_search_engine ($timeout, $search_url, $words);
1564 my @candidates = ();
1565 foreach my $u (@subpages) {
1567 # Those altavista fuckers are playing really nasty redirection games
1568 # these days: the filter your clicks through their site, but use
1569 # onMouseOver to make it look like they're not! Well, it makes it
1570 # easier for us to identify search results...
1572 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1573 $u = url_unquote($u);
1575 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1576 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1577 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1579 LOG ($verbose_filter, " candidate: $u");
1580 push @candidates, $u;
1583 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1584 $timeout, @candidates);
1589 ############################################################################
1591 # Pick images by feeding random words into Hotbot
1593 ############################################################################
1595 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1597 "&descriptiontype=0" .
1604 "&cobrand=undefined" .
1607 sub pick_from_hotbot_text($) {
1610 $last_search = $hotbot_search_url; # for warnings
1612 # lycos seems to always give us back dictionaries and word lists if
1613 # we search for more than one word...
1615 my $words = random_word();
1617 my $start = int(rand(8)) * 10 + 1;
1618 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1620 my ($search_hit_count, @subpages) =
1621 pick_from_search_engine ($timeout, $search_url, $words);
1623 my @candidates = ();
1624 foreach my $u (@subpages) {
1626 # Hotbot plays redirection games too
1628 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1629 # $u = url_decode($1);
1631 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1632 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1633 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1634 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1636 LOG ($verbose_filter, " candidate: $u");
1637 push @candidates, $u;
1640 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1641 $timeout, @candidates);
1646 ############################################################################
1648 # Pick images by feeding random words into Lycos
1650 ############################################################################
1652 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1658 sub pick_from_lycos_text($) {
1661 $last_search = $lycos_search_url; # for warnings
1663 # lycos seems to always give us back dictionaries and word lists if
1664 # we search for more than one word...
1666 my $words = random_word();
1668 my $start = int(rand(8)) * 10 + 1;
1669 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1671 my ($search_hit_count, @subpages) =
1672 pick_from_search_engine ($timeout, $search_url, $words);
1674 my @candidates = ();
1675 foreach my $u (@subpages) {
1677 # Lycos plays redirection games.
1679 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1684 # $u = url_decode($1);
1686 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1687 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1688 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1689 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1690 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1693 LOG ($verbose_filter, " candidate: $u");
1694 push @candidates, $u;
1697 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1698 $timeout, @candidates);
1703 ############################################################################
1705 # Pick images by feeding random words into news.yahoo.com
1707 ############################################################################
1709 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1714 sub pick_from_yahoo_news_text($) {
1717 $last_search = $yahoo_news_url; # for warnings
1719 my $words = random_word();
1720 my $search_url = $yahoo_news_url . $words;
1722 my ($search_hit_count, @subpages) =
1723 pick_from_search_engine ($timeout, $search_url, $words);
1725 my @candidates = ();
1726 foreach my $u (@subpages) {
1728 # de-redirectize the URLs
1729 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1731 # only accept URLs on Yahoo's news site
1732 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1733 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1734 next unless ($u =~ m@&u=/@);
1736 LOG ($verbose_filter, " candidate: $u");
1737 push @candidates, $u;
1740 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1741 $timeout, @candidates);
1746 ############################################################################
1748 # Pick images from LiveJournal's list of recently-posted images.
1750 ############################################################################
1752 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1754 # With most of our image sources, we get a random page and then select
1755 # from the images on it. However, in the case of LiveJournal, the page
1756 # of images tends to update slowly; so we'll remember the last N entries
1757 # on it and randomly select from those, to get a wider variety each time.
1759 my $lj_cache_size = 1000;
1760 my @lj_cache = (); # fifo, for ordering by age
1761 my %lj_cache = (); # hash, for detecting dups
1764 sub pick_from_livejournal_images($) {
1767 $last_search = $livejournal_img_url; # for warnings
1769 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1770 return () unless $body;
1773 $body =~ s/(<recent-image)\b/\n$1/gsi;
1775 foreach (split (/\n/, $body)) {
1776 next unless (m/^<recent-image\b/);
1777 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1778 my $img = html_unquote ($1);
1780 next if ($lj_cache{$img}); # already have it
1782 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1783 my $page = html_unquote ($1);
1784 my @pair = ($img, $page);
1785 LOG ($verbose_filter, " candidate: $img");
1786 push @lj_cache, \@pair;
1787 $lj_cache{$img} = \@pair;
1790 return () if ($#lj_cache == -1);
1792 my $n = $#lj_cache+1;
1793 my $i = int(rand($n));
1794 my ($img, $page) = @{$lj_cache[$i]};
1796 # delete this one from @lj_cache and from %lj_cache.
1798 @lj_cache = ( @lj_cache[0 .. $i-1],
1799 @lj_cache[$i+1 .. $#lj_cache] );
1800 delete $lj_cache{$img};
1802 # Keep the size of the cache under the limit by nuking older entries
1804 while ($#lj_cache >= $lj_cache_size) {
1805 my $pairP = shift @lj_cache;
1806 my $img = $pairP->[0];
1807 delete $lj_cache{$img};
1810 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1812 return ($page, $img);
1816 ############################################################################
1818 # Pick images from ircimages.com (images that have been in the /topic of
1819 # various IRC channels.)
1821 ############################################################################
1823 my $ircimages_url = "http://ircimages.com/";
1826 sub pick_from_ircimages($) {
1829 $last_search = $ircimages_url; # for warnings
1831 my $n = int(rand(2900));
1832 my $search_url = $ircimages_url . "page-$n";
1834 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1835 return () unless $body;
1837 my @candidates = ();
1840 $body =~ s/(<A)\b/\n$1/gsi;
1842 foreach (split (/\n/, $body)) {
1844 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1847 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1848 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1850 next unless ($u =~ m/^http:/i);
1851 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1852 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1854 LOG ($verbose_http, " HREF: $u");
1855 push @candidates, $u;
1858 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1860 return () if ($#candidates == -1);
1862 my $i = int(rand($#candidates+1));
1863 my $img = $candidates[$i];
1865 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1868 $search_url = $img; # hmm...
1869 return ($search_url, $img);
1873 ############################################################################
1875 # Pick images from Twitter's list of recently-posted images.
1877 ############################################################################
1879 my $twitter_img_url = "http://twitpic.com/public_timeline/feed.rss";
1881 # With most of our image sources, we get a random page and then select
1882 # from the images on it. However, in the case of Twitter, the page
1883 # of images tends to update slowly; so we'll remember the last N entries
1884 # on it and randomly select from those, to get a wider variety each time.
1886 my $twit_cache_size = 1000;
1887 my @twit_cache = (); # fifo, for ordering by age
1888 my %twit_cache = (); # hash, for detecting dups
1891 sub pick_from_twitter_images($) {
1894 $last_search = $twitter_img_url; # for warnings
1896 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
1902 $body =~ s/(<item)\b/\n$1/gsi;
1904 my @items = split (/\n/, $body);
1907 next unless (m@<link>([^<>]*)</link>@si);
1908 my $page = html_unquote ($1);
1913 next if ($twit_cache{$page}); # already have it
1915 LOG ($verbose_filter, " candidate: $page");
1916 push @twit_cache, $page;
1917 $twit_cache{$page} = $page;
1921 # Pull from the cache.
1923 return () if ($#twit_cache == -1);
1925 my $n = $#twit_cache+1;
1926 my $i = int(rand($n));
1927 my $page = $twit_cache[$i];
1929 # delete this one from @twit_cache and from %twit_cache.
1931 @twit_cache = ( @twit_cache[0 .. $i-1],
1932 @twit_cache[$i+1 .. $#twit_cache] );
1933 delete $twit_cache{$page};
1935 # Keep the size of the cache under the limit by nuking older entries
1937 while ($#twit_cache >= $twit_cache_size) {
1938 my $page = shift @twit_cache;
1939 delete $twit_cache{$page};
1942 ( $base, $body ) = get_document ($page, undef, $timeout);
1945 foreach (split (/<img\s+/, $body)) {
1946 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1949 next if m@/images/@s;
1953 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
1954 if ($img =~ m@^/@) {
1955 $base =~ s@^(https?://[^/]+)/.*@$1@s;
1956 $img = $base . $img;
1962 LOG ($verbose_load, "no matching images on $page\n");
1966 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1968 return ($page, $img);
1972 ############################################################################
1974 # Pick images from Flickr's page of recently-posted photos.
1976 ############################################################################
1978 my $flickr_img_url = "http://www.flickr.com/photos/";
1980 # Like LiveJournal, the Flickr page of images tends to update slowly,
1981 # so remember the last N entries on it and randomly select from those.
1983 # I know that Flickr has an API (http://www.flickr.com/services/api/)
1984 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
1986 my $flickr_cache_size = 1000;
1987 my @flickr_cache = (); # fifo, for ordering by age
1988 my %flickr_cache = (); # hash, for detecting dups
1992 sub pick_from_flickr_recent($) {
1995 my $start = 16 * int(rand(100));
1997 $last_search = $flickr_img_url; # for warnings
1998 $last_search .= "?start=$start" if ($start > 0);
2000 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2001 return () unless $body;
2003 $body =~ s/[\r\n]/ /gs;
2004 $body =~ s/(<a)\b/\n$1/gsi;
2008 foreach (split (/\n/, $body)) {
2009 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2010 <IMG \s [^<>]* \b SRC=\"([^<>\"]+)\" @xsi;
2011 next unless defined ($thumb);
2012 $page = html_unquote ($page);
2013 $thumb = html_unquote ($thumb);
2015 next unless ($thumb =~ m@^http://farm\d*\.static\.flickr\.com/@);
2017 my $base = "http://www.flickr.com/";
2018 $page =~ s@^/@$base@;
2019 $thumb =~ s@^/@$base@;
2022 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2025 next if ($flickr_cache{$img}); # already have it
2027 my @pair = ($img, $page, $start);
2028 LOG ($verbose_filter, " candidate: $img");
2029 push @flickr_cache, \@pair;
2030 $flickr_cache{$img} = \@pair;
2034 return () if ($#flickr_cache == -1);
2036 my $n = $#flickr_cache+1;
2037 my $i = int(rand($n));
2038 my ($img, $page) = @{$flickr_cache[$i]};
2040 # delete this one from @flickr_cache and from %flickr_cache.
2042 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2043 @flickr_cache[$i+1 .. $#flickr_cache] );
2044 delete $flickr_cache{$img};
2046 # Keep the size of the cache under the limit by nuking older entries
2048 while ($#flickr_cache >= $flickr_cache_size) {
2049 my $pairP = shift @flickr_cache;
2050 my $img = $pairP->[0];
2051 delete $flickr_cache{$img};
2054 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2056 return ($page, $img);
2060 ############################################################################
2062 # Pick images from a random RSS feed on Flickr.
2064 ############################################################################
2066 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne" .
2067 "?format=rss_200_enc&tags=");
2069 # Picks a random RSS feed; picks a random image from that feed;
2070 # returns 2 URLs: the page containing the image, and the image.
2071 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2074 sub pick_from_flickr_random($) {
2075 my $timeout = shift;
2077 my $rss = $flickr_rss_base . random_word();
2078 $last_search = $rss;
2080 print STDERR "\n\n" if ($verbose_load);
2081 LOG ($verbose_load, "URL: $last_search");
2083 $suppress_audit = 1;
2085 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2086 if (!$base || !$body) {
2092 ($base, $img) = pick_image_from_rss ($base, $body);
2094 return () unless defined ($img);
2096 LOG ($verbose_load, "redirected to: $base");
2097 return ($base, $img);
2101 ############################################################################
2103 # Pick images by waiting for driftnet to populate a temp dir with files.
2104 # Requires driftnet version 0.1.5 or later.
2105 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2106 # for images being downloaded by others.)
2107 # Driftnet/webcollage integration by jwz.
2109 ############################################################################
2112 sub pick_from_driftnet($) {
2115 my $id = $driftnet_magic;
2116 my $dir = $driftnet_dir;
2120 error ("\$driftnet_dir unset?") unless ($dir);
2123 error ("$dir unreadable") unless (-d "$dir/.");
2125 $timeout = $http_timeout unless ($timeout);
2128 while ($now = time, $now < $start + $timeout) {
2130 opendir (DIR, $dir) || error ("$dir: $!");
2131 while (my $file = readdir(DIR)) {
2132 next if ($file =~ m/^\./);
2133 $file = "$dir/$file";
2135 LOG ($verbose_load, "picked file $file ($id)");
2136 return ($id, $file);
2140 LOG (($verbose_net || $verbose_load), "timed out for $id");
2145 sub get_driftnet_file($) {
2148 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2150 my $id = $driftnet_magic;
2151 my $re = qr/$driftnet_dir/;
2152 error ("$id: $file not in $driftnet_dir?")
2153 unless ($file =~ m@^$re@o);
2156 open (IN, $file) || error ("$id: $file: $!");
2158 while (<IN>) { $body .= $_; }
2159 close IN || error ("$id: $file: $!");
2160 unlink ($file) || error ("$id: $file: rm: $!");
2161 return ($id, $body);
2165 sub spawn_driftnet($) {
2168 # make a directory to use.
2170 my $tmp = $ENV{TEMPDIR} || "/tmp";
2171 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2172 LOG ($verbose_exec, "mkdir $driftnet_dir");
2173 last if mkdir ($driftnet_dir, 0700);
2176 if (! ($cmd =~ m/\s/)) {
2177 # if the command didn't have any arguments in it, then it must be just
2178 # a pointer to the executable. Append the default args to it.
2179 my $dargs = $default_driftnet_cmd;
2180 $dargs =~ s/^[^\s]+//;
2184 # point the driftnet command at our newly-minted private directory.
2186 $cmd .= " -d $driftnet_dir";
2187 $cmd .= ">/dev/null" unless ($verbose_exec);
2190 if ($pid < 0) { error ("fork: $!\n"); }
2193 push @pids_to_kill, $pid;
2194 LOG ($verbose_exec, "forked for \"$cmd\"");
2197 nontrapping_system ($cmd) || error ("exec: $!");
2200 # wait a bit, then make sure the process actually started up.
2203 error ("pid $pid failed to start \"$cmd\"")
2204 unless (1 == kill (0, $pid));
2208 sub pick_from_local_dir {
2209 my ( $timeout ) = @_;
2211 my $id = $local_magic;
2214 my $dir = $local_dir;
2215 error ("\$local_dir unset?") unless ($dir);
2218 error ("$dir unreadable") unless (-d "$dir/.");
2220 my $v = ($verbose_exec ? "-v" : "");
2221 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2223 LOG ($verbose_load, "picked file $pick ($id)");
2224 return ($id, $pick);
2228 sub get_local_file {
2231 error ("\$local_dir unset?") unless ($local_dir);
2233 my $id = $local_magic;
2234 my $re = qr/$local_dir/;
2235 error ("$id: $file not in $local_dir?")
2236 unless ($file =~ m@^$re@o);
2239 open (IN, $file) || error ("$id: $file: $!");
2241 while (<IN>) { $body .= $_; }
2242 close IN || error ("$id: $file: $!");
2243 return ($id, $body);
2248 ############################################################################
2250 # Pick a random image in a random way
2252 ############################################################################
2255 # Picks a random image on a random page, and returns two URLs:
2256 # the page containing the image, and the image.
2257 # Returns () if nothing found this time.
2260 sub pick_image(;$) {
2263 $current_state = "select";
2264 $load_method = "none";
2266 my $n = int(rand(100));
2269 my @rest = @search_methods;
2272 my $pct = shift @rest;
2273 my $name = shift @rest;
2274 my $tfn = shift @rest;
2276 if ($total > $n && !defined($fn)) {
2278 $current_state = $name;
2279 $load_method = $current_state;
2283 if ($total != 100) {
2284 error ("internal error: \@search_methods totals to $total%!");
2287 record_attempt ($current_state);
2288 return $fn->($timeout);
2293 ############################################################################
2295 # Statistics and logging
2297 ############################################################################
2300 return strftime ("%H:%M:%S: ", localtime);
2304 return "$progname: " . timestr() . "$current_state: ";
2309 print STDERR blurb() . "$err\n";
2315 print STDERR "$progname: stack trace:\n";
2317 my ($package, $filename, $line, $subroutine) = caller($i++);
2318 last unless defined($package);
2319 $filename =~ s@^.*/@@;
2320 print STDERR " $filename#$line, $subroutine\n";
2332 my $head = "$progname: DEBUG: ";
2333 foreach (split (/\n/, $lastlog)) {
2334 print STDERR "$head$_\n";
2340 my ($print, $msg) = @_;
2341 my $blurb = timestr() . "$current_state: ";
2342 $lastlog .= "$blurb$msg\n";
2343 print STDERR "$progname: $blurb$msg\n" if $print;
2348 my %stats_successes;
2351 my $last_state = undef;
2352 sub record_attempt($) {
2356 record_failure($last_state) unless ($image_succeeded > 0);
2358 $last_state = $name;
2361 report_performance();
2364 $image_succeeded = 0;
2365 $suppress_audit = 0;
2368 sub record_success($$$) {
2369 my ($name, $url, $base) = @_;
2370 if (defined($stats_successes{$name})) {
2371 $stats_successes{$name}++;
2373 $stats_successes{$name} = 1;
2376 stop_timer ($name, 1);
2377 my $o = $current_state;
2378 $current_state = $name;
2379 save_recent_url ($url, $base);
2380 $current_state = $o;
2381 $image_succeeded = 1;
2386 sub record_failure($) {
2389 return if $image_succeeded;
2391 stop_timer ($name, 0);
2392 if ($verbose_load && !$verbose_exec) {
2394 if ($suppress_audit) {
2395 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2399 my $o = $current_state;
2400 $current_state = "DEBUG";
2402 my $line = "#" x 78;
2403 print STDERR "\n\n\n";
2404 print STDERR ("#" x 78) . "\n";
2405 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2408 print STDERR ("-" x 78) . "\n";
2409 print STDERR "\n\n";
2411 $current_state = $o;
2413 $image_succeeded = 0;
2420 my $i = $stats_successes{$name};
2421 my $j = $stats_attempts{$name};
2424 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2428 my $current_start_time = 0;
2430 sub start_timer($) {
2432 $current_start_time = time;
2434 if (defined($stats_attempts{$name})) {
2435 $stats_attempts{$name}++;
2437 $stats_attempts{$name} = 1;
2439 if (!defined($stats_elapsed{$name})) {
2440 $stats_elapsed{$name} = 0;
2444 sub stop_timer($$) {
2445 my ($name, $success) = @_;
2446 $stats_elapsed{$name} += time - $current_start_time;
2450 my $last_report_time = 0;
2451 sub report_performance() {
2453 return unless $verbose_warnings;
2456 return unless ($now >= $last_report_time + $report_performance_interval);
2457 my $ot = $last_report_time;
2458 $last_report_time = $now;
2460 return if ($ot == 0);
2462 my $blurb = "$progname: " . timestr();
2465 print STDERR "${blurb}Current standings:\n";
2467 foreach my $name (sort keys (%stats_attempts)) {
2468 my $try = $stats_attempts{$name};
2469 my $suc = $stats_successes{$name} || 0;
2470 my $pct = int($suc * 100 / $try);
2471 my $secs = $stats_elapsed{$name};
2472 my $secs_link = $secs / $try;
2473 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2474 " \t %.1f secs/link\n",
2475 "$name:", "$pct%", $suc, $try, $secs_link);
2481 my $max_recent_images = 400;
2482 my $max_recent_sites = 20;
2483 my @recent_images = ();
2484 my @recent_sites = ();
2486 sub save_recent_url($$) {
2487 my ($url, $base) = @_;
2489 return unless ($verbose_warnings);
2492 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2493 return unless defined ($site);
2495 if ($base eq $driftnet_magic || $base eq $local_magic) {
2497 @recent_images = ();
2501 foreach (@recent_images) {
2503 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2504 " (on $base via $last_search)\n";
2510 # suppress "duplicate site" warning via %warningless_sites.
2512 if ($warningless_sites{$site}) {
2514 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2515 $warningless_sites{$1}) {
2517 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2518 $warningless_sites{$1}) {
2523 foreach (@recent_sites) {
2525 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2526 " ($url on $base via $last_search)\n";
2532 push @recent_images, $url;
2533 push @recent_sites, $site;
2534 shift @recent_images if ($#recent_images >= $max_recent_images);
2535 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2540 ##############################################################################
2544 ##############################################################################
2551 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2556 # Given the raw body of a GIF document, returns the dimensions of the image.
2560 my $type = substr($body, 0, 6);
2562 return () unless ($type =~ /GIF8[7,9]a/);
2563 $s = substr ($body, 6, 10);
2564 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2565 return () unless defined ($d);
2566 return (($b<<8|$a), ($d<<8|$c));
2569 # Given the raw body of a JPEG document, returns the dimensions of the image.
2574 my $L = length($body);
2576 my $c1 = substr($body, $i, 1); $i++;
2577 my $c2 = substr($body, $i, 1); $i++;
2578 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2581 while (ord($ch) != 0xDA && $i < $L) {
2582 # Find next marker, beginning with 0xFF.
2583 while (ord($ch) != 0xFF) {
2584 return () if (length($body) <= $i);
2585 $ch = substr($body, $i, 1); $i++;
2587 # markers can be padded with any number of 0xFF.
2588 while (ord($ch) == 0xFF) {
2589 return () if (length($body) <= $i);
2590 $ch = substr($body, $i, 1); $i++;
2593 # $ch contains the value of the marker.
2594 my $marker = ord($ch);
2596 if (($marker >= 0xC0) &&
2597 ($marker <= 0xCF) &&
2598 ($marker != 0xC4) &&
2599 ($marker != 0xCC)) { # it's a SOFn marker
2601 return () if (length($body) <= $i);
2602 my $s = substr($body, $i, 4); $i += 4;
2603 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2604 return (($c<<8|$d), ($a<<8|$b));
2607 # We must skip variables, since FFs in variable names aren't
2608 # valid JPEG markers.
2609 return () if (length($body) <= $i);
2610 my $s = substr($body, $i, 2); $i += 2;
2611 my ($c1, $c2) = unpack ("C"x2, $s);
2612 my $length = ($c1 << 8) | $c2;
2613 return () if ($length < 2);
2620 # Given the raw body of a PNG document, returns the dimensions of the image.
2624 return () unless ($body =~ m/^\211PNG\r/);
2625 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2626 return () unless defined ($bits);
2627 return () unless ($bits =~ /^IHDR/);
2628 my ($ign, $w, $h) = unpack("a4N2", $bits);
2633 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2638 my ($w, $h) = gif_size ($body);
2639 if ($w && $h) { return ($w, $h); }
2640 ($w, $h) = jpeg_size ($body);
2641 if ($w && $h) { return ($w, $h); }
2642 return png_size ($body);
2646 # returns the full path of the named program, or undef.
2650 foreach (split (/:/, $ENV{PATH})) {
2651 if (-x "$_/$prog") {
2659 # Like rand(), but chooses numbers with a bell curve distribution.
2662 $_ = 1.0 unless defined($_);
2664 return (rand($_) + rand($_) + rand($_));
2668 sub exit_cleanup() {
2670 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2671 if (@pids_to_kill) {
2672 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2673 kill ('TERM', @pids_to_kill);
2677 sub signal_cleanup($) {
2679 print STDERR blurb() . (defined($sig)
2680 ? "caught signal $sig."
2683 if ($verbose_exec || $verbose_warnings);
2689 ##############################################################################
2691 # Generating a list of urls only
2693 ##############################################################################
2695 sub url_only_output() {
2697 my ($base, $img) = pick_image;
2701 print "$img $base\n";
2706 ##############################################################################
2708 # Running as an xscreensaver module, or as a web page imagemap
2710 ##############################################################################
2712 my $image_ppm = sprintf ("%s/webcollage-%08x",
2713 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2715 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x",
2716 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2718 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x",
2719 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2722 my $filter_cmd = undef;
2723 my $post_filter_cmd = undef;
2724 my $background = undef;
2726 my @imagemap_areas = ();
2727 my $imagemap_html_tmp = undef;
2728 my $imagemap_jpg_tmp = undef;
2731 my $img_width; # size of the image being generated.
2737 unlink $image_ppm, $image_tmp1, $image_tmp2;
2738 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2739 if (defined ($imagemap_html_tmp));
2743 # Like system, but prints status about exit codes, and kills this process
2744 # with whatever signal killed the sub-process, if any.
2746 sub nontrapping_system(@) {
2750 s/\"[^\"]+\"/\"...\"/g;
2752 LOG ($verbose_exec, "executing \"$_\"");
2757 LOG ($verbose_exec, "subproc exited normally.");
2758 } elsif (($rc & 0xff) == 0) {
2760 LOG ($verbose_exec, "subproc exited with status $rc.");
2763 LOG ($verbose_exec, "subproc dumped core.");
2766 LOG ($verbose_exec, "subproc died with signal $rc.");
2767 # die that way ourselves.
2775 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2776 # writes a PPM to the given output file. Returns the width/height of the
2777 # image if successful.
2779 sub image_to_pnm($$$) {
2780 my ($url, $body, $output) = @_;
2781 my ($cmd, $cmd2, $w, $h);
2783 if ((@_ = gif_size ($body))) {
2786 } elsif ((@_ = jpeg_size ($body))) {
2789 } elsif ((@_ = png_size ($body))) {
2793 LOG (($verbose_pbm || $verbose_load),
2794 "not a GIF, JPG, or PNG" .
2795 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2796 ? " (looks like HTML)" : "") .
2798 $suppress_audit = 1;
2802 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2803 # do this, the process doesn't die properly.
2804 if (!$verbose_pbm) {
2806 # We get a "giftopnm: got a 'Application Extension' extension"
2807 # warning any time it's an animgif.
2809 # Note that "giftopnm: EOF / read error on image data" is not
2810 # always a fatal error -- sometimes the image looks fine anyway.
2812 $cmd2 .= " 2>/dev/null";
2815 # There exist corrupted GIF and JPEG files that can make giftopnm and
2816 # djpeg lose their minds and go into a loop. So this gives those programs
2817 # a small timeout -- if they don't complete in time, kill them.
2823 local $SIG{ALRM} = sub {
2825 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2826 kill ('TERM', $pid) if ($pid);
2831 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2838 LOG ($verbose_exec, "awaiting $pid");
2840 LOG ($verbose_exec, "$pid completed");
2842 my $size = (stat($output))[7];
2843 $size = -1 unless defined($size);
2845 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2849 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2852 print STDERR blurb() . "$cmd failed: $!\n";
2856 die if ($@ && $@ ne "alarm\n"); # propagate errors
2870 # Same as the "ppmmake" command: creates a solid-colored PPM.
2871 # Does not understand the rgb.txt color names except "black" and "white".
2874 my ($outfile, $bgcolor, $w, $h) = @_;
2877 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
2878 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
2879 ($r, $g, $b) = (hex($1), hex($2), hex($3));
2880 } elsif ($bgcolor =~ m/^black$/i) {
2881 ($r, $g, $b) = (0, 0, 0);
2882 } elsif ($bgcolor =~ m/^white$/i) {
2883 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
2885 error ("unparsable color name: $bgcolor");
2888 my $pixel = pack('CCC', $r, $g, $b);
2889 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
2892 open (OUT, ">$outfile") || error ("$outfile: $!");
2898 sub pick_root_displayer() {
2902 # see "xscreensaver/hacks/webcollage-cocoa.m"
2903 return "echo COCOA LOAD ";
2906 foreach my $cmd (@root_displayers) {
2908 my ($name) = m/^([^ ]+)/;
2909 push @names, "\"$name\"";
2910 LOG ($verbose_exec, "looking for $name...");
2911 foreach my $dir (split (/:/, $ENV{PATH})) {
2912 LOG ($verbose_exec, " checking $dir/$name");
2913 return $cmd if (-x "$dir/$name");
2917 $names[$#names] = "or " . $names[$#names];
2918 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2922 my $ppm_to_root_window_cmd = undef;
2925 sub x_or_pbm_output($) {
2926 my ($window_id) = @_;
2928 # Check for our helper program, to see whether we need to use PPM pipelines.
2930 $_ = "webcollage-helper";
2931 if (defined ($webcollage_helper) || which ($_)) {
2932 $webcollage_helper = $_ unless (defined($webcollage_helper));
2933 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2934 $webcollage_helper .= " -v";
2936 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2939 if ($cocoa_p && !defined ($webcollage_helper)) {
2940 error ("webcollage-helper not found in Cocoa-mode!");
2944 # make sure the various programs we execute exist, right up front.
2948 if (!defined($webcollage_helper)) {
2949 # Only need these others if we don't have the helper.
2951 "giftopnm", "pngtopnm", "djpeg",
2952 "pnmpaste", "pnmscale", "pnmcut");
2956 which ($_) || error "$_ not found on \$PATH.";
2959 # find a root-window displayer program.
2961 if (!$no_output_p) {
2962 $ppm_to_root_window_cmd = pick_root_displayer();
2965 if (defined ($window_id)) {
2966 error ("-window-id only works if xscreensaver-getimage is installed")
2967 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
2969 error ("unparsable window id: $window_id")
2970 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
2971 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
2972 error ("unable to munge displayer: $ppm_to_root_window_cmd");
2975 if (!$img_width || !$img_height) {
2977 if (!defined ($window_id) &&
2978 defined ($ENV{XSCREENSAVER_WINDOW})) {
2979 $window_id = $ENV{XSCREENSAVER_WINDOW};
2982 if (!defined ($window_id)) {
2984 which ($_) || error "$_ not found on \$PATH.";
2986 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2987 if (!defined($img_height)) {
2988 error "xdpyinfo failed.";
2990 } else { # we have a window id
2992 which ($_) || error "$_ not found on \$PATH.";
2993 $_ .= " -id $window_id";
2995 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
2997 if (!defined($img_height)) {
2998 error "xwininfo failed.";
3003 my $bgcolor = "#000000";
3004 my $bgimage = undef;
3007 if ($background =~ m/^\#[0-9a-f]+$/i) {
3008 $bgcolor = $background;
3010 } elsif (-r $background) {
3011 $bgimage = $background;
3013 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3014 error "not a color or readable file: $background";
3017 # default to assuming it's a color
3018 $bgcolor = $background;
3022 # Create the sold-colored base image.
3024 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3025 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3027 # Paste the default background image in the middle of it.
3034 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
3036 while (<IMG>) { $body .= $_; }
3039 if ((@_ = gif_size ($body))) {
3041 $cmd = "giftopnm |";
3043 } elsif ((@_ = jpeg_size ($body))) {
3047 } elsif ((@_ = png_size ($body))) {
3049 $cmd = "pngtopnm |";
3051 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3057 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3060 my $x = int (($img_width - $iw) / 2);
3061 my $y = int (($img_height - $ih) / 2);
3063 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3065 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3066 open (IMG, "| $cmd") || error "running $cmd: $!";
3070 LOG ($verbose_exec, "subproc exited normally.");
3071 rename ($image_tmp1, $image_ppm) ||
3072 error "renaming $image_tmp1 to $image_ppm: $!";
3078 my ($base, $img) = pick_image();
3079 my $source = $current_state;
3080 $current_state = "loadimage";
3082 my ($headers, $body) = get_document ($img, $base);
3084 paste_image ($base, $img, $body, $source);
3088 $current_state = "idle";
3089 $load_method = "none";
3091 unlink $image_tmp1, $image_tmp2;
3096 sub paste_image($$$$) {
3097 my ($base, $img, $body, $source) = @_;
3099 $current_state = "paste";
3101 $suppress_audit = 0;
3103 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3107 # If we are using the webcollage-helper, then we do not need to convert this
3108 # image to a PPM. But, if we're using a filter command, we still must, since
3109 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3112 if (defined ($webcollage_helper) &&
3113 !defined ($filter_cmd)) {
3115 ($iw, $ih) = image_size ($body);
3117 LOG (($verbose_pbm || $verbose_load),
3118 "not a GIF, JPG, or PNG" .
3119 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3120 ? " (looks like HTML)" : "") .
3122 $suppress_audit = 1;
3128 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
3129 print OUT $body || error ("writing $image_tmp1: $!");
3130 close OUT || error ("writing $image_tmp1: $!");
3133 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3136 LOG ($verbose_pbm, "unable to make PBM from $img");
3141 record_success ($load_method, $img, $base);
3144 my $ow = $iw; # used only for error messages
3147 # don't just tack this onto the front of the pipeline -- we want it to
3148 # be able to change the size of the input image.
3151 LOG ($verbose_pbm, "running $filter_cmd");
3153 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3155 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3156 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3159 rename ($image_tmp2, $image_tmp1);
3161 # re-get the width/height in case the filter resized it.
3163 open(IMG, "<$image_tmp1") || return 0;
3166 ($iw, $ih) = m/^(\d+) (\d+)$/;
3168 return 0 unless ($iw && $ih);
3171 my $target_w = $img_width; # max rectangle into which the image must fit
3172 my $target_h = $img_height;
3178 # Usually scale the image to fit on the screen -- but sometimes scale it
3179 # to fit on half or a quarter of the screen. (We do this by reducing the
3180 # size of the target rectangle.) Note that the image is not merely scaled
3181 # to fit; we instead cut the image in half repeatedly until it fits in the
3182 # target rectangle -- that gives a wider distribution of sizes.
3184 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3185 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3187 if ($iw > $target_w || $ih > $target_h) {
3188 while ($iw > $target_w ||
3194 if ($iw <= 10 || $ih <= 10) {
3195 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3199 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3201 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3205 my $src = $image_tmp1;
3207 my $crop_x = 0; # the sub-rectangle of the image
3208 my $crop_y = 0; # that we will actually paste.
3212 # The chance that we will randomly crop out a section of an image starts
3213 # out fairly low, but goes up for images that are very large, or images
3214 # that have ratios that make them look like banners (we try to avoid
3215 # banner images entirely, but they slip through when the IMG tags didn't
3216 # have WIDTH and HEIGHT specified.)
3218 my $crop_chance = 0.2;
3219 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3220 $crop_chance += 0.2;
3222 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3223 $crop_chance += 0.2;
3225 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3226 $crop_chance += 0.7;
3229 if ($crop_chance > 0.1) {
3230 LOG ($verbose_pbm, "crop chance: $crop_chance");
3233 if (rand() < $crop_chance) {
3238 if ($crop_w > $min_width) {
3239 # if it's a banner, select the width linearly.
3240 # otherwise, select a bell.
3241 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3244 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3245 $crop_x = int (rand() * ($ow - $crop_w));
3247 if ($crop_h > $min_height) {
3248 # height always selects as a bell.
3249 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3250 $crop_y = int (rand() * ($oh - $crop_h));
3253 if ($crop_x != 0 || $crop_y != 0 ||
3254 $crop_w != $iw || $crop_h != $ih) {
3256 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3260 # Where the image should logically land -- this might be negative.
3262 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3263 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3265 # if we have chosen to paste the image outside of the rectangle of the
3266 # screen, then we need to crop it.
3270 $x + $crop_w > $img_width ||
3271 $y + $crop_h > $img_height) {
3274 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3276 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3277 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3279 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3280 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3283 # If any cropping needs to happen, add pnmcut.
3285 if ($crop_x != 0 || $crop_y != 0 ||
3286 $crop_w != $iw || $crop_h != $ih) {
3289 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3290 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3293 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3295 $cmd .= " | pnmpaste - $x $y $image_ppm";
3297 $cmd =~ s@^ *\| *@@;
3299 if (defined ($webcollage_helper)) {
3300 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3301 "$scale $opacity " .
3302 "$crop_x $crop_y $x $y " .
3307 # use a PPM pipeline
3309 $_ .= " < $image_tmp1 > $image_tmp2";
3313 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3315 $_ .= " 2> /dev/null";
3318 my $rc = nontrapping_system ($_);
3320 if (defined ($webcollage_helper) && -z $image_ppm) {
3321 LOG (1, "failed command: \"$cmd\"");
3322 print STDERR "\naudit log:\n\n\n";
3323 print STDERR ("#" x 78) . "\n";
3324 print STDERR blurb() . "$image_ppm has zero size\n";
3326 print STDERR "\n\n";
3331 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3332 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3336 if (!defined ($webcollage_helper)) {
3337 rename ($image_tmp2, $image_ppm) || return;
3340 my $target = "$image_ppm";
3342 # don't just tack this onto the end of the pipeline -- we don't want it
3343 # to end up in $image_ppm, because we don't want the results to be
3346 if ($post_filter_cmd) {
3350 $target = $image_tmp1;
3351 if (!defined ($webcollage_helper)) {
3352 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3354 # Blah, my scripts need the JPEG data, but some other folks need
3355 # the PPM data -- what to do? Ignore the problem, that's what!
3356 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3357 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3360 $rc = nontrapping_system ($cmd);
3362 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3367 if (!$no_output_p) {
3368 my $tsize = (stat($target))[7];
3370 $cmd = "$ppm_to_root_window_cmd $target";
3372 # xv seems to hate being killed. it tends to forget to clean
3373 # up after itself, and leaves windows around and colors allocated.
3374 # I had this same problem with vidwhacker, and I'm not entirely
3375 # sure what I did to fix it. But, let's try this: launch xv
3376 # in the background, so that killing this process doesn't kill it.
3377 # it will die of its own accord soon enough. So this means we
3378 # start pumping bits to the root window in parallel with starting
3379 # the next network retrieval, which is probably a better thing
3382 $cmd .= " &" unless ($cocoa_p);
3384 $rc = nontrapping_system ($cmd);
3387 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3392 LOG ($verbose_pbm, "$target size is $tsize");
3396 $source .= "-" . stats_of($source);
3397 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3398 if ($verbose_imgmap);
3399 if ($imagemap_base) {
3400 update_imagemap ($base, $x, $y, $iw, $ih,
3401 $image_ppm, $img_width, $img_height);
3410 sub update_imagemap($$$$$$$$) {
3411 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3413 $current_state = "imagemap";
3415 my $max_areas = 200;
3417 $url = html_quote ($url);
3420 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3421 unshift @imagemap_areas, $area; # put one on the front
3422 if ($#imagemap_areas >= $max_areas) {
3423 pop @imagemap_areas; # take one off the back.
3426 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3428 my $map_name = $imagemap_base;
3429 $map_name =~ s@^.*/@@;
3430 $map_name = 'collage' if ($map_name eq '');
3432 my $imagemap_html = $imagemap_base . ".html";
3433 my $imagemap_jpg = $imagemap_base . ".jpg";
3435 if (!defined ($imagemap_html_tmp)) {
3436 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3437 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3440 # Read the imagemap html file (if any) to get a template.
3442 my $template_html = '';
3445 if (open (IN, "<$imagemap_html")) {
3446 while (<IN>) { $template_html .= $_; }
3448 LOG ($verbose_pbm, "read template $imagemap_html");
3451 if ($template_html =~ m/^\s*$/s) {
3452 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3453 "<IMG SRC=\"$imagemap_base.jpg\"" .
3454 " USEMAP=\"$map_name\">\n");
3455 LOG ($verbose_pbm, "created dummy template");
3459 # Write the jpg to a tmp file
3463 if (defined ($webcollage_helper)) {
3464 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3466 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3468 my $rc = nontrapping_system ($cmd);
3470 error ("imagemap jpeg failed: \"$cmd\"\n");
3474 # Write the html to a tmp file
3477 my $body = $template_html;
3478 my $areas = join ("\n\t", @imagemap_areas);
3479 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3480 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
3482 "WIDTH=$image_width HEIGHT=$image_height " .
3483 "USEMAP=\"#$map_name\">");
3484 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3485 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3487 # if there are magic webcollage spans in the html, update those too.
3490 my @st = stat ($imagemap_jpg_tmp);
3491 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3492 my $size = int(($st[7] / 1024) + 0.5) . "K";
3493 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3494 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3498 open (OUT, ">$imagemap_html_tmp") || error ("$imagemap_html_tmp: $!");
3499 print OUT $body || error ("$imagemap_html_tmp: $!");
3500 close OUT || error ("$imagemap_html_tmp: $!");
3501 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3504 # Rename the two tmp files to the real files
3506 rename ($imagemap_html_tmp, $imagemap_html) ||
3507 error "renaming $imagemap_html_tmp to $imagemap_html";
3508 LOG ($verbose_pbm, "wrote $imagemap_html");
3509 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3510 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3511 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3515 # Figure out what the proxy server should be, either from environment
3516 # variables or by parsing the output of the (MacOS) program "scutil",
3517 # which tells us what the system-wide proxy settings are.
3521 if (! $http_proxy) {
3522 # historical suckage: the environment variable name is lower case.
3523 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3526 if (defined ($http_proxy)) {
3527 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3528 # historical suckage: allow "http://host:port" as well as "host:port".
3533 my $proxy_data = `scutil --proxy 2>/dev/null`;
3534 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3535 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3536 # Note: this ignores the "ExceptionsList".
3538 $http_proxy = $server;
3539 $http_proxy .= ":$port" if $port;
3544 LOG ($verbose_net, "proxy server: $http_proxy");
3549 sub init_signals() {
3551 $SIG{HUP} = \&signal_cleanup;
3552 $SIG{INT} = \&signal_cleanup;
3553 $SIG{QUIT} = \&signal_cleanup;
3554 $SIG{ABRT} = \&signal_cleanup;
3555 $SIG{KILL} = \&signal_cleanup;
3556 $SIG{TERM} = \&signal_cleanup;
3558 # Need this so that if giftopnm dies, we don't die.
3559 $SIG{PIPE} = 'IGNORE';
3562 END { exit_cleanup(); }
3571 my $driftnet_cmd = 0;
3573 $current_state = "init";
3574 $load_method = "none";
3577 my $window_id = undef;
3579 while ($_ = $ARGV[0]) {
3581 if ($_ eq "-display" ||
3587 $ENV{DISPLAY} = shift @ARGV;
3588 } elsif ($_ eq "-root") {
3590 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3591 $window_id = shift @ARGV;
3593 } elsif ($_ eq "-no-output") {
3595 } elsif ($_ eq "-urls-only") {
3598 } elsif ($_ eq "-cocoa") {
3600 } elsif ($_ eq "-imagemap") {
3601 $imagemap_base = shift @ARGV;
3603 } elsif ($_ eq "-verbose") {
3605 } elsif (m/^-v+$/) {
3606 $verbose += length($_)-1;
3607 } elsif ($_ eq "-delay") {
3608 $delay = shift @ARGV;
3609 } elsif ($_ eq "-timeout") {
3610 $http_timeout = shift @ARGV;
3611 } elsif ($_ eq "-filter") {
3612 $filter_cmd = shift @ARGV;
3613 } elsif ($_ eq "-filter2") {
3614 $post_filter_cmd = shift @ARGV;
3615 } elsif ($_ eq "-background" || $_ eq "-bg") {
3616 $background = shift @ARGV;
3617 } elsif ($_ eq "-size") {
3619 if (m@^(\d+)x(\d+)$@) {
3623 error "argument to \"-size\" must be of the form \"640x400\"";
3625 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3626 $http_proxy = shift @ARGV;
3627 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3628 $dict = shift @ARGV;
3629 } elsif ($_ eq "-opacity") {
3630 $opacity = shift @ARGV;
3631 error ("opacity must be between 0.0 and 1.0")
3632 if ($opacity <= 0 || $opacity > 1);
3633 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3634 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3635 if (! ($ARGV[0] =~ m/^-/)) {
3636 $driftnet_cmd = shift @ARGV;
3638 $driftnet_cmd = $default_driftnet_cmd;
3640 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3641 @search_methods = ( 100, "local", \&pick_from_local_dir );
3642 if (! ($ARGV[0] =~ m/^-/)) {
3643 $local_dir = shift @ARGV;
3645 error ("local directory path must be set")
3647 } elsif ($_ eq "-fps") {
3648 # -fps only works on MacOS, via "webcollage-cocoa.m".
3649 # Ignore it if passed to this script in an X11 context.
3650 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3651 my $which = shift @ARGV;
3652 my @rest = @search_methods;
3655 my $pct = shift @rest;
3656 my $name = shift @rest;
3657 my $tfn = shift @rest;
3659 if ($name eq $which) {
3660 @search_methods = (100, $name, $tfn);
3665 error "no such search method as \"$which\"" unless ($ok);
3666 LOG (1, "DEBUG: using only \"$which\"");
3669 print STDERR "$copyright\nusage: $progname " .
3670 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3671 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3672 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3673 "\t\t [-background color] [-opacity f]\n" .
3674 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3675 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3676 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3677 "\t\t [-directory local-image-directory]\n" .
3683 if (!$root_p && !$no_output_p && !$cocoa_p) {
3684 print STDERR $copyright;
3685 error "the -root argument is mandatory (for now.)";
3688 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3689 error "\$DISPLAY is not set.";
3693 if ($verbose == 1) {
3694 $verbose_imgmap = 1;
3695 $verbose_warnings = 1;
3697 } elsif ($verbose == 2) {
3698 $verbose_imgmap = 1;
3699 $verbose_warnings = 1;
3702 } elsif ($verbose == 3) {
3703 $verbose_imgmap = 1;
3704 $verbose_warnings = 1;
3706 $verbose_filter = 1;
3708 } elsif ($verbose == 4) {
3709 $verbose_imgmap = 1;
3710 $verbose_warnings = 1;
3712 $verbose_filter = 1;
3715 } elsif ($verbose == 5) {
3716 $verbose_imgmap = 1;
3717 $verbose_warnings = 1;
3719 $verbose_filter = 1;
3723 } elsif ($verbose == 6) {
3724 $verbose_imgmap = 1;
3725 $verbose_warnings = 1;
3727 $verbose_filter = 1;
3732 } elsif ($verbose >= 7) {
3733 $verbose_imgmap = 1;
3734 $verbose_warnings = 1;
3736 $verbose_filter = 1;
3744 error ("$dict does not exist") unless (-f $dict);
3750 if ($imagemap_base && !($img_width && $img_height)) {
3751 error ("-size WxH is required with -imagemap");
3754 if (defined ($local_dir)) {
3755 $_ = "xscreensaver-getimage-file";
3756 which ($_) || error "$_ not found on \$PATH.";
3762 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3767 x_or_pbm_output ($window_id);