3 # webcollage, Copyright © 1999-2014 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) = ('$Revision: 1.164 $' =~ m/\s(\d[.\d]+)\s/s);
61 my $copyright = "WebCollage $version, Copyright (c) 1999-2014" .
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 21, "flickr_recent", \&pick_from_flickr_recent,
83 16, "flickr_random", \&pick_from_flickr_random,
84 23, "instagram", \&pick_from_instagram,
85 4, "livejournal", \&pick_from_livejournal_images,
87 # No longer exists, as of Apr 2014
88 # 4, "yahoorand", \&pick_from_yahoo_random_link,
90 # Twitter destroyed their whole API in 2013.
91 # 0, "twitpic", \&pick_from_twitpic_images,
92 # 0, "twitter", \&pick_from_twitter_images,
94 # This is a cute way to search for a certain webcams.
95 # Not included in default methods, since these images
96 # aren't terribly interesting by themselves.
97 # See also "SurveillanceSaver".
99 0, "securitycam", \&pick_from_security_camera,
101 # Nonfunctional as of June 2011.
102 # 0, "altavista", \&pick_from_alta_vista_random_link,
104 # In Apr 2002, Google asked me to stop searching them.
105 # I asked them to add a "random link" url. They said
106 # "that would be easy, we'll think about it" and then
107 # never wrote back. Booo Google! Booooo! So, screw
108 # those turkeys, I've turned Google searching back on.
109 # I'm sure they can take it. (Jan 2005.)
111 # Jan 2005: Yahoo fucked up their search form so that
112 # it's no longer possible to do "or" searches on news
113 # images, so we rarely get any hits there any more.
115 # 0, "yahoonews", \&pick_from_yahoo_news_text,
117 # Dec 2004: the ircimages guy's server can't take the
118 # heat, so he started banning the webcollage user agent.
119 # I tried to convince him to add a lighter-weight page to
120 # support webcollage better, but he doesn't care.
122 # 0, "ircimages", \&pick_from_ircimages,
124 # Dec 2002: Alta Vista has a new "random link" URL now.
125 # They added it specifically to better support webcollage!
126 # That was super cool of them. This is how we used to do
129 # 0, "avimages", \&pick_from_alta_vista_images,
130 # 0, "avtext", \&pick_from_alta_vista_text,
132 # This broke in 2004. Eh, Lycos sucks anyway.
134 # 0, "lycos", \&pick_from_lycos_text,
136 # This broke in 2003, I think. I suspect Hotbot is
137 # actually the same search engine data as Lycos.
139 # 0, "hotbot", \&pick_from_hotbot_text,
142 # programs we can use to write to the root window (tried in ascending order.)
144 my @root_displayers = (
145 "xscreensaver-getimage -root -file",
146 "chbg -once -xscreensaver -max_size 100",
147 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
148 " -rfg black -rbg black",
149 "xli -quiet -onroot -center -border black",
150 "xloadimage -quiet -onroot -center -border black",
152 # this lame program wasn't built with vroot.h:
153 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
157 # Some sites need cookies to work properly. These are they.
160 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
161 "web.altavista.com" => "AV_ALL=1",
163 # log in as "cipherpunk"
164 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
165 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
166 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
168 "ircimages.com" => 'disclaimer=1',
172 # If this is set, it's a helper program to use for pasting images together:
173 # this is a lot faster and more efficient than using PPM pipelines, which is
174 # what we do if this program doesn't exist. (We check for "webcollage-helper"
175 # on $PATH at startup, and set this variable appropriately.)
177 my $webcollage_helper = undef;
180 # If we have the webcollage-helper program, then it will paste the images
181 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
186 # Some sites have managed to poison the search engines. These are they.
187 # (We auto-detect sites that have poisoned the search engines via excessive
188 # keywords or dictionary words, but these are ones that slip through
191 # This can contain full host names, or 2 or 3 component domains.
194 "die.net" => 1, # 'l33t h4ck3r d00dz.
195 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
196 "rootsweb.com" => 1, # Cluttering avtext with human names.
197 "akamai.net" => 1, # Lots of sites have their images on Akamai.
198 "akamaitech.net" => 1, # But those are pretty much all banners.
199 # Since Akamai is super-expensive, let's
200 # go out on a limb and assume that all of
201 # their customers are rich-and-boring.
202 "bartleby.com" => 1, # Dictionary, cluttering avtext.
203 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
204 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
205 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
206 # (I don't see how they did it, though!)
207 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
208 "nextag.com" => 1, # Poisoned Alta Vista real good.
209 "ghettodriveby.com" => 1, # Poisoned Google Images.
210 "crosswordsolver.org" => 1, # Poisoned Google Images.
211 "xona.com" => 1, # Poisoned Google Images.
212 "freepatentsonline.com" => 1, # Poisoned Google Images.
213 "herbdatanz.com" => 1, # Poisoned Google Images.
217 # When verbosity is turned on, we warn about sites that we seem to be hitting
218 # a lot: usually this means some new poisoner has made it into the search
219 # engines. But sometimes, the warning is just because that site has a lot
220 # of stuff on it. So these are the sites that are immune to the "frequent
221 # site" diagnostic message.
223 my %warningless_sites = (
224 "home.earthlink.net" => 1,
225 "www.angelfire.com" => 1,
226 "members.aol.com" => 1,
227 "img.photobucket.com" => 1,
228 "pics.livejournal.com" => 1,
231 "staticflickr.com" => 1,
235 "wikimedia.org" => 1,
237 "amazonaws.com" => 1,
239 "photoshelter.com" => 1,
240 "myspacecdn.com" => 1,
241 "feedburner.com" => 1,
248 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
249 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
250 # hits this every time.
252 "images.quizfarm.com" => 1, # damn those LJ quizzes...
253 "images.quizilla.com" => 1,
254 "images.quizdiva.net" => 1,
256 "driftnet" => 1, # builtin...
257 "local-directory" => 1, # builtin...
261 # For decoding HTML-encoded character entities to URLs.
265 "quot" => '"', "amp" => '&', "lt" => '<',
266 "gt" => '>', "nbsp" => ' ', "iexcl" => '',
267 "cent" => "\xA2", "pound" => "\xA3", "curren" => "\xA4",
268 "yen" => "\xA5", "brvbar" => "\xA6", "sect" => "\xA7",
269 "uml" => "\xA8", "copy" => "\xA9", "ordf" => "\xAA",
270 "laquo" => "\xAB", "not" => "\xAC", "shy" => "\xAD",
271 "reg" => "\xAE", "macr" => "\xAF", "deg" => "\xB0",
272 "plusmn" => "\xB1", "sup2" => "\xB2", "sup3" => "\xB3",
273 "acute" => "\xB4", "micro" => "\xB5", "para" => "\xB6",
274 "middot" => "\xB7", "cedil" => "\xB8", "sup1" => "\xB9",
275 "ordm" => "\xBA", "raquo" => "\xBB", "frac14" => "\xBC",
276 "frac12" => "\xBD", "frac34" => "\xBE", "iquest" => "\xBF",
277 "Agrave" => "\xC0", "Aacute" => "\xC1", "Acirc" => "\xC2",
278 "Atilde" => "\xC3", "Auml" => "\xC4", "Aring" => "\xC5",
279 "AElig" => "\xC6", "Ccedil" => "\xC7", "Egrave" => "\xC8",
280 "Eacute" => "\xC9", "Ecirc" => "\xCA", "Euml" => "\xCB",
281 "Igrave" => "\xCC", "Iacute" => "\xCD", "Icirc" => "\xCE",
282 "Iuml" => "\xCF", "ETH" => "\xD0", "Ntilde" => "\xD1",
283 "Ograve" => "\xD2", "Oacute" => "\xD3", "Ocirc" => "\xD4",
284 "Otilde" => "\xD5", "Ouml" => "\xD6", "times" => "\xD7",
285 "Oslash" => "\xD8", "Ugrave" => "\xD9", "Uacute" => "\xDA",
286 "Ucirc" => "\xDB", "Uuml" => "\xDC", "Yacute" => "\xDD",
287 "THORN" => "\xDE", "szlig" => "\xDF", "agrave" => "\xE0",
288 "aacute" => "\xE1", "acirc" => "\xE2", "atilde" => "\xE3",
289 "auml" => "\xE4", "aring" => "\xE5", "aelig" => "\xE6",
290 "ccedil" => "\xE7", "egrave" => "\xE8", "eacute" => "\xE9",
291 "ecirc" => "\xEA", "euml" => "\xEB", "igrave" => "\xEC",
292 "iacute" => "\xED", "icirc" => "\xEE", "iuml" => "\xEF",
293 "eth" => "\xF0", "ntilde" => "\xF1", "ograve" => "\xF2",
294 "oacute" => "\xF3", "ocirc" => "\xF4", "otilde" => "\xF5",
295 "ouml" => "\xF6", "divide" => "\xF7", "oslash" => "\xF8",
296 "ugrave" => "\xF9", "uacute" => "\xFA", "ucirc" => "\xFB",
297 "uuml" => "\xFC", "yacute" => "\xFD", "thorn" => "\xFE",
300 # HTML 4 entities that do not have 1:1 Latin1 mappings.
301 "bull" => "*", "hellip"=> "...", "prime" => "'", "Prime" => "\"",
302 "frasl" => "/", "trade" => "[tm]", "larr" => "<-", "rarr" => "->",
303 "harr" => "<->", "lArr" => "<=", "rArr" => "=>", "hArr" => "<=>",
304 "empty" => "\xD8", "minus" => "-", "lowast"=> "*", "sim" => "~",
305 "cong" => "=~", "asymp" => "~", "ne" => "!=", "equiv" => "==",
306 "le" => "<=", "ge" => ">=", "lang" => "<", "rang" => ">",
307 "loz" => "<>", "OElig" => "OE", "oelig" => "oe", "Yuml" => "Y",
308 "circ" => "^", "tilde" => "~", "ensp" => " ", "emsp" => " ",
309 "thinsp"=> " ", "ndash" => "-", "mdash" => "--", "lsquo" => "`",
310 "rsquo" => "'", "sbquo" => "'", "ldquo" => "\"", "rdquo" => "\"",
311 "bdquo" => "\"", "lsaquo"=> "<", "rsaquo"=> ">",
315 ##############################################################################
317 # Various global flags set by command line parameters, or computed
319 ##############################################################################
322 my $current_state = "???"; # for diagnostics
325 my $image_succeeded = -1;
326 my $suppress_audit = 0;
328 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
329 my $verbose_warnings = 0; # print out warnings when things go wrong
330 my $verbose_load = 0; # diagnostics about loading of URLs
331 my $verbose_filter = 0; # diagnostics about page selection/rejection
332 my $verbose_net = 0; # diagnostics about network I/O
333 my $verbose_pbm = 0; # diagnostics about PBM pipelines
334 my $verbose_http = 0; # diagnostics about all HTTP activity
335 my $verbose_exec = 0; # diagnostics about executing programs
337 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
339 my $http_proxy = undef;
340 my $http_timeout = 20;
341 my $cvt_timeout = 10;
347 my $min_gif_area = (120 * 120);
353 my $imagemap_base = undef;
355 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
357 my $driftnet_magic = 'driftnet';
358 my $driftnet_dir = undef;
359 my $default_driftnet_cmd = "driftnet -a -m 100";
361 my $local_magic = 'local-directory';
362 my $local_dir = undef;
367 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
368 "arrhenius", "arteriole", "blanket", "brainchild",
369 "burdensome", "carnival", "cherub", "chord", "clever",
370 "dedicate", "dilogarithm", "dolan", "dryden",
374 ##############################################################################
378 ##############################################################################
380 # returns three values: the HTTP response line; the document headers;
381 # and the document body.
383 sub get_document_1($$$) {
384 my ($url, $referer, $timeout) = @_;
386 if (!defined($timeout)) { $timeout = $http_timeout; }
387 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
389 my $user_agent = "$progname/$version";
391 if ($url =~ m@^http://www\.altavista\.com/@ ||
392 $url =~ m@^http://random\.yahoo\.com/@ ||
393 $url =~ m@^http://images\.google\.com/@ ||
394 $url =~ m@^http://www\.google\.com/@) {
395 # block this, you turkeys.
396 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)" .
397 " Gecko/20070914 Firefox/2.0.0.7";
399 # 28-Jun-2007: Google Images now emits the entire page in JS if
400 # you claim to be Gecko. They also still block "webcollage".
401 # They serve non-JS for unrecognised agents, so let's try this...
402 $user_agent = "NoJavascriptPlease/1.0"
403 if ($url =~ m@^http://[a-z]+\.google\.com/@);
406 my $ua = LWP::UserAgent->new;
408 $ua->agent ("$progname/$version");
409 $ua->default_header ('Referer' => $referer);
410 $ua->timeout($timeout) if $timeout;
413 LOG (1, " ==> GET $url");
414 LOG (1, " ==> User-Agent: $user_agent");
415 LOG (1, " ==> Referer: $referer") if $referer;
418 my $res = $ua->get ($url);
420 my $http = ($res ? $res->status_line : '') || '';
421 my $head = ($res ? $res->headers()->as_string : '') || '';
422 my $body = ($res && $res->is_success ? $res->decoded_content : '') || '';
424 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
426 $head =~ s/\r\n/\n/gs;
429 foreach (split (/\n/, $head)) {
430 LOG ($verbose_http, " <== $_");
434 my @L = split(/\r\n|\r|\n/, $body);
437 " <== [ body ]: $lines lines, " . length($body) . " bytes");
440 LOG (($verbose_net || $verbose_load), "null response: $url");
444 return ( $http, $head, $body );
448 # returns two values: the document headers; and the document body.
449 # if the given URL did a redirect, returns the redirected-to document.
451 sub get_document($$;$) {
452 my ($url, $referer, $timeout) = @_;
455 if (defined($referer) && $referer eq $driftnet_magic) {
456 return get_driftnet_file ($url);
459 if (defined($referer) && $referer eq $local_magic) {
460 return get_local_file ($url);
465 my $max_loop_count = 4;
468 if (defined($timeout) && $timeout <= 0) {
469 LOG (($verbose_net || $verbose_load), "timed out for $url");
474 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
476 if (defined ($timeout)) {
478 my $elapsed = $now - $start;
479 $timeout -= $elapsed;
483 return () unless $http; # error message already printed
485 $http =~ s/[\r\n]+$//s;
487 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
490 my ( $location ) = m@^location:[ \t]*(.*)$@im;
492 $location =~ s/[\r\n]$//;
494 LOG ($verbose_net, "redirect from $url to $location");
499 $referer =~ m@^(http://[^/]+)@i;
501 } elsif (! ($url =~ m@^[a-z]+:@i)) {
503 s@[^/]+$@@g if m@^http://[^/]+/@i;
504 $_ .= "/" if m@^http://[^/]+$@i;
509 LOG ($verbose_net, "no Location with \"$http\"");
510 return ( $url, $body );
513 if ($loop_count++ > $max_loop_count) {
515 "too many redirects ($max_loop_count) from $orig_url");
520 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
522 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
524 # http errors -- return nothing.
530 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
536 return ( $url, $body );
542 # If we already have a cookie defined for this site, and the site is trying
543 # to overwrite that very same cookie, let it do so. This is because nytimes
544 # expires its cookies - it lets you upgrade to a new cookie without logging
545 # in again, but you have to present the old cookie to get the new cookie.
546 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
549 my ($host, $cookie) = @_;
550 my $oc = $cookies{$host};
553 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
555 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
557 if ($oc_name eq $nc_name &&
558 $oc_value ne $nc_value) {
559 $cookies{$host} = $cookie;
560 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
565 ############################################################################
567 # Extracting image URLs from HTML
569 ############################################################################
571 # given a URL and the body text at that URL, selects and returns a random
572 # image from it. returns () if no suitable images found.
574 sub pick_image_from_body($$) {
575 my ($url, $body) = @_;
580 # if there's at least one slash after the host, take off the last
582 if ( m@^http://[^/]+/@io ) {
583 $base =~ s@[^/]+$@@go;
586 # if there are no slashes after the host at all, put one on the end.
587 if ( m@^http://[^/]+$@io ) {
593 # strip out newlines, compress whitespace
600 # There are certain web sites that list huge numbers of dictionary
601 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
602 # Porn sites tend not to be reputable!)
604 # I do not want webcollage to filter on content: I want it to select
605 # randomly from the set of images on the web. All the logic here for
606 # rejecting some images is really a set of heuristics for rejecting
607 # images that are not really images: for rejecting *text* that is in
608 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
609 # the content of the pictures to be randomly selected from among all
610 # the available content.
612 # So, filtering out "dirty" pictures by looking for "dirty" keywords
613 # would be wrong: dirty pictures exist, like it or not, so webcollage
614 # should be able to select them.
616 # However, picking a random URL is a hard thing to do. The mechanism I'm
617 # using is to search for a selection of random words. This is not
618 # perfect, but works ok most of the time. The way it breaks down is when
619 # some URLs get precedence because their pages list *every word* as
620 # related -- those URLs come up more often than others.
622 # So, after we've retrieved a URL, if it has too many keywords, reject
623 # it. We reject it not on the basis of what those keywords are, but on
624 # the basis that by having so many, the page has gotten an unfair
625 # advantage against our randomizer.
628 foreach my $trip (@tripwire_words) {
629 $trip_count++ if m/$trip/i;
632 if ($trip_count >= $#tripwire_words - 2) {
633 LOG (($verbose_filter || $verbose_load),
634 "there is probably a dictionary in \"$url\": rejecting.");
635 $rejected_urls{$url} = -1;
645 foreach (split(/ *</)) {
646 if ( m/^meta.*["']keywords["']/i ) {
648 # Likewise, reject any web pages that have a KEYWORDS meta tag
653 LOG (($verbose_filter || $verbose_load),
654 "excessive keywords ($L bytes) in $url: rejecting.");
655 $rejected_urls{$url} = $L;
660 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
663 } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
664 m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
665 ["']? (image_src|og:image) ["']? /six) {
667 my $was_inline = (lc($1) eq 'img');
668 my $was_meta = (lc($1) eq 'link' || lc($1) eq 'meta');
671 # For <link rel="image_src" href="...">
672 # and <meta property="og:image" content="...">
675 next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
679 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
680 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
685 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
687 } elsif ( ! m@^[^/:?]+:@ ) {
690 1 while (s@/[^/]+/\.\./@/@g);
694 if ( ! m@^http://@io ) {
699 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
703 # skip really short or really narrow images
704 if ( $width && $width < $min_width) {
705 if (!$height) { $height = "?"; }
706 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
710 if ( $height && $height < $min_height) {
711 if (!$width) { $width = "?"; }
712 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
716 # skip images with ratios that make them look like banners.
717 if ($min_ratio && $width && $height &&
718 ($width * $min_ratio ) > $height) {
719 if (!$height) { $height = "?"; }
720 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
724 # skip GIFs with a small number of pixels -- those usually suck.
725 if ($width && $height &&
727 ($width * $height) < $min_gif_area) {
728 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
732 # skip images with a URL that indicates a Yahoo thumbnail.
733 if (m@\.yimg\.com/.*/t/@) {
734 if (!$width) { $width = "?"; }
735 if (!$height) { $height = "?"; }
736 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
742 if ($unique_urls{$url}) {
743 LOG ($verbose_filter, " skip duplicate image $_");
747 LOG ($verbose_filter,
749 ($width && $height ? " (${width}x${height})" : "") .
750 ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
756 $weight = 20; # meta tag images are far preferable to inline images.
758 if ($url !~ m@[.](gif|png)$@io ) {
759 $weight += 2; # JPEGs are preferable to GIFs and PNGs.
762 $weight += 4; # pointers to images are preferable to inlined images.
766 $unique_urls{$url}++;
767 for (my $i = 0; $i < $weight; $i++) {
768 $urls[++$#urls] = $url;
773 my $fsp = ($body =~ m@<frameset@i);
778 @urls = depoison (@urls);
781 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
785 # pick a random element of the table
786 my $i = int(rand($#urls+1));
789 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
795 # Given a URL and the RSS feed from that URL, pick a random image from
796 # the feed. This is a lot simpler than extracting images out of a page:
797 # we already know we have reasonable images, so we just pick one.
798 # Returns: the real URL of the page (preferably not the RSS version),
801 sub pick_image_from_rss($$) {
802 my ( $url, $body ) = @_;
803 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
805 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
806 $base = $url unless $base;
808 # pick a random element of the table
810 my $i = int(rand(scalar @suitable));
811 my $url = $suitable[$i];
812 LOG ($verbose_load, "picked image " .($i+1) . "/" .
813 ($#suitable+1) . ": $url");
814 return ($base, $url);
820 ############################################################################
822 # Subroutines for getting pages and images out of search engines
824 ############################################################################
827 sub pick_dictionary() {
828 my @dicts = ("/usr/dict/words",
829 "/usr/share/dict/words",
830 "/usr/share/lib/dict/words",
831 "/usr/share/dict/cracklib-small",
832 "/usr/share/dict/cracklib-words"
834 foreach my $f (@dicts) {
840 error ("$dicts[0] does not exist") unless defined($wordlist);
843 # returns a random word from the dictionary
847 return undef unless open (my $in, '<', $wordlist);
849 my $size = (stat($in))[7];
854 error ("looping ($count) while reading $wordlist")
857 my $pos = int (rand ($size));
858 if (seek ($in, $pos, 0)) {
859 $word = <$in>; # toss partial line
860 $word = <$in>; # keep next line
864 next if ($word =~ m/^[-\']/);
868 $word =~ s/^[^a-z]+//s;
869 $word =~ s/[^a-z]+$//s;
875 $word =~ s/ally$/al/s;
876 $word =~ s/izes$/ize/s;
877 $word =~ s/esses$/ess/s;
878 $word =~ s/(.{5})ing$/$1/s;
880 next if (length ($word) > 14);
886 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
887 $word = "\%22$word\%22"; # And put quotes (%22) around it.
894 sub random_words($) {
896 return (random_word() . $sep .
897 random_word() . $sep .
898 random_word() . $sep .
899 random_word() . $sep .
906 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
913 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
922 $s =~ s/\"/"/gi;
926 sub html_unquote($) {
928 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
929 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
934 # Loads the given URL (a search on some search engine) and returns:
935 # - the total number of hits the search engine claimed it had;
936 # - a list of URLs from the page that the search engine returned;
937 # Note that this list contains all kinds of internal search engine
938 # junk URLs too -- caller must prune them.
940 sub pick_from_search_engine($$$) {
941 my ( $timeout, $search_url, $words ) = @_;
946 print STDERR "\n\n" if ($verbose_load);
948 LOG ($verbose_load, "words: $_");
949 LOG ($verbose_load, "URL: $search_url");
951 $last_search = $search_url; # for warnings
954 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
955 if (defined ($timeout)) {
956 $timeout -= (time - $start);
959 LOG (($verbose_net || $verbose_load),
960 "timed out (late) for $search_url");
966 return () if (! $body);
971 if ($body =~ m/^\{\"/s) { # Google AJAX JSON response.
973 my @chunks = split (/"GsearchResultClass"/, $body);
978 my ($img) = m/"unescapedUrl":"(.*?)"/si;
979 my ($url) = m/"originalContextUrl":"(.*?)"/si;
980 next unless ($img && $url);
982 "?imgurl=" . url_quote($img) .
983 "&imgrefurl=" . url_quote($url) .
985 $body2 .= "<A HREF=\"" . html_quote($url) . "\">$n</A>\n";
988 $body = $body2 if $body2;
991 my $search_count = "?";
992 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
994 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
996 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
998 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1000 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1002 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1004 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1006 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1008 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1009 $search_count = $1; # lycos
1010 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1011 $search_count = $1; # hotbot
1012 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1013 $search_count = "0";
1014 } elsif ($body =~ m@found no document matching@i) { # avtext
1015 $search_count = "0";
1017 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1019 # if ($search_count eq "?" || $search_count eq "0") {
1020 # my $file = "/tmp/wc.html";
1021 # open (my $out, '>', $file) || error ("writing $file: $!");
1024 # print STDERR blurb() . "###### wrote $file\n";
1028 my $length = length($body);
1037 foreach (split(/\n/)) {
1039 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1042 if (m/\bm="{(.*?)}"/s) { # Bing info is inside JSON crud
1043 my $json = html_unquote($1);
1044 my ($href) = ($json =~ m/\bsurl:"(.*?)"/s);
1045 my ($img) = ($json =~ m/\bimgurl:"(.*?)"/s);
1046 $u = "$img\t$href" if ($img && $href);
1048 } elsif ($u =~ m/^\"([^\"]*)\"/) { $u = $1 # quoted string
1049 } elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; # or token
1052 if ( $rejected_urls{$u} ) {
1053 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1057 LOG ($verbose_http, " HREF: $u");
1059 $subpages[++$#subpages] = $u;
1062 if ( $#subpages < 0 ) {
1063 LOG ($verbose_filter,
1064 "found nothing on $base ($length bytes, $href_count links).");
1068 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1070 return ($search_count, @subpages);
1078 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1080 next unless defined($h);
1082 if ($poisoners{$h}) {
1083 LOG (($verbose_filter), " rejecting poisoner: $_");
1086 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1088 LOG (($verbose_filter), " rejecting poisoner: $_");
1091 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1093 LOG (($verbose_filter), " rejecting poisoner: $_");
1103 # given a list of URLs, picks one at random; loads it; and returns a
1104 # random image from it.
1105 # returns the url of the page loaded; the url of the image chosen.
1107 sub pick_image_from_pages($$$$@) {
1108 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1110 $total_hit_count = "?" unless defined($total_hit_count);
1112 @pages = depoison (@pages);
1114 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1115 " ($total_hit_count total)");
1117 return () if ($#pages < 0);
1119 my $i = int(rand($#pages+1));
1120 my $page = $pages[$i];
1122 LOG ($verbose_load, "picked page $page");
1124 $suppress_audit = 1;
1126 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1128 if (!$base2 || !$body2) {
1133 my $img = pick_image_from_body ($base2, $body2);
1137 return ($base2, $img);
1144 #############################################################################
1146 ## Pick images from random pages returned by the Yahoo Random Link
1148 #############################################################################
1151 #my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1154 # Picks a random page; picks a random image on that page;
1155 # returns two URLs: the page containing the image, and the image.
1156 # Returns () if nothing found this time.
1158 #sub pick_from_yahoo_random_link($) {
1159 # my ($timeout) = @_;
1161 # print STDERR "\n\n" if ($verbose_load);
1162 # LOG ($verbose_load, "URL: $yahoo_random_link");
1164 # $last_search = $yahoo_random_link; # for warnings
1166 # $suppress_audit = 1;
1168 # my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1169 # if (!$base || !$body) {
1174 # LOG ($verbose_load, "redirected to: $base");
1176 # my $img = pick_image_from_body ($base, $body);
1180 # return ($base, $img);
1187 ############################################################################
1189 # Pick images from random pages returned by the Alta Vista Random Link
1190 # Note: this seems to have gotten a *lot* less random lately (2007).
1192 ############################################################################
1195 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1198 # Picks a random page; picks a random image on that page;
1199 # returns two URLs: the page containing the image, and the image.
1200 # Returns () if nothing found this time.
1202 sub pick_from_alta_vista_random_link($) {
1205 print STDERR "\n\n" if ($verbose_load);
1206 LOG ($verbose_load, "URL: $alta_vista_random_link");
1208 $last_search = $alta_vista_random_link; # for warnings
1210 $suppress_audit = 1;
1212 my ( $base, $body ) = get_document ($alta_vista_random_link,
1214 if (!$base || !$body) {
1219 LOG ($verbose_load, "redirected to: $base");
1221 my $img = pick_image_from_body ($base, $body);
1225 return ($base, $img);
1232 ############################################################################
1234 # Pick images by feeding random words into Alta Vista Image Search
1236 ############################################################################
1239 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1240 "?ipht=1" . # photos
1241 "&igrph=1" . # graphics
1244 "&micat=1" . # no partner sites
1245 "&sc=on" . # "site collapse"
1249 sub pick_from_alta_vista_images($) {
1252 my $words = random_word();
1253 my $page = (int(rand(9)) + 1);
1254 my $search_url = $alta_vista_images_url . $words;
1257 $search_url .= "&pgno=" . $page; # page number
1258 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1261 my ($search_hit_count, @subpages) =
1262 pick_from_search_engine ($timeout, $search_url, $words);
1264 my @candidates = ();
1265 foreach my $u (@subpages) {
1267 # avimages is encoding their URLs now.
1268 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1269 $u = url_unquote($u);
1271 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1272 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1273 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1274 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1275 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1277 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1278 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1280 LOG ($verbose_filter, " candidate: $u");
1281 push @candidates, $u;
1284 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1285 $timeout, @candidates);
1290 ############################################################################
1292 # Pick images from Aptix security cameras
1293 # Cribbed liberally from google image search code.
1294 # By Jason Sullivan <jasonsul@us.ibm.com>
1296 ############################################################################
1298 my $aptix_images_url = ("http://www.google.com/search" .
1299 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1302 sub pick_from_security_camera($) {
1305 my $page = (int(rand(9)) + 1);
1306 my $num = 20; # 20 images per page
1307 my $search_url = $aptix_images_url;
1310 $search_url .= "&start=" . $page*$num; # page number
1311 $search_url .= "&num=" . $num; #images per page
1314 my ($search_hit_count, @subpages) =
1315 pick_from_search_engine ($timeout, $search_url, '');
1317 my @candidates = ();
1319 foreach my $u (@subpages) {
1320 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1321 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1323 LOG ($verbose_filter, " candidate: $u");
1324 push @candidates, $u;
1328 @candidates = depoison (@candidates);
1329 return () if ($#candidates < 0);
1330 my $i = int(rand($#candidates+1));
1331 my $img = $candidates[$i];
1332 my $ref = $referers{$img};
1334 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1335 return ($ref, $img);
1339 ############################################################################
1341 # Pick images by feeding random words into Google Image Search.
1342 # By Charles Gales <gales@us.ibm.com>
1344 ############################################################################
1347 my $google_images_url = "http://ajax.googleapis.com/ajax/services/" .
1354 sub pick_from_google_images($;$$) {
1355 my ($timeout, $words, $max_page) = @_;
1357 if (!defined($words)) {
1358 $words = random_word(); # only one word for Google
1361 my $off = int(rand(40));
1362 my $search_url = $google_images_url . $words . "&start=" . $off;
1364 my ($search_hit_count, @subpages) =
1365 pick_from_search_engine ($timeout, $search_url, $words);
1367 my @candidates = ();
1369 foreach my $u (@subpages) {
1370 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1371 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1373 $u = html_unquote($u);
1374 if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1377 $ref = url_decode($ref);
1378 $img = url_decode($img);
1380 $img = "http://$img" unless ($img =~ m/^https?:/i);
1382 LOG ($verbose_filter, " candidate: $ref");
1383 push @candidates, $img;
1384 $referers{$img} = $ref;
1388 @candidates = depoison (@candidates);
1389 return () if ($#candidates < 0);
1390 my $i = int(rand($#candidates+1));
1391 my $img = $candidates[$i];
1392 my $ref = $referers{$img};
1394 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1395 return ($ref, $img);
1400 ############################################################################
1402 # Pick images by feeding random numbers into Google Image Search.
1403 # By jwz, suggested by Ian O'Donnell.
1405 ############################################################################
1409 sub pick_from_google_image_numbers($) {
1413 my $number = int(rand($max));
1415 $number = sprintf("%04d", $number)
1418 pick_from_google_images ($timeout, "$number");
1423 ############################################################################
1425 # Pick images by feeding random digital camera file names into
1426 # Google Image Search.
1427 # By jwz, inspired by the excellent Random Personal Picture Finder
1428 # at http://www.diddly.com/random/
1430 ############################################################################
1434 # Common digital camera file name formats, as described at
1435 # http://www.diddly.com/random/about.html
1437 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1438 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1439 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1440 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1441 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1442 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1443 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1444 int(rand(0xC)), int(rand(30))+1,
1446 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1447 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1448 sub { my $n = int(rand(9999)); # Canon
1449 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1450 sub { my $n = int(rand(9999)); # Canon
1451 sprintf ("1%02d-%04d_IMG.jpg",
1452 int($n/100), $n); },
1453 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1454 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1455 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1456 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1457 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1458 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1459 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1460 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1461 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1462 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1463 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1464 # int(rand(12))+1, int(rand(31))+1,
1465 # int(rand(999))); },
1466 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1467 # int(rand(6)), # year
1468 # int(rand(12))+1, int(rand(31))+1,
1469 # int(rand(999))); },
1470 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1471 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1472 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1473 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1478 sub pick_from_google_image_photos($) {
1481 my $i = int(rand($#photomakers + 1));
1482 my $fn = $photomakers[$i];
1484 #$file .= "%20filetype:jpg";
1486 pick_from_google_images ($timeout, $file);
1490 ############################################################################
1492 # Pick images by feeding random words into Google Image Search.
1493 # By the way: fuck Microsoft.
1495 ############################################################################
1497 my $bing_images_url = "http://www.bing.com/images/async" .
1504 sub pick_from_bing_images($;$$) {
1505 my ($timeout, $words, $max_page) = @_;
1507 if (!defined($words)) {
1508 $words = random_word(); # only one word for Bing
1511 my $off = int(rand(300));
1512 my $search_url = $bing_images_url . $words . "&first=" . $off;
1514 my ($search_hit_count, @subpages) =
1515 pick_from_search_engine ($timeout, $search_url, $words);
1517 my @candidates = ();
1519 foreach my $u (@subpages) {
1520 my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1522 LOG ($verbose_filter, " candidate: $ref");
1523 push @candidates, $img;
1524 $referers{$img} = $ref;
1527 @candidates = depoison (@candidates);
1528 return () if ($#candidates < 0);
1529 my $i = int(rand($#candidates+1));
1530 my $img = $candidates[$i];
1531 my $ref = $referers{$img};
1533 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1534 return ($ref, $img);
1540 ############################################################################
1542 # Pick images by feeding random numbers into Bing Image Search.
1544 ############################################################################
1547 sub pick_from_bing_image_numbers($) {
1551 my $number = int(rand($max));
1553 $number = sprintf("%04d", $number)
1556 pick_from_bing_images ($timeout, "$number");
1560 ############################################################################
1562 # Pick images by feeding random numbers into Bing Image Search.
1564 ############################################################################
1567 sub pick_from_bing_image_photos($) {
1570 my $i = int(rand($#photomakers + 1));
1571 my $fn = $photomakers[$i];
1574 pick_from_bing_images ($timeout, $file);
1578 ############################################################################
1580 # Pick images by feeding random words into Alta Vista Text Search
1582 ############################################################################
1585 my $alta_vista_url = "http://www.altavista.com/web/results" .
1589 "&sc=on" . # "site collapse"
1594 sub pick_from_alta_vista_text($) {
1597 my $words = random_words('%20');
1598 my $page = (int(rand(9)) + 1);
1599 my $search_url = $alta_vista_url . $words;
1602 $search_url .= "&pgno=" . $page;
1603 $search_url .= "&stq=" . (($page-1) * 10);
1606 my ($search_hit_count, @subpages) =
1607 pick_from_search_engine ($timeout, $search_url, $words);
1609 my @candidates = ();
1610 foreach my $u (@subpages) {
1612 # Those altavista fuckers are playing really nasty redirection games
1613 # these days: the filter your clicks through their site, but use
1614 # onMouseOver to make it look like they're not! Well, it makes it
1615 # easier for us to identify search results...
1617 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1618 $u = url_unquote($u);
1620 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1621 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1622 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1624 LOG ($verbose_filter, " candidate: $u");
1625 push @candidates, $u;
1628 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1629 $timeout, @candidates);
1634 ############################################################################
1636 # Pick images by feeding random words into Hotbot
1638 ############################################################################
1640 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1642 "&descriptiontype=0" .
1649 "&cobrand=undefined" .
1652 sub pick_from_hotbot_text($) {
1655 $last_search = $hotbot_search_url; # for warnings
1657 # lycos seems to always give us back dictionaries and word lists if
1658 # we search for more than one word...
1660 my $words = random_word();
1662 my $start = int(rand(8)) * 10 + 1;
1663 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1665 my ($search_hit_count, @subpages) =
1666 pick_from_search_engine ($timeout, $search_url, $words);
1668 my @candidates = ();
1669 foreach my $u (@subpages) {
1671 # Hotbot plays redirection games too
1673 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1674 # $u = url_decode($1);
1676 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1677 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1678 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1679 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1681 LOG ($verbose_filter, " candidate: $u");
1682 push @candidates, $u;
1685 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1686 $timeout, @candidates);
1691 ############################################################################
1693 # Pick images by feeding random words into Lycos
1695 ############################################################################
1697 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1703 sub pick_from_lycos_text($) {
1706 $last_search = $lycos_search_url; # for warnings
1708 # lycos seems to always give us back dictionaries and word lists if
1709 # we search for more than one word...
1711 my $words = random_word();
1713 my $start = int(rand(8)) * 10 + 1;
1714 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1716 my ($search_hit_count, @subpages) =
1717 pick_from_search_engine ($timeout, $search_url, $words);
1719 my @candidates = ();
1720 foreach my $u (@subpages) {
1722 # Lycos plays redirection games.
1724 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1729 # $u = url_decode($1);
1731 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1732 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1733 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1734 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1735 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1738 LOG ($verbose_filter, " candidate: $u");
1739 push @candidates, $u;
1742 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1743 $timeout, @candidates);
1748 ############################################################################
1750 # Pick images by feeding random words into news.yahoo.com
1752 ############################################################################
1754 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1759 sub pick_from_yahoo_news_text($) {
1762 $last_search = $yahoo_news_url; # for warnings
1764 my $words = random_word();
1765 my $search_url = $yahoo_news_url . $words;
1767 my ($search_hit_count, @subpages) =
1768 pick_from_search_engine ($timeout, $search_url, $words);
1770 my @candidates = ();
1771 foreach my $u (@subpages) {
1773 # de-redirectize the URLs
1774 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1776 # only accept URLs on Yahoo's news site
1777 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1778 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1779 next unless ($u =~ m@&u=/@);
1781 LOG ($verbose_filter, " candidate: $u");
1782 push @candidates, $u;
1785 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1786 $timeout, @candidates);
1791 ############################################################################
1793 # Pick images from LiveJournal's list of recently-posted images.
1795 ############################################################################
1797 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1799 # With most of our image sources, we get a random page and then select
1800 # from the images on it. However, in the case of LiveJournal, the page
1801 # of images tends to update slowly; so we'll remember the last N entries
1802 # on it and randomly select from those, to get a wider variety each time.
1804 my $lj_cache_size = 1000;
1805 my @lj_cache = (); # fifo, for ordering by age
1806 my %lj_cache = (); # hash, for detecting dups
1809 sub pick_from_livejournal_images($) {
1812 $last_search = $livejournal_img_url; # for warnings
1814 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1815 return () unless $body;
1818 $body =~ s/(<recent-image)\b/\n$1/gsi;
1820 foreach (split (/\n/, $body)) {
1821 next unless (m/^<recent-image\b/);
1822 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1823 my $img = html_unquote ($1);
1825 next if ($lj_cache{$img}); # already have it
1827 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1828 my $page = html_unquote ($1);
1829 my @pair = ($img, $page);
1830 LOG ($verbose_filter, " candidate: $img");
1831 push @lj_cache, \@pair;
1832 $lj_cache{$img} = \@pair;
1835 return () if ($#lj_cache == -1);
1837 my $n = $#lj_cache+1;
1838 my $i = int(rand($n));
1839 my ($img, $page) = @{$lj_cache[$i]};
1841 # delete this one from @lj_cache and from %lj_cache.
1843 @lj_cache = ( @lj_cache[0 .. $i-1],
1844 @lj_cache[$i+1 .. $#lj_cache] );
1845 delete $lj_cache{$img};
1847 # Keep the size of the cache under the limit by nuking older entries
1849 while ($#lj_cache >= $lj_cache_size) {
1850 my $pairP = shift @lj_cache;
1851 my $img = $pairP->[0];
1852 delete $lj_cache{$img};
1855 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1857 return ($page, $img);
1861 ############################################################################
1863 # Pick images from ircimages.com (images that have been in the /topic of
1864 # various IRC channels.)
1866 ############################################################################
1868 my $ircimages_url = "http://ircimages.com/";
1871 sub pick_from_ircimages($) {
1874 $last_search = $ircimages_url; # for warnings
1876 my $n = int(rand(2900));
1877 my $search_url = $ircimages_url . "page-$n";
1879 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1880 return () unless $body;
1882 my @candidates = ();
1885 $body =~ s/(<A)\b/\n$1/gsi;
1887 foreach (split (/\n/, $body)) {
1889 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1892 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1893 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1895 next unless ($u =~ m/^http:/i);
1896 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1897 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1899 LOG ($verbose_http, " HREF: $u");
1900 push @candidates, $u;
1903 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1905 return () if ($#candidates == -1);
1907 my $i = int(rand($#candidates+1));
1908 my $img = $candidates[$i];
1910 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1913 $search_url = $img; # hmm...
1914 return ($search_url, $img);
1918 ############################################################################
1920 # Pick images from Twitpic's list of recently-posted images.
1922 ############################################################################
1924 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1926 # With most of our image sources, we get a random page and then select
1927 # from the images on it. However, in the case of Twitpic, the page
1928 # of images tends to update slowly; so we'll remember the last N entries
1929 # on it and randomly select from those, to get a wider variety each time.
1931 my $twitpic_cache_size = 1000;
1932 my @twitpic_cache = (); # fifo, for ordering by age
1933 my %twitpic_cache = (); # hash, for detecting dups
1936 sub pick_from_twitpic_images($) {
1939 $last_search = $twitpic_img_url; # for warnings
1941 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1947 $body =~ s/(<item)\b/\n$1/gsi;
1949 my @items = split (/\n/, $body);
1952 next unless (m@<link>([^<>]*)</link>@si);
1953 my $page = html_unquote ($1);
1958 next if ($twitpic_cache{$page}); # already have it
1960 LOG ($verbose_filter, " candidate: $page");
1961 push @twitpic_cache, $page;
1962 $twitpic_cache{$page} = $page;
1966 # Pull from the cache.
1968 return () if ($#twitpic_cache == -1);
1970 my $n = $#twitpic_cache+1;
1971 my $i = int(rand($n));
1972 my $page = $twitpic_cache[$i];
1974 # delete this one from @twitpic_cache and from %twitpic_cache.
1976 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1977 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1978 delete $twitpic_cache{$page};
1980 # Keep the size of the cache under the limit by nuking older entries
1982 while ($#twitpic_cache >= $twitpic_cache_size) {
1983 my $page = shift @twitpic_cache;
1984 delete $twitpic_cache{$page};
1987 ( $base, $body ) = get_document ($page, undef, $timeout);
1989 $body = '' unless defined($body);
1991 foreach (split (/<img\s+/, $body)) {
1992 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1995 next if m@/images/@s;
1999 $img = "http:$img" if ($img =~ m@^//@s); # Oh come on
2001 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
2002 if ($img =~ m@^/@) {
2003 $base =~ s@^(https?://[^/]+)/.*@$1@s;
2004 $img = $base . $img;
2010 LOG ($verbose_load, "no matching images on $page\n");
2014 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2016 return ($page, $img);
2020 ############################################################################
2022 # Pick images from Twitter's list of recently-posted updates.
2024 ############################################################################
2026 # With most of our image sources, we get a random page and then select
2027 # from the images on it. However, in the case of Twitter, the page
2028 # of images only updates once a minute; so we'll remember the last N entries
2029 # on it and randomly select from those, to get a wider variety each time.
2031 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2032 "public_timeline.json" .
2033 "?include_entities=true" .
2034 "&include_rts=true" .
2037 my $twitter_cache_size = 1000;
2039 my @twitter_cache = (); # fifo, for ordering by age
2040 my %twitter_cache = (); # hash, for detecting dups
2044 sub pick_from_twitter_images($) {
2047 $last_search = $twitter_img_url; # for warnings
2049 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2053 $body =~ s/[\r\n]+/ /gs;
2055 # Parsing JSON is a pain in the ass. So we halfass it as usual.
2056 $body =~ s/^\[|\]$//s;
2057 $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2058 my @items = split (/},{/, $body);
2060 my ($name) = m@"screen_name":"([^\"]+)"@si;
2061 my ($img) = m@"media_url":"([^\"]+)"@si;
2062 my ($page) = m@"display_url":"([^\"]+)"@si;
2063 next unless ($name && $img && $page);
2064 foreach ($img, $page) {
2066 $_ = "http://$_" unless (m/^http/si);
2069 next if ($twitter_cache{$page}); # already have it
2071 LOG ($verbose_filter, " candidate: $page - $img");
2072 push @twitter_cache, $page;
2073 $twitter_cache{$page} = $img;
2077 # Pull from the cache.
2079 return () if ($#twitter_cache == -1);
2081 my $n = $#twitter_cache+1;
2082 my $i = int(rand($n));
2083 my $page = $twitter_cache[$i];
2084 my $url = $twitter_cache{$page};
2086 # delete this one from @twitter_cache and from %twitter_cache.
2088 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2089 @twitter_cache[$i+1 .. $#twitter_cache] );
2090 delete $twitter_cache{$page};
2092 # Keep the size of the cache under the limit by nuking older entries
2094 while ($#twitter_cache >= $twitter_cache_size) {
2095 my $page = shift @twitter_cache;
2096 delete $twitter_cache{$page};
2099 LOG ($verbose_load, "picked page $url");
2101 $suppress_audit = 1;
2103 return ($page, $url);
2107 ############################################################################
2109 # Pick images from Flickr's page of recently-posted photos.
2111 ############################################################################
2113 my $flickr_img_url = "http://www.flickr.com/explore/";
2115 # Like LiveJournal, the Flickr page of images tends to update slowly,
2116 # so remember the last N entries on it and randomly select from those.
2118 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2119 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2121 my $flickr_cache_size = 1000;
2122 my @flickr_cache = (); # fifo, for ordering by age
2123 my %flickr_cache = (); # hash, for detecting dups
2127 sub pick_from_flickr_recent($) {
2130 my $start = 16 * int(rand(100));
2132 $last_search = $flickr_img_url; # for warnings
2133 $last_search .= "?start=$start" if ($start > 0);
2135 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2136 return () unless $body;
2138 $body =~ s/[\r\n]/ /gs;
2139 $body =~ s/(<a)\b/\n$1/gsi;
2143 foreach (split (/\n/, $body)) {
2145 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2147 data-defer-src = \"([^<>\"]+)\" @xsi;
2148 next unless defined ($thumb);
2149 $page = html_unquote ($page);
2150 $thumb = html_unquote ($thumb);
2152 next unless ($thumb =~ m@^https?://[^/.]+\d*\.static\.?flickr\.com/@);
2154 my $base = "http://www.flickr.com/";
2155 $page =~ s@^/@$base@;
2156 $thumb =~ s@^/@$base@;
2159 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2162 next if ($flickr_cache{$img}); # already have it
2164 my @pair = ($img, $page, $start);
2165 LOG ($verbose_filter, " candidate: $img");
2166 push @flickr_cache, \@pair;
2167 $flickr_cache{$img} = \@pair;
2171 return () if ($#flickr_cache == -1);
2173 my $n = $#flickr_cache+1;
2174 my $i = int(rand($n));
2175 my ($img, $page) = @{$flickr_cache[$i]};
2177 # delete this one from @flickr_cache and from %flickr_cache.
2179 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2180 @flickr_cache[$i+1 .. $#flickr_cache] );
2181 delete $flickr_cache{$img};
2183 # Keep the size of the cache under the limit by nuking older entries
2185 while ($#flickr_cache >= $flickr_cache_size) {
2186 my $pairP = shift @flickr_cache;
2187 my $img = $pairP->[0];
2188 delete $flickr_cache{$img};
2191 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2193 return ($page, $img);
2197 ############################################################################
2199 # Pick images from a random RSS feed on Flickr.
2201 ############################################################################
2203 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2204 "?format=rss_200_enc&tagmode=any&tags=");
2206 # Picks a random RSS feed; picks a random image from that feed;
2207 # returns 2 URLs: the page containing the image, and the image.
2208 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2211 sub pick_from_flickr_random($) {
2212 my $timeout = shift;
2214 my $words = random_words(',');
2215 my $rss = $flickr_rss_base . $words;
2216 $last_search = $rss;
2221 print STDERR "\n\n" if ($verbose_load);
2222 LOG ($verbose_load, "words: $_");
2223 LOG ($verbose_load, "URL: $last_search");
2225 $suppress_audit = 1;
2227 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2228 if (!$base || !$body) {
2234 ($base, $img) = pick_image_from_rss ($base, $body);
2236 return () unless defined ($img);
2238 LOG ($verbose_load, "redirected to: $base");
2239 return ($base, $img);
2243 ############################################################################
2245 # Pick random images from Instagram, via gramfeed.com's key.
2247 ############################################################################
2249 my $instagram_url_base = "https://api.instagram.com/v1/media/popular" .
2250 "?client_id=b59fbe4563944b6c88cced13495c0f49";
2253 sub pick_from_instagram($) {
2254 my $timeout = shift;
2256 $last_search = $instagram_url_base;
2258 print STDERR "\n\n" if ($verbose_load);
2259 LOG ($verbose_load, "URL: $last_search");
2261 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2262 if (!$base || !$body) {
2267 $body =~ s/("link")/\001$1/gs;
2268 my @chunks = split(/\001/, $body);
2273 my ($url) = m/"link":\s*"(.*?)"/s;
2274 my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2275 ($img) = m/"url":\s*"(.*?)"/s unless $url;
2276 next unless ($url && $img);
2277 push @urls, [ $url, $img ];
2281 LOG ($verbose_load, "no images on $last_search");
2285 my $i = int(rand($#urls+1));
2286 my ($url, $img) = @{$urls[$i]};
2288 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2289 return ($url, $img);
2293 ############################################################################
2295 # Pick images by waiting for driftnet to populate a temp dir with files.
2296 # Requires driftnet version 0.1.5 or later.
2297 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2298 # for images being downloaded by others.)
2299 # Driftnet/webcollage integration by jwz.
2301 ############################################################################
2304 sub pick_from_driftnet($) {
2307 my $id = $driftnet_magic;
2308 my $dir = $driftnet_dir;
2312 error ("\$driftnet_dir unset?") unless ($dir);
2315 error ("$dir unreadable") unless (-d "$dir/.");
2317 $timeout = $http_timeout unless ($timeout);
2320 while ($now = time, $now < $start + $timeout) {
2321 opendir (my $dir, $dir) || error ("$dir: $!");
2322 while (my $file = readdir($dir)) {
2323 next if ($file =~ m/^\./);
2324 $file = "$dir/$file";
2326 LOG ($verbose_load, "picked file $file ($id)");
2327 return ($id, $file);
2331 LOG (($verbose_net || $verbose_load), "timed out for $id");
2336 sub get_driftnet_file($) {
2339 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2341 my $id = $driftnet_magic;
2342 error ("$id: $file not in $driftnet_dir?")
2343 unless ($file =~ m@^\Q$driftnet_dir@o);
2345 open (my $in, '<', $file) || error ("$id: $file: $!");
2347 local $/ = undef; # read entire file
2349 close ($in) || error ("$id: $file: $!");
2350 unlink ($file) || error ("$id: $file: rm: $!");
2351 return ($id, $body);
2355 sub spawn_driftnet($) {
2358 # make a directory to use.
2360 my $tmp = $ENV{TEMPDIR} || "/tmp";
2361 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2362 LOG ($verbose_exec, "mkdir $driftnet_dir");
2363 last if mkdir ($driftnet_dir, 0700);
2366 if (! ($cmd =~ m/\s/)) {
2367 # if the command didn't have any arguments in it, then it must be just
2368 # a pointer to the executable. Append the default args to it.
2369 my $dargs = $default_driftnet_cmd;
2370 $dargs =~ s/^[^\s]+//;
2374 # point the driftnet command at our newly-minted private directory.
2376 $cmd .= " -d $driftnet_dir";
2377 $cmd .= ">/dev/null" unless ($verbose_exec);
2380 if ($pid < 0) { error ("fork: $!\n"); }
2383 push @pids_to_kill, $pid;
2384 LOG ($verbose_exec, "forked for \"$cmd\"");
2387 nontrapping_system ($cmd) || error ("exec: $!");
2390 # wait a bit, then make sure the process actually started up.
2393 error ("pid $pid failed to start \"$cmd\"")
2394 unless (1 == kill (0, $pid));
2398 sub pick_from_local_dir($) {
2401 my $id = $local_magic;
2404 my $dir = $local_dir;
2405 error ("\$local_dir unset?") unless ($dir);
2408 error ("$dir unreadable") unless (-d "$dir/.");
2410 my $v = ($verbose_exec ? "-v" : "");
2411 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2413 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2415 LOG ($verbose_load, "picked file $pick ($id)");
2416 return ($id, $pick);
2420 sub get_local_file($) {
2423 error ("\$local_dir unset?") unless ($local_dir);
2425 my $id = $local_magic;
2426 error ("$id: $file not in $local_dir?")
2427 unless ($file =~ m@^\Q$local_dir@o);
2429 open (my $in, '<', $file) || error ("$id: $file: $!");
2430 local $/ = undef; # read entire file
2432 close ($in) || error ("$id: $file: $!");
2433 return ($id, $body);
2438 ############################################################################
2440 # Pick a random image in a random way
2442 ############################################################################
2445 # Picks a random image on a random page, and returns two URLs:
2446 # the page containing the image, and the image.
2447 # Returns () if nothing found this time.
2450 sub pick_image(;$) {
2453 $current_state = "select";
2454 $load_method = "none";
2456 my $n = int(rand(100));
2459 my @rest = @search_methods;
2462 my $pct = shift @rest;
2463 my $name = shift @rest;
2464 my $tfn = shift @rest;
2466 if ($total > $n && !defined($fn)) {
2468 $current_state = $name;
2469 $load_method = $current_state;
2473 if ($total != 100) {
2474 error ("internal error: \@search_methods totals to $total%!");
2477 record_attempt ($current_state);
2478 return $fn->($timeout);
2483 ############################################################################
2485 # Statistics and logging
2487 ############################################################################
2490 return strftime ("%H:%M:%S: ", localtime);
2494 return "$progname: " . timestr() . "$current_state: ";
2499 print STDERR blurb() . "$err\n";
2505 print STDERR "$progname: stack trace:\n";
2507 my ($package, $filename, $line, $subroutine) = caller($i++);
2508 last unless defined($package);
2509 $filename =~ s@^.*/@@;
2510 print STDERR " $filename#$line, $subroutine\n";
2522 my $head = "$progname: DEBUG: ";
2523 foreach (split (/\n/, $lastlog)) {
2524 print STDERR "$head$_\n";
2530 my ($print, $msg) = @_;
2531 my $blurb = timestr() . "$current_state: ";
2532 $lastlog .= "$blurb$msg\n";
2533 print STDERR "$progname: $blurb$msg\n" if $print;
2538 my %stats_successes;
2541 my $last_state = undef;
2542 sub record_attempt($) {
2546 record_failure($last_state) unless ($image_succeeded > 0);
2548 $last_state = $name;
2551 report_performance();
2554 $image_succeeded = 0;
2555 $suppress_audit = 0;
2558 sub record_success($$$) {
2559 my ($name, $url, $base) = @_;
2560 if (defined($stats_successes{$name})) {
2561 $stats_successes{$name}++;
2563 $stats_successes{$name} = 1;
2566 stop_timer ($name, 1);
2567 my $o = $current_state;
2568 $current_state = $name;
2569 save_recent_url ($url, $base);
2570 $current_state = $o;
2571 $image_succeeded = 1;
2576 sub record_failure($) {
2579 return if $image_succeeded;
2581 stop_timer ($name, 0);
2582 if ($verbose_load && !$verbose_exec) {
2584 if ($suppress_audit) {
2585 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2589 my $o = $current_state;
2590 $current_state = "DEBUG";
2592 my $line = "#" x 78;
2593 print STDERR "\n\n\n";
2594 print STDERR ("#" x 78) . "\n";
2595 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2598 print STDERR ("-" x 78) . "\n";
2599 print STDERR "\n\n";
2601 $current_state = $o;
2603 $image_succeeded = 0;
2610 my $i = $stats_successes{$name};
2611 my $j = $stats_attempts{$name};
2614 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2618 my $current_start_time = 0;
2620 sub start_timer($) {
2622 $current_start_time = time;
2624 if (defined($stats_attempts{$name})) {
2625 $stats_attempts{$name}++;
2627 $stats_attempts{$name} = 1;
2629 if (!defined($stats_elapsed{$name})) {
2630 $stats_elapsed{$name} = 0;
2634 sub stop_timer($$) {
2635 my ($name, $success) = @_;
2636 $stats_elapsed{$name} += time - $current_start_time;
2640 my $last_report_time = 0;
2641 sub report_performance() {
2643 return unless $verbose_warnings;
2646 return unless ($now >= $last_report_time + $report_performance_interval);
2647 my $ot = $last_report_time;
2648 $last_report_time = $now;
2650 return if ($ot == 0);
2652 my $blurb = "$progname: " . timestr();
2655 print STDERR "${blurb}Current standings:\n";
2657 foreach my $name (sort keys (%stats_attempts)) {
2658 my $try = $stats_attempts{$name};
2659 my $suc = $stats_successes{$name} || 0;
2660 my $pct = int($suc * 100 / $try);
2661 my $secs = $stats_elapsed{$name};
2662 my $secs_link = $secs / $try;
2663 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2664 " \t %.1f secs/link\n",
2665 "$name:", "$pct%", $suc, $try, $secs_link);
2671 my $max_recent_images = 400;
2672 my $max_recent_sites = 20;
2673 my @recent_images = ();
2674 my @recent_sites = ();
2676 sub save_recent_url($$) {
2677 my ($url, $base) = @_;
2679 return unless ($verbose_warnings);
2682 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2683 return unless defined ($site);
2685 if ($base eq $driftnet_magic || $base eq $local_magic) {
2687 @recent_images = ();
2691 foreach (@recent_images) {
2693 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2694 " (on $base via $last_search)\n";
2700 # suppress "duplicate site" warning via %warningless_sites.
2702 if ($warningless_sites{$site}) {
2704 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2705 $warningless_sites{$1}) {
2707 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2708 $warningless_sites{$1}) {
2713 foreach (@recent_sites) {
2715 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2716 " ($url on $base via $last_search)\n";
2722 push @recent_images, $url;
2723 push @recent_sites, $site;
2724 shift @recent_images if ($#recent_images >= $max_recent_images);
2725 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2730 ##############################################################################
2734 ##############################################################################
2741 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2746 # Given the raw body of a GIF document, returns the dimensions of the image.
2750 my $type = substr($body, 0, 6);
2752 return () unless ($type =~ /GIF8[7,9]a/);
2753 $s = substr ($body, 6, 10);
2754 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2755 return () unless defined ($d);
2756 return (($b<<8|$a), ($d<<8|$c));
2759 # Given the raw body of a JPEG document, returns the dimensions of the image.
2764 my $L = length($body);
2766 my $c1 = substr($body, $i, 1); $i++;
2767 my $c2 = substr($body, $i, 1); $i++;
2768 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2771 while (ord($ch) != 0xDA && $i < $L) {
2772 # Find next marker, beginning with 0xFF.
2773 while (ord($ch) != 0xFF) {
2774 return () if (length($body) <= $i);
2775 $ch = substr($body, $i, 1); $i++;
2777 # markers can be padded with any number of 0xFF.
2778 while (ord($ch) == 0xFF) {
2779 return () if (length($body) <= $i);
2780 $ch = substr($body, $i, 1); $i++;
2783 # $ch contains the value of the marker.
2784 my $marker = ord($ch);
2786 if (($marker >= 0xC0) &&
2787 ($marker <= 0xCF) &&
2788 ($marker != 0xC4) &&
2789 ($marker != 0xCC)) { # it's a SOFn marker
2791 return () if (length($body) <= $i);
2792 my $s = substr($body, $i, 4); $i += 4;
2793 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2794 return (($c<<8|$d), ($a<<8|$b));
2797 # We must skip variables, since FFs in variable names aren't
2798 # valid JPEG markers.
2799 return () if (length($body) <= $i);
2800 my $s = substr($body, $i, 2); $i += 2;
2801 my ($c1, $c2) = unpack ("C"x2, $s);
2802 my $length = ($c1 << 8) | $c2;
2803 return () if ($length < 2);
2810 # Given the raw body of a PNG document, returns the dimensions of the image.
2814 return () unless ($body =~ m/^\211PNG\r/);
2815 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2816 return () unless defined ($bits);
2817 return () unless ($bits =~ /^IHDR/);
2818 my ($ign, $w, $h) = unpack("a4N2", $bits);
2823 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2828 my ($w, $h) = gif_size ($body);
2829 if ($w && $h) { return ($w, $h); }
2830 ($w, $h) = jpeg_size ($body);
2831 if ($w && $h) { return ($w, $h); }
2832 return png_size ($body);
2836 # returns the full path of the named program, or undef.
2840 foreach (split (/:/, $ENV{PATH})) {
2841 if (-x "$_/$prog") {
2849 # Like rand(), but chooses numbers with a bell curve distribution.
2852 $_ = 1.0 unless defined($_);
2854 return (rand($_) + rand($_) + rand($_));
2858 sub exit_cleanup() {
2860 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2861 if (@pids_to_kill) {
2862 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2863 kill ('TERM', @pids_to_kill);
2867 sub signal_cleanup($) {
2869 print STDERR blurb() . (defined($sig)
2870 ? "caught signal $sig."
2873 if ($verbose_exec || $verbose_warnings);
2879 ##############################################################################
2881 # Generating a list of urls only
2883 ##############################################################################
2885 sub url_only_output() {
2887 my ($base, $img) = pick_image;
2891 print "$img $base\n";
2896 ##############################################################################
2898 # Running as an xscreensaver module, or as a web page imagemap
2900 ##############################################################################
2902 my $image_ppm = sprintf ("%s/webcollage-%08x.ppm",
2903 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2905 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x.ppm",
2906 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2908 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x.ppm",
2909 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2912 my $filter_cmd = undef;
2913 my $post_filter_cmd = undef;
2914 my $background = undef;
2916 my @imagemap_areas = ();
2917 my $imagemap_html_tmp = undef;
2918 my $imagemap_jpg_tmp = undef;
2921 my $img_width; # size of the image being generated.
2927 unlink $image_ppm, $image_tmp1, $image_tmp2;
2928 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2929 if (defined ($imagemap_html_tmp));
2933 # Like system, but prints status about exit codes, and kills this process
2934 # with whatever signal killed the sub-process, if any.
2936 sub nontrapping_system(@) {
2940 s/\"[^\"]+\"/\"...\"/g;
2942 LOG ($verbose_exec, "executing \"$_\"");
2947 LOG ($verbose_exec, "subproc exited normally.");
2948 } elsif (($rc & 0xff) == 0) {
2950 LOG ($verbose_exec, "subproc exited with status $rc.");
2953 LOG ($verbose_exec, "subproc dumped core.");
2956 LOG ($verbose_exec, "subproc died with signal $rc.");
2957 # die that way ourselves.
2965 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2966 # writes a PPM to the given output file. Returns the width/height of the
2967 # image if successful.
2969 sub image_to_pnm($$$) {
2970 my ($url, $body, $output) = @_;
2971 my ($cmd, $cmd2, $w, $h);
2973 if ((@_ = gif_size ($body))) {
2976 } elsif ((@_ = jpeg_size ($body))) {
2979 } elsif ((@_ = png_size ($body))) {
2983 LOG (($verbose_pbm || $verbose_load),
2984 "not a GIF, JPG, or PNG" .
2985 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2986 ? " (looks like HTML)" : "") .
2988 $suppress_audit = 1;
2992 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2993 # do this, the process doesn't die properly.
2994 if (!$verbose_pbm) {
2996 # We get a "giftopnm: got a 'Application Extension' extension"
2997 # warning any time it's an animgif.
2999 # Note that "giftopnm: EOF / read error on image data" is not
3000 # always a fatal error -- sometimes the image looks fine anyway.
3002 $cmd2 .= " 2>/dev/null";
3005 # There exist corrupted GIF and JPEG files that can make giftopnm and
3006 # djpeg lose their minds and go into a loop. So this gives those programs
3007 # a small timeout -- if they don't complete in time, kill them.
3013 local $SIG{ALRM} = sub {
3015 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3016 kill ('TERM', $pid) if ($pid);
3021 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3028 LOG ($verbose_exec, "awaiting $pid");
3030 LOG ($verbose_exec, "$pid completed");
3032 my $size = (stat($output))[7];
3033 $size = -1 unless defined($size);
3035 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3039 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3042 print STDERR blurb() . "$cmd failed: $!\n";
3046 die if ($@ && $@ ne "alarm\n"); # propagate errors
3060 # Same as the "ppmmake" command: creates a solid-colored PPM.
3061 # Does not understand the rgb.txt color names except "black" and "white".
3064 my ($outfile, $bgcolor, $w, $h) = @_;
3067 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3068 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3069 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3070 } elsif ($bgcolor =~ m/^black$/i) {
3071 ($r, $g, $b) = (0, 0, 0);
3072 } elsif ($bgcolor =~ m/^white$/i) {
3073 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3075 error ("unparsable color name: $bgcolor");
3078 my $pixel = pack('CCC', $r, $g, $b);
3079 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3081 open (my $out, '>', $outfile) || error ("$outfile: $!");
3087 sub pick_root_displayer() {
3091 # see "xscreensaver/hacks/webcollage-cocoa.m"
3092 return "echo COCOA LOAD ";
3095 foreach my $cmd (@root_displayers) {
3097 my ($name) = m/^([^ ]+)/;
3098 push @names, "\"$name\"";
3099 LOG ($verbose_exec, "looking for $name...");
3100 foreach my $dir (split (/:/, $ENV{PATH})) {
3101 LOG ($verbose_exec, " checking $dir/$name");
3102 return $cmd if (-x "$dir/$name");
3106 $names[$#names] = "or " . $names[$#names];
3107 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3111 my $ppm_to_root_window_cmd = undef;
3114 sub x_or_pbm_output($) {
3115 my ($window_id) = @_;
3117 # Check for our helper program, to see whether we need to use PPM pipelines.
3119 $_ = "webcollage-helper";
3120 if (defined ($webcollage_helper) || which ($_)) {
3121 $webcollage_helper = $_ unless (defined($webcollage_helper));
3122 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3123 $webcollage_helper .= " -v";
3125 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3128 if ($cocoa_p && !defined ($webcollage_helper)) {
3129 error ("webcollage-helper not found in Cocoa-mode!");
3133 # make sure the various programs we execute exist, right up front.
3137 if (!defined($webcollage_helper)) {
3138 # Only need these others if we don't have the helper.
3140 "giftopnm", "pngtopnm", "djpeg",
3141 "pnmpaste", "pnmscale", "pnmcut");
3145 which ($_) || error "$_ not found on \$PATH.";
3148 # find a root-window displayer program.
3150 if (!$no_output_p) {
3151 $ppm_to_root_window_cmd = pick_root_displayer();
3154 if (defined ($window_id)) {
3155 error ("-window-id only works if xscreensaver-getimage is installed")
3156 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3158 error ("unparsable window id: $window_id")
3159 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3160 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3161 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3164 if (!$img_width || !$img_height) {
3166 if (!defined ($window_id) &&
3167 defined ($ENV{XSCREENSAVER_WINDOW})) {
3168 $window_id = $ENV{XSCREENSAVER_WINDOW};
3171 if (!defined ($window_id)) {
3173 which ($_) || error "$_ not found on \$PATH.";
3175 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3176 if (!defined($img_height)) {
3177 error "xdpyinfo failed.";
3179 } else { # we have a window id
3181 which ($_) || error "$_ not found on \$PATH.";
3182 $_ .= " -id $window_id";
3184 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3186 if (!defined($img_height)) {
3187 error "xwininfo failed.";
3192 my $bgcolor = "#000000";
3193 my $bgimage = undef;
3196 if ($background =~ m/^\#[0-9a-f]+$/i) {
3197 $bgcolor = $background;
3199 } elsif (-r $background) {
3200 $bgimage = $background;
3202 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3203 error "not a color or readable file: $background";
3206 # default to assuming it's a color
3207 $bgcolor = $background;
3211 # Create the sold-colored base image.
3213 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3214 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3216 # Paste the default background image in the middle of it.
3222 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3223 local $/ = undef; # read entire file
3228 if ((@_ = gif_size ($body))) {
3230 $cmd = "giftopnm |";
3232 } elsif ((@_ = jpeg_size ($body))) {
3236 } elsif ((@_ = png_size ($body))) {
3238 $cmd = "pngtopnm |";
3240 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3246 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3249 my $x = int (($img_width - $iw) / 2);
3250 my $y = int (($img_height - $ih) / 2);
3252 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3254 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3255 open ($imgf, "| $cmd") || error "running $cmd: $!";
3259 LOG ($verbose_exec, "subproc exited normally.");
3260 rename ($image_tmp1, $image_ppm) ||
3261 error "renaming $image_tmp1 to $image_ppm: $!";
3267 my ($base, $img) = pick_image();
3268 my $source = $current_state;
3269 $current_state = "loadimage";
3271 my ($headers, $body) = get_document ($img, $base);
3273 paste_image ($base, $img, $body, $source);
3277 $current_state = "idle";
3278 $load_method = "none";
3280 unlink $image_tmp1, $image_tmp2;
3285 sub paste_image($$$$) {
3286 my ($base, $img, $body, $source) = @_;
3288 $current_state = "paste";
3290 $suppress_audit = 0;
3292 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3296 # If we are using the webcollage-helper, then we do not need to convert this
3297 # image to a PPM. But, if we're using a filter command, we still must, since
3298 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3301 if (defined ($webcollage_helper) &&
3302 !defined ($filter_cmd)) {
3304 ($iw, $ih) = image_size ($body);
3306 LOG (($verbose_pbm || $verbose_load),
3307 "not a GIF, JPG, or PNG" .
3308 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3309 ? " (looks like HTML)" : "") .
3311 $suppress_audit = 1;
3316 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3317 (print $out $body) || error ("writing $image_tmp1: $!");
3318 close ($out) || error ("writing $image_tmp1: $!");
3321 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3324 LOG ($verbose_pbm, "unable to make PBM from $img");
3329 record_success ($load_method, $img, $base);
3332 my $ow = $iw; # used only for error messages
3335 # don't just tack this onto the front of the pipeline -- we want it to
3336 # be able to change the size of the input image.
3339 LOG ($verbose_pbm, "running $filter_cmd");
3341 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3343 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3344 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3347 rename ($image_tmp2, $image_tmp1);
3349 # re-get the width/height in case the filter resized it.
3350 open (my $imgf, '<', $image_tmp1) || return 0;
3353 ($iw, $ih) = m/^(\d+) (\d+)$/;
3355 return 0 unless ($iw && $ih);
3358 my $target_w = $img_width; # max rectangle into which the image must fit
3359 my $target_h = $img_height;
3365 # Usually scale the image to fit on the screen -- but sometimes scale it
3366 # to fit on half or a quarter of the screen. (We do this by reducing the
3367 # size of the target rectangle.) Note that the image is not merely scaled
3368 # to fit; we instead cut the image in half repeatedly until it fits in the
3369 # target rectangle -- that gives a wider distribution of sizes.
3371 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3372 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3374 if ($iw > $target_w || $ih > $target_h) {
3375 while ($iw > $target_w ||
3381 if ($iw <= 10 || $ih <= 10) {
3382 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3386 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3388 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3392 my $src = $image_tmp1;
3394 my $crop_x = 0; # the sub-rectangle of the image
3395 my $crop_y = 0; # that we will actually paste.
3399 # The chance that we will randomly crop out a section of an image starts
3400 # out fairly low, but goes up for images that are very large, or images
3401 # that have ratios that make them look like banners (we try to avoid
3402 # banner images entirely, but they slip through when the IMG tags didn't
3403 # have WIDTH and HEIGHT specified.)
3405 my $crop_chance = 0.2;
3406 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3407 $crop_chance += 0.2;
3409 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3410 $crop_chance += 0.2;
3412 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3413 $crop_chance += 0.7;
3416 if ($crop_chance > 0.1) {
3417 LOG ($verbose_pbm, "crop chance: $crop_chance");
3420 if (rand() < $crop_chance) {
3425 if ($crop_w > $min_width) {
3426 # if it's a banner, select the width linearly.
3427 # otherwise, select a bell.
3428 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3431 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3432 $crop_x = int (rand() * ($ow - $crop_w));
3434 if ($crop_h > $min_height) {
3435 # height always selects as a bell.
3436 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3437 $crop_y = int (rand() * ($oh - $crop_h));
3440 if ($crop_x != 0 || $crop_y != 0 ||
3441 $crop_w != $iw || $crop_h != $ih) {
3443 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3447 # Where the image should logically land -- this might be negative.
3449 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3450 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3452 # if we have chosen to paste the image outside of the rectangle of the
3453 # screen, then we need to crop it.
3457 $x + $crop_w > $img_width ||
3458 $y + $crop_h > $img_height) {
3461 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3463 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3464 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3466 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3467 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3470 # If any cropping needs to happen, add pnmcut.
3472 if ($crop_x != 0 || $crop_y != 0 ||
3473 $crop_w != $iw || $crop_h != $ih) {
3476 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3477 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3480 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3482 $cmd .= " | pnmpaste - $x $y $image_ppm";
3484 $cmd =~ s@^ *\| *@@;
3486 if (defined ($webcollage_helper)) {
3487 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3488 "$scale $opacity " .
3489 "$crop_x $crop_y $x $y " .
3494 # use a PPM pipeline
3496 $_ .= " < $image_tmp1 > $image_tmp2";
3500 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3502 $_ .= " 2> /dev/null";
3505 my $rc = nontrapping_system ($_);
3507 if (defined ($webcollage_helper) && -z $image_ppm) {
3508 LOG (1, "failed command: \"$cmd\"");
3509 print STDERR "\naudit log:\n\n\n";
3510 print STDERR ("#" x 78) . "\n";
3511 print STDERR blurb() . "$image_ppm has zero size\n";
3513 print STDERR "\n\n";
3518 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3519 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3523 if (!defined ($webcollage_helper)) {
3524 rename ($image_tmp2, $image_ppm) || return;
3527 my $target = "$image_ppm";
3529 # don't just tack this onto the end of the pipeline -- we don't want it
3530 # to end up in $image_ppm, because we don't want the results to be
3533 if ($post_filter_cmd) {
3537 $target = $image_tmp1;
3538 if (!defined ($webcollage_helper)) {
3539 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3541 # Blah, my scripts need the JPEG data, but some other folks need
3542 # the PPM data -- what to do? Ignore the problem, that's what!
3543 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3544 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3547 $rc = nontrapping_system ($cmd);
3549 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3554 if (!$no_output_p) {
3555 my $tsize = (stat($target))[7];
3557 $cmd = "$ppm_to_root_window_cmd $target";
3559 # xv seems to hate being killed. it tends to forget to clean
3560 # up after itself, and leaves windows around and colors allocated.
3561 # I had this same problem with vidwhacker, and I'm not entirely
3562 # sure what I did to fix it. But, let's try this: launch xv
3563 # in the background, so that killing this process doesn't kill it.
3564 # it will die of its own accord soon enough. So this means we
3565 # start pumping bits to the root window in parallel with starting
3566 # the next network retrieval, which is probably a better thing
3569 $cmd .= " &" unless ($cocoa_p);
3571 $rc = nontrapping_system ($cmd);
3574 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3579 LOG ($verbose_pbm, "$target size is $tsize");
3583 $source .= "-" . stats_of($source);
3584 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3585 if ($verbose_imgmap);
3586 if ($imagemap_base) {
3587 update_imagemap ($base, $x, $y, $iw, $ih,
3588 $image_ppm, $img_width, $img_height);
3597 sub update_imagemap($$$$$$$$) {
3598 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3600 $current_state = "imagemap";
3602 my $max_areas = 200;
3604 $url = html_quote ($url);
3607 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3608 unshift @imagemap_areas, $area; # put one on the front
3609 if ($#imagemap_areas >= $max_areas) {
3610 pop @imagemap_areas; # take one off the back.
3613 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3615 my $map_name = $imagemap_base;
3616 $map_name =~ s@^.*/@@;
3617 $map_name = 'collage' if ($map_name eq '');
3619 my $imagemap_html = $imagemap_base . ".html";
3620 my $imagemap_jpg = $imagemap_base . ".jpg";
3621 my $imagemap_jpg2 = $imagemap_jpg;
3622 $imagemap_jpg2 =~ s@^.*/@@gs;
3624 if (!defined ($imagemap_html_tmp)) {
3625 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3626 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3629 # Read the imagemap html file (if any) to get a template.
3631 my $template_html = '';
3633 if (open (my $in, '<', $imagemap_html)) {
3634 local $/ = undef; # read entire file
3635 $template_html = <$in>;
3637 LOG ($verbose_pbm, "read template $imagemap_html");
3640 if ($template_html =~ m/^\s*$/s) {
3641 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3642 "<IMG SRC=\"$imagemap_jpg2\"" .
3643 " USEMAP=\"$map_name\">\n");
3644 LOG ($verbose_pbm, "created dummy template");
3648 # Write the jpg to a tmp file
3652 if (defined ($webcollage_helper)) {
3653 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3655 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3657 my $rc = nontrapping_system ($cmd);
3659 error ("imagemap jpeg failed: \"$cmd\"\n");
3663 # Write the html to a tmp file
3666 my $body = $template_html;
3667 my $areas = join ("\n\t", @imagemap_areas);
3668 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3669 my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3671 "WIDTH=$image_width HEIGHT=$image_height " .
3672 "USEMAP=\"#$map_name\">");
3673 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3674 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3676 # if there are magic webcollage spans in the html, update those too.
3679 my @st = stat ($imagemap_jpg_tmp);
3680 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3681 my $size = int(($st[7] / 1024) + 0.5) . "K";
3682 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3683 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3686 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3687 (print $out $body) || error ("$imagemap_html_tmp: $!");
3688 close ($out) || error ("$imagemap_html_tmp: $!");
3689 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3692 # Rename the two tmp files to the real files
3694 rename ($imagemap_html_tmp, $imagemap_html) ||
3695 error "renaming $imagemap_html_tmp to $imagemap_html";
3696 LOG ($verbose_pbm, "wrote $imagemap_html");
3697 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3698 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3699 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3703 # Figure out what the proxy server should be, either from environment
3704 # variables or by parsing the output of the (MacOS) program "scutil",
3705 # which tells us what the system-wide proxy settings are.
3709 if (! $http_proxy) {
3710 # historical suckage: the environment variable name is lower case.
3711 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3714 if (defined ($http_proxy)) {
3715 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3716 # historical suckage: allow "http://host:port" as well as "host:port".
3721 my $proxy_data = `scutil --proxy 2>/dev/null`;
3722 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3723 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3724 # Note: this ignores the "ExceptionsList".
3726 $http_proxy = $server;
3727 $http_proxy .= ":$port" if $port;
3732 LOG ($verbose_net, "proxy server: $http_proxy");
3737 sub init_signals() {
3739 $SIG{HUP} = \&signal_cleanup;
3740 $SIG{INT} = \&signal_cleanup;
3741 $SIG{QUIT} = \&signal_cleanup;
3742 $SIG{ABRT} = \&signal_cleanup;
3743 $SIG{KILL} = \&signal_cleanup;
3744 $SIG{TERM} = \&signal_cleanup;
3746 # Need this so that if giftopnm dies, we don't die.
3747 $SIG{PIPE} = 'IGNORE';
3750 END { exit_cleanup(); }
3759 my $driftnet_cmd = 0;
3761 $current_state = "init";
3762 $load_method = "none";
3765 my $window_id = undef;
3767 while ($_ = $ARGV[0]) {
3769 if ($_ eq "-display" ||
3775 $ENV{DISPLAY} = shift @ARGV;
3776 } elsif ($_ eq "-root") {
3778 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3779 $window_id = shift @ARGV;
3781 } elsif ($_ eq "-no-output") {
3783 } elsif ($_ eq "-urls-only") {
3786 } elsif ($_ eq "-cocoa") {
3788 } elsif ($_ eq "-imagemap") {
3789 $imagemap_base = shift @ARGV;
3791 } elsif ($_ eq "-verbose") {
3793 } elsif (m/^-v+$/) {
3794 $verbose += length($_)-1;
3795 } elsif ($_ eq "-delay") {
3796 $delay = shift @ARGV;
3797 } elsif ($_ eq "-timeout") {
3798 $http_timeout = shift @ARGV;
3799 } elsif ($_ eq "-filter") {
3800 $filter_cmd = shift @ARGV;
3801 } elsif ($_ eq "-filter2") {
3802 $post_filter_cmd = shift @ARGV;
3803 } elsif ($_ eq "-background" || $_ eq "-bg") {
3804 $background = shift @ARGV;
3805 } elsif ($_ eq "-size") {
3807 if (m@^(\d+)x(\d+)$@) {
3811 error "argument to \"-size\" must be of the form \"640x400\"";
3813 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3814 $http_proxy = shift @ARGV;
3815 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3816 $dict = shift @ARGV;
3817 } elsif ($_ eq "-opacity") {
3818 $opacity = shift @ARGV;
3819 error ("opacity must be between 0.0 and 1.0")
3820 if ($opacity <= 0 || $opacity > 1);
3821 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3822 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3823 if (! ($ARGV[0] =~ m/^-/)) {
3824 $driftnet_cmd = shift @ARGV;
3826 $driftnet_cmd = $default_driftnet_cmd;
3828 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3829 @search_methods = ( 100, "local", \&pick_from_local_dir );
3830 if (! ($ARGV[0] =~ m/^-/)) {
3831 $local_dir = shift @ARGV;
3833 error ("local directory path must be set")
3835 } elsif ($_ eq "-fps") {
3836 # -fps only works on MacOS, via "webcollage-cocoa.m".
3837 # Ignore it if passed to this script in an X11 context.
3838 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3839 my $which = shift @ARGV;
3840 my @rest = @search_methods;
3843 my $pct = shift @rest;
3844 my $name = shift @rest;
3845 my $tfn = shift @rest;
3847 if ($name eq $which) {
3848 @search_methods = (100, $name, $tfn);
3853 error "no such search method as \"$which\"" unless ($ok);
3854 LOG (1, "DEBUG: using only \"$which\"");
3857 print STDERR "$copyright\nusage: $progname " .
3858 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3859 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3860 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3861 "\t\t [-background color] [-opacity f]\n" .
3862 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3863 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3864 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3865 "\t\t [-directory local-image-directory]\n" .
3871 if (!$root_p && !$no_output_p && !$cocoa_p) {
3872 print STDERR $copyright;
3873 error "the -root argument is mandatory (for now.)";
3876 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3877 error "\$DISPLAY is not set.";
3881 if ($verbose == 1) {
3882 $verbose_imgmap = 1;
3883 $verbose_warnings = 1;
3885 } elsif ($verbose == 2) {
3886 $verbose_imgmap = 1;
3887 $verbose_warnings = 1;
3890 } elsif ($verbose == 3) {
3891 $verbose_imgmap = 1;
3892 $verbose_warnings = 1;
3894 $verbose_filter = 1;
3896 } elsif ($verbose == 4) {
3897 $verbose_imgmap = 1;
3898 $verbose_warnings = 1;
3900 $verbose_filter = 1;
3903 } elsif ($verbose == 5) {
3904 $verbose_imgmap = 1;
3905 $verbose_warnings = 1;
3907 $verbose_filter = 1;
3911 } elsif ($verbose == 6) {
3912 $verbose_imgmap = 1;
3913 $verbose_warnings = 1;
3915 $verbose_filter = 1;
3920 } elsif ($verbose >= 7) {
3921 $verbose_imgmap = 1;
3922 $verbose_warnings = 1;
3924 $verbose_filter = 1;
3932 error ("$dict does not exist") unless (-f $dict);
3938 if ($imagemap_base && !($img_width && $img_height)) {
3939 error ("-size WxH is required with -imagemap");
3942 if (defined ($local_dir)) {
3943 $_ = "xscreensaver-getimage-file";
3944 which ($_) || error "$_ not found on \$PATH.";
3950 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3955 x_or_pbm_output ($window_id);