3 # webcollage, Copyright © 1999-2015 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.171 $' =~ m/\s(\d[.\d]+)\s/s);
61 my $copyright = "WebCollage $version, Copyright (c) 1999-2015" .
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@^https?://www\.altavista\.com/@s ||
393 $url =~ m@^https?://random\.yahoo\.com/@s ||
394 $url =~ m@^https?://[^./]+\.google\.com/@s ||
395 $url =~ m@^https?://www\.livejournal\.com/@s) {
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';
401 my $ua = LWP::UserAgent->new ( agent => $user_agent,
405 $ua->proxy ('http', $http_proxy) if $http_proxy;
406 $ua->default_header ('Referer' => $referer) if $referer;
407 $ua->default_header ('Accept' => '*/*');
408 $ua->timeout($timeout) if $timeout;
411 $ua->add_handler ("request_send",
413 my ($req, $ua, $h) = @_;
414 print "\n>>[[\n"; $req->dump; print "\n]]\n";
417 $ua->add_handler ("response_data",
419 my ($req, $ua, $h, $data) = @_;
420 #print "\n<<[[\n"; print $data; print "\n]]\n";
423 $ua->add_handler ("request_done",
425 my ($req, $ua, $h) = @_;
426 print "\n<<[[\n"; $req->dump; print "\n]]\n";
432 LOG (1, " ==> GET $url");
433 LOG (1, " ==> User-Agent: $user_agent");
434 LOG (1, " ==> Referer: $referer") if $referer;
437 my $res = $ua->get ($url);
439 my $http = ($res ? $res->status_line : '') || '';
440 my $head = ($res ? $res->headers()->as_string : '') || '';
441 my $body = ($res && $res->is_success ? $res->decoded_content : '') || '';
443 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
445 $head =~ s/\r\n/\n/gs;
448 foreach (split (/\n/, $head)) {
449 LOG ($verbose_http, " <== $_");
453 my @L = split(/\r\n|\r|\n/, $body);
456 " <== [ body ]: $lines lines, " . length($body) . " bytes");
459 LOG (($verbose_net || $verbose_load), "null response: $url");
463 return ( $http, $head, $body );
467 # returns two values: the document headers; and the document body.
468 # if the given URL did a redirect, returns the redirected-to document.
470 sub get_document($$;$) {
471 my ($url, $referer, $timeout) = @_;
474 if (defined($referer) && $referer eq $driftnet_magic) {
475 return get_driftnet_file ($url);
478 if (defined($referer) && $referer eq $local_magic) {
479 return get_local_file ($url);
484 my $max_loop_count = 4;
487 if (defined($timeout) && $timeout <= 0) {
488 LOG (($verbose_net || $verbose_load), "timed out for $url");
493 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
495 if (defined ($timeout)) {
497 my $elapsed = $now - $start;
498 $timeout -= $elapsed;
502 return () unless $http; # error message already printed
504 $http =~ s/[\r\n]+$//s;
506 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
509 my ( $location ) = m@^location:[ \t]*(.*)$@im;
511 $location =~ s/[\r\n]$//;
513 LOG ($verbose_net, "redirect from $url to $location");
518 $referer =~ m@^(https?://[^/]+)@i;
520 } elsif (! ($url =~ m@^[a-z]+:@i)) {
522 s@[^/]+$@@g if m@^https?://[^/]+/@i;
523 $_ .= "/" if m@^https?://[^/]+$@i;
528 LOG ($verbose_net, "no Location with \"$http\"");
529 return ( $url, $body );
532 if ($loop_count++ > $max_loop_count) {
534 "too many redirects ($max_loop_count) from $orig_url");
539 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
541 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
543 # http errors -- return nothing.
549 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
555 return ( $url, $body );
561 # If we already have a cookie defined for this site, and the site is trying
562 # to overwrite that very same cookie, let it do so. This is because nytimes
563 # expires its cookies - it lets you upgrade to a new cookie without logging
564 # in again, but you have to present the old cookie to get the new cookie.
565 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
568 my ($host, $cookie) = @_;
569 my $oc = $cookies{$host};
572 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
574 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
576 if ($oc_name eq $nc_name &&
577 $oc_value ne $nc_value) {
578 $cookies{$host} = $cookie;
579 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
584 ############################################################################
586 # Extracting image URLs from HTML
588 ############################################################################
590 # given a URL and the body text at that URL, selects and returns a random
591 # image from it. returns () if no suitable images found.
593 sub pick_image_from_body($$) {
594 my ($url, $body) = @_;
599 # if there's at least one slash after the host, take off the last
601 if ( m@^https?://[^/]+/@io ) {
602 $base =~ s@[^/]+$@@go;
605 # if there are no slashes after the host at all, put one on the end.
606 if ( m@^https?://[^/]+$@io ) {
612 # strip out newlines, compress whitespace
619 # There are certain web sites that list huge numbers of dictionary
620 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
621 # Porn sites tend not to be reputable!)
623 # I do not want webcollage to filter on content: I want it to select
624 # randomly from the set of images on the web. All the logic here for
625 # rejecting some images is really a set of heuristics for rejecting
626 # images that are not really images: for rejecting *text* that is in
627 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
628 # the content of the pictures to be randomly selected from among all
629 # the available content.
631 # So, filtering out "dirty" pictures by looking for "dirty" keywords
632 # would be wrong: dirty pictures exist, like it or not, so webcollage
633 # should be able to select them.
635 # However, picking a random URL is a hard thing to do. The mechanism I'm
636 # using is to search for a selection of random words. This is not
637 # perfect, but works ok most of the time. The way it breaks down is when
638 # some URLs get precedence because their pages list *every word* as
639 # related -- those URLs come up more often than others.
641 # So, after we've retrieved a URL, if it has too many keywords, reject
642 # it. We reject it not on the basis of what those keywords are, but on
643 # the basis that by having so many, the page has gotten an unfair
644 # advantage against our randomizer.
647 foreach my $trip (@tripwire_words) {
648 $trip_count++ if m/$trip/i;
651 if ($trip_count >= $#tripwire_words - 2) {
652 LOG (($verbose_filter || $verbose_load),
653 "there is probably a dictionary in \"$url\": rejecting.");
654 $rejected_urls{$url} = -1;
664 foreach (split(/ *</)) {
665 if ( m/^meta.*["']keywords["']/i ) {
667 # Likewise, reject any web pages that have a KEYWORDS meta tag
672 LOG (($verbose_filter || $verbose_load),
673 "excessive keywords ($L bytes) in $url: rejecting.");
674 $rejected_urls{$url} = $L;
679 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
682 } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
683 m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
684 ["']? (image_src|og:image) ["']? /six) {
686 my $was_inline = (lc($1) eq 'img');
687 my $was_meta = (lc($1) eq 'link' || lc($1) eq 'meta');
690 # For <link rel="image_src" href="...">
691 # and <meta property="og:image" content="...">
694 next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
698 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
699 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
704 ( $site = $base ) =~ s@^(https?://[^/]*).*@$1@gio;
706 } elsif ( ! m@^[^/:?]+:@ ) {
709 1 while (s@/[^/]+/\.\./@/@g);
713 if ( ! m@^https?://@io ) {
718 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
722 # skip really short or really narrow images
723 if ( $width && $width < $min_width) {
724 if (!$height) { $height = "?"; }
725 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
729 if ( $height && $height < $min_height) {
730 if (!$width) { $width = "?"; }
731 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
735 # skip images with ratios that make them look like banners.
736 if ($min_ratio && $width && $height &&
737 ($width * $min_ratio ) > $height) {
738 if (!$height) { $height = "?"; }
739 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
743 # skip GIFs with a small number of pixels -- those usually suck.
744 if ($width && $height &&
746 ($width * $height) < $min_gif_area) {
747 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
751 # skip images with a URL that indicates a Yahoo thumbnail.
752 if (m@\.yimg\.com/.*/t/@) {
753 if (!$width) { $width = "?"; }
754 if (!$height) { $height = "?"; }
755 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
761 if ($unique_urls{$url}) {
762 LOG ($verbose_filter, " skip duplicate image $_");
766 LOG ($verbose_filter,
768 ($width && $height ? " (${width}x${height})" : "") .
769 ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
775 $weight = 20; # meta tag images are far preferable to inline images.
777 if ($url !~ m@[.](gif|png)$@io ) {
778 $weight += 2; # JPEGs are preferable to GIFs and PNGs.
781 $weight += 4; # pointers to images are preferable to inlined images.
785 $unique_urls{$url}++;
786 for (my $i = 0; $i < $weight; $i++) {
787 $urls[++$#urls] = $url;
792 my $fsp = ($body =~ m@<frameset@i);
797 @urls = depoison (@urls);
800 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
804 # pick a random element of the table
805 my $i = int(rand($#urls+1));
808 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
814 # Given a URL and the RSS feed from that URL, pick a random image from
815 # the feed. This is a lot simpler than extracting images out of a page:
816 # we already know we have reasonable images, so we just pick one.
817 # Returns: the real URL of the page (preferably not the RSS version),
820 sub pick_image_from_rss($$) {
821 my ( $url, $body ) = @_;
822 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
824 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
825 $base = $url unless $base;
827 # pick a random element of the table
829 my $i = int(rand(scalar @suitable));
830 my $url = $suitable[$i];
831 LOG ($verbose_load, "picked image " .($i+1) . "/" .
832 ($#suitable+1) . ": $url");
833 return ($base, $url);
839 ############################################################################
841 # Subroutines for getting pages and images out of search engines
843 ############################################################################
846 sub pick_dictionary() {
847 my @dicts = ("/usr/dict/words",
848 "/usr/share/dict/words",
849 "/usr/share/lib/dict/words",
850 "/usr/share/dict/cracklib-small",
851 "/usr/share/dict/cracklib-words"
853 foreach my $f (@dicts) {
859 error ("$dicts[0] does not exist") unless defined($wordlist);
862 # returns a random word from the dictionary
866 return undef unless open (my $in, '<', $wordlist);
868 my $size = (stat($in))[7];
873 error ("looping ($count) while reading $wordlist")
876 my $pos = int (rand ($size));
877 if (seek ($in, $pos, 0)) {
878 $word = <$in>; # toss partial line
879 $word = <$in>; # keep next line
883 next if ($word =~ m/^[-\']/);
887 $word =~ s/^[^a-z]+//s;
888 $word =~ s/[^a-z]+$//s;
894 $word =~ s/ally$/al/s;
895 $word =~ s/izes$/ize/s;
896 $word =~ s/esses$/ess/s;
897 $word =~ s/(.{5})ing$/$1/s;
899 next if (length ($word) > 14);
905 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
906 $word = "\%22$word\%22"; # And put quotes (%22) around it.
913 sub random_words($) {
915 return (random_word() . $sep .
916 random_word() . $sep .
917 random_word() . $sep .
918 random_word() . $sep .
925 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
932 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
941 $s =~ s/\"/"/gi;
945 sub html_unquote($) {
947 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
948 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
953 # Loads the given URL (a search on some search engine) and returns:
954 # - the total number of hits the search engine claimed it had;
955 # - a list of URLs from the page that the search engine returned;
956 # Note that this list contains all kinds of internal search engine
957 # junk URLs too -- caller must prune them.
959 sub pick_from_search_engine($$$) {
960 my ( $timeout, $search_url, $words ) = @_;
965 print STDERR "\n\n" if ($verbose_load);
967 LOG ($verbose_load, "words: $_");
968 LOG ($verbose_load, "URL: $search_url");
970 $last_search = $search_url; # for warnings
973 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
974 if (defined ($timeout)) {
975 $timeout -= (time - $start);
978 LOG (($verbose_net || $verbose_load),
979 "timed out (late) for $search_url");
985 return () if (! $body);
990 if ($body =~ m/^\{\"/s) { # Google AJAX JSON response.
992 my @chunks = split (/"GsearchResultClass"/, $body);
997 my ($img) = m/"unescapedUrl":"(.*?)"/si;
998 my ($url) = m/"originalContextUrl":"(.*?)"/si;
999 next unless ($img && $url);
1001 "?imgurl=" . url_quote($img) .
1002 "&imgrefurl=" . url_quote($url) .
1004 $body2 .= "<A HREF=\"" . html_quote($url) . "\">$n</A>\n";
1007 $body = $body2 if $body2;
1010 my $search_count = "?";
1011 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
1013 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
1015 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
1017 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1019 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1021 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1023 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1025 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1027 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1028 $search_count = $1; # lycos
1029 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1030 $search_count = $1; # hotbot
1031 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1032 $search_count = "0";
1033 } elsif ($body =~ m@found no document matching@i) { # avtext
1034 $search_count = "0";
1036 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1038 # if ($search_count eq "?" || $search_count eq "0") {
1039 # my $file = "/tmp/wc.html";
1040 # open (my $out, '>', $file) || error ("writing $file: $!");
1043 # print STDERR blurb() . "###### wrote $file\n";
1047 my $length = length($body);
1056 foreach (split(/\n/)) {
1058 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1061 if (m/\bm="{(.*?)}"/s) { # Bing info is inside JSON crud
1062 my $json = html_unquote($1);
1063 my ($href) = ($json =~ m/\bsurl:"(.*?)"/s);
1064 my ($img) = ($json =~ m/\bimgurl:"(.*?)"/s);
1065 $u = "$img\t$href" if ($img && $href);
1067 } elsif ($u =~ m/^\"([^\"]*)\"/) { $u = $1 # quoted string
1068 } elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; # or token
1071 if ( $rejected_urls{$u} ) {
1072 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1076 LOG ($verbose_http, " HREF: $u");
1078 $subpages[++$#subpages] = $u;
1081 if ( $#subpages < 0 ) {
1082 LOG ($verbose_filter,
1083 "found nothing on $base ($length bytes, $href_count links).");
1087 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1089 return ($search_count, @subpages);
1097 my ($h) = m@^https?://([^/: \t\r\n]+)@i;
1099 next unless defined($h);
1101 if ($poisoners{$h}) {
1102 LOG (($verbose_filter), " rejecting poisoner: $_");
1105 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1107 LOG (($verbose_filter), " rejecting poisoner: $_");
1110 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1112 LOG (($verbose_filter), " rejecting poisoner: $_");
1122 # given a list of URLs, picks one at random; loads it; and returns a
1123 # random image from it.
1124 # returns the url of the page loaded; the url of the image chosen.
1126 sub pick_image_from_pages($$$$@) {
1127 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1129 $total_hit_count = "?" unless defined($total_hit_count);
1131 @pages = depoison (@pages);
1133 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1134 " ($total_hit_count total)");
1136 return () if ($#pages < 0);
1138 my $i = int(rand($#pages+1));
1139 my $page = $pages[$i];
1141 LOG ($verbose_load, "picked page $page");
1143 $suppress_audit = 1;
1145 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1147 if (!$base2 || !$body2) {
1152 my $img = pick_image_from_body ($base2, $body2);
1156 return ($base2, $img);
1163 #############################################################################
1165 ## Pick images from random pages returned by the Yahoo Random Link
1167 #############################################################################
1170 #my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1173 # Picks a random page; picks a random image on that page;
1174 # returns two URLs: the page containing the image, and the image.
1175 # Returns () if nothing found this time.
1177 #sub pick_from_yahoo_random_link($) {
1178 # my ($timeout) = @_;
1180 # print STDERR "\n\n" if ($verbose_load);
1181 # LOG ($verbose_load, "URL: $yahoo_random_link");
1183 # $last_search = $yahoo_random_link; # for warnings
1185 # $suppress_audit = 1;
1187 # my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1188 # if (!$base || !$body) {
1193 # LOG ($verbose_load, "redirected to: $base");
1195 # my $img = pick_image_from_body ($base, $body);
1199 # return ($base, $img);
1206 ############################################################################
1208 # Pick images from random pages returned by the Alta Vista Random Link
1209 # Note: this seems to have gotten a *lot* less random lately (2007).
1211 ############################################################################
1214 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1217 # Picks a random page; picks a random image on that page;
1218 # returns two URLs: the page containing the image, and the image.
1219 # Returns () if nothing found this time.
1221 sub pick_from_alta_vista_random_link($) {
1224 print STDERR "\n\n" if ($verbose_load);
1225 LOG ($verbose_load, "URL: $alta_vista_random_link");
1227 $last_search = $alta_vista_random_link; # for warnings
1229 $suppress_audit = 1;
1231 my ( $base, $body ) = get_document ($alta_vista_random_link,
1233 if (!$base || !$body) {
1238 LOG ($verbose_load, "redirected to: $base");
1240 my $img = pick_image_from_body ($base, $body);
1244 return ($base, $img);
1251 ############################################################################
1253 # Pick images by feeding random words into Alta Vista Image Search
1255 ############################################################################
1258 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1259 "?ipht=1" . # photos
1260 "&igrph=1" . # graphics
1263 "&micat=1" . # no partner sites
1264 "&sc=on" . # "site collapse"
1268 sub pick_from_alta_vista_images($) {
1271 my $words = random_word();
1272 my $page = (int(rand(9)) + 1);
1273 my $search_url = $alta_vista_images_url . $words;
1276 $search_url .= "&pgno=" . $page; # page number
1277 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1280 my ($search_hit_count, @subpages) =
1281 pick_from_search_engine ($timeout, $search_url, $words);
1283 my @candidates = ();
1284 foreach my $u (@subpages) {
1286 # avimages is encoding their URLs now.
1287 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1288 $u = url_unquote($u);
1290 next unless ($u =~ m@^https?://@i); # skip non-HTTP or relative URLs
1291 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1292 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1293 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1294 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1296 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1297 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1299 LOG ($verbose_filter, " candidate: $u");
1300 push @candidates, $u;
1303 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1304 $timeout, @candidates);
1309 ############################################################################
1311 # Pick images from Aptix security cameras
1312 # Cribbed liberally from google image search code.
1313 # By Jason Sullivan <jasonsul@us.ibm.com>
1315 ############################################################################
1317 my $aptix_images_url = ("http://www.google.com/search" .
1318 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1321 sub pick_from_security_camera($) {
1324 my $page = (int(rand(9)) + 1);
1325 my $num = 20; # 20 images per page
1326 my $search_url = $aptix_images_url;
1329 $search_url .= "&start=" . $page*$num; # page number
1330 $search_url .= "&num=" . $num; #images per page
1333 my ($search_hit_count, @subpages) =
1334 pick_from_search_engine ($timeout, $search_url, '');
1336 my @candidates = ();
1338 foreach my $u (@subpages) {
1339 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1340 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1342 LOG ($verbose_filter, " candidate: $u");
1343 push @candidates, $u;
1347 @candidates = depoison (@candidates);
1348 return () if ($#candidates < 0);
1349 my $i = int(rand($#candidates+1));
1350 my $img = $candidates[$i];
1351 my $ref = $referers{$img};
1353 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1354 return ($ref, $img);
1358 ############################################################################
1360 # Pick images by feeding random words into Google Image Search.
1361 # By Charles Gales <gales@us.ibm.com>
1363 ############################################################################
1366 my $google_images_url = "http://ajax.googleapis.com/ajax/services/" .
1373 sub pick_from_google_images($;$$) {
1374 my ($timeout, $words, $max_page) = @_;
1376 if (!defined($words)) {
1377 $words = random_word(); # only one word for Google
1380 my $off = int(rand(40));
1381 my $search_url = $google_images_url . $words . "&start=" . $off;
1383 my ($search_hit_count, @subpages) =
1384 pick_from_search_engine ($timeout, $search_url, $words);
1386 my @candidates = ();
1388 foreach my $u (@subpages) {
1389 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1390 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1392 $u = html_unquote($u);
1393 if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1396 $ref = url_decode($ref);
1397 $img = url_decode($img);
1399 $img = "http://$img" unless ($img =~ m/^https?:/i);
1401 LOG ($verbose_filter, " candidate: $ref");
1402 push @candidates, $img;
1403 $referers{$img} = $ref;
1407 @candidates = depoison (@candidates);
1408 return () if ($#candidates < 0);
1409 my $i = int(rand($#candidates+1));
1410 my $img = $candidates[$i];
1411 my $ref = $referers{$img};
1413 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1414 return ($ref, $img);
1419 ############################################################################
1421 # Pick images by feeding random numbers into Google Image Search.
1422 # By jwz, suggested by Ian O'Donnell.
1424 ############################################################################
1428 sub pick_from_google_image_numbers($) {
1432 my $number = int(rand($max));
1434 $number = sprintf("%04d", $number)
1437 pick_from_google_images ($timeout, "$number");
1442 ############################################################################
1444 # Pick images by feeding random digital camera file names into
1445 # Google Image Search.
1446 # By jwz, inspired by the excellent Random Personal Picture Finder
1447 # at http://www.diddly.com/random/
1449 ############################################################################
1453 # Common digital camera file name formats, as described at
1454 # http://www.diddly.com/random/about.html
1456 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1457 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1458 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1459 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1460 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1461 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1462 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1463 int(rand(0xC)), int(rand(30))+1,
1465 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1466 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1467 sub { my $n = int(rand(9999)); # Canon
1468 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1469 sub { my $n = int(rand(9999)); # Canon
1470 sprintf ("1%02d-%04d_IMG.jpg",
1471 int($n/100), $n); },
1472 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1473 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1474 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1475 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1476 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1477 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1478 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1479 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1480 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1481 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1482 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1483 # int(rand(12))+1, int(rand(31))+1,
1484 # int(rand(999))); },
1485 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1486 # int(rand(6)), # year
1487 # int(rand(12))+1, int(rand(31))+1,
1488 # int(rand(999))); },
1489 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1490 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1491 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1492 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1497 sub pick_from_google_image_photos($) {
1500 my $i = int(rand($#photomakers + 1));
1501 my $fn = $photomakers[$i];
1503 #$file .= "%20filetype:jpg";
1505 pick_from_google_images ($timeout, $file);
1509 ############################################################################
1511 # Pick images by feeding random words into Google Image Search.
1512 # By the way: fuck Microsoft.
1514 ############################################################################
1516 my $bing_images_url = "http://www.bing.com/images/async?q=";
1520 sub pick_from_bing_images($;$$) {
1521 my ($timeout, $words, $max_page) = @_;
1523 if (!defined($words)) {
1524 $words = random_word(); # only one word for Bing
1527 my $off = int(rand(300));
1528 my $search_url = $bing_images_url . $words . "&first=" . $off;
1530 my ($search_hit_count, @subpages) =
1531 pick_from_search_engine ($timeout, $search_url, $words);
1533 my @candidates = ();
1535 foreach my $u (@subpages) {
1536 my ($img, $ref) = ($u =~ m/^(.*?)\t(.*)$/s);
1538 LOG ($verbose_filter, " candidate: $ref");
1539 push @candidates, $img;
1540 $referers{$img} = $ref;
1543 @candidates = depoison (@candidates);
1544 return () if ($#candidates < 0);
1545 my $i = int(rand($#candidates+1));
1546 my $img = $candidates[$i];
1547 my $ref = $referers{$img};
1549 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1550 return ($ref, $img);
1556 ############################################################################
1558 # Pick images by feeding random numbers into Bing Image Search.
1560 ############################################################################
1563 sub pick_from_bing_image_numbers($) {
1567 my $number = int(rand($max));
1569 $number = sprintf("%04d", $number)
1572 pick_from_bing_images ($timeout, "$number");
1576 ############################################################################
1578 # Pick images by feeding random numbers into Bing Image Search.
1580 ############################################################################
1583 sub pick_from_bing_image_photos($) {
1586 my $i = int(rand($#photomakers + 1));
1587 my $fn = $photomakers[$i];
1590 pick_from_bing_images ($timeout, $file);
1594 ############################################################################
1596 # Pick images by feeding random words into Alta Vista Text Search
1598 ############################################################################
1601 my $alta_vista_url = "http://www.altavista.com/web/results" .
1605 "&sc=on" . # "site collapse"
1610 sub pick_from_alta_vista_text($) {
1613 my $words = random_words('%20');
1614 my $page = (int(rand(9)) + 1);
1615 my $search_url = $alta_vista_url . $words;
1618 $search_url .= "&pgno=" . $page;
1619 $search_url .= "&stq=" . (($page-1) * 10);
1622 my ($search_hit_count, @subpages) =
1623 pick_from_search_engine ($timeout, $search_url, $words);
1625 my @candidates = ();
1626 foreach my $u (@subpages) {
1628 # Those altavista fuckers are playing really nasty redirection games
1629 # these days: the filter your clicks through their site, but use
1630 # onMouseOver to make it look like they're not! Well, it makes it
1631 # easier for us to identify search results...
1633 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1634 $u = url_unquote($u);
1636 next unless ($u =~ m@^https?://@i); # skip non-HTTP or relative URLs
1637 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1638 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1640 LOG ($verbose_filter, " candidate: $u");
1641 push @candidates, $u;
1644 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1645 $timeout, @candidates);
1650 ############################################################################
1652 # Pick images by feeding random words into Hotbot
1654 ############################################################################
1656 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1658 "&descriptiontype=0" .
1665 "&cobrand=undefined" .
1668 sub pick_from_hotbot_text($) {
1671 $last_search = $hotbot_search_url; # for warnings
1673 # lycos seems to always give us back dictionaries and word lists if
1674 # we search for more than one word...
1676 my $words = random_word();
1678 my $start = int(rand(8)) * 10 + 1;
1679 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1681 my ($search_hit_count, @subpages) =
1682 pick_from_search_engine ($timeout, $search_url, $words);
1684 my @candidates = ();
1685 foreach my $u (@subpages) {
1687 # Hotbot plays redirection games too
1689 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1690 # $u = url_decode($1);
1692 next unless ($u =~ m@^https?://@i); # skip non-HTTP or relative URLs
1693 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1694 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1695 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1697 LOG ($verbose_filter, " candidate: $u");
1698 push @candidates, $u;
1701 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1702 $timeout, @candidates);
1707 ############################################################################
1709 # Pick images by feeding random words into Lycos
1711 ############################################################################
1713 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1719 sub pick_from_lycos_text($) {
1722 $last_search = $lycos_search_url; # for warnings
1724 # lycos seems to always give us back dictionaries and word lists if
1725 # we search for more than one word...
1727 my $words = random_word();
1729 my $start = int(rand(8)) * 10 + 1;
1730 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1732 my ($search_hit_count, @subpages) =
1733 pick_from_search_engine ($timeout, $search_url, $words);
1735 my @candidates = ();
1736 foreach my $u (@subpages) {
1738 # Lycos plays redirection games.
1740 # next unless ($u =~ m@^https?://click.lycos.com/director.asp
1745 # $u = url_decode($1);
1747 next unless ($u =~ m@^https?://@i); # skip non-HTTP or relative URLs
1748 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1749 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1750 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1751 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1754 LOG ($verbose_filter, " candidate: $u");
1755 push @candidates, $u;
1758 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1759 $timeout, @candidates);
1764 ############################################################################
1766 # Pick images by feeding random words into news.yahoo.com
1768 ############################################################################
1770 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1775 sub pick_from_yahoo_news_text($) {
1778 $last_search = $yahoo_news_url; # for warnings
1780 my $words = random_word();
1781 my $search_url = $yahoo_news_url . $words;
1783 my ($search_hit_count, @subpages) =
1784 pick_from_search_engine ($timeout, $search_url, $words);
1786 my @candidates = ();
1787 foreach my $u (@subpages) {
1789 # de-redirectize the URLs
1790 $u =~ s@^https?://rds\.yahoo\.com/.*-http%3A@http:@s;
1792 # only accept URLs on Yahoo's news site
1793 next unless ($u =~ m@^https?://dailynews\.yahoo\.com/@i ||
1794 $u =~ m@^https?://story\.news\.yahoo\.com/@i);
1795 next unless ($u =~ m@&u=/@);
1797 LOG ($verbose_filter, " candidate: $u");
1798 push @candidates, $u;
1801 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1802 $timeout, @candidates);
1807 ############################################################################
1809 # Pick images from LiveJournal's list of recently-posted images.
1811 ############################################################################
1813 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1815 # With most of our image sources, we get a random page and then select
1816 # from the images on it. However, in the case of LiveJournal, the page
1817 # of images tends to update slowly; so we'll remember the last N entries
1818 # on it and randomly select from those, to get a wider variety each time.
1820 my $lj_cache_size = 1000;
1821 my @lj_cache = (); # fifo, for ordering by age
1822 my %lj_cache = (); # hash, for detecting dups
1825 sub pick_from_livejournal_images($) {
1828 $last_search = $livejournal_img_url; # for warnings
1830 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1832 # Often the document comes back empty. If so, just use the cache.
1833 # return () unless $body;
1834 $body = '' unless defined($body);
1837 $body =~ s/(<recent-image)\b/\n$1/gsi;
1839 foreach (split (/\n/, $body)) {
1840 next unless (m/^<recent-image\b/);
1841 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1842 my $img = html_unquote ($1);
1844 next if ($lj_cache{$img}); # already have it
1846 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1847 my $page = html_unquote ($1);
1848 my @pair = ($img, $page);
1849 LOG ($verbose_filter, " candidate: $img");
1850 push @lj_cache, \@pair;
1851 $lj_cache{$img} = \@pair;
1854 return () if ($#lj_cache == -1);
1856 my $n = $#lj_cache+1;
1857 my $i = int(rand($n));
1858 my ($img, $page) = @{$lj_cache[$i]};
1860 # delete this one from @lj_cache and from %lj_cache.
1862 @lj_cache = ( @lj_cache[0 .. $i-1],
1863 @lj_cache[$i+1 .. $#lj_cache] );
1864 delete $lj_cache{$img};
1866 # Keep the size of the cache under the limit by nuking older entries
1868 while ($#lj_cache >= $lj_cache_size) {
1869 my $pairP = shift @lj_cache;
1870 my $img = $pairP->[0];
1871 delete $lj_cache{$img};
1874 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1876 return ($page, $img);
1880 ############################################################################
1882 # Pick images from ircimages.com (images that have been in the /topic of
1883 # various IRC channels.)
1885 ############################################################################
1887 my $ircimages_url = "http://ircimages.com/";
1890 sub pick_from_ircimages($) {
1893 $last_search = $ircimages_url; # for warnings
1895 my $n = int(rand(2900));
1896 my $search_url = $ircimages_url . "page-$n";
1898 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1899 return () unless $body;
1901 my @candidates = ();
1904 $body =~ s/(<A)\b/\n$1/gsi;
1906 foreach (split (/\n/, $body)) {
1908 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1911 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1912 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1914 next unless ($u =~ m/^https?:/i);
1915 next if ($u =~ m@^https?://(searchirc\.com\|ircimages\.com)@i);
1916 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1918 LOG ($verbose_http, " HREF: $u");
1919 push @candidates, $u;
1922 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1924 return () if ($#candidates == -1);
1926 my $i = int(rand($#candidates+1));
1927 my $img = $candidates[$i];
1929 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1932 $search_url = $img; # hmm...
1933 return ($search_url, $img);
1937 ############################################################################
1939 # Pick images from Twitpic's list of recently-posted images.
1941 ############################################################################
1943 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1945 # With most of our image sources, we get a random page and then select
1946 # from the images on it. However, in the case of Twitpic, the page
1947 # of images tends to update slowly; so we'll remember the last N entries
1948 # on it and randomly select from those, to get a wider variety each time.
1950 my $twitpic_cache_size = 1000;
1951 my @twitpic_cache = (); # fifo, for ordering by age
1952 my %twitpic_cache = (); # hash, for detecting dups
1955 sub pick_from_twitpic_images($) {
1958 $last_search = $twitpic_img_url; # for warnings
1960 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1966 $body =~ s/(<item)\b/\n$1/gsi;
1968 my @items = split (/\n/, $body);
1971 next unless (m@<link>([^<>]*)</link>@si);
1972 my $page = html_unquote ($1);
1977 next if ($twitpic_cache{$page}); # already have it
1979 LOG ($verbose_filter, " candidate: $page");
1980 push @twitpic_cache, $page;
1981 $twitpic_cache{$page} = $page;
1985 # Pull from the cache.
1987 return () if ($#twitpic_cache == -1);
1989 my $n = $#twitpic_cache+1;
1990 my $i = int(rand($n));
1991 my $page = $twitpic_cache[$i];
1993 # delete this one from @twitpic_cache and from %twitpic_cache.
1995 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1996 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1997 delete $twitpic_cache{$page};
1999 # Keep the size of the cache under the limit by nuking older entries
2001 while ($#twitpic_cache >= $twitpic_cache_size) {
2002 my $page = shift @twitpic_cache;
2003 delete $twitpic_cache{$page};
2006 ( $base, $body ) = get_document ($page, undef, $timeout);
2008 $body = '' unless defined($body);
2010 foreach (split (/<img\s+/, $body)) {
2011 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
2014 next if m@/images/@s;
2018 $img = "http:$img" if ($img =~ m@^//@s); # Oh come on
2020 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
2021 if ($img =~ m@^/@) {
2022 $base =~ s@^(https?://[^/]+)/.*@$1@s;
2023 $img = $base . $img;
2029 LOG ($verbose_load, "no matching images on $page\n");
2033 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2035 return ($page, $img);
2039 ############################################################################
2041 # Pick images from Twitter's list of recently-posted updates.
2043 ############################################################################
2045 # With most of our image sources, we get a random page and then select
2046 # from the images on it. However, in the case of Twitter, the page
2047 # of images only updates once a minute; so we'll remember the last N entries
2048 # on it and randomly select from those, to get a wider variety each time.
2050 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2051 "public_timeline.json" .
2052 "?include_entities=true" .
2053 "&include_rts=true" .
2056 my $twitter_cache_size = 1000;
2058 my @twitter_cache = (); # fifo, for ordering by age
2059 my %twitter_cache = (); # hash, for detecting dups
2063 sub pick_from_twitter_images($) {
2066 $last_search = $twitter_img_url; # for warnings
2068 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2072 $body =~ s/[\r\n]+/ /gs;
2074 # Parsing JSON is a pain in the ass. So we halfass it as usual.
2075 $body =~ s/^\[|\]$//s;
2076 $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2077 my @items = split (/},{/, $body);
2079 my ($name) = m@"screen_name":"([^\"]+)"@si;
2080 my ($img) = m@"media_url":"([^\"]+)"@si;
2081 my ($page) = m@"display_url":"([^\"]+)"@si;
2082 next unless ($name && $img && $page);
2083 foreach ($img, $page) {
2085 $_ = "http://$_" unless (m/^http/si);
2088 next if ($twitter_cache{$page}); # already have it
2090 LOG ($verbose_filter, " candidate: $page - $img");
2091 push @twitter_cache, $page;
2092 $twitter_cache{$page} = $img;
2096 # Pull from the cache.
2098 return () if ($#twitter_cache == -1);
2100 my $n = $#twitter_cache+1;
2101 my $i = int(rand($n));
2102 my $page = $twitter_cache[$i];
2103 my $url = $twitter_cache{$page};
2105 # delete this one from @twitter_cache and from %twitter_cache.
2107 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2108 @twitter_cache[$i+1 .. $#twitter_cache] );
2109 delete $twitter_cache{$page};
2111 # Keep the size of the cache under the limit by nuking older entries
2113 while ($#twitter_cache >= $twitter_cache_size) {
2114 my $page = shift @twitter_cache;
2115 delete $twitter_cache{$page};
2118 LOG ($verbose_load, "picked page $url");
2120 $suppress_audit = 1;
2122 return ($page, $url);
2126 ############################################################################
2128 # Pick images from Flickr's page of recently-posted photos.
2130 ############################################################################
2132 my $flickr_img_url = "http://www.flickr.com/explore/";
2134 # Like LiveJournal, the Flickr page of images tends to update slowly,
2135 # so remember the last N entries on it and randomly select from those.
2137 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2138 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2140 my $flickr_cache_size = 1000;
2141 my @flickr_cache = (); # fifo, for ordering by age
2142 my %flickr_cache = (); # hash, for detecting dups
2146 sub pick_from_flickr_recent($) {
2149 my $start = 16 * int(rand(100));
2151 $last_search = $flickr_img_url; # for warnings
2152 $last_search .= "?start=$start" if ($start > 0);
2154 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2156 # If the document comes back empty. just use the cache.
2157 # return () unless $body;
2158 $body = '' unless defined($body);
2163 if ($body =~ m@{ *"_data": \[ ( .*? \} ) \]@six) {
2166 LOG ($verbose_load, "flickr unparsable: $last_search");
2170 $body =~ s/[\r\n]/ /gs;
2171 $body =~ s/(\},) *(\{)/$1\n$2/gs; # "_flickrModelRegistry"
2173 foreach my $chunk (split (/\n/, $body)) {
2174 my ($img) = ($chunk =~ m@"displayUrl": *"(.*?)"@six);
2175 next unless defined ($img);
2177 $img = "//" unless ($img =~ m@^/@s);
2178 $img = "http:$img" unless ($img =~ m/^http/s);
2180 my ($user) = ($chunk =~ m/"pathAlias": *"(.*?)"/si);
2181 next unless defined ($user);
2183 my ($id) = ($img =~ m@/\d+/(\d+)_([\da-f]+)_@si);
2184 my ($page) = "https://www.flickr.com/photos/$user/$id/";
2186 # $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2189 next if ($flickr_cache{$img}); # already have it
2191 my @pair = ($img, $page, $start);
2192 LOG ($verbose_filter, " candidate: $img");
2193 push @flickr_cache, \@pair;
2194 $flickr_cache{$img} = \@pair;
2198 return () if ($#flickr_cache == -1);
2200 my $n = $#flickr_cache+1;
2201 my $i = int(rand($n));
2202 my ($img, $page) = @{$flickr_cache[$i]};
2204 # delete this one from @flickr_cache and from %flickr_cache.
2206 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2207 @flickr_cache[$i+1 .. $#flickr_cache] );
2208 delete $flickr_cache{$img};
2210 # Keep the size of the cache under the limit by nuking older entries
2212 while ($#flickr_cache >= $flickr_cache_size) {
2213 my $pairP = shift @flickr_cache;
2214 my $img = $pairP->[0];
2215 delete $flickr_cache{$img};
2218 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2220 return ($page, $img);
2224 ############################################################################
2226 # Pick images from a random RSS feed on Flickr.
2228 ############################################################################
2230 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2231 "?format=rss_200_enc&tagmode=any&tags=");
2233 # Picks a random RSS feed; picks a random image from that feed;
2234 # returns 2 URLs: the page containing the image, and the image.
2235 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2238 sub pick_from_flickr_random($) {
2239 my $timeout = shift;
2241 my $words = random_words(',');
2242 my $rss = $flickr_rss_base . $words;
2243 $last_search = $rss;
2248 print STDERR "\n\n" if ($verbose_load);
2249 LOG ($verbose_load, "words: $_");
2250 LOG ($verbose_load, "URL: $last_search");
2252 $suppress_audit = 1;
2254 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2255 if (!$base || !$body) {
2261 ($base, $img) = pick_image_from_rss ($base, $body);
2263 return () unless defined ($img);
2265 LOG ($verbose_load, "redirected to: $base");
2266 return ($base, $img);
2270 ############################################################################
2272 # Pick random images from Instagram.
2274 ############################################################################
2276 my $instagram_url_base = "https://api.instagram.com/v1/media/popular";
2279 sub pick_from_instagram($) {
2280 my $timeout = shift;
2282 # Liberated access tokens.
2283 # jsdo.it search for: instagram client_id
2284 # Google search for: instagram "&client_id=" site:jsfiddle.net
2285 my @tokens = ('b59fbe4563944b6c88cced13495c0f49', # gramfeed.com
2286 'fa26679250df49c48a33fbcf30aae989', # instac.at
2287 'd9494686198d4dfeb954979a3e270e5e', # iconosquare.com
2288 '793ef48bb18e4197b61afce2d799b81c', # jsdo.it
2289 '67b8a3e0073449bba70600d0fc68e6cb', # jsdo.it
2290 '26a098e0df4d4b9ea8b4ce6c505b7742', # jsdo.it
2291 '2437cbcd906a4c10940f990d283d3cd5', # jsdo.it
2292 '191c7d7d5312464cbd92134f36ffdab5', # jsdo.it
2293 'acfec809437b4340b2c38f66503af774', # jsdo.it
2294 'e9f77604a3a24beba949c12d18130988', # jsdo.it
2295 '2cd7bcf68ae346529770073d311575b3', # jsdo.it
2296 '830c600fe8d742e2ab3f3b94f9bb22b7', # jsdo.it
2297 '55865a0397ad41e5997dd95ef4df8da1', # jsdo.it
2298 '192a5742f3644ea8bed1d25e439286a8', # jsdo.it
2299 '38ed1477e7a44595861b8842cdb8ba23', # jsdo.it
2300 'e52f79f645f54488ad0cc47f6f55ade6', # jsfiddle.net
2303 my $tok = $tokens[int(rand($#tokens+1))];
2304 $last_search = $instagram_url_base . "?client_id=" . $tok;
2306 print STDERR "\n\n" if ($verbose_load);
2307 LOG ($verbose_load, "URL: $last_search");
2309 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2310 if (!$base || !$body) {
2315 $body =~ s/("link")/\001$1/gs;
2316 my @chunks = split(/\001/, $body);
2321 my ($url) = m/"link":\s*"(.*?)"/s;
2322 my ($img) = m/"standard_resolution":{"url":\s*"(.*?)"/s;
2323 ($img) = m/"url":\s*"(.*?)"/s unless $url;
2324 next unless ($url && $img);
2325 push @urls, [ $url, $img ];
2329 LOG ($verbose_load, "no images on $last_search");
2333 my $i = int(rand($#urls+1));
2334 my ($url, $img) = @{$urls[$i]};
2336 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
2337 return ($url, $img);
2341 ############################################################################
2343 # Pick images by waiting for driftnet to populate a temp dir with files.
2344 # Requires driftnet version 0.1.5 or later.
2345 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2346 # for images being downloaded by others.)
2347 # Driftnet/webcollage integration by jwz.
2349 ############################################################################
2352 sub pick_from_driftnet($) {
2355 my $id = $driftnet_magic;
2356 my $dir = $driftnet_dir;
2360 error ("\$driftnet_dir unset?") unless ($dir);
2363 error ("$dir unreadable") unless (-d "$dir/.");
2365 $timeout = $http_timeout unless ($timeout);
2368 while ($now = time, $now < $start + $timeout) {
2369 opendir (my $dir, $dir) || error ("$dir: $!");
2370 while (my $file = readdir($dir)) {
2371 next if ($file =~ m/^\./);
2372 $file = "$dir/$file";
2374 LOG ($verbose_load, "picked file $file ($id)");
2375 return ($id, $file);
2379 LOG (($verbose_net || $verbose_load), "timed out for $id");
2384 sub get_driftnet_file($) {
2387 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2389 my $id = $driftnet_magic;
2390 error ("$id: $file not in $driftnet_dir?")
2391 unless ($file =~ m@^\Q$driftnet_dir@o);
2393 open (my $in, '<', $file) || error ("$id: $file: $!");
2395 local $/ = undef; # read entire file
2397 close ($in) || error ("$id: $file: $!");
2398 unlink ($file) || error ("$id: $file: rm: $!");
2399 return ($id, $body);
2403 sub spawn_driftnet($) {
2406 # make a directory to use.
2408 my $tmp = $ENV{TEMPDIR} || "/tmp";
2409 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2410 LOG ($verbose_exec, "mkdir $driftnet_dir");
2411 last if mkdir ($driftnet_dir, 0700);
2414 if (! ($cmd =~ m/\s/)) {
2415 # if the command didn't have any arguments in it, then it must be just
2416 # a pointer to the executable. Append the default args to it.
2417 my $dargs = $default_driftnet_cmd;
2418 $dargs =~ s/^[^\s]+//;
2422 # point the driftnet command at our newly-minted private directory.
2424 $cmd .= " -d $driftnet_dir";
2425 $cmd .= ">/dev/null" unless ($verbose_exec);
2428 if ($pid < 0) { error ("fork: $!\n"); }
2431 push @pids_to_kill, $pid;
2432 LOG ($verbose_exec, "forked for \"$cmd\"");
2435 nontrapping_system ($cmd) || error ("exec: $!");
2438 # wait a bit, then make sure the process actually started up.
2441 error ("pid $pid failed to start \"$cmd\"")
2442 unless (1 == kill (0, $pid));
2446 sub pick_from_local_dir($) {
2449 my $id = $local_magic;
2452 my $dir = $local_dir;
2453 error ("\$local_dir unset?") unless ($dir);
2456 error ("$dir unreadable") unless (-d "$dir/.");
2458 my $v = ($verbose_exec ? "-v" : "");
2459 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2461 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2463 LOG ($verbose_load, "picked file $pick ($id)");
2464 return ($id, $pick);
2468 sub get_local_file($) {
2471 error ("\$local_dir unset?") unless ($local_dir);
2473 my $id = $local_magic;
2474 error ("$id: $file not in $local_dir?")
2475 unless ($file =~ m@^\Q$local_dir@o);
2477 open (my $in, '<', $file) || error ("$id: $file: $!");
2478 local $/ = undef; # read entire file
2480 close ($in) || error ("$id: $file: $!");
2481 return ($id, $body);
2486 ############################################################################
2488 # Pick a random image in a random way
2490 ############################################################################
2493 # Picks a random image on a random page, and returns two URLs:
2494 # the page containing the image, and the image.
2495 # Returns () if nothing found this time.
2498 sub pick_image(;$) {
2501 $current_state = "select";
2502 $load_method = "none";
2504 my $n = int(rand(100));
2507 my @rest = @search_methods;
2510 my $pct = shift @rest;
2511 my $name = shift @rest;
2512 my $tfn = shift @rest;
2514 if ($total > $n && !defined($fn)) {
2516 $current_state = $name;
2517 $load_method = $current_state;
2521 if ($total != 100) {
2522 error ("internal error: \@search_methods totals to $total%!");
2525 record_attempt ($current_state);
2526 return $fn->($timeout);
2531 ############################################################################
2533 # Statistics and logging
2535 ############################################################################
2538 return strftime ("%H:%M:%S: ", localtime);
2542 return "$progname: " . timestr() . "$current_state: ";
2547 print STDERR blurb() . "$err\n";
2553 print STDERR "$progname: stack trace:\n";
2555 my ($package, $filename, $line, $subroutine) = caller($i++);
2556 last unless defined($package);
2557 $filename =~ s@^.*/@@;
2558 print STDERR " $filename#$line, $subroutine\n";
2570 my $head = "$progname: DEBUG: ";
2571 foreach (split (/\n/, $lastlog)) {
2572 print STDERR "$head$_\n";
2578 my ($print, $msg) = @_;
2579 my $blurb = timestr() . "$current_state: ";
2580 $lastlog .= "$blurb$msg\n";
2581 print STDERR "$progname: $blurb$msg\n" if $print;
2586 my %stats_successes;
2589 my $last_state = undef;
2590 sub record_attempt($) {
2594 record_failure($last_state) unless ($image_succeeded > 0);
2596 $last_state = $name;
2599 report_performance();
2602 $image_succeeded = 0;
2603 $suppress_audit = 0;
2606 sub record_success($$$) {
2607 my ($name, $url, $base) = @_;
2608 if (defined($stats_successes{$name})) {
2609 $stats_successes{$name}++;
2611 $stats_successes{$name} = 1;
2614 stop_timer ($name, 1);
2615 my $o = $current_state;
2616 $current_state = $name;
2617 save_recent_url ($url, $base);
2618 $current_state = $o;
2619 $image_succeeded = 1;
2624 sub record_failure($) {
2627 return if $image_succeeded;
2629 stop_timer ($name, 0);
2630 if ($verbose_load && !$verbose_exec) {
2632 if ($suppress_audit) {
2633 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2637 my $o = $current_state;
2638 $current_state = "DEBUG";
2640 my $line = "#" x 78;
2641 print STDERR "\n\n\n";
2642 print STDERR ("#" x 78) . "\n";
2643 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2646 print STDERR ("-" x 78) . "\n";
2647 print STDERR "\n\n";
2649 $current_state = $o;
2651 $image_succeeded = 0;
2658 my $i = $stats_successes{$name};
2659 my $j = $stats_attempts{$name};
2662 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2666 my $current_start_time = 0;
2668 sub start_timer($) {
2670 $current_start_time = time;
2672 if (defined($stats_attempts{$name})) {
2673 $stats_attempts{$name}++;
2675 $stats_attempts{$name} = 1;
2677 if (!defined($stats_elapsed{$name})) {
2678 $stats_elapsed{$name} = 0;
2682 sub stop_timer($$) {
2683 my ($name, $success) = @_;
2684 $stats_elapsed{$name} += time - $current_start_time;
2688 my $last_report_time = 0;
2689 sub report_performance() {
2691 return unless $verbose_warnings;
2694 return unless ($now >= $last_report_time + $report_performance_interval);
2695 my $ot = $last_report_time;
2696 $last_report_time = $now;
2698 return if ($ot == 0);
2700 my $blurb = "$progname: " . timestr();
2703 print STDERR "${blurb}Current standings:\n";
2705 foreach my $name (sort keys (%stats_attempts)) {
2706 my $try = $stats_attempts{$name};
2707 my $suc = $stats_successes{$name} || 0;
2708 my $pct = int($suc * 100 / $try);
2709 my $secs = $stats_elapsed{$name};
2710 my $secs_link = $secs / $try;
2711 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2712 " \t %.1f secs/link\n",
2713 "$name:", "$pct%", $suc, $try, $secs_link);
2719 my $max_recent_images = 400;
2720 my $max_recent_sites = 20;
2721 my @recent_images = ();
2722 my @recent_sites = ();
2724 sub save_recent_url($$) {
2725 my ($url, $base) = @_;
2727 return unless ($verbose_warnings);
2730 my ($site) = m@^https?://([^ \t\n\r/:]+)@;
2731 return unless defined ($site);
2733 if ($base eq $driftnet_magic || $base eq $local_magic) {
2735 @recent_images = ();
2739 foreach (@recent_images) {
2741 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2742 " (on $base via $last_search)\n";
2748 # suppress "duplicate site" warning via %warningless_sites.
2750 if ($warningless_sites{$site}) {
2752 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2753 $warningless_sites{$1}) {
2755 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2756 $warningless_sites{$1}) {
2761 foreach (@recent_sites) {
2763 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2764 " ($url on $base via $last_search)\n";
2770 push @recent_images, $url;
2771 push @recent_sites, $site;
2772 shift @recent_images if ($#recent_images >= $max_recent_images);
2773 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2778 ##############################################################################
2782 ##############################################################################
2789 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2794 # Given the raw body of a GIF document, returns the dimensions of the image.
2798 my $type = substr($body, 0, 6);
2800 return () unless ($type =~ /GIF8[7,9]a/);
2801 $s = substr ($body, 6, 10);
2802 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2803 return () unless defined ($d);
2804 return (($b<<8|$a), ($d<<8|$c));
2807 # Given the raw body of a JPEG document, returns the dimensions of the image.
2812 my $L = length($body);
2814 my $c1 = substr($body, $i, 1); $i++;
2815 my $c2 = substr($body, $i, 1); $i++;
2816 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2819 while (ord($ch) != 0xDA && $i < $L) {
2820 # Find next marker, beginning with 0xFF.
2821 while (ord($ch) != 0xFF) {
2822 return () if (length($body) <= $i);
2823 $ch = substr($body, $i, 1); $i++;
2825 # markers can be padded with any number of 0xFF.
2826 while (ord($ch) == 0xFF) {
2827 return () if (length($body) <= $i);
2828 $ch = substr($body, $i, 1); $i++;
2831 # $ch contains the value of the marker.
2832 my $marker = ord($ch);
2834 if (($marker >= 0xC0) &&
2835 ($marker <= 0xCF) &&
2836 ($marker != 0xC4) &&
2837 ($marker != 0xCC)) { # it's a SOFn marker
2839 return () if (length($body) <= $i);
2840 my $s = substr($body, $i, 4); $i += 4;
2841 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2842 return (($c<<8|$d), ($a<<8|$b));
2845 # We must skip variables, since FFs in variable names aren't
2846 # valid JPEG markers.
2847 return () if (length($body) <= $i);
2848 my $s = substr($body, $i, 2); $i += 2;
2849 my ($c1, $c2) = unpack ("C"x2, $s);
2850 my $length = ($c1 << 8) | $c2;
2851 return () if ($length < 2);
2858 # Given the raw body of a PNG document, returns the dimensions of the image.
2862 return () unless ($body =~ m/^\211PNG\r/);
2863 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2864 return () unless defined ($bits);
2865 return () unless ($bits =~ /^IHDR/);
2866 my ($ign, $w, $h) = unpack("a4N2", $bits);
2871 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2876 my ($w, $h) = gif_size ($body);
2877 if ($w && $h) { return ($w, $h); }
2878 ($w, $h) = jpeg_size ($body);
2879 if ($w && $h) { return ($w, $h); }
2880 return png_size ($body);
2884 # returns the full path of the named program, or undef.
2888 foreach (split (/:/, $ENV{PATH})) {
2889 my $path = "$_/$prog";
2898 # Like rand(), but chooses numbers with a bell curve distribution.
2901 $_ = 1.0 unless defined($_);
2903 return (rand($_) + rand($_) + rand($_));
2907 sub exit_cleanup() {
2909 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2910 if (@pids_to_kill) {
2911 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2912 kill ('TERM', @pids_to_kill);
2916 sub signal_cleanup($) {
2918 print STDERR blurb() . (defined($sig)
2919 ? "caught signal $sig."
2922 if ($verbose_exec || $verbose_warnings);
2928 ##############################################################################
2930 # Generating a list of urls only
2932 ##############################################################################
2934 sub url_only_output() {
2936 my ($base, $img) = pick_image;
2940 print "$img $base\n";
2945 ##############################################################################
2947 # Running as an xscreensaver module, or as a web page imagemap
2949 ##############################################################################
2951 my ($image_ppm, $image_tmp1, $image_tmp2);
2953 my $seed = rand(0xFFFFFFFF);
2954 $image_ppm = sprintf ("%s/webcollage-%08x",
2955 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2957 $image_tmp1 = $image_ppm . '-1.ppm';
2958 $image_tmp2 = $image_ppm . '-2.ppm';
2959 $image_ppm .= '.ppm';
2963 my $filter_cmd = undef;
2964 my $post_filter_cmd = undef;
2965 my $background = undef;
2967 my @imagemap_areas = ();
2968 my $imagemap_html_tmp = undef;
2969 my $imagemap_jpg_tmp = undef;
2972 my $img_width; # size of the image being generated.
2978 unlink $image_ppm, $image_tmp1, $image_tmp2;
2979 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2980 if (defined ($imagemap_html_tmp));
2984 # Like system, but prints status about exit codes, and kills this process
2985 # with whatever signal killed the sub-process, if any.
2987 sub nontrapping_system(@) {
2991 s/\"[^\"]+\"/\"...\"/g;
2993 LOG ($verbose_exec, "executing \"$_\"");
2998 LOG ($verbose_exec, "subproc exited normally.");
2999 } elsif (($rc & 0xff) == 0) {
3001 LOG ($verbose_exec, "subproc exited with status $rc.");
3004 LOG ($verbose_exec, "subproc dumped core.");
3007 LOG ($verbose_exec, "subproc died with signal $rc.");
3008 # die that way ourselves.
3016 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
3017 # writes a PPM to the given output file. Returns the width/height of the
3018 # image if successful.
3020 sub image_to_pnm($$$) {
3021 my ($url, $body, $output) = @_;
3022 my ($cmd, $cmd2, $w, $h);
3024 if ((@_ = gif_size ($body))) {
3027 } elsif ((@_ = jpeg_size ($body))) {
3030 } elsif ((@_ = png_size ($body))) {
3034 LOG (($verbose_pbm || $verbose_load),
3035 "not a GIF, JPG, or PNG" .
3036 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
3037 ? " (looks like HTML)" : "") .
3039 $suppress_audit = 1;
3043 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
3044 # do this, the process doesn't die properly.
3045 if (!$verbose_pbm) {
3047 # We get a "giftopnm: got a 'Application Extension' extension"
3048 # warning any time it's an animgif.
3050 # Note that "giftopnm: EOF / read error on image data" is not
3051 # always a fatal error -- sometimes the image looks fine anyway.
3053 $cmd2 .= " 2>/dev/null";
3056 # There exist corrupted GIF and JPEG files that can make giftopnm and
3057 # djpeg lose their minds and go into a loop. So this gives those programs
3058 # a small timeout -- if they don't complete in time, kill them.
3064 local $SIG{ALRM} = sub {
3066 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
3067 kill ('TERM', $pid) if ($pid);
3072 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
3079 LOG ($verbose_exec, "awaiting $pid");
3081 LOG ($verbose_exec, "$pid completed");
3083 my $size = (stat($output))[7];
3084 $size = -1 unless defined($size);
3086 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
3090 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
3093 print STDERR blurb() . "$cmd failed: $!\n";
3097 die if ($@ && $@ ne "alarm\n"); # propagate errors
3111 # Same as the "ppmmake" command: creates a solid-colored PPM.
3112 # Does not understand the rgb.txt color names except "black" and "white".
3115 my ($outfile, $bgcolor, $w, $h) = @_;
3118 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3119 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3120 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3121 } elsif ($bgcolor =~ m/^black$/i) {
3122 ($r, $g, $b) = (0, 0, 0);
3123 } elsif ($bgcolor =~ m/^white$/i) {
3124 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3126 error ("unparsable color name: $bgcolor");
3129 my $pixel = pack('CCC', $r, $g, $b);
3130 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3132 open (my $out, '>', $outfile) || error ("$outfile: $!");
3138 sub pick_root_displayer() {
3142 # see "xscreensaver/hacks/webcollage-cocoa.m"
3143 return "echo COCOA LOAD ";
3146 foreach my $cmd (@root_displayers) {
3148 my ($name) = m/^([^ ]+)/;
3149 push @names, "\"$name\"";
3150 LOG ($verbose_exec, "looking for $name...");
3151 foreach my $dir (split (/:/, $ENV{PATH})) {
3152 LOG ($verbose_exec, " checking $dir/$name");
3153 return $cmd if (-x "$dir/$name");
3157 $names[$#names] = "or " . $names[$#names];
3158 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3162 my $ppm_to_root_window_cmd = undef;
3165 sub x_or_pbm_output($) {
3166 my ($window_id) = @_;
3168 # Adjust the PATH for OS X 10.10.
3172 s/([^a-zA-Z0-9._\-+\/])/\\$1/g;
3173 $ENV{PATH} = "$_:$ENV{PATH}";
3175 # Check for our helper program, to see whether we need to use PPM pipelines.
3177 $_ = "webcollage-helper";
3179 if (! defined ($webcollage_helper)) {
3180 $webcollage_helper = which ($_);
3183 if (defined ($webcollage_helper)) {
3184 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3185 $webcollage_helper = "'$webcollage_helper' -v";
3187 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3190 if ($cocoa_p && !defined ($webcollage_helper)) {
3191 error ("webcollage-helper not found in Cocoa-mode!");
3195 # make sure the various programs we execute exist, right up front.
3199 if (!defined($webcollage_helper)) {
3200 # Only need these others if we don't have the helper.
3202 "giftopnm", "pngtopnm", "djpeg",
3203 "pnmpaste", "pnmscale", "pnmcut");
3207 which ($_) || error "$_ not found on \$PATH.";
3210 # If we're using webcollage-helper and not a filter, then the tmp files
3211 # are JPEGs, not PPMs.
3213 if (defined ($webcollage_helper) && !defined ($filter_cmd)) {
3214 foreach ($image_ppm, $image_tmp1, $image_tmp2) {
3220 # find a root-window displayer program.
3222 if (!$no_output_p) {
3223 $ppm_to_root_window_cmd = pick_root_displayer();
3226 if (defined ($window_id)) {
3227 error ("-window-id only works if xscreensaver-getimage is installed")
3228 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3230 error ("unparsable window id: $window_id")
3231 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3232 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3233 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3236 if (!$img_width || !$img_height) {
3238 if (!defined ($window_id) &&
3239 defined ($ENV{XSCREENSAVER_WINDOW})) {
3240 $window_id = $ENV{XSCREENSAVER_WINDOW};
3243 if (!defined ($window_id)) {
3245 which ($_) || error "$_ not found on \$PATH.";
3247 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3248 if (!defined($img_height)) {
3249 error "xdpyinfo failed.";
3251 } else { # we have a window id
3253 which ($_) || error "$_ not found on \$PATH.";
3254 $_ .= " -id $window_id";
3256 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3258 if (!defined($img_height)) {
3259 error "xwininfo failed.";
3264 my $bgcolor = "#000000";
3265 my $bgimage = undef;
3268 if ($background =~ m/^\#[0-9a-f]+$/i) {
3269 $bgcolor = $background;
3271 } elsif (-r $background) {
3272 $bgimage = $background;
3274 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3275 error "not a color or readable file: $background";
3278 # default to assuming it's a color
3279 $bgcolor = $background;
3283 # Create the sold-colored base image.
3285 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3286 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3288 # Paste the default background image in the middle of it.
3294 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3295 local $/ = undef; # read entire file
3300 if ((@_ = gif_size ($body))) {
3302 $cmd = "giftopnm |";
3304 } elsif ((@_ = jpeg_size ($body))) {
3308 } elsif ((@_ = png_size ($body))) {
3310 $cmd = "pngtopnm |";
3312 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3318 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3321 my $x = int (($img_width - $iw) / 2);
3322 my $y = int (($img_height - $ih) / 2);
3324 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3326 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3327 open ($imgf, "| $cmd") || error "running $cmd: $!";
3331 LOG ($verbose_exec, "subproc exited normally.");
3332 rename ($image_tmp1, $image_ppm) ||
3333 error "renaming $image_tmp1 to $image_ppm: $!";
3339 my ($base, $img) = pick_image();
3340 my $source = $current_state;
3341 $current_state = "loadimage";
3343 my ($headers, $body) = get_document ($img, $base);
3345 paste_image ($base, $img, $body, $source);
3349 $current_state = "idle";
3350 $load_method = "none";
3352 unlink $image_tmp1, $image_tmp2;
3357 sub paste_image($$$$) {
3358 my ($base, $img, $body, $source) = @_;
3360 $current_state = "paste";
3362 $suppress_audit = 0;
3364 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3368 # If we are using the webcollage-helper, then we do not need to convert this
3369 # image to a PPM. But, if we're using a filter command, we still must, since
3370 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3373 if (defined ($webcollage_helper) &&
3374 !defined ($filter_cmd)) {
3376 ($iw, $ih) = image_size ($body);
3378 LOG (($verbose_pbm || $verbose_load),
3379 "not a GIF, JPG, or PNG" .
3380 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3381 ? " (looks like HTML)" : "") .
3383 $suppress_audit = 1;
3388 if ($iw <= 0 || $ih <= 0 || $iw > 9999 || $ih > 9999) {
3389 LOG (($verbose_pbm || $verbose_load),
3390 "ludicrous image dimensions: $iw x $ih (" . length($body) .
3396 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3397 (print $out $body) || error ("writing $image_tmp1: $!");
3398 close ($out) || error ("writing $image_tmp1: $!");
3401 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3404 LOG ($verbose_pbm, "unable to make PBM from $img");
3409 record_success ($load_method, $img, $base);
3412 my $ow = $iw; # used only for error messages
3415 # don't just tack this onto the front of the pipeline -- we want it to
3416 # be able to change the size of the input image.
3419 LOG ($verbose_pbm, "running $filter_cmd");
3421 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3423 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3424 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3427 rename ($image_tmp2, $image_tmp1);
3429 # re-get the width/height in case the filter resized it.
3430 open (my $imgf, '<', $image_tmp1) || return 0;
3433 ($iw, $ih) = m/^(\d+) (\d+)$/;
3435 return 0 unless ($iw && $ih);
3438 my $target_w = $img_width; # max rectangle into which the image must fit
3439 my $target_h = $img_height;
3445 # Usually scale the image to fit on the screen -- but sometimes scale it
3446 # to fit on half or a quarter of the screen. (We do this by reducing the
3447 # size of the target rectangle.) Note that the image is not merely scaled
3448 # to fit; we instead cut the image in half repeatedly until it fits in the
3449 # target rectangle -- that gives a wider distribution of sizes.
3451 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3452 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3454 if ($iw > $target_w || $ih > $target_h) {
3455 while ($iw > $target_w ||
3461 if ($iw <= 10 || $ih <= 10) {
3462 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3466 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3468 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3472 my $src = $image_tmp1;
3474 my $crop_x = 0; # the sub-rectangle of the image
3475 my $crop_y = 0; # that we will actually paste.
3479 # The chance that we will randomly crop out a section of an image starts
3480 # out fairly low, but goes up for images that are very large, or images
3481 # that have ratios that make them look like banners (we try to avoid
3482 # banner images entirely, but they slip through when the IMG tags didn't
3483 # have WIDTH and HEIGHT specified.)
3485 my $crop_chance = 0.2;
3486 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3487 $crop_chance += 0.2;
3489 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3490 $crop_chance += 0.2;
3492 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3493 $crop_chance += 0.7;
3496 if ($crop_chance > 0.1) {
3497 LOG ($verbose_pbm, "crop chance: $crop_chance");
3500 if (rand() < $crop_chance) {
3505 if ($crop_w > $min_width) {
3506 # if it's a banner, select the width linearly.
3507 # otherwise, select a bell.
3508 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3511 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3512 $crop_x = int (rand() * ($ow - $crop_w));
3514 if ($crop_h > $min_height) {
3515 # height always selects as a bell.
3516 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3517 $crop_y = int (rand() * ($oh - $crop_h));
3520 if ($crop_x != 0 || $crop_y != 0 ||
3521 $crop_w != $iw || $crop_h != $ih) {
3523 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3527 # Where the image should logically land -- this might be negative.
3529 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3530 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3532 # if we have chosen to paste the image outside of the rectangle of the
3533 # screen, then we need to crop it.
3537 $x + $crop_w > $img_width ||
3538 $y + $crop_h > $img_height) {
3541 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3543 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3544 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3546 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3547 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3550 # If any cropping needs to happen, add pnmcut.
3552 if ($crop_x != 0 || $crop_y != 0 ||
3553 $crop_w != $iw || $crop_h != $ih) {
3556 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3557 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3560 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3562 $cmd .= " | pnmpaste - $x $y $image_ppm";
3564 $cmd =~ s@^ *\| *@@;
3566 if (defined ($webcollage_helper)) {
3567 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3568 "$scale $opacity " .
3569 "$crop_x $crop_y $x $y " .
3574 # use a PPM pipeline
3576 $_ .= " < $image_tmp1 > $image_tmp2";
3580 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3582 $_ .= " 2> /dev/null";
3585 my $rc = nontrapping_system ($_);
3587 if (defined ($webcollage_helper) && -z $image_ppm) {
3588 LOG (1, "failed command: \"$cmd\"");
3589 print STDERR "\naudit log:\n\n\n";
3590 print STDERR ("#" x 78) . "\n";
3591 print STDERR blurb() . "$image_ppm has zero size\n";
3593 print STDERR "\n\n";
3598 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3599 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3603 if (!defined ($webcollage_helper)) {
3604 rename ($image_tmp2, $image_ppm) || return;
3607 my $target = "$image_ppm";
3609 # don't just tack this onto the end of the pipeline -- we don't want it
3610 # to end up in $image_ppm, because we don't want the results to be
3613 if ($post_filter_cmd) {
3617 $target = $image_tmp1;
3618 if (!defined ($webcollage_helper)) {
3619 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3621 # Blah, my scripts need the JPEG data, but some other folks need
3622 # the PPM data -- what to do? Ignore the problem, that's what!
3623 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3624 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3627 $rc = nontrapping_system ($cmd);
3629 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3634 if (!$no_output_p) {
3635 my $tsize = (stat($target))[7];
3637 $cmd = "$ppm_to_root_window_cmd $target";
3639 # xv seems to hate being killed. it tends to forget to clean
3640 # up after itself, and leaves windows around and colors allocated.
3641 # I had this same problem with vidwhacker, and I'm not entirely
3642 # sure what I did to fix it. But, let's try this: launch xv
3643 # in the background, so that killing this process doesn't kill it.
3644 # it will die of its own accord soon enough. So this means we
3645 # start pumping bits to the root window in parallel with starting
3646 # the next network retrieval, which is probably a better thing
3649 $cmd .= " &" unless ($cocoa_p);
3651 $rc = nontrapping_system ($cmd);
3654 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3659 LOG ($verbose_pbm, "$target size is $tsize");
3663 $source .= "-" . stats_of($source);
3664 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3665 if ($verbose_imgmap);
3666 if ($imagemap_base) {
3667 update_imagemap ($base, $x, $y, $iw, $ih,
3668 $image_ppm, $img_width, $img_height);
3677 sub update_imagemap($$$$$$$$) {
3678 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3680 $current_state = "imagemap";
3682 my $max_areas = 200;
3684 $url = html_quote ($url);
3687 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3688 unshift @imagemap_areas, $area; # put one on the front
3689 if ($#imagemap_areas >= $max_areas) {
3690 pop @imagemap_areas; # take one off the back.
3693 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3695 my $map_name = $imagemap_base;
3696 $map_name =~ s@^.*/@@;
3697 $map_name = 'collage' if ($map_name eq '');
3699 my $imagemap_html = $imagemap_base . ".html";
3700 my $imagemap_jpg = $imagemap_base . ".jpg";
3701 my $imagemap_jpg2 = $imagemap_jpg;
3702 $imagemap_jpg2 =~ s@^.*/@@gs;
3704 if (!defined ($imagemap_html_tmp)) {
3705 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3706 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3709 # Read the imagemap html file (if any) to get a template.
3711 my $template_html = '';
3713 if (open (my $in, '<', $imagemap_html)) {
3714 local $/ = undef; # read entire file
3715 $template_html = <$in>;
3717 LOG ($verbose_pbm, "read template $imagemap_html");
3720 if ($template_html =~ m/^\s*$/s) {
3721 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3722 "<IMG SRC=\"$imagemap_jpg2\"" .
3723 " USEMAP=\"$map_name\">\n");
3724 LOG ($verbose_pbm, "created dummy template");
3728 # Write the jpg to a tmp file
3732 if (defined ($webcollage_helper)) {
3733 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3735 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3737 my $rc = nontrapping_system ($cmd);
3739 error ("imagemap jpeg failed: \"$cmd\"\n");
3743 # Write the html to a tmp file
3746 my $body = $template_html;
3747 my $areas = join ("\n\t", @imagemap_areas);
3748 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3749 my $img = ("<IMG SRC=\"$imagemap_jpg2\" " .
3751 "WIDTH=$image_width HEIGHT=$image_height " .
3752 "USEMAP=\"#$map_name\">");
3753 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3754 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3756 # if there are magic webcollage spans in the html, update those too.
3759 my @st = stat ($imagemap_jpg_tmp);
3760 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3761 my $size = int(($st[7] / 1024) + 0.5) . "K";
3762 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3763 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3766 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3767 (print $out $body) || error ("$imagemap_html_tmp: $!");
3768 close ($out) || error ("$imagemap_html_tmp: $!");
3769 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3772 # Rename the two tmp files to the real files
3774 rename ($imagemap_html_tmp, $imagemap_html) ||
3775 error "renaming $imagemap_html_tmp to $imagemap_html";
3776 LOG ($verbose_pbm, "wrote $imagemap_html");
3777 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3778 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3779 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3783 # Figure out what the proxy server should be, either from environment
3784 # variables or by parsing the output of the (MacOS) program "scutil",
3785 # which tells us what the system-wide proxy settings are.
3789 if (! defined($http_proxy)) {
3790 # historical suckage: the environment variable name is lower case.
3791 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3794 if (defined ($http_proxy)) {
3795 if ($http_proxy && $http_proxy =~ m@^https?://([^/]*)/?$@ ) {
3796 # historical suckage: allow "http://host:port" as well as "host:port".
3801 my $proxy_data = `scutil --proxy 2>/dev/null`;
3802 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3803 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3804 # Note: this ignores the "ExceptionsList".
3806 $http_proxy = $server;
3807 $http_proxy .= ":$port" if $port;
3811 delete $ENV{http_proxy};
3812 delete $ENV{HTTP_PROXY};
3813 delete $ENV{https_proxy};
3814 delete $ENV{HTTPS_PROXY};
3815 delete $ENV{PERL_LWP_ENV_PROXY};
3818 $http_proxy = 'http://' . $http_proxy;
3819 LOG ($verbose_net, "proxy server: $http_proxy");
3821 $http_proxy = undef; # for --proxy ''
3826 sub init_signals() {
3828 $SIG{HUP} = \&signal_cleanup;
3829 $SIG{INT} = \&signal_cleanup;
3830 $SIG{QUIT} = \&signal_cleanup;
3831 $SIG{ABRT} = \&signal_cleanup;
3832 $SIG{KILL} = \&signal_cleanup;
3833 $SIG{TERM} = \&signal_cleanup;
3835 # Need this so that if giftopnm dies, we don't die.
3836 $SIG{PIPE} = 'IGNORE';
3839 END { exit_cleanup(); }
3848 my $driftnet_cmd = 0;
3850 $current_state = "init";
3851 $load_method = "none";
3854 my $window_id = undef;
3856 while ($#ARGV >= 0) {
3858 if (m/^--?d(i(s(p(l(a(y)?)?)?)?)?)?$/s) {
3859 $ENV{DISPLAY} = shift @ARGV;
3860 } elsif (m/^--?root$/s) {
3862 } elsif (m/^--?window-id$/s) {
3863 $window_id = shift @ARGV;
3865 } elsif (m/^--?no-output$/s) {
3867 } elsif (m/^--?urls(-only)?$/s) {
3870 } elsif (m/^--?cocoa$/s) {
3872 } elsif (m/^--?imagemap$/s) {
3873 $imagemap_base = shift @ARGV;
3875 } elsif (m/^--?verbose$/s) {
3877 } elsif (m/^-v+$/) {
3878 $verbose += length($_)-1;
3879 } elsif (m/^--?delay$/s) {
3880 $delay = shift @ARGV;
3881 } elsif (m/^--?timeout$/s) {
3882 $http_timeout = shift @ARGV;
3883 } elsif (m/^--?filter$/s) {
3884 $filter_cmd = shift @ARGV;
3885 } elsif (m/^--?filter2$/s) {
3886 $post_filter_cmd = shift @ARGV;
3887 } elsif (m/^--?(background|bg)$/s) {
3888 $background = shift @ARGV;
3889 } elsif (m/^--?size$/s) {
3891 if (m@^(\d+)x(\d+)$@) {
3895 error "argument to \"--size\" must be of the form \"640x400\"";
3897 } elsif (m/^--?(http-)?proxy$/s) {
3898 $http_proxy = shift @ARGV;
3899 } elsif (m/^--?dict(ionary)?$/s) {
3900 $dict = shift @ARGV;
3901 } elsif (m/^--?opacity$/s) {
3902 $opacity = shift @ARGV;
3903 error ("opacity must be between 0.0 and 1.0")
3904 if ($opacity <= 0 || $opacity > 1);
3905 } elsif (m/^--?driftnet$/s) {
3906 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3907 if (! ($ARGV[0] =~ m/^-/)) {
3908 $driftnet_cmd = shift @ARGV;
3910 $driftnet_cmd = $default_driftnet_cmd;
3912 } elsif (m/^--?dir(ectory)?$/s) {
3913 @search_methods = ( 100, "local", \&pick_from_local_dir );
3914 if (! ($ARGV[0] =~ m/^-/)) {
3915 $local_dir = shift @ARGV;
3917 error ("local directory path must be set")
3919 } elsif (m/^--?fps$/s) {
3920 # -fps only works on MacOS, via "webcollage-cocoa.m".
3921 # Ignore it if passed to this script in an X11 context.
3922 } elsif (m/^--?debug$/s) {
3923 my $which = shift @ARGV;
3924 my @rest = @search_methods;
3927 my $pct = shift @rest;
3928 my $name = shift @rest;
3929 my $tfn = shift @rest;
3931 if ($name eq $which) {
3932 @search_methods = (100, $name, $tfn);
3937 error "no such search method as \"$which\"" unless ($ok);
3938 LOG (1, "DEBUG: using only \"$which\"");
3939 $report_performance_interval = 30;
3942 print STDERR "unknown option: $_\n\n";
3943 print STDERR "$copyright\nusage: $progname " .
3944 "[--root] [--display dpy] [--verbose] [--debug which]\n" .
3945 "\t\t [--timeout secs] [--delay secs] [--size WxH]\n" .
3946 "\t\t [--no-output] [--urls-only] [--imagemap filename]\n" .
3947 "\t\t [--background color] [--opacity f]\n" .
3948 "\t\t [--filter cmd] [--filter2 cmd]\n" .
3949 "\t\t [--dictionary dictionary-file] [--http-proxy host[:port]]\n" .
3950 "\t\t [--driftnet [driftnet-program-and-args]]\n" .
3951 "\t\t [--directory local-image-directory]\n" .
3957 if (!$root_p && !$no_output_p && !$cocoa_p) {
3958 print STDERR $copyright;
3959 error "the --root argument is mandatory (for now.)";
3962 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3963 error "\$DISPLAY is not set.";
3967 if ($verbose == 1) {
3968 $verbose_imgmap = 1;
3969 $verbose_warnings = 1;
3971 } elsif ($verbose == 2) {
3972 $verbose_imgmap = 1;
3973 $verbose_warnings = 1;
3976 } elsif ($verbose == 3) {
3977 $verbose_imgmap = 1;
3978 $verbose_warnings = 1;
3980 $verbose_filter = 1;
3982 } elsif ($verbose == 4) {
3983 $verbose_imgmap = 1;
3984 $verbose_warnings = 1;
3986 $verbose_filter = 1;
3989 } elsif ($verbose == 5) {
3990 $verbose_imgmap = 1;
3991 $verbose_warnings = 1;
3993 $verbose_filter = 1;
3997 } elsif ($verbose == 6) {
3998 $verbose_imgmap = 1;
3999 $verbose_warnings = 1;
4001 $verbose_filter = 1;
4006 } elsif ($verbose >= 7) {
4007 $verbose_imgmap = 1;
4008 $verbose_warnings = 1;
4010 $verbose_filter = 1;
4018 error ("$dict does not exist") unless (-f $dict);
4024 if ($imagemap_base && !($img_width && $img_height)) {
4025 error ("--size WxH is required with --imagemap");
4028 if (defined ($local_dir)) {
4029 $_ = "xscreensaver-getimage-file";
4030 which ($_) || error "$_ not found on \$PATH.";
4036 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
4041 x_or_pbm_output ($window_id);