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.167 $' =~ 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,
247 "cdninstagram.com" => 1,
249 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
250 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
251 # hits this every time.
253 "images.quizfarm.com" => 1, # damn those LJ quizzes...
254 "images.quizilla.com" => 1,
255 "images.quizdiva.net" => 1,
257 "driftnet" => 1, # builtin...
258 "local-directory" => 1, # builtin...
262 # For decoding HTML-encoded character entities to URLs.
266 "quot" => '"', "amp" => '&', "lt" => '<',
267 "gt" => '>', "nbsp" => ' ', "iexcl" => '',
268 "cent" => "\xA2", "pound" => "\xA3", "curren" => "\xA4",
269 "yen" => "\xA5", "brvbar" => "\xA6", "sect" => "\xA7",
270 "uml" => "\xA8", "copy" => "\xA9", "ordf" => "\xAA",
271 "laquo" => "\xAB", "not" => "\xAC", "shy" => "\xAD",
272 "reg" => "\xAE", "macr" => "\xAF", "deg" => "\xB0",
273 "plusmn" => "\xB1", "sup2" => "\xB2", "sup3" => "\xB3",
274 "acute" => "\xB4", "micro" => "\xB5", "para" => "\xB6",
275 "middot" => "\xB7", "cedil" => "\xB8", "sup1" => "\xB9",
276 "ordm" => "\xBA", "raquo" => "\xBB", "frac14" => "\xBC",
277 "frac12" => "\xBD", "frac34" => "\xBE", "iquest" => "\xBF",
278 "Agrave" => "\xC0", "Aacute" => "\xC1", "Acirc" => "\xC2",
279 "Atilde" => "\xC3", "Auml" => "\xC4", "Aring" => "\xC5",
280 "AElig" => "\xC6", "Ccedil" => "\xC7", "Egrave" => "\xC8",
281 "Eacute" => "\xC9", "Ecirc" => "\xCA", "Euml" => "\xCB",
282 "Igrave" => "\xCC", "Iacute" => "\xCD", "Icirc" => "\xCE",
283 "Iuml" => "\xCF", "ETH" => "\xD0", "Ntilde" => "\xD1",
284 "Ograve" => "\xD2", "Oacute" => "\xD3", "Ocirc" => "\xD4",
285 "Otilde" => "\xD5", "Ouml" => "\xD6", "times" => "\xD7",
286 "Oslash" => "\xD8", "Ugrave" => "\xD9", "Uacute" => "\xDA",
287 "Ucirc" => "\xDB", "Uuml" => "\xDC", "Yacute" => "\xDD",
288 "THORN" => "\xDE", "szlig" => "\xDF", "agrave" => "\xE0",
289 "aacute" => "\xE1", "acirc" => "\xE2", "atilde" => "\xE3",
290 "auml" => "\xE4", "aring" => "\xE5", "aelig" => "\xE6",
291 "ccedil" => "\xE7", "egrave" => "\xE8", "eacute" => "\xE9",
292 "ecirc" => "\xEA", "euml" => "\xEB", "igrave" => "\xEC",
293 "iacute" => "\xED", "icirc" => "\xEE", "iuml" => "\xEF",
294 "eth" => "\xF0", "ntilde" => "\xF1", "ograve" => "\xF2",
295 "oacute" => "\xF3", "ocirc" => "\xF4", "otilde" => "\xF5",
296 "ouml" => "\xF6", "divide" => "\xF7", "oslash" => "\xF8",
297 "ugrave" => "\xF9", "uacute" => "\xFA", "ucirc" => "\xFB",
298 "uuml" => "\xFC", "yacute" => "\xFD", "thorn" => "\xFE",
301 # HTML 4 entities that do not have 1:1 Latin1 mappings.
302 "bull" => "*", "hellip"=> "...", "prime" => "'", "Prime" => "\"",
303 "frasl" => "/", "trade" => "[tm]", "larr" => "<-", "rarr" => "->",
304 "harr" => "<->", "lArr" => "<=", "rArr" => "=>", "hArr" => "<=>",
305 "empty" => "\xD8", "minus" => "-", "lowast"=> "*", "sim" => "~",
306 "cong" => "=~", "asymp" => "~", "ne" => "!=", "equiv" => "==",
307 "le" => "<=", "ge" => ">=", "lang" => "<", "rang" => ">",
308 "loz" => "<>", "OElig" => "OE", "oelig" => "oe", "Yuml" => "Y",
309 "circ" => "^", "tilde" => "~", "ensp" => " ", "emsp" => " ",
310 "thinsp"=> " ", "ndash" => "-", "mdash" => "--", "lsquo" => "`",
311 "rsquo" => "'", "sbquo" => "'", "ldquo" => "\"", "rdquo" => "\"",
312 "bdquo" => "\"", "lsaquo"=> "<", "rsaquo"=> ">",
316 ##############################################################################
318 # Various global flags set by command line parameters, or computed
320 ##############################################################################
323 my $current_state = "???"; # for diagnostics
326 my $image_succeeded = -1;
327 my $suppress_audit = 0;
329 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
330 my $verbose_warnings = 0; # print out warnings when things go wrong
331 my $verbose_load = 0; # diagnostics about loading of URLs
332 my $verbose_filter = 0; # diagnostics about page selection/rejection
333 my $verbose_net = 0; # diagnostics about network I/O
334 my $verbose_pbm = 0; # diagnostics about PBM pipelines
335 my $verbose_http = 0; # diagnostics about all HTTP activity
336 my $verbose_exec = 0; # diagnostics about executing programs
338 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
340 my $http_proxy = undef;
341 my $http_timeout = 20;
342 my $cvt_timeout = 10;
348 my $min_gif_area = (120 * 120);
354 my $imagemap_base = undef;
356 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
358 my $driftnet_magic = 'driftnet';
359 my $driftnet_dir = undef;
360 my $default_driftnet_cmd = "driftnet -a -m 100";
362 my $local_magic = 'local-directory';
363 my $local_dir = undef;
368 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
369 "arrhenius", "arteriole", "blanket", "brainchild",
370 "burdensome", "carnival", "cherub", "chord", "clever",
371 "dedicate", "dilogarithm", "dolan", "dryden",
375 ##############################################################################
379 ##############################################################################
381 # returns three values: the HTTP response line; the document headers;
382 # and the document body.
384 sub get_document_1($$$) {
385 my ($url, $referer, $timeout) = @_;
387 if (!defined($timeout)) { $timeout = $http_timeout; }
388 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
390 my $user_agent = "$progname/$version";
392 if ($url =~ m@^http://www\.altavista\.com/@ ||
393 $url =~ m@^http://random\.yahoo\.com/@ ||
394 $url =~ m@^http://images\.google\.com/@ ||
395 $url =~ m@^http://www\.google\.com/@) {
396 # block this, you turkeys.
397 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)" .
398 " Gecko/20070914 Firefox/2.0.0.7";
400 # 28-Jun-2007: Google Images now emits the entire page in JS if
401 # you claim to be Gecko. They also still block "webcollage".
402 # They serve non-JS for unrecognised agents, so let's try this...
403 $user_agent = "NoJavascriptPlease/1.0"
404 if ($url =~ m@^http://[a-z]+\.google\.com/@);
407 my $ua = LWP::UserAgent->new;
409 $ua->agent ("$progname/$version");
410 $ua->default_header ('Referer' => $referer);
411 $ua->timeout($timeout) if $timeout;
414 LOG (1, " ==> GET $url");
415 LOG (1, " ==> User-Agent: $user_agent");
416 LOG (1, " ==> Referer: $referer") if $referer;
419 my $res = $ua->get ($url);
421 my $http = ($res ? $res->status_line : '') || '';
422 my $head = ($res ? $res->headers()->as_string : '') || '';
423 my $body = ($res && $res->is_success ? $res->decoded_content : '') || '';
425 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
427 $head =~ s/\r\n/\n/gs;
430 foreach (split (/\n/, $head)) {
431 LOG ($verbose_http, " <== $_");
435 my @L = split(/\r\n|\r|\n/, $body);
438 " <== [ body ]: $lines lines, " . length($body) . " bytes");
441 LOG (($verbose_net || $verbose_load), "null response: $url");
445 return ( $http, $head, $body );
449 # returns two values: the document headers; and the document body.
450 # if the given URL did a redirect, returns the redirected-to document.
452 sub get_document($$;$) {
453 my ($url, $referer, $timeout) = @_;
456 if (defined($referer) && $referer eq $driftnet_magic) {
457 return get_driftnet_file ($url);
460 if (defined($referer) && $referer eq $local_magic) {
461 return get_local_file ($url);
466 my $max_loop_count = 4;
469 if (defined($timeout) && $timeout <= 0) {
470 LOG (($verbose_net || $verbose_load), "timed out for $url");
475 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
477 if (defined ($timeout)) {
479 my $elapsed = $now - $start;
480 $timeout -= $elapsed;
484 return () unless $http; # error message already printed
486 $http =~ s/[\r\n]+$//s;
488 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
491 my ( $location ) = m@^location:[ \t]*(.*)$@im;
493 $location =~ s/[\r\n]$//;
495 LOG ($verbose_net, "redirect from $url to $location");
500 $referer =~ m@^(http://[^/]+)@i;
502 } elsif (! ($url =~ m@^[a-z]+:@i)) {
504 s@[^/]+$@@g if m@^http://[^/]+/@i;
505 $_ .= "/" if m@^http://[^/]+$@i;
510 LOG ($verbose_net, "no Location with \"$http\"");
511 return ( $url, $body );
514 if ($loop_count++ > $max_loop_count) {
516 "too many redirects ($max_loop_count) from $orig_url");
521 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
523 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
525 # http errors -- return nothing.
531 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
537 return ( $url, $body );
543 # If we already have a cookie defined for this site, and the site is trying
544 # to overwrite that very same cookie, let it do so. This is because nytimes
545 # expires its cookies - it lets you upgrade to a new cookie without logging
546 # in again, but you have to present the old cookie to get the new cookie.
547 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
550 my ($host, $cookie) = @_;
551 my $oc = $cookies{$host};
554 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
556 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
558 if ($oc_name eq $nc_name &&
559 $oc_value ne $nc_value) {
560 $cookies{$host} = $cookie;
561 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
566 ############################################################################
568 # Extracting image URLs from HTML
570 ############################################################################
572 # given a URL and the body text at that URL, selects and returns a random
573 # image from it. returns () if no suitable images found.
575 sub pick_image_from_body($$) {
576 my ($url, $body) = @_;
581 # if there's at least one slash after the host, take off the last
583 if ( m@^http://[^/]+/@io ) {
584 $base =~ s@[^/]+$@@go;
587 # if there are no slashes after the host at all, put one on the end.
588 if ( m@^http://[^/]+$@io ) {
594 # strip out newlines, compress whitespace
601 # There are certain web sites that list huge numbers of dictionary
602 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
603 # Porn sites tend not to be reputable!)
605 # I do not want webcollage to filter on content: I want it to select
606 # randomly from the set of images on the web. All the logic here for
607 # rejecting some images is really a set of heuristics for rejecting
608 # images that are not really images: for rejecting *text* that is in
609 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
610 # the content of the pictures to be randomly selected from among all
611 # the available content.
613 # So, filtering out "dirty" pictures by looking for "dirty" keywords
614 # would be wrong: dirty pictures exist, like it or not, so webcollage
615 # should be able to select them.
617 # However, picking a random URL is a hard thing to do. The mechanism I'm
618 # using is to search for a selection of random words. This is not
619 # perfect, but works ok most of the time. The way it breaks down is when
620 # some URLs get precedence because their pages list *every word* as
621 # related -- those URLs come up more often than others.
623 # So, after we've retrieved a URL, if it has too many keywords, reject
624 # it. We reject it not on the basis of what those keywords are, but on
625 # the basis that by having so many, the page has gotten an unfair
626 # advantage against our randomizer.
629 foreach my $trip (@tripwire_words) {
630 $trip_count++ if m/$trip/i;
633 if ($trip_count >= $#tripwire_words - 2) {
634 LOG (($verbose_filter || $verbose_load),
635 "there is probably a dictionary in \"$url\": rejecting.");
636 $rejected_urls{$url} = -1;
646 foreach (split(/ *</)) {
647 if ( m/^meta.*["']keywords["']/i ) {
649 # Likewise, reject any web pages that have a KEYWORDS meta tag
654 LOG (($verbose_filter || $verbose_load),
655 "excessive keywords ($L bytes) in $url: rejecting.");
656 $rejected_urls{$url} = $L;
661 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
664 } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
665 m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
666 ["']? (image_src|og:image) ["']? /six) {
668 my $was_inline = (lc($1) eq 'img');
669 my $was_meta = (lc($1) eq 'link' || lc($1) eq 'meta');
672 # For <link rel="image_src" href="...">
673 # and <meta property="og:image" content="...">
676 next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
680 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
681 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
686 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
688 } elsif ( ! m@^[^/:?]+:@ ) {
691 1 while (s@/[^/]+/\.\./@/@g);
695 if ( ! m@^http://@io ) {
700 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
704 # skip really short or really narrow images
705 if ( $width && $width < $min_width) {
706 if (!$height) { $height = "?"; }
707 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
711 if ( $height && $height < $min_height) {
712 if (!$width) { $width = "?"; }
713 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
717 # skip images with ratios that make them look like banners.
718 if ($min_ratio && $width && $height &&
719 ($width * $min_ratio ) > $height) {
720 if (!$height) { $height = "?"; }
721 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
725 # skip GIFs with a small number of pixels -- those usually suck.
726 if ($width && $height &&
728 ($width * $height) < $min_gif_area) {
729 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
733 # skip images with a URL that indicates a Yahoo thumbnail.
734 if (m@\.yimg\.com/.*/t/@) {
735 if (!$width) { $width = "?"; }
736 if (!$height) { $height = "?"; }
737 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
743 if ($unique_urls{$url}) {
744 LOG ($verbose_filter, " skip duplicate image $_");
748 LOG ($verbose_filter,
750 ($width && $height ? " (${width}x${height})" : "") .
751 ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
757 $weight = 20; # meta tag images are far preferable to inline images.
759 if ($url !~ m@[.](gif|png)$@io ) {
760 $weight += 2; # JPEGs are preferable to GIFs and PNGs.
763 $weight += 4; # pointers to images are preferable to inlined images.
767 $unique_urls{$url}++;
768 for (my $i = 0; $i < $weight; $i++) {
769 $urls[++$#urls] = $url;
774 my $fsp = ($body =~ m@<frameset@i);
779 @urls = depoison (@urls);
782 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
786 # pick a random element of the table
787 my $i = int(rand($#urls+1));
790 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
796 # Given a URL and the RSS feed from that URL, pick a random image from
797 # the feed. This is a lot simpler than extracting images out of a page:
798 # we already know we have reasonable images, so we just pick one.
799 # Returns: the real URL of the page (preferably not the RSS version),
802 sub pick_image_from_rss($$) {
803 my ( $url, $body ) = @_;
804 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
806 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
807 $base = $url unless $base;
809 # pick a random element of the table
811 my $i = int(rand(scalar @suitable));
812 my $url = $suitable[$i];
813 LOG ($verbose_load, "picked image " .($i+1) . "/" .
814 ($#suitable+1) . ": $url");
815 return ($base, $url);
821 ############################################################################
823 # Subroutines for getting pages and images out of search engines
825 ############################################################################
828 sub pick_dictionary() {
829 my @dicts = ("/usr/dict/words",
830 "/usr/share/dict/words",
831 "/usr/share/lib/dict/words",
832 "/usr/share/dict/cracklib-small",
833 "/usr/share/dict/cracklib-words"
835 foreach my $f (@dicts) {
841 error ("$dicts[0] does not exist") unless defined($wordlist);
844 # returns a random word from the dictionary
848 return undef unless open (my $in, '<', $wordlist);
850 my $size = (stat($in))[7];
855 error ("looping ($count) while reading $wordlist")
858 my $pos = int (rand ($size));
859 if (seek ($in, $pos, 0)) {
860 $word = <$in>; # toss partial line
861 $word = <$in>; # keep next line
865 next if ($word =~ m/^[-\']/);
869 $word =~ s/^[^a-z]+//s;
870 $word =~ s/[^a-z]+$//s;
876 $word =~ s/ally$/al/s;
877 $word =~ s/izes$/ize/s;
878 $word =~ s/esses$/ess/s;
879 $word =~ s/(.{5})ing$/$1/s;
881 next if (length ($word) > 14);
887 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
888 $word = "\%22$word\%22"; # And put quotes (%22) around it.
895 sub random_words($) {
897 return (random_word() . $sep .
898 random_word() . $sep .
899 random_word() . $sep .
900 random_word() . $sep .
907 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
914 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
923 $s =~ s/\"/"/gi;
927 sub html_unquote($) {
929 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
930 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
935 # Loads the given URL (a search on some search engine) and returns:
936 # - the total number of hits the search engine claimed it had;
937 # - a list of URLs from the page that the search engine returned;
938 # Note that this list contains all kinds of internal search engine
939 # junk URLs too -- caller must prune them.
941 sub pick_from_search_engine($$$) {
942 my ( $timeout, $search_url, $words ) = @_;
947 print STDERR "\n\n" if ($verbose_load);
949 LOG ($verbose_load, "words: $_");
950 LOG ($verbose_load, "URL: $search_url");
952 $last_search = $search_url; # for warnings
955 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
956 if (defined ($timeout)) {
957 $timeout -= (time - $start);
960 LOG (($verbose_net || $verbose_load),
961 "timed out (late) for $search_url");
967 return () if (! $body);
972 if ($body =~ m/^\{\"/s) { # Google AJAX JSON response.
974 my @chunks = split (/"GsearchResultClass"/, $body);
979 my ($img) = m/"unescapedUrl":"(.*?)"/si;
980 my ($url) = m/"originalContextUrl":"(.*?)"/si;
981 next unless ($img && $url);
983 "?imgurl=" . url_quote($img) .
984 "&imgrefurl=" . url_quote($url) .
986 $body2 .= "<A HREF=\"" . html_quote($url) . "\">$n</A>\n";
989 $body = $body2 if $body2;
992 my $search_count = "?";
993 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
995 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
997 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
999 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1001 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1003 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1005 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1007 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1009 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1010 $search_count = $1; # lycos
1011 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1012 $search_count = $1; # hotbot
1013 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1014 $search_count = "0";
1015 } elsif ($body =~ m@found no document matching@i) { # avtext
1016 $search_count = "0";
1018 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1020 # if ($search_count eq "?" || $search_count eq "0") {
1021 # my $file = "/tmp/wc.html";
1022 # open (my $out, '>', $file) || error ("writing $file: $!");
1025 # print STDERR blurb() . "###### wrote $file\n";
1029 my $length = length($body);
1038 foreach (split(/\n/)) {
1040 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1043 if (m/\bm="{(.*?)}"/s) { # Bing info is inside JSON crud
1044 my $json = html_unquote($1);
1045 my ($href) = ($json =~ m/\bsurl:"(.*?)"/s);
1046 my ($img) = ($json =~ m/\bimgurl:"(.*?)"/s);
1047 $u = "$img\t$href" if ($img && $href);
1049 } elsif ($u =~ m/^\"([^\"]*)\"/) { $u = $1 # quoted string
1050 } elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; # or token
1053 if ( $rejected_urls{$u} ) {
1054 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1058 LOG ($verbose_http, " HREF: $u");
1060 $subpages[++$#subpages] = $u;
1063 if ( $#subpages < 0 ) {
1064 LOG ($verbose_filter,
1065 "found nothing on $base ($length bytes, $href_count links).");
1069 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1071 return ($search_count, @subpages);
1079 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1081 next unless defined($h);
1083 if ($poisoners{$h}) {
1084 LOG (($verbose_filter), " rejecting poisoner: $_");
1087 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1089 LOG (($verbose_filter), " rejecting poisoner: $_");
1092 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1094 LOG (($verbose_filter), " rejecting poisoner: $_");
1104 # given a list of URLs, picks one at random; loads it; and returns a
1105 # random image from it.
1106 # returns the url of the page loaded; the url of the image chosen.
1108 sub pick_image_from_pages($$$$@) {
1109 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1111 $total_hit_count = "?" unless defined($total_hit_count);
1113 @pages = depoison (@pages);
1115 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1116 " ($total_hit_count total)");
1118 return () if ($#pages < 0);
1120 my $i = int(rand($#pages+1));
1121 my $page = $pages[$i];
1123 LOG ($verbose_load, "picked page $page");
1125 $suppress_audit = 1;
1127 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1129 if (!$base2 || !$body2) {
1134 my $img = pick_image_from_body ($base2, $body2);
1138 return ($base2, $img);
1145 #############################################################################
1147 ## Pick images from random pages returned by the Yahoo Random Link
1149 #############################################################################
1152 #my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1155 # Picks a random page; picks a random image on that page;
1156 # returns two URLs: the page containing the image, and the image.
1157 # Returns () if nothing found this time.
1159 #sub pick_from_yahoo_random_link($) {
1160 # my ($timeout) = @_;
1162 # print STDERR "\n\n" if ($verbose_load);
1163 # LOG ($verbose_load, "URL: $yahoo_random_link");
1165 # $last_search = $yahoo_random_link; # for warnings
1167 # $suppress_audit = 1;
1169 # my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1170 # if (!$base || !$body) {
1175 # LOG ($verbose_load, "redirected to: $base");
1177 # my $img = pick_image_from_body ($base, $body);
1181 # return ($base, $img);
1188 ############################################################################
1190 # Pick images from random pages returned by the Alta Vista Random Link
1191 # Note: this seems to have gotten a *lot* less random lately (2007).
1193 ############################################################################
1196 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1199 # Picks a random page; picks a random image on that page;
1200 # returns two URLs: the page containing the image, and the image.
1201 # Returns () if nothing found this time.
1203 sub pick_from_alta_vista_random_link($) {
1206 print STDERR "\n\n" if ($verbose_load);
1207 LOG ($verbose_load, "URL: $alta_vista_random_link");
1209 $last_search = $alta_vista_random_link; # for warnings
1211 $suppress_audit = 1;
1213 my ( $base, $body ) = get_document ($alta_vista_random_link,
1215 if (!$base || !$body) {
1220 LOG ($verbose_load, "redirected to: $base");
1222 my $img = pick_image_from_body ($base, $body);
1226 return ($base, $img);
1233 ############################################################################
1235 # Pick images by feeding random words into Alta Vista Image Search
1237 ############################################################################
1240 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1241 "?ipht=1" . # photos
1242 "&igrph=1" . # graphics
1245 "&micat=1" . # no partner sites
1246 "&sc=on" . # "site collapse"
1250 sub pick_from_alta_vista_images($) {
1253 my $words = random_word();
1254 my $page = (int(rand(9)) + 1);
1255 my $search_url = $alta_vista_images_url . $words;
1258 $search_url .= "&pgno=" . $page; # page number
1259 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1262 my ($search_hit_count, @subpages) =
1263 pick_from_search_engine ($timeout, $search_url, $words);
1265 my @candidates = ();
1266 foreach my $u (@subpages) {
1268 # avimages is encoding their URLs now.
1269 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1270 $u = url_unquote($u);
1272 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1273 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1274 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1275 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1276 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1278 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1279 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1281 LOG ($verbose_filter, " candidate: $u");
1282 push @candidates, $u;
1285 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1286 $timeout, @candidates);
1291 ############################################################################
1293 # Pick images from Aptix security cameras
1294 # Cribbed liberally from google image search code.
1295 # By Jason Sullivan <jasonsul@us.ibm.com>
1297 ############################################################################
1299 my $aptix_images_url = ("http://www.google.com/search" .
1300 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1303 sub pick_from_security_camera($) {
1306 my $page = (int(rand(9)) + 1);
1307 my $num = 20; # 20 images per page
1308 my $search_url = $aptix_images_url;
1311 $search_url .= "&start=" . $page*$num; # page number
1312 $search_url .= "&num=" . $num; #images per page
1315 my ($search_hit_count, @subpages) =
1316 pick_from_search_engine ($timeout, $search_url, '');
1318 my @candidates = ();
1320 foreach my $u (@subpages) {
1321 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1322 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1324 LOG ($verbose_filter, " candidate: $u");
1325 push @candidates, $u;
1329 @candidates = depoison (@candidates);
1330 return () if ($#candidates < 0);
1331 my $i = int(rand($#candidates+1));
1332 my $img = $candidates[$i];
1333 my $ref = $referers{$img};
1335 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1336 return ($ref, $img);
1340 ############################################################################
1342 # Pick images by feeding random words into Google Image Search.
1343 # By Charles Gales <gales@us.ibm.com>
1345 ############################################################################
1348 my $google_images_url = "http://ajax.googleapis.com/ajax/services/" .
1355 sub pick_from_google_images($;$$) {
1356 my ($timeout, $words, $max_page) = @_;
1358 if (!defined($words)) {
1359 $words = random_word(); # only one word for Google
1362 my $off = int(rand(40));
1363 my $search_url = $google_images_url . $words . "&start=" . $off;
1365 my ($search_hit_count, @subpages) =
1366 pick_from_search_engine ($timeout, $search_url, $words);
1368 my @candidates = ();
1370 foreach my $u (@subpages) {
1371 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1372 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1374 $u = html_unquote($u);
1375 if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1378 $ref = url_decode($ref);
1379 $img = url_decode($img);
1381 $img = "http://$img" unless ($img =~ m/^https?:/i);
1383 LOG ($verbose_filter, " candidate: $ref");
1384 push @candidates, $img;
1385 $referers{$img} = $ref;
1389 @candidates = depoison (@candidates);
1390 return () if ($#candidates < 0);
1391 my $i = int(rand($#candidates+1));
1392 my $img = $candidates[$i];
1393 my $ref = $referers{$img};
1395 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1396 return ($ref, $img);
1401 ############################################################################
1403 # Pick images by feeding random numbers into Google Image Search.
1404 # By jwz, suggested by Ian O'Donnell.
1406 ############################################################################
1410 sub pick_from_google_image_numbers($) {
1414 my $number = int(rand($max));
1416 $number = sprintf("%04d", $number)
1419 pick_from_google_images ($timeout, "$number");
1424 ############################################################################
1426 # Pick images by feeding random digital camera file names into
1427 # Google Image Search.
1428 # By jwz, inspired by the excellent Random Personal Picture Finder
1429 # at http://www.diddly.com/random/
1431 ############################################################################
1435 # Common digital camera file name formats, as described at
1436 # http://www.diddly.com/random/about.html
1438 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1439 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1440 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1441 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1442 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1443 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1444 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1445 int(rand(0xC)), int(rand(30))+1,
1447 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1448 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1449 sub { my $n = int(rand(9999)); # Canon
1450 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1451 sub { my $n = int(rand(9999)); # Canon
1452 sprintf ("1%02d-%04d_IMG.jpg",
1453 int($n/100), $n); },
1454 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1455 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1456 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1457 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1458 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1459 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1460 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1461 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1462 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1463 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1464 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1465 # int(rand(12))+1, int(rand(31))+1,
1466 # int(rand(999))); },
1467 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1468 # int(rand(6)), # year
1469 # int(rand(12))+1, int(rand(31))+1,
1470 # int(rand(999))); },
1471 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1472 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1473 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1474 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1479 sub pick_from_google_image_photos($) {
1482 my $i = int(rand($#photomakers + 1));
1483 my $fn = $photomakers[$i];
1485 #$file .= "%20filetype:jpg";
1487 pick_from_google_images ($timeout, $file);
1491 ############################################################################
1493 # Pick images by feeding random words into Google Image Search.
1494 # By the way: fuck Microsoft.
1496 ############################################################################
1498 my $bing_images_url = "http://www.bing.com/images/async?q=";
1502 sub pick_from_bing_images($;$$) {
1503 my ($timeout, $words, $max_page) = @_;
1505 if (!defined($words)) {
1506 $words = random_word(); # only one word for Bing
1509 my $off = int(rand(300));
1510 my $search_url = $bing_images_url . $words . "&first=" . $off;
1512 my ($search_hit_count, @subpages) =
1513 pick_from_search_engine ($timeout, $search_url, $words);
1515 my @candidates = ();
1517 foreach my $u (@subpages) {
1518 my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1520 LOG ($verbose_filter, " candidate: $ref");
1521 push @candidates, $img;
1522 $referers{$img} = $ref;
1525 @candidates = depoison (@candidates);
1526 return () if ($#candidates < 0);
1527 my $i = int(rand($#candidates+1));
1528 my $img = $candidates[$i];
1529 my $ref = $referers{$img};
1531 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1532 return ($ref, $img);
1538 ############################################################################
1540 # Pick images by feeding random numbers into Bing Image Search.
1542 ############################################################################
1545 sub pick_from_bing_image_numbers($) {
1549 my $number = int(rand($max));
1551 $number = sprintf("%04d", $number)
1554 pick_from_bing_images ($timeout, "$number");
1558 ############################################################################
1560 # Pick images by feeding random numbers into Bing Image Search.
1562 ############################################################################
1565 sub pick_from_bing_image_photos($) {
1568 my $i = int(rand($#photomakers + 1));
1569 my $fn = $photomakers[$i];
1572 pick_from_bing_images ($timeout, $file);
1576 ############################################################################
1578 # Pick images by feeding random words into Alta Vista Text Search
1580 ############################################################################
1583 my $alta_vista_url = "http://www.altavista.com/web/results" .
1587 "&sc=on" . # "site collapse"
1592 sub pick_from_alta_vista_text($) {
1595 my $words = random_words('%20');
1596 my $page = (int(rand(9)) + 1);
1597 my $search_url = $alta_vista_url . $words;
1600 $search_url .= "&pgno=" . $page;
1601 $search_url .= "&stq=" . (($page-1) * 10);
1604 my ($search_hit_count, @subpages) =
1605 pick_from_search_engine ($timeout, $search_url, $words);
1607 my @candidates = ();
1608 foreach my $u (@subpages) {
1610 # Those altavista fuckers are playing really nasty redirection games
1611 # these days: the filter your clicks through their site, but use
1612 # onMouseOver to make it look like they're not! Well, it makes it
1613 # easier for us to identify search results...
1615 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1616 $u = url_unquote($u);
1618 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1619 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1620 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1622 LOG ($verbose_filter, " candidate: $u");
1623 push @candidates, $u;
1626 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1627 $timeout, @candidates);
1632 ############################################################################
1634 # Pick images by feeding random words into Hotbot
1636 ############################################################################
1638 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1640 "&descriptiontype=0" .
1647 "&cobrand=undefined" .
1650 sub pick_from_hotbot_text($) {
1653 $last_search = $hotbot_search_url; # for warnings
1655 # lycos seems to always give us back dictionaries and word lists if
1656 # we search for more than one word...
1658 my $words = random_word();
1660 my $start = int(rand(8)) * 10 + 1;
1661 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1663 my ($search_hit_count, @subpages) =
1664 pick_from_search_engine ($timeout, $search_url, $words);
1666 my @candidates = ();
1667 foreach my $u (@subpages) {
1669 # Hotbot plays redirection games too
1671 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1672 # $u = url_decode($1);
1674 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1675 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1676 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1677 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1679 LOG ($verbose_filter, " candidate: $u");
1680 push @candidates, $u;
1683 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1684 $timeout, @candidates);
1689 ############################################################################
1691 # Pick images by feeding random words into Lycos
1693 ############################################################################
1695 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1701 sub pick_from_lycos_text($) {
1704 $last_search = $lycos_search_url; # for warnings
1706 # lycos seems to always give us back dictionaries and word lists if
1707 # we search for more than one word...
1709 my $words = random_word();
1711 my $start = int(rand(8)) * 10 + 1;
1712 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1714 my ($search_hit_count, @subpages) =
1715 pick_from_search_engine ($timeout, $search_url, $words);
1717 my @candidates = ();
1718 foreach my $u (@subpages) {
1720 # Lycos plays redirection games.
1722 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1727 # $u = url_decode($1);
1729 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1730 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1731 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1732 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1733 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1736 LOG ($verbose_filter, " candidate: $u");
1737 push @candidates, $u;
1740 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1741 $timeout, @candidates);
1746 ############################################################################
1748 # Pick images by feeding random words into news.yahoo.com
1750 ############################################################################
1752 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1757 sub pick_from_yahoo_news_text($) {
1760 $last_search = $yahoo_news_url; # for warnings
1762 my $words = random_word();
1763 my $search_url = $yahoo_news_url . $words;
1765 my ($search_hit_count, @subpages) =
1766 pick_from_search_engine ($timeout, $search_url, $words);
1768 my @candidates = ();
1769 foreach my $u (@subpages) {
1771 # de-redirectize the URLs
1772 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1774 # only accept URLs on Yahoo's news site
1775 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1776 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1777 next unless ($u =~ m@&u=/@);
1779 LOG ($verbose_filter, " candidate: $u");
1780 push @candidates, $u;
1783 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1784 $timeout, @candidates);
1789 ############################################################################
1791 # Pick images from LiveJournal's list of recently-posted images.
1793 ############################################################################
1795 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1797 # With most of our image sources, we get a random page and then select
1798 # from the images on it. However, in the case of LiveJournal, the page
1799 # of images tends to update slowly; so we'll remember the last N entries
1800 # on it and randomly select from those, to get a wider variety each time.
1802 my $lj_cache_size = 1000;
1803 my @lj_cache = (); # fifo, for ordering by age
1804 my %lj_cache = (); # hash, for detecting dups
1807 sub pick_from_livejournal_images($) {
1810 $last_search = $livejournal_img_url; # for warnings
1812 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1813 return () unless $body;
1816 $body =~ s/(<recent-image)\b/\n$1/gsi;
1818 foreach (split (/\n/, $body)) {
1819 next unless (m/^<recent-image\b/);
1820 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1821 my $img = html_unquote ($1);
1823 next if ($lj_cache{$img}); # already have it
1825 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1826 my $page = html_unquote ($1);
1827 my @pair = ($img, $page);
1828 LOG ($verbose_filter, " candidate: $img");
1829 push @lj_cache, \@pair;
1830 $lj_cache{$img} = \@pair;
1833 return () if ($#lj_cache == -1);
1835 my $n = $#lj_cache+1;
1836 my $i = int(rand($n));
1837 my ($img, $page) = @{$lj_cache[$i]};
1839 # delete this one from @lj_cache and from %lj_cache.
1841 @lj_cache = ( @lj_cache[0 .. $i-1],
1842 @lj_cache[$i+1 .. $#lj_cache] );
1843 delete $lj_cache{$img};
1845 # Keep the size of the cache under the limit by nuking older entries
1847 while ($#lj_cache >= $lj_cache_size) {
1848 my $pairP = shift @lj_cache;
1849 my $img = $pairP->[0];
1850 delete $lj_cache{$img};
1853 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1855 return ($page, $img);
1859 ############################################################################
1861 # Pick images from ircimages.com (images that have been in the /topic of
1862 # various IRC channels.)
1864 ############################################################################
1866 my $ircimages_url = "http://ircimages.com/";
1869 sub pick_from_ircimages($) {
1872 $last_search = $ircimages_url; # for warnings
1874 my $n = int(rand(2900));
1875 my $search_url = $ircimages_url . "page-$n";
1877 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1878 return () unless $body;
1880 my @candidates = ();
1883 $body =~ s/(<A)\b/\n$1/gsi;
1885 foreach (split (/\n/, $body)) {
1887 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1890 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1891 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1893 next unless ($u =~ m/^http:/i);
1894 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1895 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1897 LOG ($verbose_http, " HREF: $u");
1898 push @candidates, $u;
1901 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1903 return () if ($#candidates == -1);
1905 my $i = int(rand($#candidates+1));
1906 my $img = $candidates[$i];
1908 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1911 $search_url = $img; # hmm...
1912 return ($search_url, $img);
1916 ############################################################################
1918 # Pick images from Twitpic's list of recently-posted images.
1920 ############################################################################
1922 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1924 # With most of our image sources, we get a random page and then select
1925 # from the images on it. However, in the case of Twitpic, the page
1926 # of images tends to update slowly; so we'll remember the last N entries
1927 # on it and randomly select from those, to get a wider variety each time.
1929 my $twitpic_cache_size = 1000;
1930 my @twitpic_cache = (); # fifo, for ordering by age
1931 my %twitpic_cache = (); # hash, for detecting dups
1934 sub pick_from_twitpic_images($) {
1937 $last_search = $twitpic_img_url; # for warnings
1939 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1945 $body =~ s/(<item)\b/\n$1/gsi;
1947 my @items = split (/\n/, $body);
1950 next unless (m@<link>([^<>]*)</link>@si);
1951 my $page = html_unquote ($1);
1956 next if ($twitpic_cache{$page}); # already have it
1958 LOG ($verbose_filter, " candidate: $page");
1959 push @twitpic_cache, $page;
1960 $twitpic_cache{$page} = $page;
1964 # Pull from the cache.
1966 return () if ($#twitpic_cache == -1);
1968 my $n = $#twitpic_cache+1;
1969 my $i = int(rand($n));
1970 my $page = $twitpic_cache[$i];
1972 # delete this one from @twitpic_cache and from %twitpic_cache.
1974 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1975 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1976 delete $twitpic_cache{$page};
1978 # Keep the size of the cache under the limit by nuking older entries
1980 while ($#twitpic_cache >= $twitpic_cache_size) {
1981 my $page = shift @twitpic_cache;
1982 delete $twitpic_cache{$page};
1985 ( $base, $body ) = get_document ($page, undef, $timeout);
1987 $body = '' unless defined($body);
1989 foreach (split (/<img\s+/, $body)) {
1990 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1993 next if m@/images/@s;
1997 $img = "http:$img" if ($img =~ m@^//@s); # Oh come on
1999 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
2000 if ($img =~ m@^/@) {
2001 $base =~ s@^(https?://[^/]+)/.*@$1@s;
2002 $img = $base . $img;
2008 LOG ($verbose_load, "no matching images on $page\n");
2012 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2014 return ($page, $img);
2018 ############################################################################
2020 # Pick images from Twitter's list of recently-posted updates.
2022 ############################################################################
2024 # With most of our image sources, we get a random page and then select
2025 # from the images on it. However, in the case of Twitter, the page
2026 # of images only updates once a minute; so we'll remember the last N entries
2027 # on it and randomly select from those, to get a wider variety each time.
2029 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2030 "public_timeline.json" .
2031 "?include_entities=true" .
2032 "&include_rts=true" .
2035 my $twitter_cache_size = 1000;
2037 my @twitter_cache = (); # fifo, for ordering by age
2038 my %twitter_cache = (); # hash, for detecting dups
2042 sub pick_from_twitter_images($) {
2045 $last_search = $twitter_img_url; # for warnings
2047 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2051 $body =~ s/[\r\n]+/ /gs;
2053 # Parsing JSON is a pain in the ass. So we halfass it as usual.
2054 $body =~ s/^\[|\]$//s;
2055 $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2056 my @items = split (/},{/, $body);
2058 my ($name) = m@"screen_name":"([^\"]+)"@si;
2059 my ($img) = m@"media_url":"([^\"]+)"@si;
2060 my ($page) = m@"display_url":"([^\"]+)"@si;
2061 next unless ($name && $img && $page);
2062 foreach ($img, $page) {
2064 $_ = "http://$_" unless (m/^http/si);
2067 next if ($twitter_cache{$page}); # already have it
2069 LOG ($verbose_filter, " candidate: $page - $img");
2070 push @twitter_cache, $page;
2071 $twitter_cache{$page} = $img;
2075 # Pull from the cache.
2077 return () if ($#twitter_cache == -1);
2079 my $n = $#twitter_cache+1;
2080 my $i = int(rand($n));
2081 my $page = $twitter_cache[$i];
2082 my $url = $twitter_cache{$page};
2084 # delete this one from @twitter_cache and from %twitter_cache.
2086 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2087 @twitter_cache[$i+1 .. $#twitter_cache] );
2088 delete $twitter_cache{$page};
2090 # Keep the size of the cache under the limit by nuking older entries
2092 while ($#twitter_cache >= $twitter_cache_size) {
2093 my $page = shift @twitter_cache;
2094 delete $twitter_cache{$page};
2097 LOG ($verbose_load, "picked page $url");
2099 $suppress_audit = 1;
2101 return ($page, $url);
2105 ############################################################################
2107 # Pick images from Flickr's page of recently-posted photos.
2109 ############################################################################
2111 my $flickr_img_url = "http://www.flickr.com/explore/";
2113 # Like LiveJournal, the Flickr page of images tends to update slowly,
2114 # so remember the last N entries on it and randomly select from those.
2116 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2117 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2119 my $flickr_cache_size = 1000;
2120 my @flickr_cache = (); # fifo, for ordering by age
2121 my %flickr_cache = (); # hash, for detecting dups
2125 sub pick_from_flickr_recent($) {
2128 my $start = 16 * int(rand(100));
2130 $last_search = $flickr_img_url; # for warnings
2131 $last_search .= "?start=$start" if ($start > 0);
2133 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2134 return () unless $body;
2136 $body =~ s/[\r\n]/ /gs;
2137 $body =~ s/(<a)\b/\n$1/gsi;
2141 foreach (split (/\n/, $body)) {
2143 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2145 data-defer-src = \"([^<>\"]+)\" @xsi;
2146 next unless defined ($thumb);
2147 $page = html_unquote ($page);
2148 $thumb = html_unquote ($thumb);
2150 next unless ($thumb =~ m@^https?://[^/.]+\d*\.static\.?flickr\.com/@);
2152 my $base = "http://www.flickr.com/";
2153 $page =~ s@^/@$base@;
2154 $thumb =~ s@^/@$base@;
2157 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2160 next if ($flickr_cache{$img}); # already have it
2162 my @pair = ($img, $page, $start);
2163 LOG ($verbose_filter, " candidate: $img");
2164 push @flickr_cache, \@pair;
2165 $flickr_cache{$img} = \@pair;
2169 return () if ($#flickr_cache == -1);
2171 my $n = $#flickr_cache+1;
2172 my $i = int(rand($n));
2173 my ($img, $page) = @{$flickr_cache[$i]};
2175 # delete this one from @flickr_cache and from %flickr_cache.
2177 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2178 @flickr_cache[$i+1 .. $#flickr_cache] );
2179 delete $flickr_cache{$img};
2181 # Keep the size of the cache under the limit by nuking older entries
2183 while ($#flickr_cache >= $flickr_cache_size) {
2184 my $pairP = shift @flickr_cache;
2185 my $img = $pairP->[0];
2186 delete $flickr_cache{$img};
2189 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2191 return ($page, $img);
2195 ############################################################################
2197 # Pick images from a random RSS feed on Flickr.
2199 ############################################################################
2201 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2202 "?format=rss_200_enc&tagmode=any&tags=");
2204 # Picks a random RSS feed; picks a random image from that feed;
2205 # returns 2 URLs: the page containing the image, and the image.
2206 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2209 sub pick_from_flickr_random($) {
2210 my $timeout = shift;
2212 my $words = random_words(',');
2213 my $rss = $flickr_rss_base . $words;
2214 $last_search = $rss;
2219 print STDERR "\n\n" if ($verbose_load);
2220 LOG ($verbose_load, "words: $_");
2221 LOG ($verbose_load, "URL: $last_search");
2223 $suppress_audit = 1;
2225 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2226 if (!$base || !$body) {
2232 ($base, $img) = pick_image_from_rss ($base, $body);
2234 return () unless defined ($img);
2236 LOG ($verbose_load, "redirected to: $base");
2237 return ($base, $img);
2241 ############################################################################
2243 # Pick random images from Instagram.
2245 ############################################################################
2247 my $instagram_url_base = "https://api.instagram.com/v1/media/popular";
2250 sub pick_from_instagram($) {
2251 my $timeout = shift;
2253 # Liberated access tokens.
2254 # jsdo.it search for: instagram client_id
2255 # Google search for: instagram "&client_id=" site:jsfiddle.net
2256 my @tokens = ('b59fbe4563944b6c88cced13495c0f49', # gramfeed.com
2257 'fa26679250df49c48a33fbcf30aae989', # instac.at
2258 'd9494686198d4dfeb954979a3e270e5e', # iconosquare.com
2259 '793ef48bb18e4197b61afce2d799b81c', # jsdo.it
2260 '67b8a3e0073449bba70600d0fc68e6cb', # jsdo.it
2261 '26a098e0df4d4b9ea8b4ce6c505b7742', # jsdo.it
2262 '2437cbcd906a4c10940f990d283d3cd5', # jsdo.it
2263 '191c7d7d5312464cbd92134f36ffdab5', # jsdo.it
2264 'acfec809437b4340b2c38f66503af774', # jsdo.it
2265 'e9f77604a3a24beba949c12d18130988', # jsdo.it
2266 '2cd7bcf68ae346529770073d311575b3', # jsdo.it
2267 '830c600fe8d742e2ab3f3b94f9bb22b7', # jsdo.it
2268 '55865a0397ad41e5997dd95ef4df8da1', # jsdo.it
2269 '192a5742f3644ea8bed1d25e439286a8', # jsdo.it
2270 '38ed1477e7a44595861b8842cdb8ba23', # jsdo.it
2271 'e52f79f645f54488ad0cc47f6f55ade6', # jsfiddle.net
2274 my $tok = $tokens[int(rand($#tokens+1))];
2275 $last_search = $instagram_url_base . "?client_id=" . $tok;
2277 print STDERR "\n\n" if ($verbose_load);
2278 LOG ($verbose_load, "URL: $last_search");
2280 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2281 if (!$base || !$body) {
2286 $body =~ s/("link")/\001$1/gs;
2287 my @chunks = split(/\001/, $body);
2292 my ($url) = m/"link":\s*"(.*?)"/s;
2293 my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2294 ($img) = m/"url":\s*"(.*?)"/s unless $url;
2295 next unless ($url && $img);
2296 push @urls, [ $url, $img ];
2300 LOG ($verbose_load, "no images on $last_search");
2304 my $i = int(rand($#urls+1));
2305 my ($url, $img) = @{$urls[$i]};
2307 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2308 return ($url, $img);
2312 ############################################################################
2314 # Pick images by waiting for driftnet to populate a temp dir with files.
2315 # Requires driftnet version 0.1.5 or later.
2316 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2317 # for images being downloaded by others.)
2318 # Driftnet/webcollage integration by jwz.
2320 ############################################################################
2323 sub pick_from_driftnet($) {
2326 my $id = $driftnet_magic;
2327 my $dir = $driftnet_dir;
2331 error ("\$driftnet_dir unset?") unless ($dir);
2334 error ("$dir unreadable") unless (-d "$dir/.");
2336 $timeout = $http_timeout unless ($timeout);
2339 while ($now = time, $now < $start + $timeout) {
2340 opendir (my $dir, $dir) || error ("$dir: $!");
2341 while (my $file = readdir($dir)) {
2342 next if ($file =~ m/^\./);
2343 $file = "$dir/$file";
2345 LOG ($verbose_load, "picked file $file ($id)");
2346 return ($id, $file);
2350 LOG (($verbose_net || $verbose_load), "timed out for $id");
2355 sub get_driftnet_file($) {
2358 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2360 my $id = $driftnet_magic;
2361 error ("$id: $file not in $driftnet_dir?")
2362 unless ($file =~ m@^\Q$driftnet_dir@o);
2364 open (my $in, '<', $file) || error ("$id: $file: $!");
2366 local $/ = undef; # read entire file
2368 close ($in) || error ("$id: $file: $!");
2369 unlink ($file) || error ("$id: $file: rm: $!");
2370 return ($id, $body);
2374 sub spawn_driftnet($) {
2377 # make a directory to use.
2379 my $tmp = $ENV{TEMPDIR} || "/tmp";
2380 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2381 LOG ($verbose_exec, "mkdir $driftnet_dir");
2382 last if mkdir ($driftnet_dir, 0700);
2385 if (! ($cmd =~ m/\s/)) {
2386 # if the command didn't have any arguments in it, then it must be just
2387 # a pointer to the executable. Append the default args to it.
2388 my $dargs = $default_driftnet_cmd;
2389 $dargs =~ s/^[^\s]+//;
2393 # point the driftnet command at our newly-minted private directory.
2395 $cmd .= " -d $driftnet_dir";
2396 $cmd .= ">/dev/null" unless ($verbose_exec);
2399 if ($pid < 0) { error ("fork: $!\n"); }
2402 push @pids_to_kill, $pid;
2403 LOG ($verbose_exec, "forked for \"$cmd\"");
2406 nontrapping_system ($cmd) || error ("exec: $!");
2409 # wait a bit, then make sure the process actually started up.
2412 error ("pid $pid failed to start \"$cmd\"")
2413 unless (1 == kill (0, $pid));
2417 sub pick_from_local_dir($) {
2420 my $id = $local_magic;
2423 my $dir = $local_dir;
2424 error ("\$local_dir unset?") unless ($dir);
2427 error ("$dir unreadable") unless (-d "$dir/.");
2429 my $v = ($verbose_exec ? "-v" : "");
2430 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2432 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2434 LOG ($verbose_load, "picked file $pick ($id)");
2435 return ($id, $pick);
2439 sub get_local_file($) {
2442 error ("\$local_dir unset?") unless ($local_dir);
2444 my $id = $local_magic;
2445 error ("$id: $file not in $local_dir?")
2446 unless ($file =~ m@^\Q$local_dir@o);
2448 open (my $in, '<', $file) || error ("$id: $file: $!");
2449 local $/ = undef; # read entire file
2451 close ($in) || error ("$id: $file: $!");
2452 return ($id, $body);
2457 ############################################################################
2459 # Pick a random image in a random way
2461 ############################################################################
2464 # Picks a random image on a random page, and returns two URLs:
2465 # the page containing the image, and the image.
2466 # Returns () if nothing found this time.
2469 sub pick_image(;$) {
2472 $current_state = "select";
2473 $load_method = "none";
2475 my $n = int(rand(100));
2478 my @rest = @search_methods;
2481 my $pct = shift @rest;
2482 my $name = shift @rest;
2483 my $tfn = shift @rest;
2485 if ($total > $n && !defined($fn)) {
2487 $current_state = $name;
2488 $load_method = $current_state;
2492 if ($total != 100) {
2493 error ("internal error: \@search_methods totals to $total%!");
2496 record_attempt ($current_state);
2497 return $fn->($timeout);
2502 ############################################################################
2504 # Statistics and logging
2506 ############################################################################
2509 return strftime ("%H:%M:%S: ", localtime);
2513 return "$progname: " . timestr() . "$current_state: ";
2518 print STDERR blurb() . "$err\n";
2524 print STDERR "$progname: stack trace:\n";
2526 my ($package, $filename, $line, $subroutine) = caller($i++);
2527 last unless defined($package);
2528 $filename =~ s@^.*/@@;
2529 print STDERR " $filename#$line, $subroutine\n";
2541 my $head = "$progname: DEBUG: ";
2542 foreach (split (/\n/, $lastlog)) {
2543 print STDERR "$head$_\n";
2549 my ($print, $msg) = @_;
2550 my $blurb = timestr() . "$current_state: ";
2551 $lastlog .= "$blurb$msg\n";
2552 print STDERR "$progname: $blurb$msg\n" if $print;
2557 my %stats_successes;
2560 my $last_state = undef;
2561 sub record_attempt($) {
2565 record_failure($last_state) unless ($image_succeeded > 0);
2567 $last_state = $name;
2570 report_performance();
2573 $image_succeeded = 0;
2574 $suppress_audit = 0;
2577 sub record_success($$$) {
2578 my ($name, $url, $base) = @_;
2579 if (defined($stats_successes{$name})) {
2580 $stats_successes{$name}++;
2582 $stats_successes{$name} = 1;
2585 stop_timer ($name, 1);
2586 my $o = $current_state;
2587 $current_state = $name;
2588 save_recent_url ($url, $base);
2589 $current_state = $o;
2590 $image_succeeded = 1;
2595 sub record_failure($) {
2598 return if $image_succeeded;
2600 stop_timer ($name, 0);
2601 if ($verbose_load && !$verbose_exec) {
2603 if ($suppress_audit) {
2604 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2608 my $o = $current_state;
2609 $current_state = "DEBUG";
2611 my $line = "#" x 78;
2612 print STDERR "\n\n\n";
2613 print STDERR ("#" x 78) . "\n";
2614 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2617 print STDERR ("-" x 78) . "\n";
2618 print STDERR "\n\n";
2620 $current_state = $o;
2622 $image_succeeded = 0;
2629 my $i = $stats_successes{$name};
2630 my $j = $stats_attempts{$name};
2633 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2637 my $current_start_time = 0;
2639 sub start_timer($) {
2641 $current_start_time = time;
2643 if (defined($stats_attempts{$name})) {
2644 $stats_attempts{$name}++;
2646 $stats_attempts{$name} = 1;
2648 if (!defined($stats_elapsed{$name})) {
2649 $stats_elapsed{$name} = 0;
2653 sub stop_timer($$) {
2654 my ($name, $success) = @_;
2655 $stats_elapsed{$name} += time - $current_start_time;
2659 my $last_report_time = 0;
2660 sub report_performance() {
2662 return unless $verbose_warnings;
2665 return unless ($now >= $last_report_time + $report_performance_interval);
2666 my $ot = $last_report_time;
2667 $last_report_time = $now;
2669 return if ($ot == 0);
2671 my $blurb = "$progname: " . timestr();
2674 print STDERR "${blurb}Current standings:\n";
2676 foreach my $name (sort keys (%stats_attempts)) {
2677 my $try = $stats_attempts{$name};
2678 my $suc = $stats_successes{$name} || 0;
2679 my $pct = int($suc * 100 / $try);
2680 my $secs = $stats_elapsed{$name};
2681 my $secs_link = $secs / $try;
2682 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2683 " \t %.1f secs/link\n",
2684 "$name:", "$pct%", $suc, $try, $secs_link);
2690 my $max_recent_images = 400;
2691 my $max_recent_sites = 20;
2692 my @recent_images = ();
2693 my @recent_sites = ();
2695 sub save_recent_url($$) {
2696 my ($url, $base) = @_;
2698 return unless ($verbose_warnings);
2701 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2702 return unless defined ($site);
2704 if ($base eq $driftnet_magic || $base eq $local_magic) {
2706 @recent_images = ();
2710 foreach (@recent_images) {
2712 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2713 " (on $base via $last_search)\n";
2719 # suppress "duplicate site" warning via %warningless_sites.
2721 if ($warningless_sites{$site}) {
2723 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2724 $warningless_sites{$1}) {
2726 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2727 $warningless_sites{$1}) {
2732 foreach (@recent_sites) {
2734 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2735 " ($url on $base via $last_search)\n";
2741 push @recent_images, $url;
2742 push @recent_sites, $site;
2743 shift @recent_images if ($#recent_images >= $max_recent_images);
2744 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2749 ##############################################################################
2753 ##############################################################################
2760 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2765 # Given the raw body of a GIF document, returns the dimensions of the image.
2769 my $type = substr($body, 0, 6);
2771 return () unless ($type =~ /GIF8[7,9]a/);
2772 $s = substr ($body, 6, 10);
2773 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2774 return () unless defined ($d);
2775 return (($b<<8|$a), ($d<<8|$c));
2778 # Given the raw body of a JPEG document, returns the dimensions of the image.
2783 my $L = length($body);
2785 my $c1 = substr($body, $i, 1); $i++;
2786 my $c2 = substr($body, $i, 1); $i++;
2787 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2790 while (ord($ch) != 0xDA && $i < $L) {
2791 # Find next marker, beginning with 0xFF.
2792 while (ord($ch) != 0xFF) {
2793 return () if (length($body) <= $i);
2794 $ch = substr($body, $i, 1); $i++;
2796 # markers can be padded with any number of 0xFF.
2797 while (ord($ch) == 0xFF) {
2798 return () if (length($body) <= $i);
2799 $ch = substr($body, $i, 1); $i++;
2802 # $ch contains the value of the marker.
2803 my $marker = ord($ch);
2805 if (($marker >= 0xC0) &&
2806 ($marker <= 0xCF) &&
2807 ($marker != 0xC4) &&
2808 ($marker != 0xCC)) { # it's a SOFn marker
2810 return () if (length($body) <= $i);
2811 my $s = substr($body, $i, 4); $i += 4;
2812 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2813 return (($c<<8|$d), ($a<<8|$b));
2816 # We must skip variables, since FFs in variable names aren't
2817 # valid JPEG markers.
2818 return () if (length($body) <= $i);
2819 my $s = substr($body, $i, 2); $i += 2;
2820 my ($c1, $c2) = unpack ("C"x2, $s);
2821 my $length = ($c1 << 8) | $c2;
2822 return () if ($length < 2);
2829 # Given the raw body of a PNG document, returns the dimensions of the image.
2833 return () unless ($body =~ m/^\211PNG\r/);
2834 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2835 return () unless defined ($bits);
2836 return () unless ($bits =~ /^IHDR/);
2837 my ($ign, $w, $h) = unpack("a4N2", $bits);
2842 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2847 my ($w, $h) = gif_size ($body);
2848 if ($w && $h) { return ($w, $h); }
2849 ($w, $h) = jpeg_size ($body);
2850 if ($w && $h) { return ($w, $h); }
2851 return png_size ($body);
2855 # returns the full path of the named program, or undef.
2859 foreach (split (/:/, $ENV{PATH})) {
2860 my $path = "$_/$prog";
2869 # Like rand(), but chooses numbers with a bell curve distribution.
2872 $_ = 1.0 unless defined($_);
2874 return (rand($_) + rand($_) + rand($_));
2878 sub exit_cleanup() {
2880 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2881 if (@pids_to_kill) {
2882 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2883 kill ('TERM', @pids_to_kill);
2887 sub signal_cleanup($) {
2889 print STDERR blurb() . (defined($sig)
2890 ? "caught signal $sig."
2893 if ($verbose_exec || $verbose_warnings);
2899 ##############################################################################
2901 # Generating a list of urls only
2903 ##############################################################################
2905 sub url_only_output() {
2907 my ($base, $img) = pick_image;
2911 print "$img $base\n";
2916 ##############################################################################
2918 # Running as an xscreensaver module, or as a web page imagemap
2920 ##############################################################################
2922 my ($image_ppm, $image_tmp1, $image_tmp2);
2924 my $seed = rand(0xFFFFFFFF);
2925 $image_ppm = sprintf ("%s/webcollage-%08x",
2926 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2928 $image_tmp1 = $image_ppm . '-1.ppm';
2929 $image_tmp2 = $image_ppm . '-2.ppm';
2930 $image_ppm .= '.ppm';
2934 my $filter_cmd = undef;
2935 my $post_filter_cmd = undef;
2936 my $background = undef;
2938 my @imagemap_areas = ();
2939 my $imagemap_html_tmp = undef;
2940 my $imagemap_jpg_tmp = undef;
2943 my $img_width; # size of the image being generated.
2949 unlink $image_ppm, $image_tmp1, $image_tmp2;
2950 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2951 if (defined ($imagemap_html_tmp));
2955 # Like system, but prints status about exit codes, and kills this process
2956 # with whatever signal killed the sub-process, if any.
2958 sub nontrapping_system(@) {
2962 s/\"[^\"]+\"/\"...\"/g;
2964 LOG ($verbose_exec, "executing \"$_\"");
2969 LOG ($verbose_exec, "subproc exited normally.");
2970 } elsif (($rc & 0xff) == 0) {
2972 LOG ($verbose_exec, "subproc exited with status $rc.");
2975 LOG ($verbose_exec, "subproc dumped core.");
2978 LOG ($verbose_exec, "subproc died with signal $rc.");
2979 # die that way ourselves.
2987 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2988 # writes a PPM to the given output file. Returns the width/height of the
2989 # image if successful.
2991 sub image_to_pnm($$$) {
2992 my ($url, $body, $output) = @_;
2993 my ($cmd, $cmd2, $w, $h);
2995 if ((@_ = gif_size ($body))) {
2998 } elsif ((@_ = jpeg_size ($body))) {
3001 } elsif ((@_ = png_size ($body))) {
3005 LOG (($verbose_pbm || $verbose_load),
3006 "not a GIF, JPG, or PNG" .
3007 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
3008 ? " (looks like HTML)" : "") .
3010 $suppress_audit = 1;
3014 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
3015 # do this, the process doesn't die properly.
3016 if (!$verbose_pbm) {
3018 # We get a "giftopnm: got a 'Application Extension' extension"
3019 # warning any time it's an animgif.
3021 # Note that "giftopnm: EOF / read error on image data" is not
3022 # always a fatal error -- sometimes the image looks fine anyway.
3024 $cmd2 .= " 2>/dev/null";
3027 # There exist corrupted GIF and JPEG files that can make giftopnm and
3028 # djpeg lose their minds and go into a loop. So this gives those programs
3029 # a small timeout -- if they don't complete in time, kill them.
3035 local $SIG{ALRM} = sub {
3037 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3038 kill ('TERM', $pid) if ($pid);
3043 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3050 LOG ($verbose_exec, "awaiting $pid");
3052 LOG ($verbose_exec, "$pid completed");
3054 my $size = (stat($output))[7];
3055 $size = -1 unless defined($size);
3057 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3061 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3064 print STDERR blurb() . "$cmd failed: $!\n";
3068 die if ($@ && $@ ne "alarm\n"); # propagate errors
3082 # Same as the "ppmmake" command: creates a solid-colored PPM.
3083 # Does not understand the rgb.txt color names except "black" and "white".
3086 my ($outfile, $bgcolor, $w, $h) = @_;
3089 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3090 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3091 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3092 } elsif ($bgcolor =~ m/^black$/i) {
3093 ($r, $g, $b) = (0, 0, 0);
3094 } elsif ($bgcolor =~ m/^white$/i) {
3095 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3097 error ("unparsable color name: $bgcolor");
3100 my $pixel = pack('CCC', $r, $g, $b);
3101 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3103 open (my $out, '>', $outfile) || error ("$outfile: $!");
3109 sub pick_root_displayer() {
3113 # see "xscreensaver/hacks/webcollage-cocoa.m"
3114 return "echo COCOA LOAD ";
3117 foreach my $cmd (@root_displayers) {
3119 my ($name) = m/^([^ ]+)/;
3120 push @names, "\"$name\"";
3121 LOG ($verbose_exec, "looking for $name...");
3122 foreach my $dir (split (/:/, $ENV{PATH})) {
3123 LOG ($verbose_exec, " checking $dir/$name");
3124 return $cmd if (-x "$dir/$name");
3128 $names[$#names] = "or " . $names[$#names];
3129 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3133 my $ppm_to_root_window_cmd = undef;
3136 sub x_or_pbm_output($) {
3137 my ($window_id) = @_;
3139 # Adjust the PATH for OS X 10.10.
3143 s/([^a-zA-Z0-9._\-+\/])/\\$1/g;
3144 $ENV{PATH} = "$_:$ENV{PATH}";
3146 # Check for our helper program, to see whether we need to use PPM pipelines.
3148 $_ = "webcollage-helper";
3150 if (! defined ($webcollage_helper)) {
3151 $webcollage_helper = which ($_);
3154 if (defined ($webcollage_helper)) {
3155 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3156 $webcollage_helper .= " -v";
3158 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3161 if ($cocoa_p && !defined ($webcollage_helper)) {
3162 error ("webcollage-helper not found in Cocoa-mode!");
3166 # make sure the various programs we execute exist, right up front.
3170 if (!defined($webcollage_helper)) {
3171 # Only need these others if we don't have the helper.
3173 "giftopnm", "pngtopnm", "djpeg",
3174 "pnmpaste", "pnmscale", "pnmcut");
3178 which ($_) || error "$_ not found on \$PATH.";
3181 # If we're using webcollage-helper and not a filter, then the tmp files
3182 # are JPEGs, not PPMs.
3184 if (defined ($webcollage_helper) && !defined ($filter_cmd)) {
3185 foreach ($image_ppm, $image_tmp1, $image_tmp2) {
3191 # find a root-window displayer program.
3193 if (!$no_output_p) {
3194 $ppm_to_root_window_cmd = pick_root_displayer();
3197 if (defined ($window_id)) {
3198 error ("-window-id only works if xscreensaver-getimage is installed")
3199 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3201 error ("unparsable window id: $window_id")
3202 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3203 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3204 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3207 if (!$img_width || !$img_height) {
3209 if (!defined ($window_id) &&
3210 defined ($ENV{XSCREENSAVER_WINDOW})) {
3211 $window_id = $ENV{XSCREENSAVER_WINDOW};
3214 if (!defined ($window_id)) {
3216 which ($_) || error "$_ not found on \$PATH.";
3218 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3219 if (!defined($img_height)) {
3220 error "xdpyinfo failed.";
3222 } else { # we have a window id
3224 which ($_) || error "$_ not found on \$PATH.";
3225 $_ .= " -id $window_id";
3227 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3229 if (!defined($img_height)) {
3230 error "xwininfo failed.";
3235 my $bgcolor = "#000000";
3236 my $bgimage = undef;
3239 if ($background =~ m/^\#[0-9a-f]+$/i) {
3240 $bgcolor = $background;
3242 } elsif (-r $background) {
3243 $bgimage = $background;
3245 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3246 error "not a color or readable file: $background";
3249 # default to assuming it's a color
3250 $bgcolor = $background;
3254 # Create the sold-colored base image.
3256 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3257 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3259 # Paste the default background image in the middle of it.
3265 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3266 local $/ = undef; # read entire file
3271 if ((@_ = gif_size ($body))) {
3273 $cmd = "giftopnm |";
3275 } elsif ((@_ = jpeg_size ($body))) {
3279 } elsif ((@_ = png_size ($body))) {
3281 $cmd = "pngtopnm |";
3283 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3289 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3292 my $x = int (($img_width - $iw) / 2);
3293 my $y = int (($img_height - $ih) / 2);
3295 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3297 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3298 open ($imgf, "| $cmd") || error "running $cmd: $!";
3302 LOG ($verbose_exec, "subproc exited normally.");
3303 rename ($image_tmp1, $image_ppm) ||
3304 error "renaming $image_tmp1 to $image_ppm: $!";
3310 my ($base, $img) = pick_image();
3311 my $source = $current_state;
3312 $current_state = "loadimage";
3314 my ($headers, $body) = get_document ($img, $base);
3316 paste_image ($base, $img, $body, $source);
3320 $current_state = "idle";
3321 $load_method = "none";
3323 unlink $image_tmp1, $image_tmp2;
3328 sub paste_image($$$$) {
3329 my ($base, $img, $body, $source) = @_;
3331 $current_state = "paste";
3333 $suppress_audit = 0;
3335 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3339 # If we are using the webcollage-helper, then we do not need to convert this
3340 # image to a PPM. But, if we're using a filter command, we still must, since
3341 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3344 if (defined ($webcollage_helper) &&
3345 !defined ($filter_cmd)) {
3347 ($iw, $ih) = image_size ($body);
3349 LOG (($verbose_pbm || $verbose_load),
3350 "not a GIF, JPG, or PNG" .
3351 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3352 ? " (looks like HTML)" : "") .
3354 $suppress_audit = 1;
3359 if ($iw <= 0 || $ih <= 0 || $iw > 9999 || $ih > 9999) {
3360 LOG (($verbose_pbm || $verbose_load),
3361 "ludicrous image dimensions: $iw x $ih (" . length($body) .
3367 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3368 (print $out $body) || error ("writing $image_tmp1: $!");
3369 close ($out) || error ("writing $image_tmp1: $!");
3372 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3375 LOG ($verbose_pbm, "unable to make PBM from $img");
3380 record_success ($load_method, $img, $base);
3383 my $ow = $iw; # used only for error messages
3386 # don't just tack this onto the front of the pipeline -- we want it to
3387 # be able to change the size of the input image.
3390 LOG ($verbose_pbm, "running $filter_cmd");
3392 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3394 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3395 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3398 rename ($image_tmp2, $image_tmp1);
3400 # re-get the width/height in case the filter resized it.
3401 open (my $imgf, '<', $image_tmp1) || return 0;
3404 ($iw, $ih) = m/^(\d+) (\d+)$/;
3406 return 0 unless ($iw && $ih);
3409 my $target_w = $img_width; # max rectangle into which the image must fit
3410 my $target_h = $img_height;
3416 # Usually scale the image to fit on the screen -- but sometimes scale it
3417 # to fit on half or a quarter of the screen. (We do this by reducing the
3418 # size of the target rectangle.) Note that the image is not merely scaled
3419 # to fit; we instead cut the image in half repeatedly until it fits in the
3420 # target rectangle -- that gives a wider distribution of sizes.
3422 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3423 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3425 if ($iw > $target_w || $ih > $target_h) {
3426 while ($iw > $target_w ||
3432 if ($iw <= 10 || $ih <= 10) {
3433 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3437 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3439 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3443 my $src = $image_tmp1;
3445 my $crop_x = 0; # the sub-rectangle of the image
3446 my $crop_y = 0; # that we will actually paste.
3450 # The chance that we will randomly crop out a section of an image starts
3451 # out fairly low, but goes up for images that are very large, or images
3452 # that have ratios that make them look like banners (we try to avoid
3453 # banner images entirely, but they slip through when the IMG tags didn't
3454 # have WIDTH and HEIGHT specified.)
3456 my $crop_chance = 0.2;
3457 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3458 $crop_chance += 0.2;
3460 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3461 $crop_chance += 0.2;
3463 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3464 $crop_chance += 0.7;
3467 if ($crop_chance > 0.1) {
3468 LOG ($verbose_pbm, "crop chance: $crop_chance");
3471 if (rand() < $crop_chance) {
3476 if ($crop_w > $min_width) {
3477 # if it's a banner, select the width linearly.
3478 # otherwise, select a bell.
3479 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3482 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3483 $crop_x = int (rand() * ($ow - $crop_w));
3485 if ($crop_h > $min_height) {
3486 # height always selects as a bell.
3487 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3488 $crop_y = int (rand() * ($oh - $crop_h));
3491 if ($crop_x != 0 || $crop_y != 0 ||
3492 $crop_w != $iw || $crop_h != $ih) {
3494 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3498 # Where the image should logically land -- this might be negative.
3500 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3501 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3503 # if we have chosen to paste the image outside of the rectangle of the
3504 # screen, then we need to crop it.
3508 $x + $crop_w > $img_width ||
3509 $y + $crop_h > $img_height) {
3512 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3514 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3515 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3517 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3518 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3521 # If any cropping needs to happen, add pnmcut.
3523 if ($crop_x != 0 || $crop_y != 0 ||
3524 $crop_w != $iw || $crop_h != $ih) {
3527 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3528 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3531 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3533 $cmd .= " | pnmpaste - $x $y $image_ppm";
3535 $cmd =~ s@^ *\| *@@;
3537 if (defined ($webcollage_helper)) {
3538 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3539 "$scale $opacity " .
3540 "$crop_x $crop_y $x $y " .
3545 # use a PPM pipeline
3547 $_ .= " < $image_tmp1 > $image_tmp2";
3551 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3553 $_ .= " 2> /dev/null";
3556 my $rc = nontrapping_system ($_);
3558 if (defined ($webcollage_helper) && -z $image_ppm) {
3559 LOG (1, "failed command: \"$cmd\"");
3560 print STDERR "\naudit log:\n\n\n";
3561 print STDERR ("#" x 78) . "\n";
3562 print STDERR blurb() . "$image_ppm has zero size\n";
3564 print STDERR "\n\n";
3569 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3570 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3574 if (!defined ($webcollage_helper)) {
3575 rename ($image_tmp2, $image_ppm) || return;
3578 my $target = "$image_ppm";
3580 # don't just tack this onto the end of the pipeline -- we don't want it
3581 # to end up in $image_ppm, because we don't want the results to be
3584 if ($post_filter_cmd) {
3588 $target = $image_tmp1;
3589 if (!defined ($webcollage_helper)) {
3590 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3592 # Blah, my scripts need the JPEG data, but some other folks need
3593 # the PPM data -- what to do? Ignore the problem, that's what!
3594 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3595 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3598 $rc = nontrapping_system ($cmd);
3600 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3605 if (!$no_output_p) {
3606 my $tsize = (stat($target))[7];
3608 $cmd = "$ppm_to_root_window_cmd $target";
3610 # xv seems to hate being killed. it tends to forget to clean
3611 # up after itself, and leaves windows around and colors allocated.
3612 # I had this same problem with vidwhacker, and I'm not entirely
3613 # sure what I did to fix it. But, let's try this: launch xv
3614 # in the background, so that killing this process doesn't kill it.
3615 # it will die of its own accord soon enough. So this means we
3616 # start pumping bits to the root window in parallel with starting
3617 # the next network retrieval, which is probably a better thing
3620 $cmd .= " &" unless ($cocoa_p);
3622 $rc = nontrapping_system ($cmd);
3625 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3630 LOG ($verbose_pbm, "$target size is $tsize");
3634 $source .= "-" . stats_of($source);
3635 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3636 if ($verbose_imgmap);
3637 if ($imagemap_base) {
3638 update_imagemap ($base, $x, $y, $iw, $ih,
3639 $image_ppm, $img_width, $img_height);
3648 sub update_imagemap($$$$$$$$) {
3649 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3651 $current_state = "imagemap";
3653 my $max_areas = 200;
3655 $url = html_quote ($url);
3658 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3659 unshift @imagemap_areas, $area; # put one on the front
3660 if ($#imagemap_areas >= $max_areas) {
3661 pop @imagemap_areas; # take one off the back.
3664 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3666 my $map_name = $imagemap_base;
3667 $map_name =~ s@^.*/@@;
3668 $map_name = 'collage' if ($map_name eq '');
3670 my $imagemap_html = $imagemap_base . ".html";
3671 my $imagemap_jpg = $imagemap_base . ".jpg";
3672 my $imagemap_jpg2 = $imagemap_jpg;
3673 $imagemap_jpg2 =~ s@^.*/@@gs;
3675 if (!defined ($imagemap_html_tmp)) {
3676 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3677 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3680 # Read the imagemap html file (if any) to get a template.
3682 my $template_html = '';
3684 if (open (my $in, '<', $imagemap_html)) {
3685 local $/ = undef; # read entire file
3686 $template_html = <$in>;
3688 LOG ($verbose_pbm, "read template $imagemap_html");
3691 if ($template_html =~ m/^\s*$/s) {
3692 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3693 "<IMG SRC=\"$imagemap_jpg2\"" .
3694 " USEMAP=\"$map_name\">\n");
3695 LOG ($verbose_pbm, "created dummy template");
3699 # Write the jpg to a tmp file
3703 if (defined ($webcollage_helper)) {
3704 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3706 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3708 my $rc = nontrapping_system ($cmd);
3710 error ("imagemap jpeg failed: \"$cmd\"\n");
3714 # Write the html to a tmp file
3717 my $body = $template_html;
3718 my $areas = join ("\n\t", @imagemap_areas);
3719 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3720 my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3722 "WIDTH=$image_width HEIGHT=$image_height " .
3723 "USEMAP=\"#$map_name\">");
3724 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3725 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3727 # if there are magic webcollage spans in the html, update those too.
3730 my @st = stat ($imagemap_jpg_tmp);
3731 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3732 my $size = int(($st[7] / 1024) + 0.5) . "K";
3733 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3734 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3737 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3738 (print $out $body) || error ("$imagemap_html_tmp: $!");
3739 close ($out) || error ("$imagemap_html_tmp: $!");
3740 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3743 # Rename the two tmp files to the real files
3745 rename ($imagemap_html_tmp, $imagemap_html) ||
3746 error "renaming $imagemap_html_tmp to $imagemap_html";
3747 LOG ($verbose_pbm, "wrote $imagemap_html");
3748 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3749 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3750 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3754 # Figure out what the proxy server should be, either from environment
3755 # variables or by parsing the output of the (MacOS) program "scutil",
3756 # which tells us what the system-wide proxy settings are.
3760 if (! $http_proxy) {
3761 # historical suckage: the environment variable name is lower case.
3762 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3765 if (defined ($http_proxy)) {
3766 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3767 # historical suckage: allow "http://host:port" as well as "host:port".
3772 my $proxy_data = `scutil --proxy 2>/dev/null`;
3773 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3774 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3775 # Note: this ignores the "ExceptionsList".
3777 $http_proxy = $server;
3778 $http_proxy .= ":$port" if $port;
3783 LOG ($verbose_net, "proxy server: $http_proxy");
3788 sub init_signals() {
3790 $SIG{HUP} = \&signal_cleanup;
3791 $SIG{INT} = \&signal_cleanup;
3792 $SIG{QUIT} = \&signal_cleanup;
3793 $SIG{ABRT} = \&signal_cleanup;
3794 $SIG{KILL} = \&signal_cleanup;
3795 $SIG{TERM} = \&signal_cleanup;
3797 # Need this so that if giftopnm dies, we don't die.
3798 $SIG{PIPE} = 'IGNORE';
3801 END { exit_cleanup(); }
3810 my $driftnet_cmd = 0;
3812 $current_state = "init";
3813 $load_method = "none";
3816 my $window_id = undef;
3818 while ($_ = $ARGV[0]) {
3820 if ($_ eq "-display" ||
3826 $ENV{DISPLAY} = shift @ARGV;
3827 } elsif ($_ eq "-root") {
3829 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3830 $window_id = shift @ARGV;
3832 } elsif ($_ eq "-no-output") {
3834 } elsif ($_ eq "-urls-only") {
3837 } elsif ($_ eq "-cocoa") {
3839 } elsif ($_ eq "-imagemap") {
3840 $imagemap_base = shift @ARGV;
3842 } elsif ($_ eq "-verbose") {
3844 } elsif (m/^-v+$/) {
3845 $verbose += length($_)-1;
3846 } elsif ($_ eq "-delay") {
3847 $delay = shift @ARGV;
3848 } elsif ($_ eq "-timeout") {
3849 $http_timeout = shift @ARGV;
3850 } elsif ($_ eq "-filter") {
3851 $filter_cmd = shift @ARGV;
3852 } elsif ($_ eq "-filter2") {
3853 $post_filter_cmd = shift @ARGV;
3854 } elsif ($_ eq "-background" || $_ eq "-bg") {
3855 $background = shift @ARGV;
3856 } elsif ($_ eq "-size") {
3858 if (m@^(\d+)x(\d+)$@) {
3862 error "argument to \"-size\" must be of the form \"640x400\"";
3864 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3865 $http_proxy = shift @ARGV;
3866 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3867 $dict = shift @ARGV;
3868 } elsif ($_ eq "-opacity") {
3869 $opacity = shift @ARGV;
3870 error ("opacity must be between 0.0 and 1.0")
3871 if ($opacity <= 0 || $opacity > 1);
3872 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3873 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3874 if (! ($ARGV[0] =~ m/^-/)) {
3875 $driftnet_cmd = shift @ARGV;
3877 $driftnet_cmd = $default_driftnet_cmd;
3879 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3880 @search_methods = ( 100, "local", \&pick_from_local_dir );
3881 if (! ($ARGV[0] =~ m/^-/)) {
3882 $local_dir = shift @ARGV;
3884 error ("local directory path must be set")
3886 } elsif ($_ eq "-fps") {
3887 # -fps only works on MacOS, via "webcollage-cocoa.m".
3888 # Ignore it if passed to this script in an X11 context.
3889 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3890 my $which = shift @ARGV;
3891 my @rest = @search_methods;
3894 my $pct = shift @rest;
3895 my $name = shift @rest;
3896 my $tfn = shift @rest;
3898 if ($name eq $which) {
3899 @search_methods = (100, $name, $tfn);
3904 error "no such search method as \"$which\"" unless ($ok);
3905 LOG (1, "DEBUG: using only \"$which\"");
3908 print STDERR "$copyright\nusage: $progname " .
3909 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3910 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3911 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3912 "\t\t [-background color] [-opacity f]\n" .
3913 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3914 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3915 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3916 "\t\t [-directory local-image-directory]\n" .
3922 if (!$root_p && !$no_output_p && !$cocoa_p) {
3923 print STDERR $copyright;
3924 error "the -root argument is mandatory (for now.)";
3927 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3928 error "\$DISPLAY is not set.";
3932 if ($verbose == 1) {
3933 $verbose_imgmap = 1;
3934 $verbose_warnings = 1;
3936 } elsif ($verbose == 2) {
3937 $verbose_imgmap = 1;
3938 $verbose_warnings = 1;
3941 } elsif ($verbose == 3) {
3942 $verbose_imgmap = 1;
3943 $verbose_warnings = 1;
3945 $verbose_filter = 1;
3947 } elsif ($verbose == 4) {
3948 $verbose_imgmap = 1;
3949 $verbose_warnings = 1;
3951 $verbose_filter = 1;
3954 } elsif ($verbose == 5) {
3955 $verbose_imgmap = 1;
3956 $verbose_warnings = 1;
3958 $verbose_filter = 1;
3962 } elsif ($verbose == 6) {
3963 $verbose_imgmap = 1;
3964 $verbose_warnings = 1;
3966 $verbose_filter = 1;
3971 } elsif ($verbose >= 7) {
3972 $verbose_imgmap = 1;
3973 $verbose_warnings = 1;
3975 $verbose_filter = 1;
3983 error ("$dict does not exist") unless (-f $dict);
3989 if ($imagemap_base && !($img_width && $img_height)) {
3990 error ("-size WxH is required with -imagemap");
3993 if (defined ($local_dir)) {
3994 $_ = "xscreensaver-getimage-file";
3995 which ($_) || error "$_ not found on \$PATH.";
4001 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
4006 x_or_pbm_output ($window_id);