3 # webcollage, Copyright (c) 1999-2005 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!
54 use Fcntl ':flock'; # import LOCK_* constants
55 use POSIX qw(strftime);
57 use bytes; # Larry can take Unicode and shove it up his ass sideways.
58 # Perl 5.8.0 causes us to start getting incomprehensible
59 # errors about UTF-8 all over the place without this.
62 my $progname = $0; $progname =~ s@.*/@@g;
63 my $version = q{ $Revision: 1.130 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
64 my $copyright = "WebCollage $version, Copyright (c) 1999-2005" .
65 " Jamie Zawinski <jwz\@jwz.org>\n" .
66 " http://www.jwz.org/webcollage/\n";
70 my @search_methods = ( 56, "altavista", \&pick_from_alta_vista_random_link,
71 11, "livejournal", \&pick_from_livejournal_images,
72 5, "yahoorand", \&pick_from_yahoo_random_link,
73 10, "googlephotos", \&pick_from_google_image_photos,
74 5, "googleimgs", \&pick_from_google_images,
75 3, "googlenums", \&pick_from_google_image_numbers,
76 2, "flickr_recent", \&pick_from_flickr_recent,
77 8, "flickr_random", \&pick_from_flickr_random,
79 # In Apr 2002, Google asked me to stop searching them.
80 # I asked them to add a "random link" url. They said
81 # "that would be easy, we'll think about it" and then
82 # never wrote back. Booo Google! Booooo! So, screw
83 # those turkeys, I've turned Google searching back on.
84 # I'm sure they can take it. (Jan 2005.)
86 # Jan 2005: Yahoo fucked up their search form so that
87 # it's no longer possible to do "or" searches on news
88 # images, so we rarely get any hits there any more.
90 # 0, "yahoonews", \&pick_from_yahoo_news_text,
92 # Dec 2004: the ircimages guy's server can't take the
93 # heat, so he started banning the webcollage user agent.
94 # I tried to convince him to add a lighter-weight page to
95 # support webcollage better, but he doesn't care.
97 # 0, "ircimages", \&pick_from_ircimages,
99 # Dec 2002: Alta Vista has a new "random link" URL now.
100 # They added it specifically to better support webcollage!
101 # That was super cool of them. This is how we used to do
104 # 0, "avimages", \&pick_from_alta_vista_images,
105 # 0, "avtext", \&pick_from_alta_vista_text,
107 # This broke in 2004. Eh, Lycos sucks anyway.
109 # 0, "lycos", \&pick_from_lycos_text,
111 # This broke in 2003, I think. I suspect Hotbot is
112 # actually the same search engine data as Lycos.
114 # 0, "hotbot", \&pick_from_hotbot_text,
117 # programs we can use to write to the root window (tried in ascending order.)
119 my @root_displayers = (
120 "xscreensaver-getimage -root -file",
121 "chbg -once -xscreensaver -max_size 100",
122 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
123 " -rfg black -rbg black",
124 "xli -quiet -onroot -center -border black",
125 "xloadimage -quiet -onroot -center -border black",
127 # this lame program wasn't built with vroot.h:
128 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
132 # Some sites need cookies to work properly. These are they.
135 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
136 "web.altavista.com" => "AV_ALL=1",
138 # log in as "cipherpunk"
139 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
140 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
141 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
143 "ircimages.com" => 'disclaimer=1',
147 # If this is set, it's a helper program to use for pasting images together:
148 # this is a lot faster and more efficient than using PPM pipelines, which is
149 # what we do if this program doesn't exist. (We check for "webcollage-helper"
150 # on $PATH at startup, and set this variable appropriately.)
152 my $webcollage_helper = undef;
155 # If we have the webcollage-helper program, then it will paste the images
156 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
161 # Some sites have managed to poison the search engines. These are they.
162 # (We auto-detect sites that have poisoned the search engines via excessive
163 # keywords or dictionary words, but these are ones that slip through
166 # This can contain full host names, or 2 or 3 component domains.
169 "die.net" => 1, # 'l33t h4ck3r d00dz.
170 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
171 "rootsweb.com" => 1, # Cluttering avtext with human names.
172 "akamai.net" => 1, # Lots of sites have their images on Akamai.
173 "akamaitech.net" => 1, # But those are pretty much all banners.
174 # Since Akamai is super-expensive, let's
175 # go out on a limb and assume that all of
176 # their customers are rich-and-boring.
177 "bartleby.com" => 1, # Dictionary, cluttering avtext.
178 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
179 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
180 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
181 # (I don't see how they did it, though!)
182 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
183 "nextag.com" => 1, # Poisoned Alta Vista real good.
187 # When verbosity is turned on, we warn about sites that we seem to be hitting
188 # a lot: usually this means some new poisoner has made it into the search
189 # engines. But sometimes, the warning is just because that site has a lot
190 # of stuff on it. So these are the sites that are immune to the "frequent
191 # site" diagnostic message.
193 my %warningless_sites = (
194 "home.earthlink.net" => 1, # Lots of home pages here.
195 "www.geocities.com" => 1,
196 "www.angelfire.com" => 1,
197 "members.aol.com" => 1,
198 "img.photobucket.com" => 1,
199 "pics.livejournal.com" => 1,
203 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
204 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
205 # hits this every time.
207 "images.quizfarm.com" => 1, # damn those LJ quizzes...
208 "images.quizilla.com" => 1,
209 "images.quizdiva.net" => 1,
211 "driftnet" => 1, # builtin...
212 "local-directory" => 1, # builtin...
216 # For decoding HTML-encoded character entities to URLs.
220 "quot" => '"', "amp" => '&', "lt" => '<', "gt" => '>',
221 "nbsp" => ' ', "iexcl" => '¡', "cent" => '¢', "pound" => '£',
222 "curren" => '¤', "yen" => '¥', "brvbar" => '¦', "sect" => '§',
223 "uml" => '¨', "copy" => '©', "ordf" => 'ª', "laquo" => '«',
224 "not" => '¬', "shy" => '', "reg" => '®', "macr" => '¯',
225 "deg" => '°', "plusmn" => '±', "sup2" => '²', "sup3" => '³',
226 "acute" => '´', "micro" => 'µ', "para" => '¶', "middot" => '·',
227 "cedil" => '¸', "sup1" => '¹', "ordm" => 'º', "raquo" => '»',
228 "frac14" => '¼', "frac12" => '½', "frac34" => '¾', "iquest" => '¿',
229 "Agrave" => 'À', "Aacute" => 'Á', "Acirc" => 'Â', "Atilde" => 'Ã',
230 "Auml" => 'Ä', "Aring" => 'Å', "AElig" => 'Æ', "Ccedil" => 'Ç',
231 "Egrave" => 'È', "Eacute" => 'É', "Ecirc" => 'Ê', "Euml" => 'Ë',
232 "Igrave" => 'Ì', "Iacute" => 'Í', "Icirc" => 'Î', "Iuml" => 'Ï',
233 "ETH" => 'Ð', "Ntilde" => 'Ñ', "Ograve" => 'Ò', "Oacute" => 'Ó',
234 "Ocirc" => 'Ô', "Otilde" => 'Õ', "Ouml" => 'Ö', "times" => '×',
235 "Oslash" => 'Ø', "Ugrave" => 'Ù', "Uacute" => 'Ú', "Ucirc" => 'Û',
236 "Uuml" => 'Ü', "Yacute" => 'Ý', "THORN" => 'Þ', "szlig" => 'ß',
237 "agrave" => 'à', "aacute" => 'á', "acirc" => 'â', "atilde" => 'ã',
238 "auml" => 'ä', "aring" => 'å', "aelig" => 'æ', "ccedil" => 'ç',
239 "egrave" => 'è', "eacute" => 'é', "ecirc" => 'ê', "euml" => 'ë',
240 "igrave" => 'ì', "iacute" => 'í', "icirc" => 'î', "iuml" => 'ï',
241 "eth" => 'ð', "ntilde" => 'ñ', "ograve" => 'ò', "oacute" => 'ó',
242 "ocirc" => 'ô', "otilde" => 'õ', "ouml" => 'ö', "divide" => '÷',
243 "oslash" => 'ø', "ugrave" => 'ù', "uacute" => 'ú', "ucirc" => 'û',
244 "uuml" => 'ü', "yacute" => 'ý', "thorn" => 'þ', "yuml" => 'ÿ',
245 "ndash" => '-', "mdash" => "--"
249 ##############################################################################
251 # Various global flags set by command line parameters, or computed
253 ##############################################################################
256 my $current_state = "???"; # for diagnostics
259 my $image_succeeded = -1;
260 my $suppress_audit = 0;
262 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
263 my $verbose_warnings = 0; # print out warnings when things go wrong
264 my $verbose_load = 0; # diagnostics about loading of URLs
265 my $verbose_filter = 0; # diagnostics about page selection/rejection
266 my $verbose_net = 0; # diagnostics about network I/O
267 my $verbose_pbm = 0; # diagnostics about PBM pipelines
268 my $verbose_http = 0; # diagnostics about all HTTP activity
269 my $verbose_exec = 0; # diagnostics about executing programs
271 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
273 my $http_proxy = undef;
274 my $http_timeout = 20;
275 my $cvt_timeout = 10;
281 my $min_gif_area = (120 * 120);
286 my $imagemap_base = undef;
288 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
290 my $driftnet_magic = 'driftnet';
291 my $driftnet_dir = undef;
292 my $default_driftnet_cmd = "driftnet -a -m 100";
294 my $local_magic = 'local-directory';
295 my $local_dir = undef;
300 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
301 "arrhenius", "arteriole", "blanket", "brainchild",
302 "burdensome", "carnival", "cherub", "chord", "clever",
303 "dedicate", "dilogarithm", "dolan", "dryden",
307 ##############################################################################
311 ##############################################################################
313 # returns three values: the HTTP response line; the document headers;
314 # and the document body.
316 sub get_document_1($$$) {
317 my ($url, $referer, $timeout) = @_;
319 if (!defined($timeout)) { $timeout = $http_timeout; }
320 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
323 LOG (($verbose_net || $verbose_load), "timed out for $url");
327 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
329 if (! ($url =~ m@^http://@i)) {
330 LOG ($verbose_net, "not an HTTP URL: $url");
334 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
335 $path = "" unless $path;
337 if (!$url_proto || !$serverstring) {
338 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
342 my ($them,$port) = split(/:/, $serverstring);
343 $port = 80 unless $port;
348 $serverstring = $http_proxy if $http_proxy;
349 $serverstring =~ s@^[a-z]+://@@;
350 ($them2,$port2) = split(/:/, $serverstring);
351 $port2 = 80 unless $port2;
354 my ($remote, $iaddr, $paddr, $proto, $line);
356 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
358 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
361 $iaddr = inet_aton($remote);
363 LOG (($verbose_net || $verbose_load), "host not found: $remote");
366 $paddr = sockaddr_in($port2, $iaddr);
374 local $SIG{ALRM} = sub {
375 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
380 $proto = getprotobyname('tcp');
381 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
382 LOG (($verbose_net || $verbose_load), "socket: $!");
385 if (!connect(S, $paddr)) {
386 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
390 select(S); $| = 1; select(STDOUT);
392 my $cookie = $cookies{$them};
394 my $user_agent = "$progname/$version";
396 if ($url =~ m@^http://www\.altavista\.com/@ ||
397 $url =~ m@^http://random\.yahoo\.com/@ ||
398 $url =~ m@^http://images\.google\.com/@) {
399 # block this, you turkeys.
400 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.5)" .
401 " Gecko/20041111 Firefox/1.0";
404 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
406 "User-Agent: $user_agent\r\n";
408 $hdrs .= "Referer: $referer\r\n";
411 my @cc = split(/\r?\n/, $cookie);
412 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
416 foreach (split('\r?\n', $hdrs)) {
417 LOG ($verbose_http, " ==> $_");
420 my $http = <S> || "";
422 # Kludge: the Yahoo Random Link is now returning as its first
423 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
425 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
429 LOG ($verbose_http, " <== $_");
435 LOG ($verbose_http, " <== $_");
437 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
438 set_cookie($them, $1)
449 " <== [ body ]: $lines lines, " . length($body) . " bytes");
454 LOG (($verbose_net || $verbose_load), "null response: $url");
458 $SIG{ALRM} = 'DEFAULT'; # seem to be suffering a race?
459 return ( $http, $head, $body );
461 die if ($@ && $@ ne "alarm\n"); # propagate errors
463 if ($@ && $@ ne "alarm\n") {
464 print STDERR blurb() . "DIE " . join(" ", $@) . "\n";
482 # returns two values: the document headers; and the document body.
483 # if the given URL did a redirect, returns the redirected-to document.
485 sub get_document($$;$) {
486 my ($url, $referer, $timeout) = @_;
489 if (defined($referer) && $referer eq $driftnet_magic) {
490 return get_driftnet_file ($url);
493 if (defined($referer) && $referer eq $local_magic) {
494 return get_local_file ($url);
499 my $max_loop_count = 4;
502 if (defined($timeout) && $timeout <= 0) {
503 LOG (($verbose_net || $verbose_load), "timed out for $url");
508 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
510 if (defined ($timeout)) {
512 my $elapsed = $now - $start;
513 $timeout -= $elapsed;
517 return () unless $http; # error message already printed
519 $http =~ s/[\r\n]+$//s;
521 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
524 my ( $location ) = m@^location:[ \t]*(.*)$@im;
526 $location =~ s/[\r\n]$//;
528 LOG ($verbose_net, "redirect from $url to $location");
533 $referer =~ m@^(http://[^/]+)@i;
535 } elsif (! ($url =~ m@^[a-z]+:@i)) {
537 s@[^/]+$@@g if m@^http://[^/]+/@i;
538 $_ .= "/" if m@^http://[^/]+$@i;
543 LOG ($verbose_net, "no Location with \"$http\"");
544 return ( $url, $body );
547 if ($loop_count++ > $max_loop_count) {
549 "too many redirects ($max_loop_count) from $orig_url");
554 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
556 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
558 # http errors -- return nothing.
564 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
570 return ( $url, $body );
576 # If we already have a cookie defined for this site, and the site is trying
577 # to overwrite that very same cookie, let it do so. This is because nytimes
578 # expires its cookies - it lets you upgrade to a new cookie without logging
579 # in again, but you have to present the old cookie to get the new cookie.
580 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
583 my ($host, $cookie) = @_;
584 my $oc = $cookies{$host};
587 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
589 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
591 if ($oc_name eq $nc_name &&
592 $oc_value ne $nc_value) {
593 $cookies{$host} = $cookie;
594 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
599 ############################################################################
601 # Extracting image URLs from HTML
603 ############################################################################
605 # given a URL and the body text at that URL, selects and returns a random
606 # image from it. returns () if no suitable images found.
608 sub pick_image_from_body($$) {
609 my ($url, $body) = @_;
614 # if there's at least one slash after the host, take off the last
616 if ( m@^http://[^/]+/@io ) {
617 $base =~ s@[^/]+$@@go;
620 # if there are no slashes after the host at all, put one on the end.
621 if ( m@^http://[^/]+$@io ) {
627 # strip out newlines, compress whitespace
634 # There are certain web sites that list huge numbers of dictionary
635 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
636 # Porn sites tend not to be reputable!)
638 # I do not want webcollage to filter on content: I want it to select
639 # randomly from the set of images on the web. All the logic here for
640 # rejecting some images is really a set of heuristics for rejecting
641 # images that are not really images: for rejecting *text* that is in
642 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
643 # the content of the pictures to be randomly selected from among all
644 # the available content.
646 # So, filtering out "dirty" pictures by looking for "dirty" keywords
647 # would be wrong: dirty pictures exist, like it or not, so webcollage
648 # should be able to select them.
650 # However, picking a random URL is a hard thing to do. The mechanism I'm
651 # using is to search for a selection of random words. This is not
652 # perfect, but works ok most of the time. The way it breaks down is when
653 # some URLs get precedence because their pages list *every word* as
654 # related -- those URLs come up more often than others.
656 # So, after we've retrieved a URL, if it has too many keywords, reject
657 # it. We reject it not on the basis of what those keywords are, but on
658 # the basis that by having so many, the page has gotten an unfair
659 # advantage against our randomizer.
662 foreach my $trip (@tripwire_words) {
663 $trip_count++ if m/$trip/i;
666 if ($trip_count >= $#tripwire_words - 2) {
667 LOG (($verbose_filter || $verbose_load),
668 "there is probably a dictionary in \"$url\": rejecting.");
669 $rejected_urls{$url} = -1;
679 foreach (split(/ *</)) {
682 # Likewise, reject any web pages that have a KEYWORDS meta tag
685 if (m/name ?= ?\"?keywords\"?/i &&
686 m/content ?= ?\"([^\"]+)\"/) {
689 LOG (($verbose_filter || $verbose_load),
690 "excessive keywords ($L bytes) in $url: rejecting.");
691 $rejected_urls{$url} = $L;
696 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
700 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
702 my $was_inline = (! ( "$1" eq "a" || "$1" eq "A" ));
704 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
705 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
710 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
712 } elsif ( ! m@^[^/:?]+:@ ) {
715 1 while (s@/[^/]+/\.\./@/@g);
719 if ( ! m@^http://@io ) {
724 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
728 # skip really short or really narrow images
729 if ( $width && $width < $min_width) {
730 if (!$height) { $height = "?"; }
731 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
735 if ( $height && $height < $min_height) {
736 if (!$width) { $width = "?"; }
737 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
741 # skip images with ratios that make them look like banners.
742 if ($min_ratio && $width && $height &&
743 ($width * $min_ratio ) > $height) {
744 if (!$height) { $height = "?"; }
745 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
749 # skip GIFs with a small number of pixels -- those usually suck.
750 if ($width && $height &&
752 ($width * $height) < $min_gif_area) {
753 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
757 # skip images with a URL that indicates a Yahoo thumbnail.
758 if (m@\.yimg\.com/.*/t/@) {
759 if (!$width) { $width = "?"; }
760 if (!$height) { $height = "?"; }
761 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
767 if ($unique_urls{$url}) {
768 LOG ($verbose_filter, " skip duplicate image $_");
772 LOG ($verbose_filter,
774 ($width && $height ? " (${width}x${height})" : "") .
775 ($was_inline ? " (inline)" : ""));
777 $urls[++$#urls] = $url;
778 $unique_urls{$url}++;
780 # JPEGs are preferable to GIFs and PNGs.
782 if ( ! m@[.](gif|png)$@io ) {
783 $urls[++$#urls] = $url;
786 # pointers to images are preferable to inlined images.
787 if ( ! $was_inline ) {
788 $urls[++$#urls] = $url;
789 $urls[++$#urls] = $url;
794 my $fsp = ($body =~ m@<frameset@i);
799 @urls = depoison (@urls);
802 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
806 # pick a random element of the table
807 my $i = int(rand($#urls+1));
810 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
815 # Given a URL and the RSS feed from that URL, pick a random image from
816 # the feed. This is a lot simpler than extracting images out of a page:
817 # we already know we have reasonable images, so we just pick one.
818 # Returns: the real URL of the page (preferably not the RSS version),
821 sub pick_image_from_rss($$) {
822 my ( $url, $body ) = @_;
823 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
825 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
826 $base = $url unless $base;
828 # pick a random element of the table
830 my $i = int(rand(scalar @suitable));
831 my $url = $suitable[$i];
832 LOG ($verbose_load, "picked image " .($i+1) . "/" .
833 ($#suitable+1) . ": $url");
834 return ($base, $url);
840 ############################################################################
842 # Subroutines for getting pages and images out of search engines
844 ############################################################################
847 sub pick_dictionary() {
848 my @dicts = ("/usr/dict/words",
849 "/usr/share/dict/words",
850 "/usr/share/lib/dict/words");
851 foreach my $f (@dicts) {
857 error ("$dicts[0] does not exist") unless defined($wordlist);
860 # returns a random word from the dictionary
865 if (! open (IN, "<$wordlist")) {
869 my $size = (stat(IN))[7];
874 error ("looping ($count) while reading $wordlist")
877 my $pos = int (rand ($size));
878 if (seek (IN, $pos, 0)) {
879 $word = <IN>; # toss partial line
880 $word = <IN>; # keep next line
884 next if ($word =~ m/^[-\']/);
888 $word =~ s/^[^a-z]+//s;
889 $word =~ s/[^a-z]+$//s;
895 $word =~ s/ally$/al/s;
896 $word =~ s/izes$/ize/s;
897 $word =~ s/esses$/ess/s;
898 $word =~ s/(.{5})ing$/$1/s;
900 next if (length ($word) > 14);
906 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
907 $word = "\%22$word\%22"; # And put quotes (%22) around it.
914 sub random_words($) {
916 my $sep = ($or_p ? "%20OR%20" : "%20");
917 return (random_word . $sep .
927 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
934 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
943 $s =~ s/\"/"/gi;
947 sub html_unquote($) {
949 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
950 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
955 # Loads the given URL (a search on some search engine) and returns:
956 # - the total number of hits the search engine claimed it had;
957 # - a list of URLs from the page that the search engine returned;
958 # Note that this list contains all kinds of internal search engine
959 # junk URLs too -- caller must prune them.
961 sub pick_from_search_engine($$$) {
962 my ( $timeout, $search_url, $words ) = @_;
967 print STDERR "\n\n" if ($verbose_load);
969 LOG ($verbose_load, "words: $_");
970 LOG ($verbose_load, "URL: $search_url");
972 $last_search = $search_url; # for warnings
975 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
976 if (defined ($timeout)) {
977 $timeout -= (time - $start);
980 LOG (($verbose_net || $verbose_load),
981 "timed out (late) for $search_url");
987 return () if (! $body);
992 my $search_count = "?";
993 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
995 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
997 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
999 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1001 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1003 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1005 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1007 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1009 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1010 $search_count = $1; # lycos
1011 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1012 $search_count = $1; # hotbot
1013 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1014 $search_count = "0";
1015 } elsif ($body =~ m@found no document matching@i) { # avtext
1016 $search_count = "0";
1018 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1020 # if ($search_count eq "?" || $search_count eq "0") {
1022 # my $file = "/tmp/wc.html";
1023 # open(OUT, ">$file") || error ("writing $file: $!");
1026 # print STDERR blurb() . "###### wrote $file\n";
1030 my $length = length($body);
1039 foreach (split(/\n/)) {
1041 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1044 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1045 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1047 if ( $rejected_urls{$u} ) {
1048 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1052 LOG ($verbose_http, " HREF: $u");
1054 $subpages[++$#subpages] = $u;
1057 if ( $#subpages < 0 ) {
1058 LOG ($verbose_filter,
1059 "found nothing on $base ($length bytes, $href_count links).");
1063 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1065 return ($search_count, @subpages);
1073 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1075 next unless defined($h);
1077 if ($poisoners{$h}) {
1078 LOG (($verbose_filter), " rejecting poisoner: $_");
1081 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1083 LOG (($verbose_filter), " rejecting poisoner: $_");
1086 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1088 LOG (($verbose_filter), " rejecting poisoner: $_");
1098 # given a list of URLs, picks one at random; loads it; and returns a
1099 # random image from it.
1100 # returns the url of the page loaded; the url of the image chosen.
1102 sub pick_image_from_pages($$$$@) {
1103 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1105 $total_hit_count = "?" unless defined($total_hit_count);
1107 @pages = depoison (@pages);
1109 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1110 " ($total_hit_count total)");
1112 return () if ($#pages < 0);
1114 my $i = int(rand($#pages+1));
1115 my $page = $pages[$i];
1117 LOG ($verbose_load, "picked page $page");
1119 $suppress_audit = 1;
1121 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1123 if (!$base2 || !$body2) {
1128 my $img = pick_image_from_body ($base2, $body2);
1132 return ($base2, $img);
1139 ############################################################################
1141 # Pick images from random pages returned by the Yahoo Random Link
1143 ############################################################################
1146 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1149 # Picks a random page; picks a random image on that page;
1150 # returns two URLs: the page containing the image, and the image.
1151 # Returns () if nothing found this time.
1153 sub pick_from_yahoo_random_link($) {
1156 print STDERR "\n\n" if ($verbose_load);
1157 LOG ($verbose_load, "URL: $yahoo_random_link");
1159 $last_search = $yahoo_random_link; # for warnings
1161 $suppress_audit = 1;
1163 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1164 if (!$base || !$body) {
1169 LOG ($verbose_load, "redirected to: $base");
1171 my $img = pick_image_from_body ($base, $body);
1175 return ($base, $img);
1182 ############################################################################
1184 # Pick images from random pages returned by the Alta Vista Random Link
1186 ############################################################################
1189 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1192 # Picks a random page; picks a random image on that page;
1193 # returns two URLs: the page containing the image, and the image.
1194 # Returns () if nothing found this time.
1196 sub pick_from_alta_vista_random_link($) {
1199 print STDERR "\n\n" if ($verbose_load);
1200 LOG ($verbose_load, "URL: $alta_vista_random_link");
1202 $last_search = $alta_vista_random_link; # for warnings
1204 $suppress_audit = 1;
1206 my ( $base, $body ) = get_document ($alta_vista_random_link,
1208 if (!$base || !$body) {
1213 LOG ($verbose_load, "redirected to: $base");
1215 my $img = pick_image_from_body ($base, $body);
1219 return ($base, $img);
1226 ############################################################################
1228 # Pick images by feeding random words into Alta Vista Image Search
1230 ############################################################################
1233 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1234 "?ipht=1" . # photos
1235 "&igrph=1" . # graphics
1238 "&micat=1" . # no partner sites
1239 "&sc=on" . # "site collapse"
1243 sub pick_from_alta_vista_images($) {
1246 my $words = random_word();
1247 my $page = (int(rand(9)) + 1);
1248 my $search_url = $alta_vista_images_url . $words;
1251 $search_url .= "&pgno=" . $page; # page number
1252 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1255 my ($search_hit_count, @subpages) =
1256 pick_from_search_engine ($timeout, $search_url, $words);
1258 my @candidates = ();
1259 foreach my $u (@subpages) {
1261 # avimages is encoding their URLs now.
1262 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1263 $u = url_unquote($u);
1265 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1266 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1267 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1268 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1269 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1271 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1272 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1274 LOG ($verbose_filter, " candidate: $u");
1275 push @candidates, $u;
1278 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1279 $timeout, @candidates);
1284 ############################################################################
1286 # Pick images by feeding random words into Google Image Search.
1287 # By Charles Gales <gales@us.ibm.com>
1289 ############################################################################
1292 my $google_images_url = "http://images.google.com/images" .
1293 "?site=images" . # photos
1294 "&btnG=Search" . # graphics
1295 "&safe=off" . # no screening
1300 sub pick_from_google_images($;$$) {
1301 my ($timeout, $words, $max_page) = @_;
1303 if (!defined($words)) {
1304 $words = random_word; # only one word for Google
1307 my $page = (int(rand(9)) + 1);
1308 my $num = 20; # 20 images per page
1309 my $search_url = $google_images_url . $words;
1312 $search_url .= "&start=" . $page*$num; # page number
1313 $search_url .= "&num=" . $num; #images per page
1316 my ($search_hit_count, @subpages) =
1317 pick_from_search_engine ($timeout, $search_url, $words);
1319 my @candidates = ();
1321 foreach my $u (@subpages) {
1322 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1323 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1325 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1328 $img = "http://$img" unless ($img =~ m/^http:/i);
1330 LOG ($verbose_filter, " candidate: $ref");
1331 push @candidates, $img;
1332 $referers{$img} = $ref;
1336 @candidates = depoison (@candidates);
1337 return () if ($#candidates < 0);
1338 my $i = int(rand($#candidates+1));
1339 my $img = $candidates[$i];
1340 my $ref = $referers{$img};
1342 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1343 return ($ref, $img);
1348 ############################################################################
1350 # Pick images by feeding random numbers into Google Image Search.
1351 # By jwz, suggested by Ian O'Donnell.
1353 ############################################################################
1357 sub pick_from_google_image_numbers($) {
1361 my $number = int(rand($max));
1363 $number = sprintf("%04d", $number)
1366 pick_from_google_images ($timeout, "$number");
1371 ############################################################################
1373 # Pick images by feeding random digital camera file names into
1374 # Google Image Search.
1375 # By jwz, inspired by the excellent Random Personal Picture Finder
1376 # at http://www.diddly.com/random/
1378 ############################################################################
1382 # Common digital camera file name formats, as described at
1383 # http://www.diddly.com/random/about.html
1385 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1386 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1387 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1388 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1389 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1390 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1391 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1392 int(rand(0xC)), int(rand(30))+1,
1394 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1395 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1396 sub { my $n = int(rand(9999)); # Canon
1397 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1398 sub { my $n = int(rand(9999)); # Canon
1399 sprintf ("1%02d-%04d_IMG.jpg",
1400 int($n/100), $n); },
1401 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1402 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1403 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1404 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1405 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1406 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1407 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1408 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1409 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1410 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1411 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1412 # int(rand(12))+1, int(rand(31))+1,
1413 # int(rand(999))); },
1414 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1415 # int(rand(6)), # year
1416 # int(rand(12))+1, int(rand(31))+1,
1417 # int(rand(999))); },
1418 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1419 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1420 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1421 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1426 sub pick_from_google_image_photos($) {
1429 my $i = int(rand($#photomakers + 1));
1430 my $fn = $photomakers[$i];
1432 my $words .= $file . "%20filetype:jpg";
1434 pick_from_google_images ($timeout, $words);
1439 ############################################################################
1441 # Pick images by feeding random words into Alta Vista Text Search
1443 ############################################################################
1446 my $alta_vista_url = "http://www.altavista.com/web/results" .
1450 "&sc=on" . # "site collapse"
1455 sub pick_from_alta_vista_text($) {
1458 my $words = random_words(0);
1459 my $page = (int(rand(9)) + 1);
1460 my $search_url = $alta_vista_url . $words;
1463 $search_url .= "&pgno=" . $page;
1464 $search_url .= "&stq=" . (($page-1) * 10);
1467 my ($search_hit_count, @subpages) =
1468 pick_from_search_engine ($timeout, $search_url, $words);
1470 my @candidates = ();
1471 foreach my $u (@subpages) {
1473 # Those altavista fuckers are playing really nasty redirection games
1474 # these days: the filter your clicks through their site, but use
1475 # onMouseOver to make it look like they're not! Well, it makes it
1476 # easier for us to identify search results...
1478 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1479 $u = url_unquote($u);
1481 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1482 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1483 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1485 LOG ($verbose_filter, " candidate: $u");
1486 push @candidates, $u;
1489 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1490 $timeout, @candidates);
1495 ############################################################################
1497 # Pick images by feeding random words into Hotbot
1499 ############################################################################
1501 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1503 "&descriptiontype=0" .
1510 "&cobrand=undefined" .
1513 sub pick_from_hotbot_text($) {
1516 $last_search = $hotbot_search_url; # for warnings
1518 # lycos seems to always give us back dictionaries and word lists if
1519 # we search for more than one word...
1521 my $words = random_word();
1523 my $start = int(rand(8)) * 10 + 1;
1524 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1526 my ($search_hit_count, @subpages) =
1527 pick_from_search_engine ($timeout, $search_url, $words);
1529 my @candidates = ();
1530 foreach my $u (@subpages) {
1532 # Hotbot plays redirection games too
1534 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1535 # $u = url_decode($1);
1537 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1538 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1539 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1540 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1542 LOG ($verbose_filter, " candidate: $u");
1543 push @candidates, $u;
1546 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1547 $timeout, @candidates);
1552 ############################################################################
1554 # Pick images by feeding random words into Lycos
1556 ############################################################################
1558 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1564 sub pick_from_lycos_text($) {
1567 $last_search = $lycos_search_url; # for warnings
1569 # lycos seems to always give us back dictionaries and word lists if
1570 # we search for more than one word...
1572 my $words = random_word();
1574 my $start = int(rand(8)) * 10 + 1;
1575 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1577 my ($search_hit_count, @subpages) =
1578 pick_from_search_engine ($timeout, $search_url, $words);
1580 my @candidates = ();
1581 foreach my $u (@subpages) {
1583 # Lycos plays redirection games.
1585 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1590 # $u = url_decode($1);
1592 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1593 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1594 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1595 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1596 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1599 LOG ($verbose_filter, " candidate: $u");
1600 push @candidates, $u;
1603 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1604 $timeout, @candidates);
1609 ############################################################################
1611 # Pick images by feeding random words into news.yahoo.com
1613 ############################################################################
1615 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1620 sub pick_from_yahoo_news_text($) {
1623 $last_search = $yahoo_news_url; # for warnings
1625 my $words = random_word();
1626 my $search_url = $yahoo_news_url . $words;
1628 my ($search_hit_count, @subpages) =
1629 pick_from_search_engine ($timeout, $search_url, $words);
1631 my @candidates = ();
1632 foreach my $u (@subpages) {
1634 # de-redirectize the URLs
1635 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1637 # only accept URLs on Yahoo's news site
1638 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1639 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1640 next unless ($u =~ m@&u=/@);
1642 LOG ($verbose_filter, " candidate: $u");
1643 push @candidates, $u;
1646 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1647 $timeout, @candidates);
1652 ############################################################################
1654 # Pick images from LiveJournal's list of recently-posted images.
1656 ############################################################################
1658 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1660 # With most of our image sources, we get a random page and then select
1661 # from the images on it. However, in the case of LiveJournal, the page
1662 # of images tends to update slowly; so we'll remember the last N entries
1663 # on it and randomly select from those, to get a wider variety each time.
1665 my $lj_cache_size = 1000;
1666 my @lj_cache = (); # fifo, for ordering by age
1667 my %lj_cache = (); # hash, for detecting dups
1670 sub pick_from_livejournal_images($) {
1673 $last_search = $livejournal_img_url; # for warnings
1675 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1676 return () unless $body;
1679 $body =~ s/(<recent-image)\b/\n$1/gsi;
1681 foreach (split (/\n/, $body)) {
1682 next unless (m/^<recent-image\b/);
1683 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1684 my $img = html_unquote ($1);
1686 next if ($lj_cache{$img}); # already have it
1688 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1689 my $page = html_unquote ($1);
1690 my @pair = ($img, $page);
1691 LOG ($verbose_filter, " candidate: $img");
1692 push @lj_cache, \@pair;
1693 $lj_cache{$img} = \@pair;
1696 return () if ($#lj_cache == -1);
1698 my $n = $#lj_cache+1;
1699 my $i = int(rand($n));
1700 my ($img, $page) = @{$lj_cache[$i]};
1702 # delete this one from @lj_cache and from %lj_cache.
1704 @lj_cache = ( @lj_cache[0 .. $i-1],
1705 @lj_cache[$i+1 .. $#lj_cache] );
1706 delete $lj_cache{$img};
1708 # Keep the size of the cache under the limit by nuking older entries
1710 while ($#lj_cache >= $lj_cache_size) {
1711 my $pairP = shift @lj_cache;
1712 my $img = $pairP->[0];
1713 delete $lj_cache{$img};
1716 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1718 return ($page, $img);
1722 ############################################################################
1724 # Pick images from ircimages.com (images that have been in the /topic of
1725 # various IRC channels.)
1727 ############################################################################
1729 my $ircimages_url = "http://ircimages.com/";
1732 sub pick_from_ircimages($) {
1735 $last_search = $ircimages_url; # for warnings
1737 my $n = int(rand(2900));
1738 my $search_url = $ircimages_url . "page-$n";
1740 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1741 return () unless $body;
1743 my @candidates = ();
1746 $body =~ s/(<A)\b/\n$1/gsi;
1748 foreach (split (/\n/, $body)) {
1750 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1753 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1754 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1756 next unless ($u =~ m/^http:/i);
1757 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1758 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1760 LOG ($verbose_http, " HREF: $u");
1761 push @candidates, $u;
1764 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1766 return () if ($#candidates == -1);
1768 my $i = int(rand($#candidates+1));
1769 my $img = $candidates[$i];
1771 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1774 $search_url = $img; # hmm...
1775 return ($search_url, $img);
1779 ############################################################################
1781 # Pick images from Flickr's page of recently-posted photos.
1783 ############################################################################
1785 my $flickr_img_url = "http://www.flickr.com/photos/";
1787 # Like LiveJournal, the Flickr page of images tends to update slowly,
1788 # so remember the last N entries on it and randomly select from those.
1790 # I know that Flickr has an API (http://www.flickr.com/services/api/)
1791 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
1793 my $flickr_cache_size = 1000;
1794 my @flickr_cache = (); # fifo, for ordering by age
1795 my %flickr_cache = (); # hash, for detecting dups
1799 sub pick_from_flickr_recent($) {
1802 my $start = 16 * int(rand(100));
1804 $last_search = $flickr_img_url; # for warnings
1805 $last_search .= "?start=$start" if ($start > 0);
1807 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
1808 return () unless $body;
1810 $body =~ s/[\r\n]/ /gs;
1811 $body =~ s/(<a)\b/\n$1/gsi;
1815 foreach (split (/\n/, $body)) {
1816 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
1817 <IMG \s [^<>]* \b SRC=\"([^<>\"]+)\" @xsi;
1818 next unless defined ($thumb);
1819 $page = html_unquote ($page);
1820 $thumb = html_unquote ($thumb);
1822 next unless ($thumb =~ m@^http://photos\d*\.flickr\.com/@);
1824 my $base = "http://www.flickr.com/";
1825 $page =~ s@^/@$base@;
1826 $thumb =~ s@^/@$base@;
1829 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
1832 next if ($flickr_cache{$img}); # already have it
1834 my @pair = ($img, $page, $start);
1835 LOG ($verbose_filter, " candidate: $img");
1836 push @flickr_cache, \@pair;
1837 $flickr_cache{$img} = \@pair;
1841 return () if ($#flickr_cache == -1);
1843 my $n = $#flickr_cache+1;
1844 my $i = int(rand($n));
1845 my ($img, $page) = @{$flickr_cache[$i]};
1847 # delete this one from @flickr_cache and from %flickr_cache.
1849 @flickr_cache = ( @flickr_cache[0 .. $i-1],
1850 @flickr_cache[$i+1 .. $#flickr_cache] );
1851 delete $flickr_cache{$img};
1853 # Keep the size of the cache under the limit by nuking older entries
1855 while ($#flickr_cache >= $flickr_cache_size) {
1856 my $pairP = shift @flickr_cache;
1857 my $img = $pairP->[0];
1858 delete $flickr_cache{$img};
1861 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1863 return ($page, $img);
1867 ############################################################################
1869 # Pick images from a random RSS feed on Flickr.
1871 ############################################################################
1873 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne" .
1874 "?format=rss_200_enc&tags=");
1876 # Picks a random RSS feed; picks a random image from that feed;
1877 # returns 2 URLs: the page containing the image, and the image.
1878 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
1881 sub pick_from_flickr_random($) {
1882 my $timeout = shift;
1884 my $rss = $flickr_rss_base . random_word();
1885 $last_search = $rss;
1887 print STDERR "\n\n" if ($verbose_load);
1888 LOG ($verbose_load, "URL: $last_search");
1890 $suppress_audit = 1;
1892 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
1893 if (!$base || !$body) {
1899 ($base, $img) = pick_image_from_rss ($base, $body);
1901 return () unless defined ($img);
1903 LOG ($verbose_load, "redirected to: $base");
1904 return ($base, $img);
1908 ############################################################################
1910 # Pick images by waiting for driftnet to populate a temp dir with files.
1911 # Requires driftnet version 0.1.5 or later.
1912 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1913 # for images being downloaded by others.)
1914 # Driftnet/webcollage integration by jwz.
1916 ############################################################################
1919 sub pick_from_driftnet($) {
1922 my $id = $driftnet_magic;
1923 my $dir = $driftnet_dir;
1927 error ("\$driftnet_dir unset?") unless ($dir);
1930 error ("$dir unreadable") unless (-d "$dir/.");
1932 $timeout = $http_timeout unless ($timeout);
1935 while ($now = time, $now < $start + $timeout) {
1937 opendir (DIR, $dir) || error ("$dir: $!");
1938 while (my $file = readdir(DIR)) {
1939 next if ($file =~ m/^\./);
1940 $file = "$dir/$file";
1942 LOG ($verbose_load, "picked file $file ($id)");
1943 return ($id, $file);
1947 LOG (($verbose_net || $verbose_load), "timed out for $id");
1952 sub get_driftnet_file($) {
1955 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1957 my $id = $driftnet_magic;
1958 my $re = qr/$driftnet_dir/;
1959 error ("$id: $file not in $driftnet_dir?")
1960 unless ($file =~ m@^$re@o);
1963 open (IN, $file) || error ("$id: $file: $!");
1965 while (<IN>) { $body .= $_; }
1966 close IN || error ("$id: $file: $!");
1967 unlink ($file) || error ("$id: $file: rm: $!");
1968 return ($id, $body);
1972 sub spawn_driftnet($) {
1975 # make a directory to use.
1977 my $tmp = $ENV{TEMPDIR} || "/tmp";
1978 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1979 LOG ($verbose_exec, "mkdir $driftnet_dir");
1980 last if mkdir ($driftnet_dir, 0700);
1983 if (! ($cmd =~ m/\s/)) {
1984 # if the command didn't have any arguments in it, then it must be just
1985 # a pointer to the executable. Append the default args to it.
1986 my $dargs = $default_driftnet_cmd;
1987 $dargs =~ s/^[^\s]+//;
1991 # point the driftnet command at our newly-minted private directory.
1993 $cmd .= " -d $driftnet_dir";
1994 $cmd .= ">/dev/null" unless ($verbose_exec);
1997 if ($pid < 0) { error ("fork: $!\n"); }
2000 push @pids_to_kill, $pid;
2001 LOG ($verbose_exec, "forked for \"$cmd\"");
2004 nontrapping_system ($cmd) || error ("exec: $!");
2007 # wait a bit, then make sure the process actually started up.
2010 error ("pid $pid failed to start \"$cmd\"")
2011 unless (1 == kill (0, $pid));
2015 sub pick_from_local_dir {
2016 my ( $timeout ) = @_;
2018 my $id = $local_magic;
2021 my $dir = $local_dir;
2022 error ("\$local_dir unset?") unless ($dir);
2025 error ("$dir unreadable") unless (-d "$dir/.");
2027 my $v = ($verbose_exec ? "-v" : "");
2028 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2030 LOG ($verbose_load, "picked file $pick ($id)");
2031 return ($id, $pick);
2035 sub get_local_file {
2038 error ("\$local_dir unset?") unless ($local_dir);
2040 my $id = $local_magic;
2041 my $re = qr/$local_dir/;
2042 error ("$id: $file not in $local_dir?")
2043 unless ($file =~ m@^$re@o);
2046 open (IN, $file) || error ("$id: $file: $!");
2048 while (<IN>) { $body .= $_; }
2049 close IN || error ("$id: $file: $!");
2050 return ($id, $body);
2055 ############################################################################
2057 # Pick a random image in a random way
2059 ############################################################################
2062 # Picks a random image on a random page, and returns two URLs:
2063 # the page containing the image, and the image.
2064 # Returns () if nothing found this time.
2067 sub pick_image(;$) {
2070 $current_state = "select";
2071 $load_method = "none";
2073 my $n = int(rand(100));
2076 my @rest = @search_methods;
2079 my $pct = shift @rest;
2080 my $name = shift @rest;
2081 my $tfn = shift @rest;
2083 if ($total > $n && !defined($fn)) {
2085 $current_state = $name;
2086 $load_method = $current_state;
2090 if ($total != 100) {
2091 error ("internal error: \@search_methods totals to $total%!");
2094 record_attempt ($current_state);
2095 return $fn->($timeout);
2100 ############################################################################
2102 # Statistics and logging
2104 ############################################################################
2107 return strftime ("%H:%M:%S: ", localtime);
2111 return "$progname: " . timestr() . "$current_state: ";
2116 print STDERR blurb() . "$err\n";
2122 print STDERR "$progname: stack trace:\n";
2124 my ($package, $filename, $line, $subroutine) = caller($i++);
2125 last unless defined($package);
2126 $filename =~ s@^.*/@@;
2127 print STDERR " $filename#$line, $subroutine\n";
2139 my $head = "$progname: DEBUG: ";
2140 foreach (split (/\n/, $lastlog)) {
2141 print STDERR "$head$_\n";
2147 my ($print, $msg) = @_;
2148 my $blurb = timestr() . "$current_state: ";
2149 $lastlog .= "$blurb$msg\n";
2150 print STDERR "$progname: $blurb$msg\n" if $print;
2155 my %stats_successes;
2158 my $last_state = undef;
2159 sub record_attempt($) {
2163 record_failure($last_state) unless ($image_succeeded > 0);
2165 $last_state = $name;
2168 report_performance();
2171 $image_succeeded = 0;
2172 $suppress_audit = 0;
2175 sub record_success($$$) {
2176 my ($name, $url, $base) = @_;
2177 if (defined($stats_successes{$name})) {
2178 $stats_successes{$name}++;
2180 $stats_successes{$name} = 1;
2183 stop_timer ($name, 1);
2184 my $o = $current_state;
2185 $current_state = $name;
2186 save_recent_url ($url, $base);
2187 $current_state = $o;
2188 $image_succeeded = 1;
2193 sub record_failure($) {
2196 return if $image_succeeded;
2198 stop_timer ($name, 0);
2199 if ($verbose_load && !$verbose_exec) {
2201 if ($suppress_audit) {
2202 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2206 my $o = $current_state;
2207 $current_state = "DEBUG";
2209 my $line = "#" x 78;
2210 print STDERR "\n\n\n";
2211 print STDERR ("#" x 78) . "\n";
2212 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2215 print STDERR ("-" x 78) . "\n";
2216 print STDERR "\n\n";
2218 $current_state = $o;
2220 $image_succeeded = 0;
2227 my $i = $stats_successes{$name};
2228 my $j = $stats_attempts{$name};
2231 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2235 my $current_start_time = 0;
2237 sub start_timer($) {
2239 $current_start_time = time;
2241 if (defined($stats_attempts{$name})) {
2242 $stats_attempts{$name}++;
2244 $stats_attempts{$name} = 1;
2246 if (!defined($stats_elapsed{$name})) {
2247 $stats_elapsed{$name} = 0;
2251 sub stop_timer($$) {
2252 my ($name, $success) = @_;
2253 $stats_elapsed{$name} += time - $current_start_time;
2257 my $last_report_time = 0;
2258 sub report_performance() {
2260 return unless $verbose_warnings;
2263 return unless ($now >= $last_report_time + $report_performance_interval);
2264 my $ot = $last_report_time;
2265 $last_report_time = $now;
2267 return if ($ot == 0);
2269 my $blurb = "$progname: " . timestr();
2272 print STDERR "${blurb}Current standings:\n";
2274 foreach my $name (sort keys (%stats_attempts)) {
2275 my $try = $stats_attempts{$name};
2276 my $suc = $stats_successes{$name} || 0;
2277 my $pct = int($suc * 100 / $try);
2278 my $secs = $stats_elapsed{$name};
2279 my $secs_link = int($secs / $try);
2280 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
2281 "$name:", "$pct%", $suc, $try, $secs_link);
2287 my $max_recent_images = 400;
2288 my $max_recent_sites = 20;
2289 my @recent_images = ();
2290 my @recent_sites = ();
2292 sub save_recent_url($$) {
2293 my ($url, $base) = @_;
2295 return unless ($verbose_warnings);
2298 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2299 return unless defined ($site);
2301 if ($base eq $driftnet_magic || $base eq $local_magic) {
2303 @recent_images = ();
2307 foreach (@recent_images) {
2309 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2310 " (on $base via $last_search)\n";
2316 # suppress "duplicate site" warning via %warningless_sites.
2318 if ($warningless_sites{$site}) {
2320 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2321 $warningless_sites{$1}) {
2323 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2324 $warningless_sites{$1}) {
2329 foreach (@recent_sites) {
2331 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2332 " ($url on $base via $last_search)\n";
2338 push @recent_images, $url;
2339 push @recent_sites, $site;
2340 shift @recent_images if ($#recent_images >= $max_recent_images);
2341 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2346 ##############################################################################
2350 ##############################################################################
2357 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2362 # Given the raw body of a GIF document, returns the dimensions of the image.
2366 my $type = substr($body, 0, 6);
2368 return () unless ($type =~ /GIF8[7,9]a/);
2369 $s = substr ($body, 6, 10);
2370 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2371 return (($b<<8|$a), ($d<<8|$c));
2374 # Given the raw body of a JPEG document, returns the dimensions of the image.
2379 my $L = length($body);
2381 my $c1 = substr($body, $i, 1); $i++;
2382 my $c2 = substr($body, $i, 1); $i++;
2383 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2386 while (ord($ch) != 0xDA && $i < $L) {
2387 # Find next marker, beginning with 0xFF.
2388 while (ord($ch) != 0xFF) {
2389 return () if (length($body) <= $i);
2390 $ch = substr($body, $i, 1); $i++;
2392 # markers can be padded with any number of 0xFF.
2393 while (ord($ch) == 0xFF) {
2394 return () if (length($body) <= $i);
2395 $ch = substr($body, $i, 1); $i++;
2398 # $ch contains the value of the marker.
2399 my $marker = ord($ch);
2401 if (($marker >= 0xC0) &&
2402 ($marker <= 0xCF) &&
2403 ($marker != 0xC4) &&
2404 ($marker != 0xCC)) { # it's a SOFn marker
2406 return () if (length($body) <= $i);
2407 my $s = substr($body, $i, 4); $i += 4;
2408 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2409 return (($c<<8|$d), ($a<<8|$b));
2412 # We must skip variables, since FFs in variable names aren't
2413 # valid JPEG markers.
2414 return () if (length($body) <= $i);
2415 my $s = substr($body, $i, 2); $i += 2;
2416 my ($c1, $c2) = unpack ("C"x2, $s);
2417 my $length = ($c1 << 8) | $c2;
2418 return () if ($length < 2);
2425 # Given the raw body of a PNG document, returns the dimensions of the image.
2429 return () unless ($body =~ m/^\211PNG\r/);
2430 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2431 return () unless defined ($bits);
2432 return () unless ($bits =~ /^IHDR/);
2433 my ($ign, $w, $h) = unpack("a4N2", $bits);
2438 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2443 my ($w, $h) = gif_size ($body);
2444 if ($w && $h) { return ($w, $h); }
2445 ($w, $h) = jpeg_size ($body);
2446 if ($w && $h) { return ($w, $h); }
2447 return png_size ($body);
2451 # returns the full path of the named program, or undef.
2455 foreach (split (/:/, $ENV{PATH})) {
2456 if (-x "$_/$prog") {
2464 # Like rand(), but chooses numbers with a bell curve distribution.
2467 $_ = 1.0 unless defined($_);
2469 return (rand($_) + rand($_) + rand($_));
2473 sub exit_cleanup() {
2475 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2476 if (@pids_to_kill) {
2477 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2478 kill ('TERM', @pids_to_kill);
2482 sub signal_cleanup($) {
2484 print STDERR blurb() . (defined($sig)
2485 ? "caught signal $sig."
2488 if ($verbose_exec || $verbose_warnings);
2494 ##############################################################################
2496 # Generating a list of urls only
2498 ##############################################################################
2500 sub url_only_output() {
2502 my ($base, $img) = pick_image;
2506 print "$img $base\n";
2511 ##############################################################################
2513 # Running as an xscreensaver module, or as a web page imagemap
2515 ##############################################################################
2517 my $image_ppm = sprintf ("%s/webcollage-%08x",
2518 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2520 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x",
2521 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2523 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x",
2524 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2527 my $filter_cmd = undef;
2528 my $post_filter_cmd = undef;
2529 my $background = undef;
2531 my @imagemap_areas = ();
2532 my $imagemap_html_tmp = undef;
2533 my $imagemap_jpg_tmp = undef;
2536 my $img_width; # size of the image being generated.
2542 unlink $image_ppm, $image_tmp1, $image_tmp2;
2543 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2544 if (defined ($imagemap_html_tmp));
2548 # Like system, but prints status about exit codes, and kills this process
2549 # with whatever signal killed the sub-process, if any.
2551 sub nontrapping_system(@) {
2555 s/\"[^\"]+\"/\"...\"/g;
2557 LOG ($verbose_exec, "executing \"$_\"");
2562 LOG ($verbose_exec, "subproc exited normally.");
2563 } elsif (($rc & 0xff) == 0) {
2565 LOG ($verbose_exec, "subproc exited with status $rc.");
2568 LOG ($verbose_exec, "subproc dumped core.");
2571 LOG ($verbose_exec, "subproc died with signal $rc.");
2572 # die that way ourselves.
2580 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2581 # writes a PPM to the given output file. Returns the width/height of the
2582 # image if successful.
2584 sub image_to_pnm($$$) {
2585 my ($url, $body, $output) = @_;
2586 my ($cmd, $cmd2, $w, $h);
2588 if ((@_ = gif_size ($body))) {
2591 } elsif ((@_ = jpeg_size ($body))) {
2594 } elsif ((@_ = png_size ($body))) {
2598 LOG (($verbose_pbm || $verbose_load),
2599 "not a GIF, JPG, or PNG" .
2600 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2601 ? " (looks like HTML)" : "") .
2603 $suppress_audit = 1;
2607 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2608 # do this, the process doesn't die properly.
2609 if (!$verbose_pbm) {
2611 # We get a "giftopnm: got a 'Application Extension' extension"
2612 # warning any time it's an animgif.
2614 # Note that "giftopnm: EOF / read error on image data" is not
2615 # always a fatal error -- sometimes the image looks fine anyway.
2617 $cmd2 .= " 2>/dev/null";
2620 # There exist corrupted GIF and JPEG files that can make giftopnm and
2621 # djpeg lose their minds and go into a loop. So this gives those programs
2622 # a small timeout -- if they don't complete in time, kill them.
2628 local $SIG{ALRM} = sub {
2630 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2631 kill ('TERM', $pid) if ($pid);
2636 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2643 LOG ($verbose_exec, "awaiting $pid");
2645 LOG ($verbose_exec, "$pid completed");
2647 my $size = (stat($output))[7];
2648 $size = -1 unless defined($size);
2650 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2654 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2657 print STDERR blurb() . "$cmd failed: $!\n";
2661 die if ($@ && $@ ne "alarm\n"); # propagate errors
2674 sub pick_root_displayer() {
2677 foreach my $cmd (@root_displayers) {
2679 my ($name) = m/^([^ ]+)/;
2680 push @names, "\"$name\"";
2681 LOG ($verbose_exec, "looking for $name...");
2682 foreach my $dir (split (/:/, $ENV{PATH})) {
2683 LOG ($verbose_exec, " checking $dir/$name");
2684 return $cmd if (-x "$dir/$name");
2688 $names[$#names] = "or " . $names[$#names];
2689 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2693 my $ppm_to_root_window_cmd = undef;
2696 sub x_or_pbm_output($) {
2697 my ($window_id) = @_;
2699 # Check for our helper program, to see whether we need to use PPM pipelines.
2701 $_ = "webcollage-helper";
2702 if (defined ($webcollage_helper) || which ($_)) {
2703 $webcollage_helper = $_ unless (defined($webcollage_helper));
2704 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2705 $webcollage_helper .= " -v";
2707 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2710 # make sure the various programs we execute exist, right up front.
2712 my @progs = ("ppmmake"); # always need this one
2714 if (!defined($webcollage_helper)) {
2715 # Only need these others if we don't have the helper.
2717 "giftopnm", "pngtopnm", "djpeg",
2718 "pnmpaste", "pnmscale", "pnmcut");
2722 which ($_) || error "$_ not found on \$PATH.";
2725 # find a root-window displayer program.
2727 $ppm_to_root_window_cmd = pick_root_displayer();
2729 if (defined ($window_id)) {
2730 error ("-window-id only works if xscreensaver-getimage is installed")
2731 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
2733 error ("unparsable window id: $window_id")
2734 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
2735 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
2736 error ("unable to munge displayer: $ppm_to_root_window_cmd");
2739 if (!$img_width || !$img_height) {
2741 if (!defined ($window_id) &&
2742 defined ($ENV{XSCREENSAVER_WINDOW})) {
2743 $window_id = $ENV{XSCREENSAVER_WINDOW};
2746 if (!defined ($window_id)) {
2748 which ($_) || error "$_ not found on \$PATH.";
2750 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2751 if (!defined($img_height)) {
2752 error "xdpyinfo failed.";
2754 } else { # we have a window id
2756 which ($_) || error "$_ not found on \$PATH.";
2757 $_ .= " -id $window_id";
2759 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
2761 if (!defined($img_height)) {
2762 error "xwininfo failed.";
2767 my $bgcolor = "#000000";
2768 my $bgimage = undef;
2771 if ($background =~ m/^\#[0-9a-f]+$/i) {
2772 $bgcolor = $background;
2774 } elsif (-r $background) {
2775 $bgimage = $background;
2777 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2778 error "not a color or readable file: $background";
2781 # default to assuming it's a color
2782 $bgcolor = $background;
2786 # Create the sold-colored base image.
2788 $_ = "ppmmake '$bgcolor' $img_width $img_height";
2789 LOG ($verbose_pbm, "creating base image: $_");
2790 nontrapping_system "$_ > $image_ppm";
2792 # Paste the default background image in the middle of it.
2799 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2801 while (<IMG>) { $body .= $_; }
2804 if ((@_ = gif_size ($body))) {
2806 $cmd = "giftopnm |";
2808 } elsif ((@_ = jpeg_size ($body))) {
2812 } elsif ((@_ = png_size ($body))) {
2814 $cmd = "pngtopnm |";
2816 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2822 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
2825 my $x = int (($img_width - $iw) / 2);
2826 my $y = int (($img_height - $ih) / 2);
2828 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2830 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2831 open (IMG, "| $cmd") || error "running $cmd: $!";
2835 LOG ($verbose_exec, "subproc exited normally.");
2836 rename ($image_tmp1, $image_ppm) ||
2837 error "renaming $image_tmp1 to $image_ppm: $!";
2843 my ($base, $img) = pick_image();
2844 my $source = $current_state;
2845 $current_state = "loadimage";
2847 my ($headers, $body) = get_document ($img, $base);
2849 paste_image ($base, $img, $body, $source);
2853 $current_state = "idle";
2854 $load_method = "none";
2856 unlink $image_tmp1, $image_tmp2;
2861 sub paste_image($$$$) {
2862 my ($base, $img, $body, $source) = @_;
2864 $current_state = "paste";
2866 $suppress_audit = 0;
2868 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2872 # If we are using the webcollage-helper, then we do not need to convert this
2873 # image to a PPM. But, if we're using a filter command, we still must, since
2874 # that's what the filters expect (webcollage-helper can read PPMs, so that's
2877 if (defined ($webcollage_helper) &&
2878 !defined ($filter_cmd)) {
2880 ($iw, $ih) = image_size ($body);
2882 LOG (($verbose_pbm || $verbose_load),
2883 "not a GIF, JPG, or PNG" .
2884 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2885 ? " (looks like HTML)" : "") .
2887 $suppress_audit = 1;
2893 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2894 print OUT $body || error ("writing $image_tmp1: $!");
2895 close OUT || error ("writing $image_tmp1: $!");
2898 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2901 LOG ($verbose_pbm, "unable to make PBM from $img");
2906 record_success ($load_method, $img, $base);
2909 my $ow = $iw; # used only for error messages
2912 # don't just tack this onto the front of the pipeline -- we want it to
2913 # be able to change the size of the input image.
2916 LOG ($verbose_pbm, "running $filter_cmd");
2918 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2920 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2921 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2924 rename ($image_tmp2, $image_tmp1);
2926 # re-get the width/height in case the filter resized it.
2928 open(IMG, "<$image_tmp1") || return 0;
2931 ($iw, $ih) = m/^(\d+) (\d+)$/;
2933 return 0 unless ($iw && $ih);
2936 my $target_w = $img_width; # max rectangle into which the image must fit
2937 my $target_h = $img_height;
2943 # Usually scale the image to fit on the screen -- but sometimes scale it
2944 # to fit on half or a quarter of the screen. (We do this by reducing the
2945 # size of the target rectangle.) Note that the image is not merely scaled
2946 # to fit; we instead cut the image in half repeatedly until it fits in the
2947 # target rectangle -- that gives a wider distribution of sizes.
2949 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
2950 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
2952 if ($iw > $target_w || $ih > $target_h) {
2953 while ($iw > $target_w ||
2959 if ($iw <= 10 || $ih <= 10) {
2960 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2964 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
2966 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2970 my $src = $image_tmp1;
2972 my $crop_x = 0; # the sub-rectangle of the image
2973 my $crop_y = 0; # that we will actually paste.
2977 # The chance that we will randomly crop out a section of an image starts
2978 # out fairly low, but goes up for images that are very large, or images
2979 # that have ratios that make them look like banners (we try to avoid
2980 # banner images entirely, but they slip through when the IMG tags didn't
2981 # have WIDTH and HEIGHT specified.)
2983 my $crop_chance = 0.2;
2984 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2985 $crop_chance += 0.2;
2987 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2988 $crop_chance += 0.2;
2990 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2991 $crop_chance += 0.7;
2994 if ($crop_chance > 0.1) {
2995 LOG ($verbose_pbm, "crop chance: $crop_chance");
2998 if (rand() < $crop_chance) {
3003 if ($crop_w > $min_width) {
3004 # if it's a banner, select the width linearly.
3005 # otherwise, select a bell.
3006 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3009 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3010 $crop_x = int (rand() * ($ow - $crop_w));
3012 if ($crop_h > $min_height) {
3013 # height always selects as a bell.
3014 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3015 $crop_y = int (rand() * ($oh - $crop_h));
3018 if ($crop_x != 0 || $crop_y != 0 ||
3019 $crop_w != $iw || $crop_h != $ih) {
3021 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3025 # Where the image should logically land -- this might be negative.
3027 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3028 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3030 # if we have chosen to paste the image outside of the rectangle of the
3031 # screen, then we need to crop it.
3035 $x + $crop_w > $img_width ||
3036 $y + $crop_h > $img_height) {
3039 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3041 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3042 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3044 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3045 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3048 # If any cropping needs to happen, add pnmcut.
3050 if ($crop_x != 0 || $crop_y != 0 ||
3051 $crop_w != $iw || $crop_h != $ih) {
3054 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3055 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3058 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3060 $cmd .= " | pnmpaste - $x $y $image_ppm";
3062 $cmd =~ s@^ *\| *@@;
3064 if (defined ($webcollage_helper)) {
3065 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3066 "$scale $opacity " .
3067 "$crop_x $crop_y $x $y " .
3072 # use a PPM pipeline
3074 $_ .= " < $image_tmp1 > $image_tmp2";
3078 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3080 $_ .= " 2> /dev/null";
3083 my $rc = nontrapping_system ($_);
3085 if (defined ($webcollage_helper) && -z $image_ppm) {
3086 LOG (1, "failed command: \"$cmd\"");
3087 print STDERR "\naudit log:\n\n\n";
3088 print STDERR ("#" x 78) . "\n";
3089 print STDERR blurb() . "$image_ppm has zero size\n";
3091 print STDERR "\n\n";
3096 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3097 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3101 if (!defined ($webcollage_helper)) {
3102 rename ($image_tmp2, $image_ppm) || return;
3105 my $target = "$image_ppm";
3107 # don't just tack this onto the end of the pipeline -- we don't want it
3108 # to end up in $image_ppm, because we don't want the results to be
3111 if ($post_filter_cmd) {
3115 $target = $image_tmp1;
3116 if (!defined ($webcollage_helper)) {
3117 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3119 # Blah, my scripts need the JPEG data, but some other folks need
3120 # the PPM data -- what to do? Ignore the problem, that's what!
3121 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3122 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3125 $rc = nontrapping_system ($cmd);
3127 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3132 if (!$no_output_p) {
3133 my $tsize = (stat($target))[7];
3135 $cmd = "$ppm_to_root_window_cmd $target";
3137 # xv seems to hate being killed. it tends to forget to clean
3138 # up after itself, and leaves windows around and colors allocated.
3139 # I had this same problem with vidwhacker, and I'm not entirely
3140 # sure what I did to fix it. But, let's try this: launch xv
3141 # in the background, so that killing this process doesn't kill it.
3142 # it will die of its own accord soon enough. So this means we
3143 # start pumping bits to the root window in parallel with starting
3144 # the next network retrieval, which is probably a better thing
3149 $rc = nontrapping_system ($cmd);
3152 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3157 LOG ($verbose_pbm, "$target size is $tsize");
3161 $source .= "-" . stats_of($source);
3162 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3163 if ($verbose_imgmap);
3164 if ($imagemap_base) {
3165 update_imagemap ($base, $x, $y, $iw, $ih,
3166 $image_ppm, $img_width, $img_height);
3175 sub update_imagemap($$$$$$$$) {
3176 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3178 $current_state = "imagemap";
3180 my $max_areas = 200;
3182 $url = html_quote ($url);
3185 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3186 unshift @imagemap_areas, $area; # put one on the front
3187 if ($#imagemap_areas >= $max_areas) {
3188 pop @imagemap_areas; # take one off the back.
3191 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3193 my $map_name = $imagemap_base;
3194 $map_name =~ s@^.*/@@;
3195 $map_name = 'collage' if ($map_name eq '');
3197 my $imagemap_html = $imagemap_base . ".html";
3198 my $imagemap_jpg = $imagemap_base . ".jpg";
3200 if (!defined ($imagemap_html_tmp)) {
3201 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3202 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3205 # Read the imagemap html file (if any) to get a template.
3207 my $template_html = '';
3210 if (open (IN, "<$imagemap_html")) {
3211 while (<IN>) { $template_html .= $_; }
3213 LOG ($verbose_pbm, "read template $imagemap_html");
3216 if ($template_html =~ m/^\s*$/s) {
3217 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3218 "<IMG SRC=\"$imagemap_base.jpg\"" .
3219 " USEMAP=\"$map_name\">\n");
3220 LOG ($verbose_pbm, "created dummy template");
3224 # Write the jpg to a tmp file
3228 if (defined ($webcollage_helper)) {
3229 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3231 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3233 my $rc = nontrapping_system ($cmd);
3235 error ("imagemap jpeg failed: \"$cmd\"\n");
3239 # Write the html to a tmp file
3242 my $body = $template_html;
3243 my $areas = join ("\n\t", @imagemap_areas);
3244 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3245 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
3247 "WIDTH=$image_width HEIGHT=$image_height " .
3248 "USEMAP=\"#$map_name\">");
3249 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3250 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3252 # if there are magic webcollage spans in the html, update those too.
3255 my @st = stat ($imagemap_jpg_tmp);
3256 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3257 my $size = int(($st[7] / 1024) + 0.5) . "K";
3258 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3259 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3263 open (OUT, ">$imagemap_html_tmp") || error ("$imagemap_html_tmp: $!");
3264 print OUT $body || error ("$imagemap_html_tmp: $!");
3265 close OUT || error ("$imagemap_html_tmp: $!");
3266 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3269 # Rename the two tmp files to the real files
3271 rename ($imagemap_html_tmp, $imagemap_html) ||
3272 error "renaming $imagemap_html_tmp to $imagemap_html";
3273 LOG ($verbose_pbm, "wrote $imagemap_html");
3274 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3275 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3276 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3280 sub init_signals() {
3282 $SIG{HUP} = \&signal_cleanup;
3283 $SIG{INT} = \&signal_cleanup;
3284 $SIG{QUIT} = \&signal_cleanup;
3285 $SIG{ABRT} = \&signal_cleanup;
3286 $SIG{KILL} = \&signal_cleanup;
3287 $SIG{TERM} = \&signal_cleanup;
3289 # Need this so that if giftopnm dies, we don't die.
3290 $SIG{PIPE} = 'IGNORE';
3293 END { exit_cleanup(); }
3302 my $driftnet_cmd = 0;
3304 $current_state = "init";
3305 $load_method = "none";
3308 my $window_id = undef;
3310 # historical suckage: the environment variable name is lower case.
3311 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3313 while ($_ = $ARGV[0]) {
3315 if ($_ eq "-display" ||
3321 $ENV{DISPLAY} = shift @ARGV;
3322 } elsif ($_ eq "-root") {
3324 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3325 $window_id = shift @ARGV;
3327 } elsif ($_ eq "-no-output") {
3329 } elsif ($_ eq "-urls-only") {
3332 } elsif ($_ eq "-imagemap") {
3333 $imagemap_base = shift @ARGV;
3335 } elsif ($_ eq "-verbose") {
3337 } elsif (m/^-v+$/) {
3338 $verbose += length($_)-1;
3339 } elsif ($_ eq "-delay") {
3340 $delay = shift @ARGV;
3341 } elsif ($_ eq "-timeout") {
3342 $http_timeout = shift @ARGV;
3343 } elsif ($_ eq "-filter") {
3344 $filter_cmd = shift @ARGV;
3345 } elsif ($_ eq "-filter2") {
3346 $post_filter_cmd = shift @ARGV;
3347 } elsif ($_ eq "-background" || $_ eq "-bg") {
3348 $background = shift @ARGV;
3349 } elsif ($_ eq "-size") {
3351 if (m@^(\d+)x(\d+)$@) {
3355 error "argument to \"-size\" must be of the form \"640x400\"";
3357 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3358 $http_proxy = shift @ARGV;
3359 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3360 $dict = shift @ARGV;
3361 } elsif ($_ eq "-opacity") {
3362 $opacity = shift @ARGV;
3363 error ("opacity must be between 0.0 and 1.0")
3364 if ($opacity <= 0 || $opacity > 1);
3365 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3366 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3367 if (! ($ARGV[0] =~ m/^-/)) {
3368 $driftnet_cmd = shift @ARGV;
3370 $driftnet_cmd = $default_driftnet_cmd;
3372 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3373 @search_methods = ( 100, "local", \&pick_from_local_dir );
3374 if (! ($ARGV[0] =~ m/^-/)) {
3375 $local_dir = shift @ARGV;
3377 error ("local directory path must be set")
3379 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3380 my $which = shift @ARGV;
3381 my @rest = @search_methods;
3384 my $pct = shift @rest;
3385 my $name = shift @rest;
3386 my $tfn = shift @rest;
3388 if ($name eq $which) {
3389 @search_methods = (100, $name, $tfn);
3394 error "no such search method as \"$which\"" unless ($ok);
3395 LOG (1, "DEBUG: using only \"$which\"");
3398 print STDERR "$copyright\nusage: $progname " .
3399 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3400 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3401 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3402 "\t\t [-filter cmd] [-filter2 cmd] [-background color]\n" .
3403 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3404 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3405 "\t\t [-directory local-image-directory]\n" .
3411 if ($http_proxy && $http_proxy eq "") {
3412 $http_proxy = undef;
3414 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3415 # historical suckage: allow "http://host:port" as well as "host:port".
3419 if (!$root_p && !$no_output_p) {
3420 print STDERR $copyright;
3421 error "the -root argument is mandatory (for now.)";
3424 if (!$no_output_p && !$ENV{DISPLAY}) {
3425 error "\$DISPLAY is not set.";
3429 if ($verbose == 1) {
3430 $verbose_imgmap = 1;
3431 $verbose_warnings = 1;
3433 } elsif ($verbose == 2) {
3434 $verbose_imgmap = 1;
3435 $verbose_warnings = 1;
3438 } elsif ($verbose == 3) {
3439 $verbose_imgmap = 1;
3440 $verbose_warnings = 1;
3442 $verbose_filter = 1;
3444 } elsif ($verbose == 4) {
3445 $verbose_imgmap = 1;
3446 $verbose_warnings = 1;
3448 $verbose_filter = 1;
3451 } elsif ($verbose == 5) {
3452 $verbose_imgmap = 1;
3453 $verbose_warnings = 1;
3455 $verbose_filter = 1;
3459 } elsif ($verbose == 6) {
3460 $verbose_imgmap = 1;
3461 $verbose_warnings = 1;
3463 $verbose_filter = 1;
3468 } elsif ($verbose >= 7) {
3469 $verbose_imgmap = 1;
3470 $verbose_warnings = 1;
3472 $verbose_filter = 1;
3480 error ("$dict does not exist") unless (-f $dict);
3486 if ($imagemap_base && !($img_width && $img_height)) {
3487 error ("-size WxH is required with -imagemap");
3490 if (defined ($local_dir)) {
3491 $_ = "xscreensaver-getimage-file";
3492 which ($_) || error "$_ not found on \$PATH.";
3497 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3502 x_or_pbm_output ($window_id);