3 # webcollage, Copyright © 1999-2013 by Jamie Zawinski <jwz@jwz.org>
4 # This program decorates the screen with random images from the web.
5 # One satisfied customer described it as "a nonstop pop culture brainbath."
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!
53 use Fcntl ':flock'; # import LOCK_* constants
54 use POSIX qw(strftime);
59 my $progname = $0; $progname =~ s@.*/@@g;
60 my $version = q{ $Revision: 1.162 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
61 my $copyright = "WebCollage $version, Copyright (c) 1999-2013" .
62 " Jamie Zawinski <jwz\@jwz.org>\n" .
63 " http://www.jwz.org/webcollage/\n";
67 my @search_methods = (
68 # Google is rate-limiting us now, so this works ok from
69 # a short-running screen saver, but not as a batch job.
70 # I haven't found a workaround.
72 7, "googlephotos", \&pick_from_google_image_photos,
73 5, "googleimgs", \&pick_from_google_images,
74 5, "googlenums", \&pick_from_google_image_numbers,
76 # So let's try Bing instead. No rate limiting yet!
78 7, "bingphotos", \&pick_from_bing_image_photos,
79 6, "bingimgs", \&pick_from_bing_images,
80 6, "bingnums", \&pick_from_bing_image_numbers,
82 19, "flickr_recent", \&pick_from_flickr_recent,
83 15, "flickr_random", \&pick_from_flickr_random,
84 20, "instagram", \&pick_from_instagram,
85 6, "livejournal", \&pick_from_livejournal_images,
86 4, "yahoorand", \&pick_from_yahoo_random_link,
88 # Twitter destroyed their whole API in 2013.
89 # 0, "twitpic", \&pick_from_twitpic_images,
90 # 0, "twitter", \&pick_from_twitter_images,
92 # This is a cute way to search for a certain webcams.
93 # Not included in default methods, since these images
94 # aren't terribly interesting by themselves.
95 # See also "SurveillanceSaver".
97 0, "securitycam", \&pick_from_security_camera,
99 # Nonfunctional as of June 2011.
100 # 0, "altavista", \&pick_from_alta_vista_random_link,
102 # In Apr 2002, Google asked me to stop searching them.
103 # I asked them to add a "random link" url. They said
104 # "that would be easy, we'll think about it" and then
105 # never wrote back. Booo Google! Booooo! So, screw
106 # those turkeys, I've turned Google searching back on.
107 # I'm sure they can take it. (Jan 2005.)
109 # Jan 2005: Yahoo fucked up their search form so that
110 # it's no longer possible to do "or" searches on news
111 # images, so we rarely get any hits there any more.
113 # 0, "yahoonews", \&pick_from_yahoo_news_text,
115 # Dec 2004: the ircimages guy's server can't take the
116 # heat, so he started banning the webcollage user agent.
117 # I tried to convince him to add a lighter-weight page to
118 # support webcollage better, but he doesn't care.
120 # 0, "ircimages", \&pick_from_ircimages,
122 # Dec 2002: Alta Vista has a new "random link" URL now.
123 # They added it specifically to better support webcollage!
124 # That was super cool of them. This is how we used to do
127 # 0, "avimages", \&pick_from_alta_vista_images,
128 # 0, "avtext", \&pick_from_alta_vista_text,
130 # This broke in 2004. Eh, Lycos sucks anyway.
132 # 0, "lycos", \&pick_from_lycos_text,
134 # This broke in 2003, I think. I suspect Hotbot is
135 # actually the same search engine data as Lycos.
137 # 0, "hotbot", \&pick_from_hotbot_text,
140 # programs we can use to write to the root window (tried in ascending order.)
142 my @root_displayers = (
143 "xscreensaver-getimage -root -file",
144 "chbg -once -xscreensaver -max_size 100",
145 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
146 " -rfg black -rbg black",
147 "xli -quiet -onroot -center -border black",
148 "xloadimage -quiet -onroot -center -border black",
150 # this lame program wasn't built with vroot.h:
151 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
155 # Some sites need cookies to work properly. These are they.
158 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
159 "web.altavista.com" => "AV_ALL=1",
161 # log in as "cipherpunk"
162 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
163 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
164 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
166 "ircimages.com" => 'disclaimer=1',
170 # If this is set, it's a helper program to use for pasting images together:
171 # this is a lot faster and more efficient than using PPM pipelines, which is
172 # what we do if this program doesn't exist. (We check for "webcollage-helper"
173 # on $PATH at startup, and set this variable appropriately.)
175 my $webcollage_helper = undef;
178 # If we have the webcollage-helper program, then it will paste the images
179 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
184 # Some sites have managed to poison the search engines. These are they.
185 # (We auto-detect sites that have poisoned the search engines via excessive
186 # keywords or dictionary words, but these are ones that slip through
189 # This can contain full host names, or 2 or 3 component domains.
192 "die.net" => 1, # 'l33t h4ck3r d00dz.
193 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
194 "rootsweb.com" => 1, # Cluttering avtext with human names.
195 "akamai.net" => 1, # Lots of sites have their images on Akamai.
196 "akamaitech.net" => 1, # But those are pretty much all banners.
197 # Since Akamai is super-expensive, let's
198 # go out on a limb and assume that all of
199 # their customers are rich-and-boring.
200 "bartleby.com" => 1, # Dictionary, cluttering avtext.
201 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
202 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
203 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
204 # (I don't see how they did it, though!)
205 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
206 "nextag.com" => 1, # Poisoned Alta Vista real good.
207 "ghettodriveby.com" => 1, # Poisoned Google Images.
208 "crosswordsolver.org" => 1, # Poisoned Google Images.
209 "xona.com" => 1, # Poisoned Google Images.
210 "freepatentsonline.com" => 1, # Poisoned Google Images.
211 "herbdatanz.com" => 1, # Poisoned Google Images.
215 # When verbosity is turned on, we warn about sites that we seem to be hitting
216 # a lot: usually this means some new poisoner has made it into the search
217 # engines. But sometimes, the warning is just because that site has a lot
218 # of stuff on it. So these are the sites that are immune to the "frequent
219 # site" diagnostic message.
221 my %warningless_sites = (
222 "home.earthlink.net" => 1,
223 "www.angelfire.com" => 1,
224 "members.aol.com" => 1,
225 "img.photobucket.com" => 1,
226 "pics.livejournal.com" => 1,
229 "staticflickr.com" => 1,
233 "wikimedia.org" => 1,
235 "amazonaws.com" => 1,
237 "photoshelter.com" => 1,
238 "myspacecdn.com" => 1,
239 "feedburner.com" => 1,
246 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
247 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
248 # hits this every time.
250 "images.quizfarm.com" => 1, # damn those LJ quizzes...
251 "images.quizilla.com" => 1,
252 "images.quizdiva.net" => 1,
254 "driftnet" => 1, # builtin...
255 "local-directory" => 1, # builtin...
259 # For decoding HTML-encoded character entities to URLs.
263 "quot" => '"', "amp" => '&', "lt" => '<',
264 "gt" => '>', "nbsp" => ' ', "iexcl" => '',
265 "cent" => "\xA2", "pound" => "\xA3", "curren" => "\xA4",
266 "yen" => "\xA5", "brvbar" => "\xA6", "sect" => "\xA7",
267 "uml" => "\xA8", "copy" => "\xA9", "ordf" => "\xAA",
268 "laquo" => "\xAB", "not" => "\xAC", "shy" => "\xAD",
269 "reg" => "\xAE", "macr" => "\xAF", "deg" => "\xB0",
270 "plusmn" => "\xB1", "sup2" => "\xB2", "sup3" => "\xB3",
271 "acute" => "\xB4", "micro" => "\xB5", "para" => "\xB6",
272 "middot" => "\xB7", "cedil" => "\xB8", "sup1" => "\xB9",
273 "ordm" => "\xBA", "raquo" => "\xBB", "frac14" => "\xBC",
274 "frac12" => "\xBD", "frac34" => "\xBE", "iquest" => "\xBF",
275 "Agrave" => "\xC0", "Aacute" => "\xC1", "Acirc" => "\xC2",
276 "Atilde" => "\xC3", "Auml" => "\xC4", "Aring" => "\xC5",
277 "AElig" => "\xC6", "Ccedil" => "\xC7", "Egrave" => "\xC8",
278 "Eacute" => "\xC9", "Ecirc" => "\xCA", "Euml" => "\xCB",
279 "Igrave" => "\xCC", "Iacute" => "\xCD", "Icirc" => "\xCE",
280 "Iuml" => "\xCF", "ETH" => "\xD0", "Ntilde" => "\xD1",
281 "Ograve" => "\xD2", "Oacute" => "\xD3", "Ocirc" => "\xD4",
282 "Otilde" => "\xD5", "Ouml" => "\xD6", "times" => "\xD7",
283 "Oslash" => "\xD8", "Ugrave" => "\xD9", "Uacute" => "\xDA",
284 "Ucirc" => "\xDB", "Uuml" => "\xDC", "Yacute" => "\xDD",
285 "THORN" => "\xDE", "szlig" => "\xDF", "agrave" => "\xE0",
286 "aacute" => "\xE1", "acirc" => "\xE2", "atilde" => "\xE3",
287 "auml" => "\xE4", "aring" => "\xE5", "aelig" => "\xE6",
288 "ccedil" => "\xE7", "egrave" => "\xE8", "eacute" => "\xE9",
289 "ecirc" => "\xEA", "euml" => "\xEB", "igrave" => "\xEC",
290 "iacute" => "\xED", "icirc" => "\xEE", "iuml" => "\xEF",
291 "eth" => "\xF0", "ntilde" => "\xF1", "ograve" => "\xF2",
292 "oacute" => "\xF3", "ocirc" => "\xF4", "otilde" => "\xF5",
293 "ouml" => "\xF6", "divide" => "\xF7", "oslash" => "\xF8",
294 "ugrave" => "\xF9", "uacute" => "\xFA", "ucirc" => "\xFB",
295 "uuml" => "\xFC", "yacute" => "\xFD", "thorn" => "\xFE",
298 # HTML 4 entities that do not have 1:1 Latin1 mappings.
299 "bull" => "*", "hellip"=> "...", "prime" => "'", "Prime" => "\"",
300 "frasl" => "/", "trade" => "[tm]", "larr" => "<-", "rarr" => "->",
301 "harr" => "<->", "lArr" => "<=", "rArr" => "=>", "hArr" => "<=>",
302 "empty" => "\xD8", "minus" => "-", "lowast"=> "*", "sim" => "~",
303 "cong" => "=~", "asymp" => "~", "ne" => "!=", "equiv" => "==",
304 "le" => "<=", "ge" => ">=", "lang" => "<", "rang" => ">",
305 "loz" => "<>", "OElig" => "OE", "oelig" => "oe", "Yuml" => "Y",
306 "circ" => "^", "tilde" => "~", "ensp" => " ", "emsp" => " ",
307 "thinsp"=> " ", "ndash" => "-", "mdash" => "--", "lsquo" => "`",
308 "rsquo" => "'", "sbquo" => "'", "ldquo" => "\"", "rdquo" => "\"",
309 "bdquo" => "\"", "lsaquo"=> "<", "rsaquo"=> ">",
313 ##############################################################################
315 # Various global flags set by command line parameters, or computed
317 ##############################################################################
320 my $current_state = "???"; # for diagnostics
323 my $image_succeeded = -1;
324 my $suppress_audit = 0;
326 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
327 my $verbose_warnings = 0; # print out warnings when things go wrong
328 my $verbose_load = 0; # diagnostics about loading of URLs
329 my $verbose_filter = 0; # diagnostics about page selection/rejection
330 my $verbose_net = 0; # diagnostics about network I/O
331 my $verbose_pbm = 0; # diagnostics about PBM pipelines
332 my $verbose_http = 0; # diagnostics about all HTTP activity
333 my $verbose_exec = 0; # diagnostics about executing programs
335 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
337 my $http_proxy = undef;
338 my $http_timeout = 20;
339 my $cvt_timeout = 10;
345 my $min_gif_area = (120 * 120);
351 my $imagemap_base = undef;
353 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
355 my $driftnet_magic = 'driftnet';
356 my $driftnet_dir = undef;
357 my $default_driftnet_cmd = "driftnet -a -m 100";
359 my $local_magic = 'local-directory';
360 my $local_dir = undef;
365 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
366 "arrhenius", "arteriole", "blanket", "brainchild",
367 "burdensome", "carnival", "cherub", "chord", "clever",
368 "dedicate", "dilogarithm", "dolan", "dryden",
372 ##############################################################################
376 ##############################################################################
378 # returns three values: the HTTP response line; the document headers;
379 # and the document body.
381 sub get_document_1($$$) {
382 my ($url, $referer, $timeout) = @_;
384 if (!defined($timeout)) { $timeout = $http_timeout; }
385 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
387 my $user_agent = "$progname/$version";
389 if ($url =~ m@^http://www\.altavista\.com/@ ||
390 $url =~ m@^http://random\.yahoo\.com/@ ||
391 $url =~ m@^http://images\.google\.com/@ ||
392 $url =~ m@^http://www\.google\.com/@) {
393 # block this, you turkeys.
394 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)" .
395 " Gecko/20070914 Firefox/2.0.0.7";
397 # 28-Jun-2007: Google Images now emits the entire page in JS if
398 # you claim to be Gecko. They also still block "webcollage".
399 # They serve non-JS for unrecognised agents, so let's try this...
400 $user_agent = "NoJavascriptPlease/1.0"
401 if ($url =~ m@^http://[a-z]+\.google\.com/@);
404 my $ua = LWP::UserAgent->new;
406 $ua->agent ("$progname/$version");
407 $ua->default_header ('Referer' => $referer);
408 $ua->timeout($timeout) if $timeout;
411 LOG (1, " ==> GET $url");
412 LOG (1, " ==> User-Agent: $user_agent");
413 LOG (1, " ==> Referer: $referer") if $referer;
416 my $res = $ua->get ($url);
418 my $http = ($res ? $res->status_line : '') || '';
419 my $head = ($res ? $res->headers()->as_string : '') || '';
420 my $body = ($res && $res->is_success ? $res->decoded_content : '') || '';
422 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
424 $head =~ s/\r\n/\n/gs;
427 foreach (split (/\n/, $head)) {
428 LOG ($verbose_http, " <== $_");
432 my @L = split(/\r\n|\r|\n/, $body);
435 " <== [ body ]: $lines lines, " . length($body) . " bytes");
438 LOG (($verbose_net || $verbose_load), "null response: $url");
442 return ( $http, $head, $body );
446 # returns two values: the document headers; and the document body.
447 # if the given URL did a redirect, returns the redirected-to document.
449 sub get_document($$;$) {
450 my ($url, $referer, $timeout) = @_;
453 if (defined($referer) && $referer eq $driftnet_magic) {
454 return get_driftnet_file ($url);
457 if (defined($referer) && $referer eq $local_magic) {
458 return get_local_file ($url);
463 my $max_loop_count = 4;
466 if (defined($timeout) && $timeout <= 0) {
467 LOG (($verbose_net || $verbose_load), "timed out for $url");
472 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
474 if (defined ($timeout)) {
476 my $elapsed = $now - $start;
477 $timeout -= $elapsed;
481 return () unless $http; # error message already printed
483 $http =~ s/[\r\n]+$//s;
485 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
488 my ( $location ) = m@^location:[ \t]*(.*)$@im;
490 $location =~ s/[\r\n]$//;
492 LOG ($verbose_net, "redirect from $url to $location");
497 $referer =~ m@^(http://[^/]+)@i;
499 } elsif (! ($url =~ m@^[a-z]+:@i)) {
501 s@[^/]+$@@g if m@^http://[^/]+/@i;
502 $_ .= "/" if m@^http://[^/]+$@i;
507 LOG ($verbose_net, "no Location with \"$http\"");
508 return ( $url, $body );
511 if ($loop_count++ > $max_loop_count) {
513 "too many redirects ($max_loop_count) from $orig_url");
518 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
520 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
522 # http errors -- return nothing.
528 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
534 return ( $url, $body );
540 # If we already have a cookie defined for this site, and the site is trying
541 # to overwrite that very same cookie, let it do so. This is because nytimes
542 # expires its cookies - it lets you upgrade to a new cookie without logging
543 # in again, but you have to present the old cookie to get the new cookie.
544 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
547 my ($host, $cookie) = @_;
548 my $oc = $cookies{$host};
551 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
553 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
555 if ($oc_name eq $nc_name &&
556 $oc_value ne $nc_value) {
557 $cookies{$host} = $cookie;
558 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
563 ############################################################################
565 # Extracting image URLs from HTML
567 ############################################################################
569 # given a URL and the body text at that URL, selects and returns a random
570 # image from it. returns () if no suitable images found.
572 sub pick_image_from_body($$) {
573 my ($url, $body) = @_;
578 # if there's at least one slash after the host, take off the last
580 if ( m@^http://[^/]+/@io ) {
581 $base =~ s@[^/]+$@@go;
584 # if there are no slashes after the host at all, put one on the end.
585 if ( m@^http://[^/]+$@io ) {
591 # strip out newlines, compress whitespace
598 # There are certain web sites that list huge numbers of dictionary
599 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
600 # Porn sites tend not to be reputable!)
602 # I do not want webcollage to filter on content: I want it to select
603 # randomly from the set of images on the web. All the logic here for
604 # rejecting some images is really a set of heuristics for rejecting
605 # images that are not really images: for rejecting *text* that is in
606 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
607 # the content of the pictures to be randomly selected from among all
608 # the available content.
610 # So, filtering out "dirty" pictures by looking for "dirty" keywords
611 # would be wrong: dirty pictures exist, like it or not, so webcollage
612 # should be able to select them.
614 # However, picking a random URL is a hard thing to do. The mechanism I'm
615 # using is to search for a selection of random words. This is not
616 # perfect, but works ok most of the time. The way it breaks down is when
617 # some URLs get precedence because their pages list *every word* as
618 # related -- those URLs come up more often than others.
620 # So, after we've retrieved a URL, if it has too many keywords, reject
621 # it. We reject it not on the basis of what those keywords are, but on
622 # the basis that by having so many, the page has gotten an unfair
623 # advantage against our randomizer.
626 foreach my $trip (@tripwire_words) {
627 $trip_count++ if m/$trip/i;
630 if ($trip_count >= $#tripwire_words - 2) {
631 LOG (($verbose_filter || $verbose_load),
632 "there is probably a dictionary in \"$url\": rejecting.");
633 $rejected_urls{$url} = -1;
643 foreach (split(/ *</)) {
644 if ( m/^meta.*["']keywords["']/i ) {
646 # Likewise, reject any web pages that have a KEYWORDS meta tag
651 LOG (($verbose_filter || $verbose_load),
652 "excessive keywords ($L bytes) in $url: rejecting.");
653 $rejected_urls{$url} = $L;
658 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
661 } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
662 m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
663 ["']? (image_src|og:image) ["']? /six) {
665 my $was_inline = (lc($1) eq 'img');
666 my $was_meta = (lc($1) eq 'link' || lc($1) eq 'meta');
669 # For <link rel="image_src" href="...">
670 # and <meta property="og:image" content="...">
673 next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
677 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
678 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
683 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
685 } elsif ( ! m@^[^/:?]+:@ ) {
688 1 while (s@/[^/]+/\.\./@/@g);
692 if ( ! m@^http://@io ) {
697 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
701 # skip really short or really narrow images
702 if ( $width && $width < $min_width) {
703 if (!$height) { $height = "?"; }
704 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
708 if ( $height && $height < $min_height) {
709 if (!$width) { $width = "?"; }
710 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
714 # skip images with ratios that make them look like banners.
715 if ($min_ratio && $width && $height &&
716 ($width * $min_ratio ) > $height) {
717 if (!$height) { $height = "?"; }
718 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
722 # skip GIFs with a small number of pixels -- those usually suck.
723 if ($width && $height &&
725 ($width * $height) < $min_gif_area) {
726 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
730 # skip images with a URL that indicates a Yahoo thumbnail.
731 if (m@\.yimg\.com/.*/t/@) {
732 if (!$width) { $width = "?"; }
733 if (!$height) { $height = "?"; }
734 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
740 if ($unique_urls{$url}) {
741 LOG ($verbose_filter, " skip duplicate image $_");
745 LOG ($verbose_filter,
747 ($width && $height ? " (${width}x${height})" : "") .
748 ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
754 $weight = 20; # meta tag images are far preferable to inline images.
756 if ($url !~ m@[.](gif|png)$@io ) {
757 $weight += 2; # JPEGs are preferable to GIFs and PNGs.
760 $weight += 4; # pointers to images are preferable to inlined images.
764 $unique_urls{$url}++;
765 for (my $i = 0; $i < $weight; $i++) {
766 $urls[++$#urls] = $url;
771 my $fsp = ($body =~ m@<frameset@i);
776 @urls = depoison (@urls);
779 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
783 # pick a random element of the table
784 my $i = int(rand($#urls+1));
787 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
793 # Given a URL and the RSS feed from that URL, pick a random image from
794 # the feed. This is a lot simpler than extracting images out of a page:
795 # we already know we have reasonable images, so we just pick one.
796 # Returns: the real URL of the page (preferably not the RSS version),
799 sub pick_image_from_rss($$) {
800 my ( $url, $body ) = @_;
801 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
803 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
804 $base = $url unless $base;
806 # pick a random element of the table
808 my $i = int(rand(scalar @suitable));
809 my $url = $suitable[$i];
810 LOG ($verbose_load, "picked image " .($i+1) . "/" .
811 ($#suitable+1) . ": $url");
812 return ($base, $url);
818 ############################################################################
820 # Subroutines for getting pages and images out of search engines
822 ############################################################################
825 sub pick_dictionary() {
826 my @dicts = ("/usr/dict/words",
827 "/usr/share/dict/words",
828 "/usr/share/lib/dict/words",
829 "/usr/share/dict/cracklib-small",
830 "/usr/share/dict/cracklib-words"
832 foreach my $f (@dicts) {
838 error ("$dicts[0] does not exist") unless defined($wordlist);
841 # returns a random word from the dictionary
845 return undef unless open (my $in, '<', $wordlist);
847 my $size = (stat($in))[7];
852 error ("looping ($count) while reading $wordlist")
855 my $pos = int (rand ($size));
856 if (seek ($in, $pos, 0)) {
857 $word = <$in>; # toss partial line
858 $word = <$in>; # keep next line
862 next if ($word =~ m/^[-\']/);
866 $word =~ s/^[^a-z]+//s;
867 $word =~ s/[^a-z]+$//s;
873 $word =~ s/ally$/al/s;
874 $word =~ s/izes$/ize/s;
875 $word =~ s/esses$/ess/s;
876 $word =~ s/(.{5})ing$/$1/s;
878 next if (length ($word) > 14);
884 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
885 $word = "\%22$word\%22"; # And put quotes (%22) around it.
892 sub random_words($) {
894 return (random_word() . $sep .
895 random_word() . $sep .
896 random_word() . $sep .
897 random_word() . $sep .
904 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
911 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
920 $s =~ s/\"/"/gi;
924 sub html_unquote($) {
926 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
927 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
932 # Loads the given URL (a search on some search engine) and returns:
933 # - the total number of hits the search engine claimed it had;
934 # - a list of URLs from the page that the search engine returned;
935 # Note that this list contains all kinds of internal search engine
936 # junk URLs too -- caller must prune them.
938 sub pick_from_search_engine($$$) {
939 my ( $timeout, $search_url, $words ) = @_;
944 print STDERR "\n\n" if ($verbose_load);
946 LOG ($verbose_load, "words: $_");
947 LOG ($verbose_load, "URL: $search_url");
949 $last_search = $search_url; # for warnings
952 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
953 if (defined ($timeout)) {
954 $timeout -= (time - $start);
957 LOG (($verbose_net || $verbose_load),
958 "timed out (late) for $search_url");
964 return () if (! $body);
969 if ($body =~ m/^\{\"/s) { # Google AJAX JSON response.
971 my @chunks = split (/"GsearchResultClass"/, $body);
976 my ($img) = m/"unescapedUrl":"(.*?)"/si;
977 my ($url) = m/"originalContextUrl":"(.*?)"/si;
978 next unless ($img && $url);
980 "?imgurl=" . url_quote($img) .
981 "&imgrefurl=" . url_quote($url) .
983 $body2 .= "<A HREF=\"" . html_quote($url) . "\">$n</A>\n";
986 $body = $body2 if $body2;
989 my $search_count = "?";
990 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
992 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
994 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
996 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
998 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1000 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1002 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1004 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1006 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1007 $search_count = $1; # lycos
1008 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1009 $search_count = $1; # hotbot
1010 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1011 $search_count = "0";
1012 } elsif ($body =~ m@found no document matching@i) { # avtext
1013 $search_count = "0";
1015 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1017 # if ($search_count eq "?" || $search_count eq "0") {
1018 # my $file = "/tmp/wc.html";
1019 # open (my $out, '>', $file) || error ("writing $file: $!");
1022 # print STDERR blurb() . "###### wrote $file\n";
1026 my $length = length($body);
1035 foreach (split(/\n/)) {
1037 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1040 if (m/\bm="{(.*?)}"/s) { # Bing info is inside JSON crud
1041 my $json = html_unquote($1);
1042 my ($href) = ($json =~ m/\bsurl:"(.*?)"/s);
1043 my ($img) = ($json =~ m/\bimgurl:"(.*?)"/s);
1044 $u = "$img\t$href" if ($img && $href);
1046 } elsif ($u =~ m/^\"([^\"]*)\"/) { $u = $1 # quoted string
1047 } elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; # or token
1050 if ( $rejected_urls{$u} ) {
1051 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1055 LOG ($verbose_http, " HREF: $u");
1057 $subpages[++$#subpages] = $u;
1060 if ( $#subpages < 0 ) {
1061 LOG ($verbose_filter,
1062 "found nothing on $base ($length bytes, $href_count links).");
1066 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1068 return ($search_count, @subpages);
1076 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1078 next unless defined($h);
1080 if ($poisoners{$h}) {
1081 LOG (($verbose_filter), " rejecting poisoner: $_");
1084 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1086 LOG (($verbose_filter), " rejecting poisoner: $_");
1089 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1091 LOG (($verbose_filter), " rejecting poisoner: $_");
1101 # given a list of URLs, picks one at random; loads it; and returns a
1102 # random image from it.
1103 # returns the url of the page loaded; the url of the image chosen.
1105 sub pick_image_from_pages($$$$@) {
1106 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1108 $total_hit_count = "?" unless defined($total_hit_count);
1110 @pages = depoison (@pages);
1112 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1113 " ($total_hit_count total)");
1115 return () if ($#pages < 0);
1117 my $i = int(rand($#pages+1));
1118 my $page = $pages[$i];
1120 LOG ($verbose_load, "picked page $page");
1122 $suppress_audit = 1;
1124 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1126 if (!$base2 || !$body2) {
1131 my $img = pick_image_from_body ($base2, $body2);
1135 return ($base2, $img);
1142 ############################################################################
1144 # Pick images from random pages returned by the Yahoo Random Link
1146 ############################################################################
1149 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1152 # Picks a random page; picks a random image on that page;
1153 # returns two URLs: the page containing the image, and the image.
1154 # Returns () if nothing found this time.
1156 sub pick_from_yahoo_random_link($) {
1159 print STDERR "\n\n" if ($verbose_load);
1160 LOG ($verbose_load, "URL: $yahoo_random_link");
1162 $last_search = $yahoo_random_link; # for warnings
1164 $suppress_audit = 1;
1166 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1167 if (!$base || !$body) {
1172 LOG ($verbose_load, "redirected to: $base");
1174 my $img = pick_image_from_body ($base, $body);
1178 return ($base, $img);
1185 ############################################################################
1187 # Pick images from random pages returned by the Alta Vista Random Link
1188 # Note: this seems to have gotten a *lot* less random lately (2007).
1190 ############################################################################
1193 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1196 # Picks a random page; picks a random image on that page;
1197 # returns two URLs: the page containing the image, and the image.
1198 # Returns () if nothing found this time.
1200 sub pick_from_alta_vista_random_link($) {
1203 print STDERR "\n\n" if ($verbose_load);
1204 LOG ($verbose_load, "URL: $alta_vista_random_link");
1206 $last_search = $alta_vista_random_link; # for warnings
1208 $suppress_audit = 1;
1210 my ( $base, $body ) = get_document ($alta_vista_random_link,
1212 if (!$base || !$body) {
1217 LOG ($verbose_load, "redirected to: $base");
1219 my $img = pick_image_from_body ($base, $body);
1223 return ($base, $img);
1230 ############################################################################
1232 # Pick images by feeding random words into Alta Vista Image Search
1234 ############################################################################
1237 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1238 "?ipht=1" . # photos
1239 "&igrph=1" . # graphics
1242 "&micat=1" . # no partner sites
1243 "&sc=on" . # "site collapse"
1247 sub pick_from_alta_vista_images($) {
1250 my $words = random_word();
1251 my $page = (int(rand(9)) + 1);
1252 my $search_url = $alta_vista_images_url . $words;
1255 $search_url .= "&pgno=" . $page; # page number
1256 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1259 my ($search_hit_count, @subpages) =
1260 pick_from_search_engine ($timeout, $search_url, $words);
1262 my @candidates = ();
1263 foreach my $u (@subpages) {
1265 # avimages is encoding their URLs now.
1266 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1267 $u = url_unquote($u);
1269 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1270 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1271 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1272 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1273 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1275 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1276 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1278 LOG ($verbose_filter, " candidate: $u");
1279 push @candidates, $u;
1282 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1283 $timeout, @candidates);
1288 ############################################################################
1290 # Pick images from Aptix security cameras
1291 # Cribbed liberally from google image search code.
1292 # By Jason Sullivan <jasonsul@us.ibm.com>
1294 ############################################################################
1296 my $aptix_images_url = ("http://www.google.com/search" .
1297 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1300 sub pick_from_security_camera($) {
1303 my $page = (int(rand(9)) + 1);
1304 my $num = 20; # 20 images per page
1305 my $search_url = $aptix_images_url;
1308 $search_url .= "&start=" . $page*$num; # page number
1309 $search_url .= "&num=" . $num; #images per page
1312 my ($search_hit_count, @subpages) =
1313 pick_from_search_engine ($timeout, $search_url, '');
1315 my @candidates = ();
1317 foreach my $u (@subpages) {
1318 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1319 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1321 LOG ($verbose_filter, " candidate: $u");
1322 push @candidates, $u;
1326 @candidates = depoison (@candidates);
1327 return () if ($#candidates < 0);
1328 my $i = int(rand($#candidates+1));
1329 my $img = $candidates[$i];
1330 my $ref = $referers{$img};
1332 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1333 return ($ref, $img);
1337 ############################################################################
1339 # Pick images by feeding random words into Google Image Search.
1340 # By Charles Gales <gales@us.ibm.com>
1342 ############################################################################
1345 my $google_images_url = "http://ajax.googleapis.com/ajax/services/" .
1352 sub pick_from_google_images($;$$) {
1353 my ($timeout, $words, $max_page) = @_;
1355 if (!defined($words)) {
1356 $words = random_word(); # only one word for Google
1359 my $off = int(rand(40));
1360 my $search_url = $google_images_url . $words . "&start=" . $off;
1362 my ($search_hit_count, @subpages) =
1363 pick_from_search_engine ($timeout, $search_url, $words);
1365 my @candidates = ();
1367 foreach my $u (@subpages) {
1368 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1369 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1371 $u = html_unquote($u);
1372 if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1375 $ref = url_decode($ref);
1376 $img = url_decode($img);
1378 $img = "http://$img" unless ($img =~ m/^https?:/i);
1380 LOG ($verbose_filter, " candidate: $ref");
1381 push @candidates, $img;
1382 $referers{$img} = $ref;
1386 @candidates = depoison (@candidates);
1387 return () if ($#candidates < 0);
1388 my $i = int(rand($#candidates+1));
1389 my $img = $candidates[$i];
1390 my $ref = $referers{$img};
1392 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1393 return ($ref, $img);
1398 ############################################################################
1400 # Pick images by feeding random numbers into Google Image Search.
1401 # By jwz, suggested by Ian O'Donnell.
1403 ############################################################################
1407 sub pick_from_google_image_numbers($) {
1411 my $number = int(rand($max));
1413 $number = sprintf("%04d", $number)
1416 pick_from_google_images ($timeout, "$number");
1421 ############################################################################
1423 # Pick images by feeding random digital camera file names into
1424 # Google Image Search.
1425 # By jwz, inspired by the excellent Random Personal Picture Finder
1426 # at http://www.diddly.com/random/
1428 ############################################################################
1432 # Common digital camera file name formats, as described at
1433 # http://www.diddly.com/random/about.html
1435 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1436 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1437 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1438 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1439 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1440 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1441 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1442 int(rand(0xC)), int(rand(30))+1,
1444 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1445 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1446 sub { my $n = int(rand(9999)); # Canon
1447 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1448 sub { my $n = int(rand(9999)); # Canon
1449 sprintf ("1%02d-%04d_IMG.jpg",
1450 int($n/100), $n); },
1451 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1452 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1453 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1454 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1455 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1456 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1457 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1458 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1459 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1460 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1461 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1462 # int(rand(12))+1, int(rand(31))+1,
1463 # int(rand(999))); },
1464 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1465 # int(rand(6)), # year
1466 # int(rand(12))+1, int(rand(31))+1,
1467 # int(rand(999))); },
1468 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1469 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1470 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1471 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1476 sub pick_from_google_image_photos($) {
1479 my $i = int(rand($#photomakers + 1));
1480 my $fn = $photomakers[$i];
1482 #$file .= "%20filetype:jpg";
1484 pick_from_google_images ($timeout, $file);
1488 ############################################################################
1490 # Pick images by feeding random words into Google Image Search.
1491 # By the way: fuck Microsoft.
1493 ############################################################################
1495 my $bing_images_url = "http://www.bing.com/images/async" .
1502 sub pick_from_bing_images($;$$) {
1503 my ($timeout, $words, $max_page) = @_;
1505 if (!defined($words)) {
1506 $words = random_word(); # only one word for Bing
1509 my $off = int(rand(300));
1510 my $search_url = $bing_images_url . $words . "&first=" . $off;
1512 my ($search_hit_count, @subpages) =
1513 pick_from_search_engine ($timeout, $search_url, $words);
1515 my @candidates = ();
1517 foreach my $u (@subpages) {
1518 my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1520 LOG ($verbose_filter, " candidate: $ref");
1521 push @candidates, $img;
1522 $referers{$img} = $ref;
1525 @candidates = depoison (@candidates);
1526 return () if ($#candidates < 0);
1527 my $i = int(rand($#candidates+1));
1528 my $img = $candidates[$i];
1529 my $ref = $referers{$img};
1531 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1532 return ($ref, $img);
1538 ############################################################################
1540 # Pick images by feeding random numbers into Bing Image Search.
1542 ############################################################################
1545 sub pick_from_bing_image_numbers($) {
1549 my $number = int(rand($max));
1551 $number = sprintf("%04d", $number)
1554 pick_from_bing_images ($timeout, "$number");
1558 ############################################################################
1560 # Pick images by feeding random numbers into Bing Image Search.
1562 ############################################################################
1565 sub pick_from_bing_image_photos($) {
1568 my $i = int(rand($#photomakers + 1));
1569 my $fn = $photomakers[$i];
1572 pick_from_bing_images ($timeout, $file);
1576 ############################################################################
1578 # Pick images by feeding random words into Alta Vista Text Search
1580 ############################################################################
1583 my $alta_vista_url = "http://www.altavista.com/web/results" .
1587 "&sc=on" . # "site collapse"
1592 sub pick_from_alta_vista_text($) {
1595 my $words = random_words('%20');
1596 my $page = (int(rand(9)) + 1);
1597 my $search_url = $alta_vista_url . $words;
1600 $search_url .= "&pgno=" . $page;
1601 $search_url .= "&stq=" . (($page-1) * 10);
1604 my ($search_hit_count, @subpages) =
1605 pick_from_search_engine ($timeout, $search_url, $words);
1607 my @candidates = ();
1608 foreach my $u (@subpages) {
1610 # Those altavista fuckers are playing really nasty redirection games
1611 # these days: the filter your clicks through their site, but use
1612 # onMouseOver to make it look like they're not! Well, it makes it
1613 # easier for us to identify search results...
1615 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1616 $u = url_unquote($u);
1618 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1619 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1620 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1622 LOG ($verbose_filter, " candidate: $u");
1623 push @candidates, $u;
1626 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1627 $timeout, @candidates);
1632 ############################################################################
1634 # Pick images by feeding random words into Hotbot
1636 ############################################################################
1638 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1640 "&descriptiontype=0" .
1647 "&cobrand=undefined" .
1650 sub pick_from_hotbot_text($) {
1653 $last_search = $hotbot_search_url; # for warnings
1655 # lycos seems to always give us back dictionaries and word lists if
1656 # we search for more than one word...
1658 my $words = random_word();
1660 my $start = int(rand(8)) * 10 + 1;
1661 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1663 my ($search_hit_count, @subpages) =
1664 pick_from_search_engine ($timeout, $search_url, $words);
1666 my @candidates = ();
1667 foreach my $u (@subpages) {
1669 # Hotbot plays redirection games too
1671 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1672 # $u = url_decode($1);
1674 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1675 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1676 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1677 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1679 LOG ($verbose_filter, " candidate: $u");
1680 push @candidates, $u;
1683 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1684 $timeout, @candidates);
1689 ############################################################################
1691 # Pick images by feeding random words into Lycos
1693 ############################################################################
1695 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1701 sub pick_from_lycos_text($) {
1704 $last_search = $lycos_search_url; # for warnings
1706 # lycos seems to always give us back dictionaries and word lists if
1707 # we search for more than one word...
1709 my $words = random_word();
1711 my $start = int(rand(8)) * 10 + 1;
1712 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1714 my ($search_hit_count, @subpages) =
1715 pick_from_search_engine ($timeout, $search_url, $words);
1717 my @candidates = ();
1718 foreach my $u (@subpages) {
1720 # Lycos plays redirection games.
1722 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1727 # $u = url_decode($1);
1729 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1730 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1731 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1732 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1733 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
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 by feeding random words into news.yahoo.com
1750 ############################################################################
1752 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1757 sub pick_from_yahoo_news_text($) {
1760 $last_search = $yahoo_news_url; # for warnings
1762 my $words = random_word();
1763 my $search_url = $yahoo_news_url . $words;
1765 my ($search_hit_count, @subpages) =
1766 pick_from_search_engine ($timeout, $search_url, $words);
1768 my @candidates = ();
1769 foreach my $u (@subpages) {
1771 # de-redirectize the URLs
1772 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1774 # only accept URLs on Yahoo's news site
1775 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1776 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1777 next unless ($u =~ m@&u=/@);
1779 LOG ($verbose_filter, " candidate: $u");
1780 push @candidates, $u;
1783 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1784 $timeout, @candidates);
1789 ############################################################################
1791 # Pick images from LiveJournal's list of recently-posted images.
1793 ############################################################################
1795 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1797 # With most of our image sources, we get a random page and then select
1798 # from the images on it. However, in the case of LiveJournal, the page
1799 # of images tends to update slowly; so we'll remember the last N entries
1800 # on it and randomly select from those, to get a wider variety each time.
1802 my $lj_cache_size = 1000;
1803 my @lj_cache = (); # fifo, for ordering by age
1804 my %lj_cache = (); # hash, for detecting dups
1807 sub pick_from_livejournal_images($) {
1810 $last_search = $livejournal_img_url; # for warnings
1812 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1813 return () unless $body;
1816 $body =~ s/(<recent-image)\b/\n$1/gsi;
1818 foreach (split (/\n/, $body)) {
1819 next unless (m/^<recent-image\b/);
1820 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1821 my $img = html_unquote ($1);
1823 next if ($lj_cache{$img}); # already have it
1825 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1826 my $page = html_unquote ($1);
1827 my @pair = ($img, $page);
1828 LOG ($verbose_filter, " candidate: $img");
1829 push @lj_cache, \@pair;
1830 $lj_cache{$img} = \@pair;
1833 return () if ($#lj_cache == -1);
1835 my $n = $#lj_cache+1;
1836 my $i = int(rand($n));
1837 my ($img, $page) = @{$lj_cache[$i]};
1839 # delete this one from @lj_cache and from %lj_cache.
1841 @lj_cache = ( @lj_cache[0 .. $i-1],
1842 @lj_cache[$i+1 .. $#lj_cache] );
1843 delete $lj_cache{$img};
1845 # Keep the size of the cache under the limit by nuking older entries
1847 while ($#lj_cache >= $lj_cache_size) {
1848 my $pairP = shift @lj_cache;
1849 my $img = $pairP->[0];
1850 delete $lj_cache{$img};
1853 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1855 return ($page, $img);
1859 ############################################################################
1861 # Pick images from ircimages.com (images that have been in the /topic of
1862 # various IRC channels.)
1864 ############################################################################
1866 my $ircimages_url = "http://ircimages.com/";
1869 sub pick_from_ircimages($) {
1872 $last_search = $ircimages_url; # for warnings
1874 my $n = int(rand(2900));
1875 my $search_url = $ircimages_url . "page-$n";
1877 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1878 return () unless $body;
1880 my @candidates = ();
1883 $body =~ s/(<A)\b/\n$1/gsi;
1885 foreach (split (/\n/, $body)) {
1887 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1890 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1891 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1893 next unless ($u =~ m/^http:/i);
1894 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1895 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1897 LOG ($verbose_http, " HREF: $u");
1898 push @candidates, $u;
1901 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1903 return () if ($#candidates == -1);
1905 my $i = int(rand($#candidates+1));
1906 my $img = $candidates[$i];
1908 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1911 $search_url = $img; # hmm...
1912 return ($search_url, $img);
1916 ############################################################################
1918 # Pick images from Twitpic's list of recently-posted images.
1920 ############################################################################
1922 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1924 # With most of our image sources, we get a random page and then select
1925 # from the images on it. However, in the case of Twitpic, the page
1926 # of images tends to update slowly; so we'll remember the last N entries
1927 # on it and randomly select from those, to get a wider variety each time.
1929 my $twitpic_cache_size = 1000;
1930 my @twitpic_cache = (); # fifo, for ordering by age
1931 my %twitpic_cache = (); # hash, for detecting dups
1934 sub pick_from_twitpic_images($) {
1937 $last_search = $twitpic_img_url; # for warnings
1939 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1945 $body =~ s/(<item)\b/\n$1/gsi;
1947 my @items = split (/\n/, $body);
1950 next unless (m@<link>([^<>]*)</link>@si);
1951 my $page = html_unquote ($1);
1956 next if ($twitpic_cache{$page}); # already have it
1958 LOG ($verbose_filter, " candidate: $page");
1959 push @twitpic_cache, $page;
1960 $twitpic_cache{$page} = $page;
1964 # Pull from the cache.
1966 return () if ($#twitpic_cache == -1);
1968 my $n = $#twitpic_cache+1;
1969 my $i = int(rand($n));
1970 my $page = $twitpic_cache[$i];
1972 # delete this one from @twitpic_cache and from %twitpic_cache.
1974 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1975 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1976 delete $twitpic_cache{$page};
1978 # Keep the size of the cache under the limit by nuking older entries
1980 while ($#twitpic_cache >= $twitpic_cache_size) {
1981 my $page = shift @twitpic_cache;
1982 delete $twitpic_cache{$page};
1985 ( $base, $body ) = get_document ($page, undef, $timeout);
1987 $body = '' unless defined($body);
1989 foreach (split (/<img\s+/, $body)) {
1990 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1993 next if m@/images/@s;
1997 $img = "http:$img" if ($img =~ m@^//@s); # Oh come on
1999 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
2000 if ($img =~ m@^/@) {
2001 $base =~ s@^(https?://[^/]+)/.*@$1@s;
2002 $img = $base . $img;
2008 LOG ($verbose_load, "no matching images on $page\n");
2012 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2014 return ($page, $img);
2018 ############################################################################
2020 # Pick images from Twitter's list of recently-posted updates.
2022 ############################################################################
2024 # With most of our image sources, we get a random page and then select
2025 # from the images on it. However, in the case of Twitter, the page
2026 # of images only updates once a minute; so we'll remember the last N entries
2027 # on it and randomly select from those, to get a wider variety each time.
2029 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2030 "public_timeline.json" .
2031 "?include_entities=true" .
2032 "&include_rts=true" .
2035 my $twitter_cache_size = 1000;
2037 my @twitter_cache = (); # fifo, for ordering by age
2038 my %twitter_cache = (); # hash, for detecting dups
2042 sub pick_from_twitter_images($) {
2045 $last_search = $twitter_img_url; # for warnings
2047 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2051 $body =~ s/[\r\n]+/ /gs;
2053 # Parsing JSON is a pain in the ass. So we halfass it as usual.
2054 $body =~ s/^\[|\]$//s;
2055 $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2056 my @items = split (/},{/, $body);
2058 my ($name) = m@"screen_name":"([^\"]+)"@si;
2059 my ($img) = m@"media_url":"([^\"]+)"@si;
2060 my ($page) = m@"display_url":"([^\"]+)"@si;
2061 next unless ($name && $img && $page);
2062 foreach ($img, $page) {
2064 $_ = "http://$_" unless (m/^http/si);
2067 next if ($twitter_cache{$page}); # already have it
2069 LOG ($verbose_filter, " candidate: $page - $img");
2070 push @twitter_cache, $page;
2071 $twitter_cache{$page} = $img;
2075 # Pull from the cache.
2077 return () if ($#twitter_cache == -1);
2079 my $n = $#twitter_cache+1;
2080 my $i = int(rand($n));
2081 my $page = $twitter_cache[$i];
2082 my $url = $twitter_cache{$page};
2084 # delete this one from @twitter_cache and from %twitter_cache.
2086 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2087 @twitter_cache[$i+1 .. $#twitter_cache] );
2088 delete $twitter_cache{$page};
2090 # Keep the size of the cache under the limit by nuking older entries
2092 while ($#twitter_cache >= $twitter_cache_size) {
2093 my $page = shift @twitter_cache;
2094 delete $twitter_cache{$page};
2097 LOG ($verbose_load, "picked page $url");
2099 $suppress_audit = 1;
2101 return ($page, $url);
2105 ############################################################################
2107 # Pick images from Flickr's page of recently-posted photos.
2109 ############################################################################
2111 my $flickr_img_url = "http://www.flickr.com/explore/";
2113 # Like LiveJournal, the Flickr page of images tends to update slowly,
2114 # so remember the last N entries on it and randomly select from those.
2116 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2117 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2119 my $flickr_cache_size = 1000;
2120 my @flickr_cache = (); # fifo, for ordering by age
2121 my %flickr_cache = (); # hash, for detecting dups
2125 sub pick_from_flickr_recent($) {
2128 my $start = 16 * int(rand(100));
2130 $last_search = $flickr_img_url; # for warnings
2131 $last_search .= "?start=$start" if ($start > 0);
2133 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2134 return () unless $body;
2136 $body =~ s/[\r\n]/ /gs;
2137 $body =~ s/(<a)\b/\n$1/gsi;
2141 foreach (split (/\n/, $body)) {
2143 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2145 data-defer-src = \"([^<>\"]+)\" @xsi;
2146 next unless defined ($thumb);
2147 $page = html_unquote ($page);
2148 $thumb = html_unquote ($thumb);
2150 next unless ($thumb =~ m@^http://farm\d*\.static\.?flickr\.com/@);
2152 my $base = "http://www.flickr.com/";
2153 $page =~ s@^/@$base@;
2154 $thumb =~ s@^/@$base@;
2157 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2160 next if ($flickr_cache{$img}); # already have it
2162 my @pair = ($img, $page, $start);
2163 LOG ($verbose_filter, " candidate: $img");
2164 push @flickr_cache, \@pair;
2165 $flickr_cache{$img} = \@pair;
2169 return () if ($#flickr_cache == -1);
2171 my $n = $#flickr_cache+1;
2172 my $i = int(rand($n));
2173 my ($img, $page) = @{$flickr_cache[$i]};
2175 # delete this one from @flickr_cache and from %flickr_cache.
2177 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2178 @flickr_cache[$i+1 .. $#flickr_cache] );
2179 delete $flickr_cache{$img};
2181 # Keep the size of the cache under the limit by nuking older entries
2183 while ($#flickr_cache >= $flickr_cache_size) {
2184 my $pairP = shift @flickr_cache;
2185 my $img = $pairP->[0];
2186 delete $flickr_cache{$img};
2189 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2191 return ($page, $img);
2195 ############################################################################
2197 # Pick images from a random RSS feed on Flickr.
2199 ############################################################################
2201 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2202 "?format=rss_200_enc&tagmode=any&tags=");
2204 # Picks a random RSS feed; picks a random image from that feed;
2205 # returns 2 URLs: the page containing the image, and the image.
2206 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2209 sub pick_from_flickr_random($) {
2210 my $timeout = shift;
2212 my $words = random_words(',');
2213 my $rss = $flickr_rss_base . $words;
2214 $last_search = $rss;
2219 print STDERR "\n\n" if ($verbose_load);
2220 LOG ($verbose_load, "words: $_");
2221 LOG ($verbose_load, "URL: $last_search");
2223 $suppress_audit = 1;
2225 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2226 if (!$base || !$body) {
2232 ($base, $img) = pick_image_from_rss ($base, $body);
2234 return () unless defined ($img);
2236 LOG ($verbose_load, "redirected to: $base");
2237 return ($base, $img);
2241 ############################################################################
2243 # Pick random images from Instagram, via gramfeed.com's key.
2245 ############################################################################
2247 my $instagram_url_base = "https://api.instagram.com/v1/media/popular" .
2248 "?client_id=b59fbe4563944b6c88cced13495c0f49";
2251 sub pick_from_instagram($) {
2252 my $timeout = shift;
2254 $last_search = $instagram_url_base;
2256 print STDERR "\n\n" if ($verbose_load);
2257 LOG ($verbose_load, "URL: $last_search");
2259 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2260 if (!$base || !$body) {
2265 $body =~ s/("link")/\001$1/gs;
2266 my @chunks = split(/\001/, $body);
2271 my ($url) = m/"link":\s*"(.*?)"/s;
2272 my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2273 ($img) = m/"url":\s*"(.*?)"/s unless $url;
2274 next unless ($url && $img);
2275 push @urls, [ $url, $img ];
2279 LOG ($verbose_load, "no images on $last_search");
2283 my $i = int(rand($#urls+1));
2284 my ($url, $img) = @{$urls[$i]};
2286 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2287 return ($url, $img);
2291 ############################################################################
2293 # Pick images by waiting for driftnet to populate a temp dir with files.
2294 # Requires driftnet version 0.1.5 or later.
2295 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2296 # for images being downloaded by others.)
2297 # Driftnet/webcollage integration by jwz.
2299 ############################################################################
2302 sub pick_from_driftnet($) {
2305 my $id = $driftnet_magic;
2306 my $dir = $driftnet_dir;
2310 error ("\$driftnet_dir unset?") unless ($dir);
2313 error ("$dir unreadable") unless (-d "$dir/.");
2315 $timeout = $http_timeout unless ($timeout);
2318 while ($now = time, $now < $start + $timeout) {
2319 opendir (my $dir, $dir) || error ("$dir: $!");
2320 while (my $file = readdir($dir)) {
2321 next if ($file =~ m/^\./);
2322 $file = "$dir/$file";
2324 LOG ($verbose_load, "picked file $file ($id)");
2325 return ($id, $file);
2329 LOG (($verbose_net || $verbose_load), "timed out for $id");
2334 sub get_driftnet_file($) {
2337 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2339 my $id = $driftnet_magic;
2340 error ("$id: $file not in $driftnet_dir?")
2341 unless ($file =~ m@^\Q$driftnet_dir@o);
2343 open (my $in, '<', $file) || error ("$id: $file: $!");
2345 local $/ = undef; # read entire file
2347 close ($in) || error ("$id: $file: $!");
2348 unlink ($file) || error ("$id: $file: rm: $!");
2349 return ($id, $body);
2353 sub spawn_driftnet($) {
2356 # make a directory to use.
2358 my $tmp = $ENV{TEMPDIR} || "/tmp";
2359 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2360 LOG ($verbose_exec, "mkdir $driftnet_dir");
2361 last if mkdir ($driftnet_dir, 0700);
2364 if (! ($cmd =~ m/\s/)) {
2365 # if the command didn't have any arguments in it, then it must be just
2366 # a pointer to the executable. Append the default args to it.
2367 my $dargs = $default_driftnet_cmd;
2368 $dargs =~ s/^[^\s]+//;
2372 # point the driftnet command at our newly-minted private directory.
2374 $cmd .= " -d $driftnet_dir";
2375 $cmd .= ">/dev/null" unless ($verbose_exec);
2378 if ($pid < 0) { error ("fork: $!\n"); }
2381 push @pids_to_kill, $pid;
2382 LOG ($verbose_exec, "forked for \"$cmd\"");
2385 nontrapping_system ($cmd) || error ("exec: $!");
2388 # wait a bit, then make sure the process actually started up.
2391 error ("pid $pid failed to start \"$cmd\"")
2392 unless (1 == kill (0, $pid));
2396 sub pick_from_local_dir($) {
2399 my $id = $local_magic;
2402 my $dir = $local_dir;
2403 error ("\$local_dir unset?") unless ($dir);
2406 error ("$dir unreadable") unless (-d "$dir/.");
2408 my $v = ($verbose_exec ? "-v" : "");
2409 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2411 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2413 LOG ($verbose_load, "picked file $pick ($id)");
2414 return ($id, $pick);
2418 sub get_local_file($) {
2421 error ("\$local_dir unset?") unless ($local_dir);
2423 my $id = $local_magic;
2424 error ("$id: $file not in $local_dir?")
2425 unless ($file =~ m@^\Q$local_dir@o);
2427 open (my $in, '<', $file) || error ("$id: $file: $!");
2428 local $/ = undef; # read entire file
2430 close ($in) || error ("$id: $file: $!");
2431 return ($id, $body);
2436 ############################################################################
2438 # Pick a random image in a random way
2440 ############################################################################
2443 # Picks a random image on a random page, and returns two URLs:
2444 # the page containing the image, and the image.
2445 # Returns () if nothing found this time.
2448 sub pick_image(;$) {
2451 $current_state = "select";
2452 $load_method = "none";
2454 my $n = int(rand(100));
2457 my @rest = @search_methods;
2460 my $pct = shift @rest;
2461 my $name = shift @rest;
2462 my $tfn = shift @rest;
2464 if ($total > $n && !defined($fn)) {
2466 $current_state = $name;
2467 $load_method = $current_state;
2471 if ($total != 100) {
2472 error ("internal error: \@search_methods totals to $total%!");
2475 record_attempt ($current_state);
2476 return $fn->($timeout);
2481 ############################################################################
2483 # Statistics and logging
2485 ############################################################################
2488 return strftime ("%H:%M:%S: ", localtime);
2492 return "$progname: " . timestr() . "$current_state: ";
2497 print STDERR blurb() . "$err\n";
2503 print STDERR "$progname: stack trace:\n";
2505 my ($package, $filename, $line, $subroutine) = caller($i++);
2506 last unless defined($package);
2507 $filename =~ s@^.*/@@;
2508 print STDERR " $filename#$line, $subroutine\n";
2520 my $head = "$progname: DEBUG: ";
2521 foreach (split (/\n/, $lastlog)) {
2522 print STDERR "$head$_\n";
2528 my ($print, $msg) = @_;
2529 my $blurb = timestr() . "$current_state: ";
2530 $lastlog .= "$blurb$msg\n";
2531 print STDERR "$progname: $blurb$msg\n" if $print;
2536 my %stats_successes;
2539 my $last_state = undef;
2540 sub record_attempt($) {
2544 record_failure($last_state) unless ($image_succeeded > 0);
2546 $last_state = $name;
2549 report_performance();
2552 $image_succeeded = 0;
2553 $suppress_audit = 0;
2556 sub record_success($$$) {
2557 my ($name, $url, $base) = @_;
2558 if (defined($stats_successes{$name})) {
2559 $stats_successes{$name}++;
2561 $stats_successes{$name} = 1;
2564 stop_timer ($name, 1);
2565 my $o = $current_state;
2566 $current_state = $name;
2567 save_recent_url ($url, $base);
2568 $current_state = $o;
2569 $image_succeeded = 1;
2574 sub record_failure($) {
2577 return if $image_succeeded;
2579 stop_timer ($name, 0);
2580 if ($verbose_load && !$verbose_exec) {
2582 if ($suppress_audit) {
2583 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2587 my $o = $current_state;
2588 $current_state = "DEBUG";
2590 my $line = "#" x 78;
2591 print STDERR "\n\n\n";
2592 print STDERR ("#" x 78) . "\n";
2593 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2596 print STDERR ("-" x 78) . "\n";
2597 print STDERR "\n\n";
2599 $current_state = $o;
2601 $image_succeeded = 0;
2608 my $i = $stats_successes{$name};
2609 my $j = $stats_attempts{$name};
2612 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2616 my $current_start_time = 0;
2618 sub start_timer($) {
2620 $current_start_time = time;
2622 if (defined($stats_attempts{$name})) {
2623 $stats_attempts{$name}++;
2625 $stats_attempts{$name} = 1;
2627 if (!defined($stats_elapsed{$name})) {
2628 $stats_elapsed{$name} = 0;
2632 sub stop_timer($$) {
2633 my ($name, $success) = @_;
2634 $stats_elapsed{$name} += time - $current_start_time;
2638 my $last_report_time = 0;
2639 sub report_performance() {
2641 return unless $verbose_warnings;
2644 return unless ($now >= $last_report_time + $report_performance_interval);
2645 my $ot = $last_report_time;
2646 $last_report_time = $now;
2648 return if ($ot == 0);
2650 my $blurb = "$progname: " . timestr();
2653 print STDERR "${blurb}Current standings:\n";
2655 foreach my $name (sort keys (%stats_attempts)) {
2656 my $try = $stats_attempts{$name};
2657 my $suc = $stats_successes{$name} || 0;
2658 my $pct = int($suc * 100 / $try);
2659 my $secs = $stats_elapsed{$name};
2660 my $secs_link = $secs / $try;
2661 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2662 " \t %.1f secs/link\n",
2663 "$name:", "$pct%", $suc, $try, $secs_link);
2669 my $max_recent_images = 400;
2670 my $max_recent_sites = 20;
2671 my @recent_images = ();
2672 my @recent_sites = ();
2674 sub save_recent_url($$) {
2675 my ($url, $base) = @_;
2677 return unless ($verbose_warnings);
2680 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2681 return unless defined ($site);
2683 if ($base eq $driftnet_magic || $base eq $local_magic) {
2685 @recent_images = ();
2689 foreach (@recent_images) {
2691 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2692 " (on $base via $last_search)\n";
2698 # suppress "duplicate site" warning via %warningless_sites.
2700 if ($warningless_sites{$site}) {
2702 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2703 $warningless_sites{$1}) {
2705 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2706 $warningless_sites{$1}) {
2711 foreach (@recent_sites) {
2713 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2714 " ($url on $base via $last_search)\n";
2720 push @recent_images, $url;
2721 push @recent_sites, $site;
2722 shift @recent_images if ($#recent_images >= $max_recent_images);
2723 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2728 ##############################################################################
2732 ##############################################################################
2739 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2744 # Given the raw body of a GIF document, returns the dimensions of the image.
2748 my $type = substr($body, 0, 6);
2750 return () unless ($type =~ /GIF8[7,9]a/);
2751 $s = substr ($body, 6, 10);
2752 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2753 return () unless defined ($d);
2754 return (($b<<8|$a), ($d<<8|$c));
2757 # Given the raw body of a JPEG document, returns the dimensions of the image.
2762 my $L = length($body);
2764 my $c1 = substr($body, $i, 1); $i++;
2765 my $c2 = substr($body, $i, 1); $i++;
2766 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2769 while (ord($ch) != 0xDA && $i < $L) {
2770 # Find next marker, beginning with 0xFF.
2771 while (ord($ch) != 0xFF) {
2772 return () if (length($body) <= $i);
2773 $ch = substr($body, $i, 1); $i++;
2775 # markers can be padded with any number of 0xFF.
2776 while (ord($ch) == 0xFF) {
2777 return () if (length($body) <= $i);
2778 $ch = substr($body, $i, 1); $i++;
2781 # $ch contains the value of the marker.
2782 my $marker = ord($ch);
2784 if (($marker >= 0xC0) &&
2785 ($marker <= 0xCF) &&
2786 ($marker != 0xC4) &&
2787 ($marker != 0xCC)) { # it's a SOFn marker
2789 return () if (length($body) <= $i);
2790 my $s = substr($body, $i, 4); $i += 4;
2791 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2792 return (($c<<8|$d), ($a<<8|$b));
2795 # We must skip variables, since FFs in variable names aren't
2796 # valid JPEG markers.
2797 return () if (length($body) <= $i);
2798 my $s = substr($body, $i, 2); $i += 2;
2799 my ($c1, $c2) = unpack ("C"x2, $s);
2800 my $length = ($c1 << 8) | $c2;
2801 return () if ($length < 2);
2808 # Given the raw body of a PNG document, returns the dimensions of the image.
2812 return () unless ($body =~ m/^\211PNG\r/);
2813 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2814 return () unless defined ($bits);
2815 return () unless ($bits =~ /^IHDR/);
2816 my ($ign, $w, $h) = unpack("a4N2", $bits);
2821 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2826 my ($w, $h) = gif_size ($body);
2827 if ($w && $h) { return ($w, $h); }
2828 ($w, $h) = jpeg_size ($body);
2829 if ($w && $h) { return ($w, $h); }
2830 return png_size ($body);
2834 # returns the full path of the named program, or undef.
2838 foreach (split (/:/, $ENV{PATH})) {
2839 if (-x "$_/$prog") {
2847 # Like rand(), but chooses numbers with a bell curve distribution.
2850 $_ = 1.0 unless defined($_);
2852 return (rand($_) + rand($_) + rand($_));
2856 sub exit_cleanup() {
2858 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2859 if (@pids_to_kill) {
2860 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2861 kill ('TERM', @pids_to_kill);
2865 sub signal_cleanup($) {
2867 print STDERR blurb() . (defined($sig)
2868 ? "caught signal $sig."
2871 if ($verbose_exec || $verbose_warnings);
2877 ##############################################################################
2879 # Generating a list of urls only
2881 ##############################################################################
2883 sub url_only_output() {
2885 my ($base, $img) = pick_image;
2889 print "$img $base\n";
2894 ##############################################################################
2896 # Running as an xscreensaver module, or as a web page imagemap
2898 ##############################################################################
2900 my $image_ppm = sprintf ("%s/webcollage-%08x.ppm",
2901 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2903 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x.ppm",
2904 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2906 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x.ppm",
2907 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2910 my $filter_cmd = undef;
2911 my $post_filter_cmd = undef;
2912 my $background = undef;
2914 my @imagemap_areas = ();
2915 my $imagemap_html_tmp = undef;
2916 my $imagemap_jpg_tmp = undef;
2919 my $img_width; # size of the image being generated.
2925 unlink $image_ppm, $image_tmp1, $image_tmp2;
2926 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2927 if (defined ($imagemap_html_tmp));
2931 # Like system, but prints status about exit codes, and kills this process
2932 # with whatever signal killed the sub-process, if any.
2934 sub nontrapping_system(@) {
2938 s/\"[^\"]+\"/\"...\"/g;
2940 LOG ($verbose_exec, "executing \"$_\"");
2945 LOG ($verbose_exec, "subproc exited normally.");
2946 } elsif (($rc & 0xff) == 0) {
2948 LOG ($verbose_exec, "subproc exited with status $rc.");
2951 LOG ($verbose_exec, "subproc dumped core.");
2954 LOG ($verbose_exec, "subproc died with signal $rc.");
2955 # die that way ourselves.
2963 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2964 # writes a PPM to the given output file. Returns the width/height of the
2965 # image if successful.
2967 sub image_to_pnm($$$) {
2968 my ($url, $body, $output) = @_;
2969 my ($cmd, $cmd2, $w, $h);
2971 if ((@_ = gif_size ($body))) {
2974 } elsif ((@_ = jpeg_size ($body))) {
2977 } elsif ((@_ = png_size ($body))) {
2981 LOG (($verbose_pbm || $verbose_load),
2982 "not a GIF, JPG, or PNG" .
2983 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2984 ? " (looks like HTML)" : "") .
2986 $suppress_audit = 1;
2990 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2991 # do this, the process doesn't die properly.
2992 if (!$verbose_pbm) {
2994 # We get a "giftopnm: got a 'Application Extension' extension"
2995 # warning any time it's an animgif.
2997 # Note that "giftopnm: EOF / read error on image data" is not
2998 # always a fatal error -- sometimes the image looks fine anyway.
3000 $cmd2 .= " 2>/dev/null";
3003 # There exist corrupted GIF and JPEG files that can make giftopnm and
3004 # djpeg lose their minds and go into a loop. So this gives those programs
3005 # a small timeout -- if they don't complete in time, kill them.
3011 local $SIG{ALRM} = sub {
3013 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3014 kill ('TERM', $pid) if ($pid);
3019 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3026 LOG ($verbose_exec, "awaiting $pid");
3028 LOG ($verbose_exec, "$pid completed");
3030 my $size = (stat($output))[7];
3031 $size = -1 unless defined($size);
3033 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3037 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3040 print STDERR blurb() . "$cmd failed: $!\n";
3044 die if ($@ && $@ ne "alarm\n"); # propagate errors
3058 # Same as the "ppmmake" command: creates a solid-colored PPM.
3059 # Does not understand the rgb.txt color names except "black" and "white".
3062 my ($outfile, $bgcolor, $w, $h) = @_;
3065 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3066 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3067 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3068 } elsif ($bgcolor =~ m/^black$/i) {
3069 ($r, $g, $b) = (0, 0, 0);
3070 } elsif ($bgcolor =~ m/^white$/i) {
3071 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3073 error ("unparsable color name: $bgcolor");
3076 my $pixel = pack('CCC', $r, $g, $b);
3077 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3079 open (my $out, '>', $outfile) || error ("$outfile: $!");
3085 sub pick_root_displayer() {
3089 # see "xscreensaver/hacks/webcollage-cocoa.m"
3090 return "echo COCOA LOAD ";
3093 foreach my $cmd (@root_displayers) {
3095 my ($name) = m/^([^ ]+)/;
3096 push @names, "\"$name\"";
3097 LOG ($verbose_exec, "looking for $name...");
3098 foreach my $dir (split (/:/, $ENV{PATH})) {
3099 LOG ($verbose_exec, " checking $dir/$name");
3100 return $cmd if (-x "$dir/$name");
3104 $names[$#names] = "or " . $names[$#names];
3105 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3109 my $ppm_to_root_window_cmd = undef;
3112 sub x_or_pbm_output($) {
3113 my ($window_id) = @_;
3115 # Check for our helper program, to see whether we need to use PPM pipelines.
3117 $_ = "webcollage-helper";
3118 if (defined ($webcollage_helper) || which ($_)) {
3119 $webcollage_helper = $_ unless (defined($webcollage_helper));
3120 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3121 $webcollage_helper .= " -v";
3123 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3126 if ($cocoa_p && !defined ($webcollage_helper)) {
3127 error ("webcollage-helper not found in Cocoa-mode!");
3131 # make sure the various programs we execute exist, right up front.
3135 if (!defined($webcollage_helper)) {
3136 # Only need these others if we don't have the helper.
3138 "giftopnm", "pngtopnm", "djpeg",
3139 "pnmpaste", "pnmscale", "pnmcut");
3143 which ($_) || error "$_ not found on \$PATH.";
3146 # find a root-window displayer program.
3148 if (!$no_output_p) {
3149 $ppm_to_root_window_cmd = pick_root_displayer();
3152 if (defined ($window_id)) {
3153 error ("-window-id only works if xscreensaver-getimage is installed")
3154 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3156 error ("unparsable window id: $window_id")
3157 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3158 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3159 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3162 if (!$img_width || !$img_height) {
3164 if (!defined ($window_id) &&
3165 defined ($ENV{XSCREENSAVER_WINDOW})) {
3166 $window_id = $ENV{XSCREENSAVER_WINDOW};
3169 if (!defined ($window_id)) {
3171 which ($_) || error "$_ not found on \$PATH.";
3173 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3174 if (!defined($img_height)) {
3175 error "xdpyinfo failed.";
3177 } else { # we have a window id
3179 which ($_) || error "$_ not found on \$PATH.";
3180 $_ .= " -id $window_id";
3182 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3184 if (!defined($img_height)) {
3185 error "xwininfo failed.";
3190 my $bgcolor = "#000000";
3191 my $bgimage = undef;
3194 if ($background =~ m/^\#[0-9a-f]+$/i) {
3195 $bgcolor = $background;
3197 } elsif (-r $background) {
3198 $bgimage = $background;
3200 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3201 error "not a color or readable file: $background";
3204 # default to assuming it's a color
3205 $bgcolor = $background;
3209 # Create the sold-colored base image.
3211 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3212 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3214 # Paste the default background image in the middle of it.
3220 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3221 local $/ = undef; # read entire file
3226 if ((@_ = gif_size ($body))) {
3228 $cmd = "giftopnm |";
3230 } elsif ((@_ = jpeg_size ($body))) {
3234 } elsif ((@_ = png_size ($body))) {
3236 $cmd = "pngtopnm |";
3238 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3244 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3247 my $x = int (($img_width - $iw) / 2);
3248 my $y = int (($img_height - $ih) / 2);
3250 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3252 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3253 open ($imgf, "| $cmd") || error "running $cmd: $!";
3257 LOG ($verbose_exec, "subproc exited normally.");
3258 rename ($image_tmp1, $image_ppm) ||
3259 error "renaming $image_tmp1 to $image_ppm: $!";
3265 my ($base, $img) = pick_image();
3266 my $source = $current_state;
3267 $current_state = "loadimage";
3269 my ($headers, $body) = get_document ($img, $base);
3271 paste_image ($base, $img, $body, $source);
3275 $current_state = "idle";
3276 $load_method = "none";
3278 unlink $image_tmp1, $image_tmp2;
3283 sub paste_image($$$$) {
3284 my ($base, $img, $body, $source) = @_;
3286 $current_state = "paste";
3288 $suppress_audit = 0;
3290 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3294 # If we are using the webcollage-helper, then we do not need to convert this
3295 # image to a PPM. But, if we're using a filter command, we still must, since
3296 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3299 if (defined ($webcollage_helper) &&
3300 !defined ($filter_cmd)) {
3302 ($iw, $ih) = image_size ($body);
3304 LOG (($verbose_pbm || $verbose_load),
3305 "not a GIF, JPG, or PNG" .
3306 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3307 ? " (looks like HTML)" : "") .
3309 $suppress_audit = 1;
3314 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3315 (print $out $body) || error ("writing $image_tmp1: $!");
3316 close ($out) || error ("writing $image_tmp1: $!");
3319 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3322 LOG ($verbose_pbm, "unable to make PBM from $img");
3327 record_success ($load_method, $img, $base);
3330 my $ow = $iw; # used only for error messages
3333 # don't just tack this onto the front of the pipeline -- we want it to
3334 # be able to change the size of the input image.
3337 LOG ($verbose_pbm, "running $filter_cmd");
3339 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3341 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3342 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3345 rename ($image_tmp2, $image_tmp1);
3347 # re-get the width/height in case the filter resized it.
3348 open (my $imgf, '<', $image_tmp1) || return 0;
3351 ($iw, $ih) = m/^(\d+) (\d+)$/;
3353 return 0 unless ($iw && $ih);
3356 my $target_w = $img_width; # max rectangle into which the image must fit
3357 my $target_h = $img_height;
3363 # Usually scale the image to fit on the screen -- but sometimes scale it
3364 # to fit on half or a quarter of the screen. (We do this by reducing the
3365 # size of the target rectangle.) Note that the image is not merely scaled
3366 # to fit; we instead cut the image in half repeatedly until it fits in the
3367 # target rectangle -- that gives a wider distribution of sizes.
3369 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3370 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3372 if ($iw > $target_w || $ih > $target_h) {
3373 while ($iw > $target_w ||
3379 if ($iw <= 10 || $ih <= 10) {
3380 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3384 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3386 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3390 my $src = $image_tmp1;
3392 my $crop_x = 0; # the sub-rectangle of the image
3393 my $crop_y = 0; # that we will actually paste.
3397 # The chance that we will randomly crop out a section of an image starts
3398 # out fairly low, but goes up for images that are very large, or images
3399 # that have ratios that make them look like banners (we try to avoid
3400 # banner images entirely, but they slip through when the IMG tags didn't
3401 # have WIDTH and HEIGHT specified.)
3403 my $crop_chance = 0.2;
3404 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3405 $crop_chance += 0.2;
3407 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3408 $crop_chance += 0.2;
3410 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3411 $crop_chance += 0.7;
3414 if ($crop_chance > 0.1) {
3415 LOG ($verbose_pbm, "crop chance: $crop_chance");
3418 if (rand() < $crop_chance) {
3423 if ($crop_w > $min_width) {
3424 # if it's a banner, select the width linearly.
3425 # otherwise, select a bell.
3426 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3429 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3430 $crop_x = int (rand() * ($ow - $crop_w));
3432 if ($crop_h > $min_height) {
3433 # height always selects as a bell.
3434 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3435 $crop_y = int (rand() * ($oh - $crop_h));
3438 if ($crop_x != 0 || $crop_y != 0 ||
3439 $crop_w != $iw || $crop_h != $ih) {
3441 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3445 # Where the image should logically land -- this might be negative.
3447 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3448 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3450 # if we have chosen to paste the image outside of the rectangle of the
3451 # screen, then we need to crop it.
3455 $x + $crop_w > $img_width ||
3456 $y + $crop_h > $img_height) {
3459 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3461 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3462 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3464 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3465 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3468 # If any cropping needs to happen, add pnmcut.
3470 if ($crop_x != 0 || $crop_y != 0 ||
3471 $crop_w != $iw || $crop_h != $ih) {
3474 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3475 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3478 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3480 $cmd .= " | pnmpaste - $x $y $image_ppm";
3482 $cmd =~ s@^ *\| *@@;
3484 if (defined ($webcollage_helper)) {
3485 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3486 "$scale $opacity " .
3487 "$crop_x $crop_y $x $y " .
3492 # use a PPM pipeline
3494 $_ .= " < $image_tmp1 > $image_tmp2";
3498 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3500 $_ .= " 2> /dev/null";
3503 my $rc = nontrapping_system ($_);
3505 if (defined ($webcollage_helper) && -z $image_ppm) {
3506 LOG (1, "failed command: \"$cmd\"");
3507 print STDERR "\naudit log:\n\n\n";
3508 print STDERR ("#" x 78) . "\n";
3509 print STDERR blurb() . "$image_ppm has zero size\n";
3511 print STDERR "\n\n";
3516 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3517 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3521 if (!defined ($webcollage_helper)) {
3522 rename ($image_tmp2, $image_ppm) || return;
3525 my $target = "$image_ppm";
3527 # don't just tack this onto the end of the pipeline -- we don't want it
3528 # to end up in $image_ppm, because we don't want the results to be
3531 if ($post_filter_cmd) {
3535 $target = $image_tmp1;
3536 if (!defined ($webcollage_helper)) {
3537 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3539 # Blah, my scripts need the JPEG data, but some other folks need
3540 # the PPM data -- what to do? Ignore the problem, that's what!
3541 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3542 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3545 $rc = nontrapping_system ($cmd);
3547 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3552 if (!$no_output_p) {
3553 my $tsize = (stat($target))[7];
3555 $cmd = "$ppm_to_root_window_cmd $target";
3557 # xv seems to hate being killed. it tends to forget to clean
3558 # up after itself, and leaves windows around and colors allocated.
3559 # I had this same problem with vidwhacker, and I'm not entirely
3560 # sure what I did to fix it. But, let's try this: launch xv
3561 # in the background, so that killing this process doesn't kill it.
3562 # it will die of its own accord soon enough. So this means we
3563 # start pumping bits to the root window in parallel with starting
3564 # the next network retrieval, which is probably a better thing
3567 $cmd .= " &" unless ($cocoa_p);
3569 $rc = nontrapping_system ($cmd);
3572 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3577 LOG ($verbose_pbm, "$target size is $tsize");
3581 $source .= "-" . stats_of($source);
3582 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3583 if ($verbose_imgmap);
3584 if ($imagemap_base) {
3585 update_imagemap ($base, $x, $y, $iw, $ih,
3586 $image_ppm, $img_width, $img_height);
3595 sub update_imagemap($$$$$$$$) {
3596 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3598 $current_state = "imagemap";
3600 my $max_areas = 200;
3602 $url = html_quote ($url);
3605 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3606 unshift @imagemap_areas, $area; # put one on the front
3607 if ($#imagemap_areas >= $max_areas) {
3608 pop @imagemap_areas; # take one off the back.
3611 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3613 my $map_name = $imagemap_base;
3614 $map_name =~ s@^.*/@@;
3615 $map_name = 'collage' if ($map_name eq '');
3617 my $imagemap_html = $imagemap_base . ".html";
3618 my $imagemap_jpg = $imagemap_base . ".jpg";
3619 my $imagemap_jpg2 = $imagemap_jpg;
3620 $imagemap_jpg2 =~ s@^.*/@@gs;
3622 if (!defined ($imagemap_html_tmp)) {
3623 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3624 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3627 # Read the imagemap html file (if any) to get a template.
3629 my $template_html = '';
3631 if (open (my $in, '<', $imagemap_html)) {
3632 local $/ = undef; # read entire file
3633 $template_html = <$in>;
3635 LOG ($verbose_pbm, "read template $imagemap_html");
3638 if ($template_html =~ m/^\s*$/s) {
3639 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3640 "<IMG SRC=\"$imagemap_jpg2\"" .
3641 " USEMAP=\"$map_name\">\n");
3642 LOG ($verbose_pbm, "created dummy template");
3646 # Write the jpg to a tmp file
3650 if (defined ($webcollage_helper)) {
3651 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3653 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3655 my $rc = nontrapping_system ($cmd);
3657 error ("imagemap jpeg failed: \"$cmd\"\n");
3661 # Write the html to a tmp file
3664 my $body = $template_html;
3665 my $areas = join ("\n\t", @imagemap_areas);
3666 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3667 my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3669 "WIDTH=$image_width HEIGHT=$image_height " .
3670 "USEMAP=\"#$map_name\">");
3671 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3672 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3674 # if there are magic webcollage spans in the html, update those too.
3677 my @st = stat ($imagemap_jpg_tmp);
3678 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3679 my $size = int(($st[7] / 1024) + 0.5) . "K";
3680 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3681 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3684 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3685 (print $out $body) || error ("$imagemap_html_tmp: $!");
3686 close ($out) || error ("$imagemap_html_tmp: $!");
3687 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3690 # Rename the two tmp files to the real files
3692 rename ($imagemap_html_tmp, $imagemap_html) ||
3693 error "renaming $imagemap_html_tmp to $imagemap_html";
3694 LOG ($verbose_pbm, "wrote $imagemap_html");
3695 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3696 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3697 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3701 # Figure out what the proxy server should be, either from environment
3702 # variables or by parsing the output of the (MacOS) program "scutil",
3703 # which tells us what the system-wide proxy settings are.
3707 if (! $http_proxy) {
3708 # historical suckage: the environment variable name is lower case.
3709 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3712 if (defined ($http_proxy)) {
3713 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3714 # historical suckage: allow "http://host:port" as well as "host:port".
3719 my $proxy_data = `scutil --proxy 2>/dev/null`;
3720 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3721 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3722 # Note: this ignores the "ExceptionsList".
3724 $http_proxy = $server;
3725 $http_proxy .= ":$port" if $port;
3730 LOG ($verbose_net, "proxy server: $http_proxy");
3735 sub init_signals() {
3737 $SIG{HUP} = \&signal_cleanup;
3738 $SIG{INT} = \&signal_cleanup;
3739 $SIG{QUIT} = \&signal_cleanup;
3740 $SIG{ABRT} = \&signal_cleanup;
3741 $SIG{KILL} = \&signal_cleanup;
3742 $SIG{TERM} = \&signal_cleanup;
3744 # Need this so that if giftopnm dies, we don't die.
3745 $SIG{PIPE} = 'IGNORE';
3748 END { exit_cleanup(); }
3757 my $driftnet_cmd = 0;
3759 $current_state = "init";
3760 $load_method = "none";
3763 my $window_id = undef;
3765 while ($_ = $ARGV[0]) {
3767 if ($_ eq "-display" ||
3773 $ENV{DISPLAY} = shift @ARGV;
3774 } elsif ($_ eq "-root") {
3776 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3777 $window_id = shift @ARGV;
3779 } elsif ($_ eq "-no-output") {
3781 } elsif ($_ eq "-urls-only") {
3784 } elsif ($_ eq "-cocoa") {
3786 } elsif ($_ eq "-imagemap") {
3787 $imagemap_base = shift @ARGV;
3789 } elsif ($_ eq "-verbose") {
3791 } elsif (m/^-v+$/) {
3792 $verbose += length($_)-1;
3793 } elsif ($_ eq "-delay") {
3794 $delay = shift @ARGV;
3795 } elsif ($_ eq "-timeout") {
3796 $http_timeout = shift @ARGV;
3797 } elsif ($_ eq "-filter") {
3798 $filter_cmd = shift @ARGV;
3799 } elsif ($_ eq "-filter2") {
3800 $post_filter_cmd = shift @ARGV;
3801 } elsif ($_ eq "-background" || $_ eq "-bg") {
3802 $background = shift @ARGV;
3803 } elsif ($_ eq "-size") {
3805 if (m@^(\d+)x(\d+)$@) {
3809 error "argument to \"-size\" must be of the form \"640x400\"";
3811 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3812 $http_proxy = shift @ARGV;
3813 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3814 $dict = shift @ARGV;
3815 } elsif ($_ eq "-opacity") {
3816 $opacity = shift @ARGV;
3817 error ("opacity must be between 0.0 and 1.0")
3818 if ($opacity <= 0 || $opacity > 1);
3819 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3820 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3821 if (! ($ARGV[0] =~ m/^-/)) {
3822 $driftnet_cmd = shift @ARGV;
3824 $driftnet_cmd = $default_driftnet_cmd;
3826 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3827 @search_methods = ( 100, "local", \&pick_from_local_dir );
3828 if (! ($ARGV[0] =~ m/^-/)) {
3829 $local_dir = shift @ARGV;
3831 error ("local directory path must be set")
3833 } elsif ($_ eq "-fps") {
3834 # -fps only works on MacOS, via "webcollage-cocoa.m".
3835 # Ignore it if passed to this script in an X11 context.
3836 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3837 my $which = shift @ARGV;
3838 my @rest = @search_methods;
3841 my $pct = shift @rest;
3842 my $name = shift @rest;
3843 my $tfn = shift @rest;
3845 if ($name eq $which) {
3846 @search_methods = (100, $name, $tfn);
3851 error "no such search method as \"$which\"" unless ($ok);
3852 LOG (1, "DEBUG: using only \"$which\"");
3855 print STDERR "$copyright\nusage: $progname " .
3856 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3857 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3858 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3859 "\t\t [-background color] [-opacity f]\n" .
3860 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3861 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3862 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3863 "\t\t [-directory local-image-directory]\n" .
3869 if (!$root_p && !$no_output_p && !$cocoa_p) {
3870 print STDERR $copyright;
3871 error "the -root argument is mandatory (for now.)";
3874 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3875 error "\$DISPLAY is not set.";
3879 if ($verbose == 1) {
3880 $verbose_imgmap = 1;
3881 $verbose_warnings = 1;
3883 } elsif ($verbose == 2) {
3884 $verbose_imgmap = 1;
3885 $verbose_warnings = 1;
3888 } elsif ($verbose == 3) {
3889 $verbose_imgmap = 1;
3890 $verbose_warnings = 1;
3892 $verbose_filter = 1;
3894 } elsif ($verbose == 4) {
3895 $verbose_imgmap = 1;
3896 $verbose_warnings = 1;
3898 $verbose_filter = 1;
3901 } elsif ($verbose == 5) {
3902 $verbose_imgmap = 1;
3903 $verbose_warnings = 1;
3905 $verbose_filter = 1;
3909 } elsif ($verbose == 6) {
3910 $verbose_imgmap = 1;
3911 $verbose_warnings = 1;
3913 $verbose_filter = 1;
3918 } elsif ($verbose >= 7) {
3919 $verbose_imgmap = 1;
3920 $verbose_warnings = 1;
3922 $verbose_filter = 1;
3930 error ("$dict does not exist") unless (-f $dict);
3936 if ($imagemap_base && !($img_width && $img_height)) {
3937 error ("-size WxH is required with -imagemap");
3940 if (defined ($local_dir)) {
3941 $_ = "xscreensaver-getimage-file";
3942 which ($_) || error "$_ not found on \$PATH.";
3948 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3953 x_or_pbm_output ($window_id);