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.165 $' =~ 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?q=";
1501 sub pick_from_bing_images($;$$) {
1502 my ($timeout, $words, $max_page) = @_;
1504 if (!defined($words)) {
1505 $words = random_word(); # only one word for Bing
1508 my $off = int(rand(300));
1509 my $search_url = $bing_images_url . $words . "&first=" . $off;
1511 my ($search_hit_count, @subpages) =
1512 pick_from_search_engine ($timeout, $search_url, $words);
1514 my @candidates = ();
1516 foreach my $u (@subpages) {
1517 my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1519 LOG ($verbose_filter, " candidate: $ref");
1520 push @candidates, $img;
1521 $referers{$img} = $ref;
1524 @candidates = depoison (@candidates);
1525 return () if ($#candidates < 0);
1526 my $i = int(rand($#candidates+1));
1527 my $img = $candidates[$i];
1528 my $ref = $referers{$img};
1530 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1531 return ($ref, $img);
1537 ############################################################################
1539 # Pick images by feeding random numbers into Bing Image Search.
1541 ############################################################################
1544 sub pick_from_bing_image_numbers($) {
1548 my $number = int(rand($max));
1550 $number = sprintf("%04d", $number)
1553 pick_from_bing_images ($timeout, "$number");
1557 ############################################################################
1559 # Pick images by feeding random numbers into Bing Image Search.
1561 ############################################################################
1564 sub pick_from_bing_image_photos($) {
1567 my $i = int(rand($#photomakers + 1));
1568 my $fn = $photomakers[$i];
1571 pick_from_bing_images ($timeout, $file);
1575 ############################################################################
1577 # Pick images by feeding random words into Alta Vista Text Search
1579 ############################################################################
1582 my $alta_vista_url = "http://www.altavista.com/web/results" .
1586 "&sc=on" . # "site collapse"
1591 sub pick_from_alta_vista_text($) {
1594 my $words = random_words('%20');
1595 my $page = (int(rand(9)) + 1);
1596 my $search_url = $alta_vista_url . $words;
1599 $search_url .= "&pgno=" . $page;
1600 $search_url .= "&stq=" . (($page-1) * 10);
1603 my ($search_hit_count, @subpages) =
1604 pick_from_search_engine ($timeout, $search_url, $words);
1606 my @candidates = ();
1607 foreach my $u (@subpages) {
1609 # Those altavista fuckers are playing really nasty redirection games
1610 # these days: the filter your clicks through their site, but use
1611 # onMouseOver to make it look like they're not! Well, it makes it
1612 # easier for us to identify search results...
1614 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1615 $u = url_unquote($u);
1617 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1618 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1619 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1621 LOG ($verbose_filter, " candidate: $u");
1622 push @candidates, $u;
1625 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1626 $timeout, @candidates);
1631 ############################################################################
1633 # Pick images by feeding random words into Hotbot
1635 ############################################################################
1637 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1639 "&descriptiontype=0" .
1646 "&cobrand=undefined" .
1649 sub pick_from_hotbot_text($) {
1652 $last_search = $hotbot_search_url; # for warnings
1654 # lycos seems to always give us back dictionaries and word lists if
1655 # we search for more than one word...
1657 my $words = random_word();
1659 my $start = int(rand(8)) * 10 + 1;
1660 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1662 my ($search_hit_count, @subpages) =
1663 pick_from_search_engine ($timeout, $search_url, $words);
1665 my @candidates = ();
1666 foreach my $u (@subpages) {
1668 # Hotbot plays redirection games too
1670 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1671 # $u = url_decode($1);
1673 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1674 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1675 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1676 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1678 LOG ($verbose_filter, " candidate: $u");
1679 push @candidates, $u;
1682 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1683 $timeout, @candidates);
1688 ############################################################################
1690 # Pick images by feeding random words into Lycos
1692 ############################################################################
1694 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1700 sub pick_from_lycos_text($) {
1703 $last_search = $lycos_search_url; # for warnings
1705 # lycos seems to always give us back dictionaries and word lists if
1706 # we search for more than one word...
1708 my $words = random_word();
1710 my $start = int(rand(8)) * 10 + 1;
1711 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1713 my ($search_hit_count, @subpages) =
1714 pick_from_search_engine ($timeout, $search_url, $words);
1716 my @candidates = ();
1717 foreach my $u (@subpages) {
1719 # Lycos plays redirection games.
1721 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1726 # $u = url_decode($1);
1728 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1729 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1730 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1731 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1732 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1735 LOG ($verbose_filter, " candidate: $u");
1736 push @candidates, $u;
1739 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1740 $timeout, @candidates);
1745 ############################################################################
1747 # Pick images by feeding random words into news.yahoo.com
1749 ############################################################################
1751 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1756 sub pick_from_yahoo_news_text($) {
1759 $last_search = $yahoo_news_url; # for warnings
1761 my $words = random_word();
1762 my $search_url = $yahoo_news_url . $words;
1764 my ($search_hit_count, @subpages) =
1765 pick_from_search_engine ($timeout, $search_url, $words);
1767 my @candidates = ();
1768 foreach my $u (@subpages) {
1770 # de-redirectize the URLs
1771 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1773 # only accept URLs on Yahoo's news site
1774 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1775 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1776 next unless ($u =~ m@&u=/@);
1778 LOG ($verbose_filter, " candidate: $u");
1779 push @candidates, $u;
1782 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1783 $timeout, @candidates);
1788 ############################################################################
1790 # Pick images from LiveJournal's list of recently-posted images.
1792 ############################################################################
1794 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1796 # With most of our image sources, we get a random page and then select
1797 # from the images on it. However, in the case of LiveJournal, the page
1798 # of images tends to update slowly; so we'll remember the last N entries
1799 # on it and randomly select from those, to get a wider variety each time.
1801 my $lj_cache_size = 1000;
1802 my @lj_cache = (); # fifo, for ordering by age
1803 my %lj_cache = (); # hash, for detecting dups
1806 sub pick_from_livejournal_images($) {
1809 $last_search = $livejournal_img_url; # for warnings
1811 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1812 return () unless $body;
1815 $body =~ s/(<recent-image)\b/\n$1/gsi;
1817 foreach (split (/\n/, $body)) {
1818 next unless (m/^<recent-image\b/);
1819 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1820 my $img = html_unquote ($1);
1822 next if ($lj_cache{$img}); # already have it
1824 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1825 my $page = html_unquote ($1);
1826 my @pair = ($img, $page);
1827 LOG ($verbose_filter, " candidate: $img");
1828 push @lj_cache, \@pair;
1829 $lj_cache{$img} = \@pair;
1832 return () if ($#lj_cache == -1);
1834 my $n = $#lj_cache+1;
1835 my $i = int(rand($n));
1836 my ($img, $page) = @{$lj_cache[$i]};
1838 # delete this one from @lj_cache and from %lj_cache.
1840 @lj_cache = ( @lj_cache[0 .. $i-1],
1841 @lj_cache[$i+1 .. $#lj_cache] );
1842 delete $lj_cache{$img};
1844 # Keep the size of the cache under the limit by nuking older entries
1846 while ($#lj_cache >= $lj_cache_size) {
1847 my $pairP = shift @lj_cache;
1848 my $img = $pairP->[0];
1849 delete $lj_cache{$img};
1852 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1854 return ($page, $img);
1858 ############################################################################
1860 # Pick images from ircimages.com (images that have been in the /topic of
1861 # various IRC channels.)
1863 ############################################################################
1865 my $ircimages_url = "http://ircimages.com/";
1868 sub pick_from_ircimages($) {
1871 $last_search = $ircimages_url; # for warnings
1873 my $n = int(rand(2900));
1874 my $search_url = $ircimages_url . "page-$n";
1876 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1877 return () unless $body;
1879 my @candidates = ();
1882 $body =~ s/(<A)\b/\n$1/gsi;
1884 foreach (split (/\n/, $body)) {
1886 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1889 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1890 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1892 next unless ($u =~ m/^http:/i);
1893 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1894 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1896 LOG ($verbose_http, " HREF: $u");
1897 push @candidates, $u;
1900 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1902 return () if ($#candidates == -1);
1904 my $i = int(rand($#candidates+1));
1905 my $img = $candidates[$i];
1907 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1910 $search_url = $img; # hmm...
1911 return ($search_url, $img);
1915 ############################################################################
1917 # Pick images from Twitpic's list of recently-posted images.
1919 ############################################################################
1921 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1923 # With most of our image sources, we get a random page and then select
1924 # from the images on it. However, in the case of Twitpic, the page
1925 # of images tends to update slowly; so we'll remember the last N entries
1926 # on it and randomly select from those, to get a wider variety each time.
1928 my $twitpic_cache_size = 1000;
1929 my @twitpic_cache = (); # fifo, for ordering by age
1930 my %twitpic_cache = (); # hash, for detecting dups
1933 sub pick_from_twitpic_images($) {
1936 $last_search = $twitpic_img_url; # for warnings
1938 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1944 $body =~ s/(<item)\b/\n$1/gsi;
1946 my @items = split (/\n/, $body);
1949 next unless (m@<link>([^<>]*)</link>@si);
1950 my $page = html_unquote ($1);
1955 next if ($twitpic_cache{$page}); # already have it
1957 LOG ($verbose_filter, " candidate: $page");
1958 push @twitpic_cache, $page;
1959 $twitpic_cache{$page} = $page;
1963 # Pull from the cache.
1965 return () if ($#twitpic_cache == -1);
1967 my $n = $#twitpic_cache+1;
1968 my $i = int(rand($n));
1969 my $page = $twitpic_cache[$i];
1971 # delete this one from @twitpic_cache and from %twitpic_cache.
1973 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1974 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1975 delete $twitpic_cache{$page};
1977 # Keep the size of the cache under the limit by nuking older entries
1979 while ($#twitpic_cache >= $twitpic_cache_size) {
1980 my $page = shift @twitpic_cache;
1981 delete $twitpic_cache{$page};
1984 ( $base, $body ) = get_document ($page, undef, $timeout);
1986 $body = '' unless defined($body);
1988 foreach (split (/<img\s+/, $body)) {
1989 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1992 next if m@/images/@s;
1996 $img = "http:$img" if ($img =~ m@^//@s); # Oh come on
1998 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
1999 if ($img =~ m@^/@) {
2000 $base =~ s@^(https?://[^/]+)/.*@$1@s;
2001 $img = $base . $img;
2007 LOG ($verbose_load, "no matching images on $page\n");
2011 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2013 return ($page, $img);
2017 ############################################################################
2019 # Pick images from Twitter's list of recently-posted updates.
2021 ############################################################################
2023 # With most of our image sources, we get a random page and then select
2024 # from the images on it. However, in the case of Twitter, the page
2025 # of images only updates once a minute; so we'll remember the last N entries
2026 # on it and randomly select from those, to get a wider variety each time.
2028 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2029 "public_timeline.json" .
2030 "?include_entities=true" .
2031 "&include_rts=true" .
2034 my $twitter_cache_size = 1000;
2036 my @twitter_cache = (); # fifo, for ordering by age
2037 my %twitter_cache = (); # hash, for detecting dups
2041 sub pick_from_twitter_images($) {
2044 $last_search = $twitter_img_url; # for warnings
2046 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2050 $body =~ s/[\r\n]+/ /gs;
2052 # Parsing JSON is a pain in the ass. So we halfass it as usual.
2053 $body =~ s/^\[|\]$//s;
2054 $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2055 my @items = split (/},{/, $body);
2057 my ($name) = m@"screen_name":"([^\"]+)"@si;
2058 my ($img) = m@"media_url":"([^\"]+)"@si;
2059 my ($page) = m@"display_url":"([^\"]+)"@si;
2060 next unless ($name && $img && $page);
2061 foreach ($img, $page) {
2063 $_ = "http://$_" unless (m/^http/si);
2066 next if ($twitter_cache{$page}); # already have it
2068 LOG ($verbose_filter, " candidate: $page - $img");
2069 push @twitter_cache, $page;
2070 $twitter_cache{$page} = $img;
2074 # Pull from the cache.
2076 return () if ($#twitter_cache == -1);
2078 my $n = $#twitter_cache+1;
2079 my $i = int(rand($n));
2080 my $page = $twitter_cache[$i];
2081 my $url = $twitter_cache{$page};
2083 # delete this one from @twitter_cache and from %twitter_cache.
2085 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2086 @twitter_cache[$i+1 .. $#twitter_cache] );
2087 delete $twitter_cache{$page};
2089 # Keep the size of the cache under the limit by nuking older entries
2091 while ($#twitter_cache >= $twitter_cache_size) {
2092 my $page = shift @twitter_cache;
2093 delete $twitter_cache{$page};
2096 LOG ($verbose_load, "picked page $url");
2098 $suppress_audit = 1;
2100 return ($page, $url);
2104 ############################################################################
2106 # Pick images from Flickr's page of recently-posted photos.
2108 ############################################################################
2110 my $flickr_img_url = "http://www.flickr.com/explore/";
2112 # Like LiveJournal, the Flickr page of images tends to update slowly,
2113 # so remember the last N entries on it and randomly select from those.
2115 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2116 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2118 my $flickr_cache_size = 1000;
2119 my @flickr_cache = (); # fifo, for ordering by age
2120 my %flickr_cache = (); # hash, for detecting dups
2124 sub pick_from_flickr_recent($) {
2127 my $start = 16 * int(rand(100));
2129 $last_search = $flickr_img_url; # for warnings
2130 $last_search .= "?start=$start" if ($start > 0);
2132 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2133 return () unless $body;
2135 $body =~ s/[\r\n]/ /gs;
2136 $body =~ s/(<a)\b/\n$1/gsi;
2140 foreach (split (/\n/, $body)) {
2142 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2144 data-defer-src = \"([^<>\"]+)\" @xsi;
2145 next unless defined ($thumb);
2146 $page = html_unquote ($page);
2147 $thumb = html_unquote ($thumb);
2149 next unless ($thumb =~ m@^https?://[^/.]+\d*\.static\.?flickr\.com/@);
2151 my $base = "http://www.flickr.com/";
2152 $page =~ s@^/@$base@;
2153 $thumb =~ s@^/@$base@;
2156 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2159 next if ($flickr_cache{$img}); # already have it
2161 my @pair = ($img, $page, $start);
2162 LOG ($verbose_filter, " candidate: $img");
2163 push @flickr_cache, \@pair;
2164 $flickr_cache{$img} = \@pair;
2168 return () if ($#flickr_cache == -1);
2170 my $n = $#flickr_cache+1;
2171 my $i = int(rand($n));
2172 my ($img, $page) = @{$flickr_cache[$i]};
2174 # delete this one from @flickr_cache and from %flickr_cache.
2176 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2177 @flickr_cache[$i+1 .. $#flickr_cache] );
2178 delete $flickr_cache{$img};
2180 # Keep the size of the cache under the limit by nuking older entries
2182 while ($#flickr_cache >= $flickr_cache_size) {
2183 my $pairP = shift @flickr_cache;
2184 my $img = $pairP->[0];
2185 delete $flickr_cache{$img};
2188 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2190 return ($page, $img);
2194 ############################################################################
2196 # Pick images from a random RSS feed on Flickr.
2198 ############################################################################
2200 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2201 "?format=rss_200_enc&tagmode=any&tags=");
2203 # Picks a random RSS feed; picks a random image from that feed;
2204 # returns 2 URLs: the page containing the image, and the image.
2205 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2208 sub pick_from_flickr_random($) {
2209 my $timeout = shift;
2211 my $words = random_words(',');
2212 my $rss = $flickr_rss_base . $words;
2213 $last_search = $rss;
2218 print STDERR "\n\n" if ($verbose_load);
2219 LOG ($verbose_load, "words: $_");
2220 LOG ($verbose_load, "URL: $last_search");
2222 $suppress_audit = 1;
2224 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2225 if (!$base || !$body) {
2231 ($base, $img) = pick_image_from_rss ($base, $body);
2233 return () unless defined ($img);
2235 LOG ($verbose_load, "redirected to: $base");
2236 return ($base, $img);
2240 ############################################################################
2242 # Pick random images from Instagram, via gramfeed.com's key.
2244 ############################################################################
2246 my $instagram_url_base = "https://api.instagram.com/v1/media/popular" .
2247 "?client_id=b59fbe4563944b6c88cced13495c0f49";
2250 sub pick_from_instagram($) {
2251 my $timeout = shift;
2253 $last_search = $instagram_url_base;
2255 print STDERR "\n\n" if ($verbose_load);
2256 LOG ($verbose_load, "URL: $last_search");
2258 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2259 if (!$base || !$body) {
2264 $body =~ s/("link")/\001$1/gs;
2265 my @chunks = split(/\001/, $body);
2270 my ($url) = m/"link":\s*"(.*?)"/s;
2271 my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2272 ($img) = m/"url":\s*"(.*?)"/s unless $url;
2273 next unless ($url && $img);
2274 push @urls, [ $url, $img ];
2278 LOG ($verbose_load, "no images on $last_search");
2282 my $i = int(rand($#urls+1));
2283 my ($url, $img) = @{$urls[$i]};
2285 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2286 return ($url, $img);
2290 ############################################################################
2292 # Pick images by waiting for driftnet to populate a temp dir with files.
2293 # Requires driftnet version 0.1.5 or later.
2294 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2295 # for images being downloaded by others.)
2296 # Driftnet/webcollage integration by jwz.
2298 ############################################################################
2301 sub pick_from_driftnet($) {
2304 my $id = $driftnet_magic;
2305 my $dir = $driftnet_dir;
2309 error ("\$driftnet_dir unset?") unless ($dir);
2312 error ("$dir unreadable") unless (-d "$dir/.");
2314 $timeout = $http_timeout unless ($timeout);
2317 while ($now = time, $now < $start + $timeout) {
2318 opendir (my $dir, $dir) || error ("$dir: $!");
2319 while (my $file = readdir($dir)) {
2320 next if ($file =~ m/^\./);
2321 $file = "$dir/$file";
2323 LOG ($verbose_load, "picked file $file ($id)");
2324 return ($id, $file);
2328 LOG (($verbose_net || $verbose_load), "timed out for $id");
2333 sub get_driftnet_file($) {
2336 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2338 my $id = $driftnet_magic;
2339 error ("$id: $file not in $driftnet_dir?")
2340 unless ($file =~ m@^\Q$driftnet_dir@o);
2342 open (my $in, '<', $file) || error ("$id: $file: $!");
2344 local $/ = undef; # read entire file
2346 close ($in) || error ("$id: $file: $!");
2347 unlink ($file) || error ("$id: $file: rm: $!");
2348 return ($id, $body);
2352 sub spawn_driftnet($) {
2355 # make a directory to use.
2357 my $tmp = $ENV{TEMPDIR} || "/tmp";
2358 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2359 LOG ($verbose_exec, "mkdir $driftnet_dir");
2360 last if mkdir ($driftnet_dir, 0700);
2363 if (! ($cmd =~ m/\s/)) {
2364 # if the command didn't have any arguments in it, then it must be just
2365 # a pointer to the executable. Append the default args to it.
2366 my $dargs = $default_driftnet_cmd;
2367 $dargs =~ s/^[^\s]+//;
2371 # point the driftnet command at our newly-minted private directory.
2373 $cmd .= " -d $driftnet_dir";
2374 $cmd .= ">/dev/null" unless ($verbose_exec);
2377 if ($pid < 0) { error ("fork: $!\n"); }
2380 push @pids_to_kill, $pid;
2381 LOG ($verbose_exec, "forked for \"$cmd\"");
2384 nontrapping_system ($cmd) || error ("exec: $!");
2387 # wait a bit, then make sure the process actually started up.
2390 error ("pid $pid failed to start \"$cmd\"")
2391 unless (1 == kill (0, $pid));
2395 sub pick_from_local_dir($) {
2398 my $id = $local_magic;
2401 my $dir = $local_dir;
2402 error ("\$local_dir unset?") unless ($dir);
2405 error ("$dir unreadable") unless (-d "$dir/.");
2407 my $v = ($verbose_exec ? "-v" : "");
2408 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2410 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2412 LOG ($verbose_load, "picked file $pick ($id)");
2413 return ($id, $pick);
2417 sub get_local_file($) {
2420 error ("\$local_dir unset?") unless ($local_dir);
2422 my $id = $local_magic;
2423 error ("$id: $file not in $local_dir?")
2424 unless ($file =~ m@^\Q$local_dir@o);
2426 open (my $in, '<', $file) || error ("$id: $file: $!");
2427 local $/ = undef; # read entire file
2429 close ($in) || error ("$id: $file: $!");
2430 return ($id, $body);
2435 ############################################################################
2437 # Pick a random image in a random way
2439 ############################################################################
2442 # Picks a random image on a random page, and returns two URLs:
2443 # the page containing the image, and the image.
2444 # Returns () if nothing found this time.
2447 sub pick_image(;$) {
2450 $current_state = "select";
2451 $load_method = "none";
2453 my $n = int(rand(100));
2456 my @rest = @search_methods;
2459 my $pct = shift @rest;
2460 my $name = shift @rest;
2461 my $tfn = shift @rest;
2463 if ($total > $n && !defined($fn)) {
2465 $current_state = $name;
2466 $load_method = $current_state;
2470 if ($total != 100) {
2471 error ("internal error: \@search_methods totals to $total%!");
2474 record_attempt ($current_state);
2475 return $fn->($timeout);
2480 ############################################################################
2482 # Statistics and logging
2484 ############################################################################
2487 return strftime ("%H:%M:%S: ", localtime);
2491 return "$progname: " . timestr() . "$current_state: ";
2496 print STDERR blurb() . "$err\n";
2502 print STDERR "$progname: stack trace:\n";
2504 my ($package, $filename, $line, $subroutine) = caller($i++);
2505 last unless defined($package);
2506 $filename =~ s@^.*/@@;
2507 print STDERR " $filename#$line, $subroutine\n";
2519 my $head = "$progname: DEBUG: ";
2520 foreach (split (/\n/, $lastlog)) {
2521 print STDERR "$head$_\n";
2527 my ($print, $msg) = @_;
2528 my $blurb = timestr() . "$current_state: ";
2529 $lastlog .= "$blurb$msg\n";
2530 print STDERR "$progname: $blurb$msg\n" if $print;
2535 my %stats_successes;
2538 my $last_state = undef;
2539 sub record_attempt($) {
2543 record_failure($last_state) unless ($image_succeeded > 0);
2545 $last_state = $name;
2548 report_performance();
2551 $image_succeeded = 0;
2552 $suppress_audit = 0;
2555 sub record_success($$$) {
2556 my ($name, $url, $base) = @_;
2557 if (defined($stats_successes{$name})) {
2558 $stats_successes{$name}++;
2560 $stats_successes{$name} = 1;
2563 stop_timer ($name, 1);
2564 my $o = $current_state;
2565 $current_state = $name;
2566 save_recent_url ($url, $base);
2567 $current_state = $o;
2568 $image_succeeded = 1;
2573 sub record_failure($) {
2576 return if $image_succeeded;
2578 stop_timer ($name, 0);
2579 if ($verbose_load && !$verbose_exec) {
2581 if ($suppress_audit) {
2582 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2586 my $o = $current_state;
2587 $current_state = "DEBUG";
2589 my $line = "#" x 78;
2590 print STDERR "\n\n\n";
2591 print STDERR ("#" x 78) . "\n";
2592 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2595 print STDERR ("-" x 78) . "\n";
2596 print STDERR "\n\n";
2598 $current_state = $o;
2600 $image_succeeded = 0;
2607 my $i = $stats_successes{$name};
2608 my $j = $stats_attempts{$name};
2611 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2615 my $current_start_time = 0;
2617 sub start_timer($) {
2619 $current_start_time = time;
2621 if (defined($stats_attempts{$name})) {
2622 $stats_attempts{$name}++;
2624 $stats_attempts{$name} = 1;
2626 if (!defined($stats_elapsed{$name})) {
2627 $stats_elapsed{$name} = 0;
2631 sub stop_timer($$) {
2632 my ($name, $success) = @_;
2633 $stats_elapsed{$name} += time - $current_start_time;
2637 my $last_report_time = 0;
2638 sub report_performance() {
2640 return unless $verbose_warnings;
2643 return unless ($now >= $last_report_time + $report_performance_interval);
2644 my $ot = $last_report_time;
2645 $last_report_time = $now;
2647 return if ($ot == 0);
2649 my $blurb = "$progname: " . timestr();
2652 print STDERR "${blurb}Current standings:\n";
2654 foreach my $name (sort keys (%stats_attempts)) {
2655 my $try = $stats_attempts{$name};
2656 my $suc = $stats_successes{$name} || 0;
2657 my $pct = int($suc * 100 / $try);
2658 my $secs = $stats_elapsed{$name};
2659 my $secs_link = $secs / $try;
2660 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2661 " \t %.1f secs/link\n",
2662 "$name:", "$pct%", $suc, $try, $secs_link);
2668 my $max_recent_images = 400;
2669 my $max_recent_sites = 20;
2670 my @recent_images = ();
2671 my @recent_sites = ();
2673 sub save_recent_url($$) {
2674 my ($url, $base) = @_;
2676 return unless ($verbose_warnings);
2679 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2680 return unless defined ($site);
2682 if ($base eq $driftnet_magic || $base eq $local_magic) {
2684 @recent_images = ();
2688 foreach (@recent_images) {
2690 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2691 " (on $base via $last_search)\n";
2697 # suppress "duplicate site" warning via %warningless_sites.
2699 if ($warningless_sites{$site}) {
2701 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2702 $warningless_sites{$1}) {
2704 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2705 $warningless_sites{$1}) {
2710 foreach (@recent_sites) {
2712 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2713 " ($url on $base via $last_search)\n";
2719 push @recent_images, $url;
2720 push @recent_sites, $site;
2721 shift @recent_images if ($#recent_images >= $max_recent_images);
2722 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2727 ##############################################################################
2731 ##############################################################################
2738 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2743 # Given the raw body of a GIF document, returns the dimensions of the image.
2747 my $type = substr($body, 0, 6);
2749 return () unless ($type =~ /GIF8[7,9]a/);
2750 $s = substr ($body, 6, 10);
2751 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2752 return () unless defined ($d);
2753 return (($b<<8|$a), ($d<<8|$c));
2756 # Given the raw body of a JPEG document, returns the dimensions of the image.
2761 my $L = length($body);
2763 my $c1 = substr($body, $i, 1); $i++;
2764 my $c2 = substr($body, $i, 1); $i++;
2765 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2768 while (ord($ch) != 0xDA && $i < $L) {
2769 # Find next marker, beginning with 0xFF.
2770 while (ord($ch) != 0xFF) {
2771 return () if (length($body) <= $i);
2772 $ch = substr($body, $i, 1); $i++;
2774 # markers can be padded with any number of 0xFF.
2775 while (ord($ch) == 0xFF) {
2776 return () if (length($body) <= $i);
2777 $ch = substr($body, $i, 1); $i++;
2780 # $ch contains the value of the marker.
2781 my $marker = ord($ch);
2783 if (($marker >= 0xC0) &&
2784 ($marker <= 0xCF) &&
2785 ($marker != 0xC4) &&
2786 ($marker != 0xCC)) { # it's a SOFn marker
2788 return () if (length($body) <= $i);
2789 my $s = substr($body, $i, 4); $i += 4;
2790 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2791 return (($c<<8|$d), ($a<<8|$b));
2794 # We must skip variables, since FFs in variable names aren't
2795 # valid JPEG markers.
2796 return () if (length($body) <= $i);
2797 my $s = substr($body, $i, 2); $i += 2;
2798 my ($c1, $c2) = unpack ("C"x2, $s);
2799 my $length = ($c1 << 8) | $c2;
2800 return () if ($length < 2);
2807 # Given the raw body of a PNG document, returns the dimensions of the image.
2811 return () unless ($body =~ m/^\211PNG\r/);
2812 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2813 return () unless defined ($bits);
2814 return () unless ($bits =~ /^IHDR/);
2815 my ($ign, $w, $h) = unpack("a4N2", $bits);
2820 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2825 my ($w, $h) = gif_size ($body);
2826 if ($w && $h) { return ($w, $h); }
2827 ($w, $h) = jpeg_size ($body);
2828 if ($w && $h) { return ($w, $h); }
2829 return png_size ($body);
2833 # returns the full path of the named program, or undef.
2837 foreach (split (/:/, $ENV{PATH})) {
2838 if (-x "$_/$prog") {
2846 # Like rand(), but chooses numbers with a bell curve distribution.
2849 $_ = 1.0 unless defined($_);
2851 return (rand($_) + rand($_) + rand($_));
2855 sub exit_cleanup() {
2857 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2858 if (@pids_to_kill) {
2859 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2860 kill ('TERM', @pids_to_kill);
2864 sub signal_cleanup($) {
2866 print STDERR blurb() . (defined($sig)
2867 ? "caught signal $sig."
2870 if ($verbose_exec || $verbose_warnings);
2876 ##############################################################################
2878 # Generating a list of urls only
2880 ##############################################################################
2882 sub url_only_output() {
2884 my ($base, $img) = pick_image;
2888 print "$img $base\n";
2893 ##############################################################################
2895 # Running as an xscreensaver module, or as a web page imagemap
2897 ##############################################################################
2899 my $image_ppm = sprintf ("%s/webcollage-%08x.ppm",
2900 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2902 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x.ppm",
2903 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2905 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x.ppm",
2906 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2909 my $filter_cmd = undef;
2910 my $post_filter_cmd = undef;
2911 my $background = undef;
2913 my @imagemap_areas = ();
2914 my $imagemap_html_tmp = undef;
2915 my $imagemap_jpg_tmp = undef;
2918 my $img_width; # size of the image being generated.
2924 unlink $image_ppm, $image_tmp1, $image_tmp2;
2925 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2926 if (defined ($imagemap_html_tmp));
2930 # Like system, but prints status about exit codes, and kills this process
2931 # with whatever signal killed the sub-process, if any.
2933 sub nontrapping_system(@) {
2937 s/\"[^\"]+\"/\"...\"/g;
2939 LOG ($verbose_exec, "executing \"$_\"");
2944 LOG ($verbose_exec, "subproc exited normally.");
2945 } elsif (($rc & 0xff) == 0) {
2947 LOG ($verbose_exec, "subproc exited with status $rc.");
2950 LOG ($verbose_exec, "subproc dumped core.");
2953 LOG ($verbose_exec, "subproc died with signal $rc.");
2954 # die that way ourselves.
2962 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2963 # writes a PPM to the given output file. Returns the width/height of the
2964 # image if successful.
2966 sub image_to_pnm($$$) {
2967 my ($url, $body, $output) = @_;
2968 my ($cmd, $cmd2, $w, $h);
2970 if ((@_ = gif_size ($body))) {
2973 } elsif ((@_ = jpeg_size ($body))) {
2976 } elsif ((@_ = png_size ($body))) {
2980 LOG (($verbose_pbm || $verbose_load),
2981 "not a GIF, JPG, or PNG" .
2982 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2983 ? " (looks like HTML)" : "") .
2985 $suppress_audit = 1;
2989 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2990 # do this, the process doesn't die properly.
2991 if (!$verbose_pbm) {
2993 # We get a "giftopnm: got a 'Application Extension' extension"
2994 # warning any time it's an animgif.
2996 # Note that "giftopnm: EOF / read error on image data" is not
2997 # always a fatal error -- sometimes the image looks fine anyway.
2999 $cmd2 .= " 2>/dev/null";
3002 # There exist corrupted GIF and JPEG files that can make giftopnm and
3003 # djpeg lose their minds and go into a loop. So this gives those programs
3004 # a small timeout -- if they don't complete in time, kill them.
3010 local $SIG{ALRM} = sub {
3012 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3013 kill ('TERM', $pid) if ($pid);
3018 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3025 LOG ($verbose_exec, "awaiting $pid");
3027 LOG ($verbose_exec, "$pid completed");
3029 my $size = (stat($output))[7];
3030 $size = -1 unless defined($size);
3032 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3036 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3039 print STDERR blurb() . "$cmd failed: $!\n";
3043 die if ($@ && $@ ne "alarm\n"); # propagate errors
3057 # Same as the "ppmmake" command: creates a solid-colored PPM.
3058 # Does not understand the rgb.txt color names except "black" and "white".
3061 my ($outfile, $bgcolor, $w, $h) = @_;
3064 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3065 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3066 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3067 } elsif ($bgcolor =~ m/^black$/i) {
3068 ($r, $g, $b) = (0, 0, 0);
3069 } elsif ($bgcolor =~ m/^white$/i) {
3070 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3072 error ("unparsable color name: $bgcolor");
3075 my $pixel = pack('CCC', $r, $g, $b);
3076 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3078 open (my $out, '>', $outfile) || error ("$outfile: $!");
3084 sub pick_root_displayer() {
3088 # see "xscreensaver/hacks/webcollage-cocoa.m"
3089 return "echo COCOA LOAD ";
3092 foreach my $cmd (@root_displayers) {
3094 my ($name) = m/^([^ ]+)/;
3095 push @names, "\"$name\"";
3096 LOG ($verbose_exec, "looking for $name...");
3097 foreach my $dir (split (/:/, $ENV{PATH})) {
3098 LOG ($verbose_exec, " checking $dir/$name");
3099 return $cmd if (-x "$dir/$name");
3103 $names[$#names] = "or " . $names[$#names];
3104 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3108 my $ppm_to_root_window_cmd = undef;
3111 sub x_or_pbm_output($) {
3112 my ($window_id) = @_;
3114 # Check for our helper program, to see whether we need to use PPM pipelines.
3116 $_ = "webcollage-helper";
3117 if (defined ($webcollage_helper) || which ($_)) {
3118 $webcollage_helper = $_ unless (defined($webcollage_helper));
3119 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3120 $webcollage_helper .= " -v";
3122 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3125 if ($cocoa_p && !defined ($webcollage_helper)) {
3126 error ("webcollage-helper not found in Cocoa-mode!");
3130 # make sure the various programs we execute exist, right up front.
3134 if (!defined($webcollage_helper)) {
3135 # Only need these others if we don't have the helper.
3137 "giftopnm", "pngtopnm", "djpeg",
3138 "pnmpaste", "pnmscale", "pnmcut");
3142 which ($_) || error "$_ not found on \$PATH.";
3145 # find a root-window displayer program.
3147 if (!$no_output_p) {
3148 $ppm_to_root_window_cmd = pick_root_displayer();
3151 if (defined ($window_id)) {
3152 error ("-window-id only works if xscreensaver-getimage is installed")
3153 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3155 error ("unparsable window id: $window_id")
3156 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3157 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3158 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3161 if (!$img_width || !$img_height) {
3163 if (!defined ($window_id) &&
3164 defined ($ENV{XSCREENSAVER_WINDOW})) {
3165 $window_id = $ENV{XSCREENSAVER_WINDOW};
3168 if (!defined ($window_id)) {
3170 which ($_) || error "$_ not found on \$PATH.";
3172 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3173 if (!defined($img_height)) {
3174 error "xdpyinfo failed.";
3176 } else { # we have a window id
3178 which ($_) || error "$_ not found on \$PATH.";
3179 $_ .= " -id $window_id";
3181 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3183 if (!defined($img_height)) {
3184 error "xwininfo failed.";
3189 my $bgcolor = "#000000";
3190 my $bgimage = undef;
3193 if ($background =~ m/^\#[0-9a-f]+$/i) {
3194 $bgcolor = $background;
3196 } elsif (-r $background) {
3197 $bgimage = $background;
3199 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3200 error "not a color or readable file: $background";
3203 # default to assuming it's a color
3204 $bgcolor = $background;
3208 # Create the sold-colored base image.
3210 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3211 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3213 # Paste the default background image in the middle of it.
3219 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3220 local $/ = undef; # read entire file
3225 if ((@_ = gif_size ($body))) {
3227 $cmd = "giftopnm |";
3229 } elsif ((@_ = jpeg_size ($body))) {
3233 } elsif ((@_ = png_size ($body))) {
3235 $cmd = "pngtopnm |";
3237 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3243 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3246 my $x = int (($img_width - $iw) / 2);
3247 my $y = int (($img_height - $ih) / 2);
3249 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3251 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3252 open ($imgf, "| $cmd") || error "running $cmd: $!";
3256 LOG ($verbose_exec, "subproc exited normally.");
3257 rename ($image_tmp1, $image_ppm) ||
3258 error "renaming $image_tmp1 to $image_ppm: $!";
3264 my ($base, $img) = pick_image();
3265 my $source = $current_state;
3266 $current_state = "loadimage";
3268 my ($headers, $body) = get_document ($img, $base);
3270 paste_image ($base, $img, $body, $source);
3274 $current_state = "idle";
3275 $load_method = "none";
3277 unlink $image_tmp1, $image_tmp2;
3282 sub paste_image($$$$) {
3283 my ($base, $img, $body, $source) = @_;
3285 $current_state = "paste";
3287 $suppress_audit = 0;
3289 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3293 # If we are using the webcollage-helper, then we do not need to convert this
3294 # image to a PPM. But, if we're using a filter command, we still must, since
3295 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3298 if (defined ($webcollage_helper) &&
3299 !defined ($filter_cmd)) {
3301 ($iw, $ih) = image_size ($body);
3303 LOG (($verbose_pbm || $verbose_load),
3304 "not a GIF, JPG, or PNG" .
3305 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3306 ? " (looks like HTML)" : "") .
3308 $suppress_audit = 1;
3313 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3314 (print $out $body) || error ("writing $image_tmp1: $!");
3315 close ($out) || error ("writing $image_tmp1: $!");
3318 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3321 LOG ($verbose_pbm, "unable to make PBM from $img");
3326 record_success ($load_method, $img, $base);
3329 my $ow = $iw; # used only for error messages
3332 # don't just tack this onto the front of the pipeline -- we want it to
3333 # be able to change the size of the input image.
3336 LOG ($verbose_pbm, "running $filter_cmd");
3338 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3340 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3341 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3344 rename ($image_tmp2, $image_tmp1);
3346 # re-get the width/height in case the filter resized it.
3347 open (my $imgf, '<', $image_tmp1) || return 0;
3350 ($iw, $ih) = m/^(\d+) (\d+)$/;
3352 return 0 unless ($iw && $ih);
3355 my $target_w = $img_width; # max rectangle into which the image must fit
3356 my $target_h = $img_height;
3362 # Usually scale the image to fit on the screen -- but sometimes scale it
3363 # to fit on half or a quarter of the screen. (We do this by reducing the
3364 # size of the target rectangle.) Note that the image is not merely scaled
3365 # to fit; we instead cut the image in half repeatedly until it fits in the
3366 # target rectangle -- that gives a wider distribution of sizes.
3368 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3369 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3371 if ($iw > $target_w || $ih > $target_h) {
3372 while ($iw > $target_w ||
3378 if ($iw <= 10 || $ih <= 10) {
3379 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3383 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3385 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3389 my $src = $image_tmp1;
3391 my $crop_x = 0; # the sub-rectangle of the image
3392 my $crop_y = 0; # that we will actually paste.
3396 # The chance that we will randomly crop out a section of an image starts
3397 # out fairly low, but goes up for images that are very large, or images
3398 # that have ratios that make them look like banners (we try to avoid
3399 # banner images entirely, but they slip through when the IMG tags didn't
3400 # have WIDTH and HEIGHT specified.)
3402 my $crop_chance = 0.2;
3403 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3404 $crop_chance += 0.2;
3406 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3407 $crop_chance += 0.2;
3409 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3410 $crop_chance += 0.7;
3413 if ($crop_chance > 0.1) {
3414 LOG ($verbose_pbm, "crop chance: $crop_chance");
3417 if (rand() < $crop_chance) {
3422 if ($crop_w > $min_width) {
3423 # if it's a banner, select the width linearly.
3424 # otherwise, select a bell.
3425 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3428 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3429 $crop_x = int (rand() * ($ow - $crop_w));
3431 if ($crop_h > $min_height) {
3432 # height always selects as a bell.
3433 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3434 $crop_y = int (rand() * ($oh - $crop_h));
3437 if ($crop_x != 0 || $crop_y != 0 ||
3438 $crop_w != $iw || $crop_h != $ih) {
3440 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3444 # Where the image should logically land -- this might be negative.
3446 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3447 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3449 # if we have chosen to paste the image outside of the rectangle of the
3450 # screen, then we need to crop it.
3454 $x + $crop_w > $img_width ||
3455 $y + $crop_h > $img_height) {
3458 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3460 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3461 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3463 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3464 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3467 # If any cropping needs to happen, add pnmcut.
3469 if ($crop_x != 0 || $crop_y != 0 ||
3470 $crop_w != $iw || $crop_h != $ih) {
3473 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3474 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3477 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3479 $cmd .= " | pnmpaste - $x $y $image_ppm";
3481 $cmd =~ s@^ *\| *@@;
3483 if (defined ($webcollage_helper)) {
3484 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3485 "$scale $opacity " .
3486 "$crop_x $crop_y $x $y " .
3491 # use a PPM pipeline
3493 $_ .= " < $image_tmp1 > $image_tmp2";
3497 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3499 $_ .= " 2> /dev/null";
3502 my $rc = nontrapping_system ($_);
3504 if (defined ($webcollage_helper) && -z $image_ppm) {
3505 LOG (1, "failed command: \"$cmd\"");
3506 print STDERR "\naudit log:\n\n\n";
3507 print STDERR ("#" x 78) . "\n";
3508 print STDERR blurb() . "$image_ppm has zero size\n";
3510 print STDERR "\n\n";
3515 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3516 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3520 if (!defined ($webcollage_helper)) {
3521 rename ($image_tmp2, $image_ppm) || return;
3524 my $target = "$image_ppm";
3526 # don't just tack this onto the end of the pipeline -- we don't want it
3527 # to end up in $image_ppm, because we don't want the results to be
3530 if ($post_filter_cmd) {
3534 $target = $image_tmp1;
3535 if (!defined ($webcollage_helper)) {
3536 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3538 # Blah, my scripts need the JPEG data, but some other folks need
3539 # the PPM data -- what to do? Ignore the problem, that's what!
3540 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3541 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3544 $rc = nontrapping_system ($cmd);
3546 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3551 if (!$no_output_p) {
3552 my $tsize = (stat($target))[7];
3554 $cmd = "$ppm_to_root_window_cmd $target";
3556 # xv seems to hate being killed. it tends to forget to clean
3557 # up after itself, and leaves windows around and colors allocated.
3558 # I had this same problem with vidwhacker, and I'm not entirely
3559 # sure what I did to fix it. But, let's try this: launch xv
3560 # in the background, so that killing this process doesn't kill it.
3561 # it will die of its own accord soon enough. So this means we
3562 # start pumping bits to the root window in parallel with starting
3563 # the next network retrieval, which is probably a better thing
3566 $cmd .= " &" unless ($cocoa_p);
3568 $rc = nontrapping_system ($cmd);
3571 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3576 LOG ($verbose_pbm, "$target size is $tsize");
3580 $source .= "-" . stats_of($source);
3581 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3582 if ($verbose_imgmap);
3583 if ($imagemap_base) {
3584 update_imagemap ($base, $x, $y, $iw, $ih,
3585 $image_ppm, $img_width, $img_height);
3594 sub update_imagemap($$$$$$$$) {
3595 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3597 $current_state = "imagemap";
3599 my $max_areas = 200;
3601 $url = html_quote ($url);
3604 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3605 unshift @imagemap_areas, $area; # put one on the front
3606 if ($#imagemap_areas >= $max_areas) {
3607 pop @imagemap_areas; # take one off the back.
3610 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3612 my $map_name = $imagemap_base;
3613 $map_name =~ s@^.*/@@;
3614 $map_name = 'collage' if ($map_name eq '');
3616 my $imagemap_html = $imagemap_base . ".html";
3617 my $imagemap_jpg = $imagemap_base . ".jpg";
3618 my $imagemap_jpg2 = $imagemap_jpg;
3619 $imagemap_jpg2 =~ s@^.*/@@gs;
3621 if (!defined ($imagemap_html_tmp)) {
3622 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3623 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3626 # Read the imagemap html file (if any) to get a template.
3628 my $template_html = '';
3630 if (open (my $in, '<', $imagemap_html)) {
3631 local $/ = undef; # read entire file
3632 $template_html = <$in>;
3634 LOG ($verbose_pbm, "read template $imagemap_html");
3637 if ($template_html =~ m/^\s*$/s) {
3638 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3639 "<IMG SRC=\"$imagemap_jpg2\"" .
3640 " USEMAP=\"$map_name\">\n");
3641 LOG ($verbose_pbm, "created dummy template");
3645 # Write the jpg to a tmp file
3649 if (defined ($webcollage_helper)) {
3650 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3652 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3654 my $rc = nontrapping_system ($cmd);
3656 error ("imagemap jpeg failed: \"$cmd\"\n");
3660 # Write the html to a tmp file
3663 my $body = $template_html;
3664 my $areas = join ("\n\t", @imagemap_areas);
3665 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3666 my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3668 "WIDTH=$image_width HEIGHT=$image_height " .
3669 "USEMAP=\"#$map_name\">");
3670 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3671 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3673 # if there are magic webcollage spans in the html, update those too.
3676 my @st = stat ($imagemap_jpg_tmp);
3677 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3678 my $size = int(($st[7] / 1024) + 0.5) . "K";
3679 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3680 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3683 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3684 (print $out $body) || error ("$imagemap_html_tmp: $!");
3685 close ($out) || error ("$imagemap_html_tmp: $!");
3686 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3689 # Rename the two tmp files to the real files
3691 rename ($imagemap_html_tmp, $imagemap_html) ||
3692 error "renaming $imagemap_html_tmp to $imagemap_html";
3693 LOG ($verbose_pbm, "wrote $imagemap_html");
3694 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3695 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3696 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3700 # Figure out what the proxy server should be, either from environment
3701 # variables or by parsing the output of the (MacOS) program "scutil",
3702 # which tells us what the system-wide proxy settings are.
3706 if (! $http_proxy) {
3707 # historical suckage: the environment variable name is lower case.
3708 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3711 if (defined ($http_proxy)) {
3712 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3713 # historical suckage: allow "http://host:port" as well as "host:port".
3718 my $proxy_data = `scutil --proxy 2>/dev/null`;
3719 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3720 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3721 # Note: this ignores the "ExceptionsList".
3723 $http_proxy = $server;
3724 $http_proxy .= ":$port" if $port;
3729 LOG ($verbose_net, "proxy server: $http_proxy");
3734 sub init_signals() {
3736 $SIG{HUP} = \&signal_cleanup;
3737 $SIG{INT} = \&signal_cleanup;
3738 $SIG{QUIT} = \&signal_cleanup;
3739 $SIG{ABRT} = \&signal_cleanup;
3740 $SIG{KILL} = \&signal_cleanup;
3741 $SIG{TERM} = \&signal_cleanup;
3743 # Need this so that if giftopnm dies, we don't die.
3744 $SIG{PIPE} = 'IGNORE';
3747 END { exit_cleanup(); }
3756 my $driftnet_cmd = 0;
3758 $current_state = "init";
3759 $load_method = "none";
3762 my $window_id = undef;
3764 while ($_ = $ARGV[0]) {
3766 if ($_ eq "-display" ||
3772 $ENV{DISPLAY} = shift @ARGV;
3773 } elsif ($_ eq "-root") {
3775 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3776 $window_id = shift @ARGV;
3778 } elsif ($_ eq "-no-output") {
3780 } elsif ($_ eq "-urls-only") {
3783 } elsif ($_ eq "-cocoa") {
3785 } elsif ($_ eq "-imagemap") {
3786 $imagemap_base = shift @ARGV;
3788 } elsif ($_ eq "-verbose") {
3790 } elsif (m/^-v+$/) {
3791 $verbose += length($_)-1;
3792 } elsif ($_ eq "-delay") {
3793 $delay = shift @ARGV;
3794 } elsif ($_ eq "-timeout") {
3795 $http_timeout = shift @ARGV;
3796 } elsif ($_ eq "-filter") {
3797 $filter_cmd = shift @ARGV;
3798 } elsif ($_ eq "-filter2") {
3799 $post_filter_cmd = shift @ARGV;
3800 } elsif ($_ eq "-background" || $_ eq "-bg") {
3801 $background = shift @ARGV;
3802 } elsif ($_ eq "-size") {
3804 if (m@^(\d+)x(\d+)$@) {
3808 error "argument to \"-size\" must be of the form \"640x400\"";
3810 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3811 $http_proxy = shift @ARGV;
3812 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3813 $dict = shift @ARGV;
3814 } elsif ($_ eq "-opacity") {
3815 $opacity = shift @ARGV;
3816 error ("opacity must be between 0.0 and 1.0")
3817 if ($opacity <= 0 || $opacity > 1);
3818 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3819 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3820 if (! ($ARGV[0] =~ m/^-/)) {
3821 $driftnet_cmd = shift @ARGV;
3823 $driftnet_cmd = $default_driftnet_cmd;
3825 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3826 @search_methods = ( 100, "local", \&pick_from_local_dir );
3827 if (! ($ARGV[0] =~ m/^-/)) {
3828 $local_dir = shift @ARGV;
3830 error ("local directory path must be set")
3832 } elsif ($_ eq "-fps") {
3833 # -fps only works on MacOS, via "webcollage-cocoa.m".
3834 # Ignore it if passed to this script in an X11 context.
3835 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3836 my $which = shift @ARGV;
3837 my @rest = @search_methods;
3840 my $pct = shift @rest;
3841 my $name = shift @rest;
3842 my $tfn = shift @rest;
3844 if ($name eq $which) {
3845 @search_methods = (100, $name, $tfn);
3850 error "no such search method as \"$which\"" unless ($ok);
3851 LOG (1, "DEBUG: using only \"$which\"");
3854 print STDERR "$copyright\nusage: $progname " .
3855 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3856 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3857 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3858 "\t\t [-background color] [-opacity f]\n" .
3859 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3860 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3861 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3862 "\t\t [-directory local-image-directory]\n" .
3868 if (!$root_p && !$no_output_p && !$cocoa_p) {
3869 print STDERR $copyright;
3870 error "the -root argument is mandatory (for now.)";
3873 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3874 error "\$DISPLAY is not set.";
3878 if ($verbose == 1) {
3879 $verbose_imgmap = 1;
3880 $verbose_warnings = 1;
3882 } elsif ($verbose == 2) {
3883 $verbose_imgmap = 1;
3884 $verbose_warnings = 1;
3887 } elsif ($verbose == 3) {
3888 $verbose_imgmap = 1;
3889 $verbose_warnings = 1;
3891 $verbose_filter = 1;
3893 } elsif ($verbose == 4) {
3894 $verbose_imgmap = 1;
3895 $verbose_warnings = 1;
3897 $verbose_filter = 1;
3900 } elsif ($verbose == 5) {
3901 $verbose_imgmap = 1;
3902 $verbose_warnings = 1;
3904 $verbose_filter = 1;
3908 } elsif ($verbose == 6) {
3909 $verbose_imgmap = 1;
3910 $verbose_warnings = 1;
3912 $verbose_filter = 1;
3917 } elsif ($verbose >= 7) {
3918 $verbose_imgmap = 1;
3919 $verbose_warnings = 1;
3921 $verbose_filter = 1;
3929 error ("$dict does not exist") unless (-f $dict);
3935 if ($imagemap_base && !($img_width && $img_height)) {
3936 error ("-size WxH is required with -imagemap");
3939 if (defined ($local_dir)) {
3940 $_ = "xscreensaver-getimage-file";
3941 which ($_) || error "$_ not found on \$PATH.";
3947 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3952 x_or_pbm_output ($window_id);