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.129 $ }; $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...
215 # For decoding HTML-encoded character entities to URLs.
219 "quot" => '"', "amp" => '&', "lt" => '<', "gt" => '>',
220 "nbsp" => ' ', "iexcl" => '¡', "cent" => '¢', "pound" => '£',
221 "curren" => '¤', "yen" => '¥', "brvbar" => '¦', "sect" => '§',
222 "uml" => '¨', "copy" => '©', "ordf" => 'ª', "laquo" => '«',
223 "not" => '¬', "shy" => '', "reg" => '®', "macr" => '¯',
224 "deg" => '°', "plusmn" => '±', "sup2" => '²', "sup3" => '³',
225 "acute" => '´', "micro" => 'µ', "para" => '¶', "middot" => '·',
226 "cedil" => '¸', "sup1" => '¹', "ordm" => 'º', "raquo" => '»',
227 "frac14" => '¼', "frac12" => '½', "frac34" => '¾', "iquest" => '¿',
228 "Agrave" => 'À', "Aacute" => 'Á', "Acirc" => 'Â', "Atilde" => 'Ã',
229 "Auml" => 'Ä', "Aring" => 'Å', "AElig" => 'Æ', "Ccedil" => 'Ç',
230 "Egrave" => 'È', "Eacute" => 'É', "Ecirc" => 'Ê', "Euml" => 'Ë',
231 "Igrave" => 'Ì', "Iacute" => 'Í', "Icirc" => 'Î', "Iuml" => 'Ï',
232 "ETH" => 'Ð', "Ntilde" => 'Ñ', "Ograve" => 'Ò', "Oacute" => 'Ó',
233 "Ocirc" => 'Ô', "Otilde" => 'Õ', "Ouml" => 'Ö', "times" => '×',
234 "Oslash" => 'Ø', "Ugrave" => 'Ù', "Uacute" => 'Ú', "Ucirc" => 'Û',
235 "Uuml" => 'Ü', "Yacute" => 'Ý', "THORN" => 'Þ', "szlig" => 'ß',
236 "agrave" => 'à', "aacute" => 'á', "acirc" => 'â', "atilde" => 'ã',
237 "auml" => 'ä', "aring" => 'å', "aelig" => 'æ', "ccedil" => 'ç',
238 "egrave" => 'è', "eacute" => 'é', "ecirc" => 'ê', "euml" => 'ë',
239 "igrave" => 'ì', "iacute" => 'í', "icirc" => 'î', "iuml" => 'ï',
240 "eth" => 'ð', "ntilde" => 'ñ', "ograve" => 'ò', "oacute" => 'ó',
241 "ocirc" => 'ô', "otilde" => 'õ', "ouml" => 'ö', "divide" => '÷',
242 "oslash" => 'ø', "ugrave" => 'ù', "uacute" => 'ú', "ucirc" => 'û',
243 "uuml" => 'ü', "yacute" => 'ý', "thorn" => 'þ', "yuml" => 'ÿ',
244 "ndash" => '-', "mdash" => "--"
248 ##############################################################################
250 # Various global flags set by command line parameters, or computed
252 ##############################################################################
255 my $current_state = "???"; # for diagnostics
258 my $image_succeeded = -1;
259 my $suppress_audit = 0;
261 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
262 my $verbose_warnings = 0; # print out warnings when things go wrong
263 my $verbose_load = 0; # diagnostics about loading of URLs
264 my $verbose_filter = 0; # diagnostics about page selection/rejection
265 my $verbose_net = 0; # diagnostics about network I/O
266 my $verbose_pbm = 0; # diagnostics about PBM pipelines
267 my $verbose_http = 0; # diagnostics about all HTTP activity
268 my $verbose_exec = 0; # diagnostics about executing programs
270 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
272 my $http_proxy = undef;
273 my $http_timeout = 20;
274 my $cvt_timeout = 10;
280 my $min_gif_area = (120 * 120);
285 my $imagemap_base = undef;
287 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
289 my $driftnet_magic = 'driftnet';
290 my $driftnet_dir = undef;
291 my $default_driftnet_cmd = "driftnet -a -m 100";
296 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
297 "arrhenius", "arteriole", "blanket", "brainchild",
298 "burdensome", "carnival", "cherub", "chord", "clever",
299 "dedicate", "dilogarithm", "dolan", "dryden",
303 ##############################################################################
307 ##############################################################################
309 # returns three values: the HTTP response line; the document headers;
310 # and the document body.
312 sub get_document_1($$$) {
313 my ($url, $referer, $timeout) = @_;
315 if (!defined($timeout)) { $timeout = $http_timeout; }
316 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
319 LOG (($verbose_net || $verbose_load), "timed out for $url");
323 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
325 if (! ($url =~ m@^http://@i)) {
326 LOG ($verbose_net, "not an HTTP URL: $url");
330 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
331 $path = "" unless $path;
333 if (!$url_proto || !$serverstring) {
334 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
338 my ($them,$port) = split(/:/, $serverstring);
339 $port = 80 unless $port;
344 $serverstring = $http_proxy if $http_proxy;
345 $serverstring =~ s@^[a-z]+://@@;
346 ($them2,$port2) = split(/:/, $serverstring);
347 $port2 = 80 unless $port2;
350 my ($remote, $iaddr, $paddr, $proto, $line);
352 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
354 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
357 $iaddr = inet_aton($remote);
359 LOG (($verbose_net || $verbose_load), "host not found: $remote");
362 $paddr = sockaddr_in($port2, $iaddr);
370 local $SIG{ALRM} = sub {
371 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
376 $proto = getprotobyname('tcp');
377 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
378 LOG (($verbose_net || $verbose_load), "socket: $!");
381 if (!connect(S, $paddr)) {
382 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
386 select(S); $| = 1; select(STDOUT);
388 my $cookie = $cookies{$them};
390 my $user_agent = "$progname/$version";
392 if ($url =~ m@^http://www\.altavista\.com/@ ||
393 $url =~ m@^http://random\.yahoo\.com/@ ||
394 $url =~ m@^http://images\.google\.com/@) {
395 # block this, you turkeys.
396 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.5)" .
397 " Gecko/20041111 Firefox/1.0";
400 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
402 "User-Agent: $user_agent\r\n";
404 $hdrs .= "Referer: $referer\r\n";
407 my @cc = split(/\r?\n/, $cookie);
408 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
412 foreach (split('\r?\n', $hdrs)) {
413 LOG ($verbose_http, " ==> $_");
416 my $http = <S> || "";
418 # Kludge: the Yahoo Random Link is now returning as its first
419 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
421 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
425 LOG ($verbose_http, " <== $_");
431 LOG ($verbose_http, " <== $_");
433 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
434 set_cookie($them, $1)
445 " <== [ body ]: $lines lines, " . length($body) . " bytes");
450 LOG (($verbose_net || $verbose_load), "null response: $url");
454 $SIG{ALRM} = 'DEFAULT'; # seem to be suffering a race?
455 return ( $http, $head, $body );
457 die if ($@ && $@ ne "alarm\n"); # propagate errors
459 if ($@ && $@ ne "alarm\n") {
460 print STDERR blurb() . "DIE " . join(" ", $@) . "\n";
478 # returns two values: the document headers; and the document body.
479 # if the given URL did a redirect, returns the redirected-to document.
481 sub get_document($$;$) {
482 my ($url, $referer, $timeout) = @_;
485 if (defined($referer) && $referer eq $driftnet_magic) {
486 return get_driftnet_file ($url);
491 my $max_loop_count = 4;
494 if (defined($timeout) && $timeout <= 0) {
495 LOG (($verbose_net || $verbose_load), "timed out for $url");
500 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
502 if (defined ($timeout)) {
504 my $elapsed = $now - $start;
505 $timeout -= $elapsed;
509 return () unless $http; # error message already printed
511 $http =~ s/[\r\n]+$//s;
513 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
516 my ( $location ) = m@^location:[ \t]*(.*)$@im;
518 $location =~ s/[\r\n]$//;
520 LOG ($verbose_net, "redirect from $url to $location");
525 $referer =~ m@^(http://[^/]+)@i;
527 } elsif (! ($url =~ m@^[a-z]+:@i)) {
529 s@[^/]+$@@g if m@^http://[^/]+/@i;
530 $_ .= "/" if m@^http://[^/]+$@i;
535 LOG ($verbose_net, "no Location with \"$http\"");
536 return ( $url, $body );
539 if ($loop_count++ > $max_loop_count) {
541 "too many redirects ($max_loop_count) from $orig_url");
546 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
548 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
550 # http errors -- return nothing.
556 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
562 return ( $url, $body );
568 # If we already have a cookie defined for this site, and the site is trying
569 # to overwrite that very same cookie, let it do so. This is because nytimes
570 # expires its cookies - it lets you upgrade to a new cookie without logging
571 # in again, but you have to present the old cookie to get the new cookie.
572 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
575 my ($host, $cookie) = @_;
576 my $oc = $cookies{$host};
579 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
581 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
583 if ($oc_name eq $nc_name &&
584 $oc_value ne $nc_value) {
585 $cookies{$host} = $cookie;
586 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
591 ############################################################################
593 # Extracting image URLs from HTML
595 ############################################################################
597 # given a URL and the body text at that URL, selects and returns a random
598 # image from it. returns () if no suitable images found.
600 sub pick_image_from_body($$) {
601 my ($url, $body) = @_;
606 # if there's at least one slash after the host, take off the last
608 if ( m@^http://[^/]+/@io ) {
609 $base =~ s@[^/]+$@@go;
612 # if there are no slashes after the host at all, put one on the end.
613 if ( m@^http://[^/]+$@io ) {
619 # strip out newlines, compress whitespace
626 # There are certain web sites that list huge numbers of dictionary
627 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
628 # Porn sites tend not to be reputable!)
630 # I do not want webcollage to filter on content: I want it to select
631 # randomly from the set of images on the web. All the logic here for
632 # rejecting some images is really a set of heuristics for rejecting
633 # images that are not really images: for rejecting *text* that is in
634 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
635 # the content of the pictures to be randomly selected from among all
636 # the available content.
638 # So, filtering out "dirty" pictures by looking for "dirty" keywords
639 # would be wrong: dirty pictures exist, like it or not, so webcollage
640 # should be able to select them.
642 # However, picking a random URL is a hard thing to do. The mechanism I'm
643 # using is to search for a selection of random words. This is not
644 # perfect, but works ok most of the time. The way it breaks down is when
645 # some URLs get precedence because their pages list *every word* as
646 # related -- those URLs come up more often than others.
648 # So, after we've retrieved a URL, if it has too many keywords, reject
649 # it. We reject it not on the basis of what those keywords are, but on
650 # the basis that by having so many, the page has gotten an unfair
651 # advantage against our randomizer.
654 foreach my $trip (@tripwire_words) {
655 $trip_count++ if m/$trip/i;
658 if ($trip_count >= $#tripwire_words - 2) {
659 LOG (($verbose_filter || $verbose_load),
660 "there is probably a dictionary in \"$url\": rejecting.");
661 $rejected_urls{$url} = -1;
671 foreach (split(/ *</)) {
674 # Likewise, reject any web pages that have a KEYWORDS meta tag
677 if (m/name ?= ?\"?keywords\"?/i &&
678 m/content ?= ?\"([^\"]+)\"/) {
681 LOG (($verbose_filter || $verbose_load),
682 "excessive keywords ($L bytes) in $url: rejecting.");
683 $rejected_urls{$url} = $L;
688 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
692 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
694 my $was_inline = (! ( "$1" eq "a" || "$1" eq "A" ));
696 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
697 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
702 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
704 } elsif ( ! m@^[^/:?]+:@ ) {
707 1 while (s@/[^/]+/\.\./@/@g);
711 if ( ! m@^http://@io ) {
716 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
720 # skip really short or really narrow images
721 if ( $width && $width < $min_width) {
722 if (!$height) { $height = "?"; }
723 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
727 if ( $height && $height < $min_height) {
728 if (!$width) { $width = "?"; }
729 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
733 # skip images with ratios that make them look like banners.
734 if ($min_ratio && $width && $height &&
735 ($width * $min_ratio ) > $height) {
736 if (!$height) { $height = "?"; }
737 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
741 # skip GIFs with a small number of pixels -- those usually suck.
742 if ($width && $height &&
744 ($width * $height) < $min_gif_area) {
745 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
749 # skip images with a URL that indicates a Yahoo thumbnail.
750 if (m@\.yimg\.com/.*/t/@) {
751 if (!$width) { $width = "?"; }
752 if (!$height) { $height = "?"; }
753 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
759 if ($unique_urls{$url}) {
760 LOG ($verbose_filter, " skip duplicate image $_");
764 LOG ($verbose_filter,
766 ($width && $height ? " (${width}x${height})" : "") .
767 ($was_inline ? " (inline)" : ""));
769 $urls[++$#urls] = $url;
770 $unique_urls{$url}++;
772 # JPEGs are preferable to GIFs and PNGs.
774 if ( ! m@[.](gif|png)$@io ) {
775 $urls[++$#urls] = $url;
778 # pointers to images are preferable to inlined images.
779 if ( ! $was_inline ) {
780 $urls[++$#urls] = $url;
781 $urls[++$#urls] = $url;
786 my $fsp = ($body =~ m@<frameset@i);
791 @urls = depoison (@urls);
794 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
798 # pick a random element of the table
799 my $i = int(rand($#urls+1));
802 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
807 # Given a URL and the RSS feed from that URL, pick a random image from
808 # the feed. This is a lot simpler than extracting images out of a page:
809 # we already know we have reasonable images, so we just pick one.
810 # Returns: the real URL of the page (preferably not the RSS version),
813 sub pick_image_from_rss($$) {
814 my ( $url, $body ) = @_;
815 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
817 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
818 $base = $url unless $base;
820 # pick a random element of the table
822 my $i = int(rand(scalar @suitable));
823 my $url = $suitable[$i];
824 LOG ($verbose_load, "picked image " .($i+1) . "/" .
825 ($#suitable+1) . ": $url");
826 return ($base, $url);
832 ############################################################################
834 # Subroutines for getting pages and images out of search engines
836 ############################################################################
839 sub pick_dictionary() {
840 my @dicts = ("/usr/dict/words",
841 "/usr/share/dict/words",
842 "/usr/share/lib/dict/words");
843 foreach my $f (@dicts) {
849 error ("$dicts[0] does not exist") unless defined($wordlist);
852 # returns a random word from the dictionary
857 if (! open (IN, "<$wordlist")) {
861 my $size = (stat(IN))[7];
866 error ("looping ($count) while reading $wordlist")
869 my $pos = int (rand ($size));
870 if (seek (IN, $pos, 0)) {
871 $word = <IN>; # toss partial line
872 $word = <IN>; # keep next line
876 next if ($word =~ m/^[-\']/);
880 $word =~ s/^[^a-z]+//s;
881 $word =~ s/[^a-z]+$//s;
887 $word =~ s/ally$/al/s;
888 $word =~ s/izes$/ize/s;
889 $word =~ s/esses$/ess/s;
890 $word =~ s/(.{5})ing$/$1/s;
892 next if (length ($word) > 14);
898 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
899 $word = "\%22$word\%22"; # And put quotes (%22) around it.
906 sub random_words($) {
908 my $sep = ($or_p ? "%20OR%20" : "%20");
909 return (random_word . $sep .
919 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
926 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
935 $s =~ s/\"/"/gi;
939 sub html_unquote($) {
941 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
942 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
947 # Loads the given URL (a search on some search engine) and returns:
948 # - the total number of hits the search engine claimed it had;
949 # - a list of URLs from the page that the search engine returned;
950 # Note that this list contains all kinds of internal search engine
951 # junk URLs too -- caller must prune them.
953 sub pick_from_search_engine($$$) {
954 my ( $timeout, $search_url, $words ) = @_;
959 print STDERR "\n\n" if ($verbose_load);
961 LOG ($verbose_load, "words: $_");
962 LOG ($verbose_load, "URL: $search_url");
964 $last_search = $search_url; # for warnings
967 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
968 if (defined ($timeout)) {
969 $timeout -= (time - $start);
972 LOG (($verbose_net || $verbose_load),
973 "timed out (late) for $search_url");
979 return () if (! $body);
984 my $search_count = "?";
985 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
987 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
989 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
991 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
993 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
995 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
997 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
999 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1001 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1002 $search_count = $1; # lycos
1003 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1004 $search_count = $1; # hotbot
1005 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1006 $search_count = "0";
1007 } elsif ($body =~ m@found no document matching@i) { # avtext
1008 $search_count = "0";
1010 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1012 # if ($search_count eq "?" || $search_count eq "0") {
1014 # my $file = "/tmp/wc.html";
1015 # open(OUT, ">$file") || error ("writing $file: $!");
1018 # print STDERR blurb() . "###### wrote $file\n";
1022 my $length = length($body);
1031 foreach (split(/\n/)) {
1033 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1036 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1037 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1039 if ( $rejected_urls{$u} ) {
1040 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1044 LOG ($verbose_http, " HREF: $u");
1046 $subpages[++$#subpages] = $u;
1049 if ( $#subpages < 0 ) {
1050 LOG ($verbose_filter,
1051 "found nothing on $base ($length bytes, $href_count links).");
1055 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1057 return ($search_count, @subpages);
1065 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1067 next unless defined($h);
1069 if ($poisoners{$h}) {
1070 LOG (($verbose_filter), " rejecting poisoner: $_");
1073 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1075 LOG (($verbose_filter), " rejecting poisoner: $_");
1078 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1080 LOG (($verbose_filter), " rejecting poisoner: $_");
1090 # given a list of URLs, picks one at random; loads it; and returns a
1091 # random image from it.
1092 # returns the url of the page loaded; the url of the image chosen.
1094 sub pick_image_from_pages($$$$@) {
1095 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1097 $total_hit_count = "?" unless defined($total_hit_count);
1099 @pages = depoison (@pages);
1101 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1102 " ($total_hit_count total)");
1104 return () if ($#pages < 0);
1106 my $i = int(rand($#pages+1));
1107 my $page = $pages[$i];
1109 LOG ($verbose_load, "picked page $page");
1111 $suppress_audit = 1;
1113 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1115 if (!$base2 || !$body2) {
1120 my $img = pick_image_from_body ($base2, $body2);
1124 return ($base2, $img);
1131 ############################################################################
1133 # Pick images from random pages returned by the Yahoo Random Link
1135 ############################################################################
1138 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1141 # Picks a random page; picks a random image on that page;
1142 # returns two URLs: the page containing the image, and the image.
1143 # Returns () if nothing found this time.
1145 sub pick_from_yahoo_random_link($) {
1148 print STDERR "\n\n" if ($verbose_load);
1149 LOG ($verbose_load, "URL: $yahoo_random_link");
1151 $last_search = $yahoo_random_link; # for warnings
1153 $suppress_audit = 1;
1155 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1156 if (!$base || !$body) {
1161 LOG ($verbose_load, "redirected to: $base");
1163 my $img = pick_image_from_body ($base, $body);
1167 return ($base, $img);
1174 ############################################################################
1176 # Pick images from random pages returned by the Alta Vista Random Link
1178 ############################################################################
1181 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1184 # Picks a random page; picks a random image on that page;
1185 # returns two URLs: the page containing the image, and the image.
1186 # Returns () if nothing found this time.
1188 sub pick_from_alta_vista_random_link($) {
1191 print STDERR "\n\n" if ($verbose_load);
1192 LOG ($verbose_load, "URL: $alta_vista_random_link");
1194 $last_search = $alta_vista_random_link; # for warnings
1196 $suppress_audit = 1;
1198 my ( $base, $body ) = get_document ($alta_vista_random_link,
1200 if (!$base || !$body) {
1205 LOG ($verbose_load, "redirected to: $base");
1207 my $img = pick_image_from_body ($base, $body);
1211 return ($base, $img);
1218 ############################################################################
1220 # Pick images by feeding random words into Alta Vista Image Search
1222 ############################################################################
1225 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1226 "?ipht=1" . # photos
1227 "&igrph=1" . # graphics
1230 "&micat=1" . # no partner sites
1231 "&sc=on" . # "site collapse"
1235 sub pick_from_alta_vista_images($) {
1238 my $words = random_word();
1239 my $page = (int(rand(9)) + 1);
1240 my $search_url = $alta_vista_images_url . $words;
1243 $search_url .= "&pgno=" . $page; # page number
1244 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1247 my ($search_hit_count, @subpages) =
1248 pick_from_search_engine ($timeout, $search_url, $words);
1250 my @candidates = ();
1251 foreach my $u (@subpages) {
1253 # avimages is encoding their URLs now.
1254 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1255 $u = url_unquote($u);
1257 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1258 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1259 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1260 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1261 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1263 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1264 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1266 LOG ($verbose_filter, " candidate: $u");
1267 push @candidates, $u;
1270 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1271 $timeout, @candidates);
1276 ############################################################################
1278 # Pick images by feeding random words into Google Image Search.
1279 # By Charles Gales <gales@us.ibm.com>
1281 ############################################################################
1284 my $google_images_url = "http://images.google.com/images" .
1285 "?site=images" . # photos
1286 "&btnG=Search" . # graphics
1287 "&safe=off" . # no screening
1292 sub pick_from_google_images($;$$) {
1293 my ($timeout, $words, $max_page) = @_;
1295 if (!defined($words)) {
1296 $words = random_word; # only one word for Google
1299 my $page = (int(rand(9)) + 1);
1300 my $num = 20; # 20 images per page
1301 my $search_url = $google_images_url . $words;
1304 $search_url .= "&start=" . $page*$num; # page number
1305 $search_url .= "&num=" . $num; #images per page
1308 my ($search_hit_count, @subpages) =
1309 pick_from_search_engine ($timeout, $search_url, $words);
1311 my @candidates = ();
1313 foreach my $u (@subpages) {
1314 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1315 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1317 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1320 $img = "http://$img" unless ($img =~ m/^http:/i);
1322 LOG ($verbose_filter, " candidate: $ref");
1323 push @candidates, $img;
1324 $referers{$img} = $ref;
1328 @candidates = depoison (@candidates);
1329 return () if ($#candidates < 0);
1330 my $i = int(rand($#candidates+1));
1331 my $img = $candidates[$i];
1332 my $ref = $referers{$img};
1334 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1335 return ($ref, $img);
1340 ############################################################################
1342 # Pick images by feeding random numbers into Google Image Search.
1343 # By jwz, suggested by Ian O'Donnell.
1345 ############################################################################
1349 sub pick_from_google_image_numbers($) {
1353 my $number = int(rand($max));
1355 $number = sprintf("%04d", $number)
1358 pick_from_google_images ($timeout, "$number");
1363 ############################################################################
1365 # Pick images by feeding random digital camera file names into
1366 # Google Image Search.
1367 # By jwz, inspired by the excellent Random Personal Picture Finder
1368 # at http://www.diddly.com/random/
1370 ############################################################################
1374 # Common digital camera file name formats, as described at
1375 # http://www.diddly.com/random/about.html
1377 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1378 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1379 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1380 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1381 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1382 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1383 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1384 int(rand(0xC)), int(rand(30))+1,
1386 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1387 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1388 sub { my $n = int(rand(9999)); # Canon
1389 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1390 sub { my $n = int(rand(9999)); # Canon
1391 sprintf ("1%02d-%04d_IMG.jpg",
1392 int($n/100), $n); },
1393 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1394 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1395 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1396 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1397 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1398 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1399 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1400 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1401 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1402 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1403 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1404 # int(rand(12))+1, int(rand(31))+1,
1405 # int(rand(999))); },
1406 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1407 # int(rand(6)), # year
1408 # int(rand(12))+1, int(rand(31))+1,
1409 # int(rand(999))); },
1410 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1411 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1412 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1413 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1418 sub pick_from_google_image_photos($) {
1421 my $i = int(rand($#photomakers + 1));
1422 my $fn = $photomakers[$i];
1424 my $words .= $file . "%20filetype:jpg";
1426 pick_from_google_images ($timeout, $words);
1431 ############################################################################
1433 # Pick images by feeding random words into Alta Vista Text Search
1435 ############################################################################
1438 my $alta_vista_url = "http://www.altavista.com/web/results" .
1442 "&sc=on" . # "site collapse"
1447 sub pick_from_alta_vista_text($) {
1450 my $words = random_words(0);
1451 my $page = (int(rand(9)) + 1);
1452 my $search_url = $alta_vista_url . $words;
1455 $search_url .= "&pgno=" . $page;
1456 $search_url .= "&stq=" . (($page-1) * 10);
1459 my ($search_hit_count, @subpages) =
1460 pick_from_search_engine ($timeout, $search_url, $words);
1462 my @candidates = ();
1463 foreach my $u (@subpages) {
1465 # Those altavista fuckers are playing really nasty redirection games
1466 # these days: the filter your clicks through their site, but use
1467 # onMouseOver to make it look like they're not! Well, it makes it
1468 # easier for us to identify search results...
1470 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1471 $u = url_unquote($u);
1473 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1474 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1475 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1477 LOG ($verbose_filter, " candidate: $u");
1478 push @candidates, $u;
1481 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1482 $timeout, @candidates);
1487 ############################################################################
1489 # Pick images by feeding random words into Hotbot
1491 ############################################################################
1493 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1495 "&descriptiontype=0" .
1502 "&cobrand=undefined" .
1505 sub pick_from_hotbot_text($) {
1508 $last_search = $hotbot_search_url; # for warnings
1510 # lycos seems to always give us back dictionaries and word lists if
1511 # we search for more than one word...
1513 my $words = random_word();
1515 my $start = int(rand(8)) * 10 + 1;
1516 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1518 my ($search_hit_count, @subpages) =
1519 pick_from_search_engine ($timeout, $search_url, $words);
1521 my @candidates = ();
1522 foreach my $u (@subpages) {
1524 # Hotbot plays redirection games too
1526 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1527 # $u = url_decode($1);
1529 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1530 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1531 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1532 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1534 LOG ($verbose_filter, " candidate: $u");
1535 push @candidates, $u;
1538 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1539 $timeout, @candidates);
1544 ############################################################################
1546 # Pick images by feeding random words into Lycos
1548 ############################################################################
1550 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1556 sub pick_from_lycos_text($) {
1559 $last_search = $lycos_search_url; # for warnings
1561 # lycos seems to always give us back dictionaries and word lists if
1562 # we search for more than one word...
1564 my $words = random_word();
1566 my $start = int(rand(8)) * 10 + 1;
1567 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1569 my ($search_hit_count, @subpages) =
1570 pick_from_search_engine ($timeout, $search_url, $words);
1572 my @candidates = ();
1573 foreach my $u (@subpages) {
1575 # Lycos plays redirection games.
1577 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1582 # $u = url_decode($1);
1584 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1585 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1586 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1587 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1588 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1591 LOG ($verbose_filter, " candidate: $u");
1592 push @candidates, $u;
1595 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1596 $timeout, @candidates);
1601 ############################################################################
1603 # Pick images by feeding random words into news.yahoo.com
1605 ############################################################################
1607 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1612 sub pick_from_yahoo_news_text($) {
1615 $last_search = $yahoo_news_url; # for warnings
1617 my $words = random_word();
1618 my $search_url = $yahoo_news_url . $words;
1620 my ($search_hit_count, @subpages) =
1621 pick_from_search_engine ($timeout, $search_url, $words);
1623 my @candidates = ();
1624 foreach my $u (@subpages) {
1626 # de-redirectize the URLs
1627 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1629 # only accept URLs on Yahoo's news site
1630 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1631 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1632 next unless ($u =~ m@&u=/@);
1634 LOG ($verbose_filter, " candidate: $u");
1635 push @candidates, $u;
1638 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1639 $timeout, @candidates);
1644 ############################################################################
1646 # Pick images from LiveJournal's list of recently-posted images.
1648 ############################################################################
1650 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1652 # With most of our image sources, we get a random page and then select
1653 # from the images on it. However, in the case of LiveJournal, the page
1654 # of images tends to update slowly; so we'll remember the last N entries
1655 # on it and randomly select from those, to get a wider variety each time.
1657 my $lj_cache_size = 1000;
1658 my @lj_cache = (); # fifo, for ordering by age
1659 my %lj_cache = (); # hash, for detecting dups
1662 sub pick_from_livejournal_images($) {
1665 $last_search = $livejournal_img_url; # for warnings
1667 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1668 return () unless $body;
1671 $body =~ s/(<recent-image)\b/\n$1/gsi;
1673 foreach (split (/\n/, $body)) {
1674 next unless (m/^<recent-image\b/);
1675 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1676 my $img = html_unquote ($1);
1678 next if ($lj_cache{$img}); # already have it
1680 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1681 my $page = html_unquote ($1);
1682 my @pair = ($img, $page);
1683 LOG ($verbose_filter, " candidate: $img");
1684 push @lj_cache, \@pair;
1685 $lj_cache{$img} = \@pair;
1688 return () if ($#lj_cache == -1);
1690 my $n = $#lj_cache+1;
1691 my $i = int(rand($n));
1692 my ($img, $page) = @{$lj_cache[$i]};
1694 # delete this one from @lj_cache and from %lj_cache.
1696 @lj_cache = ( @lj_cache[0 .. $i-1],
1697 @lj_cache[$i+1 .. $#lj_cache] );
1698 delete $lj_cache{$img};
1700 # Keep the size of the cache under the limit by nuking older entries
1702 while ($#lj_cache >= $lj_cache_size) {
1703 my $pairP = shift @lj_cache;
1704 my $img = $pairP->[0];
1705 delete $lj_cache{$img};
1708 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1710 return ($page, $img);
1714 ############################################################################
1716 # Pick images from ircimages.com (images that have been in the /topic of
1717 # various IRC channels.)
1719 ############################################################################
1721 my $ircimages_url = "http://ircimages.com/";
1724 sub pick_from_ircimages($) {
1727 $last_search = $ircimages_url; # for warnings
1729 my $n = int(rand(2900));
1730 my $search_url = $ircimages_url . "page-$n";
1732 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1733 return () unless $body;
1735 my @candidates = ();
1738 $body =~ s/(<A)\b/\n$1/gsi;
1740 foreach (split (/\n/, $body)) {
1742 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1745 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1746 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1748 next unless ($u =~ m/^http:/i);
1749 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1750 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1752 LOG ($verbose_http, " HREF: $u");
1753 push @candidates, $u;
1756 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1758 return () if ($#candidates == -1);
1760 my $i = int(rand($#candidates+1));
1761 my $img = $candidates[$i];
1763 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1766 $search_url = $img; # hmm...
1767 return ($search_url, $img);
1771 ############################################################################
1773 # Pick images from Flickr's page of recently-posted photos.
1775 ############################################################################
1777 my $flickr_img_url = "http://www.flickr.com/photos/";
1779 # Like LiveJournal, the Flickr page of images tends to update slowly,
1780 # so remember the last N entries on it and randomly select from those.
1782 # I know that Flickr has an API (http://www.flickr.com/services/api/)
1783 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
1785 my $flickr_cache_size = 1000;
1786 my @flickr_cache = (); # fifo, for ordering by age
1787 my %flickr_cache = (); # hash, for detecting dups
1791 sub pick_from_flickr_recent($) {
1794 my $start = 16 * int(rand(100));
1796 $last_search = $flickr_img_url; # for warnings
1797 $last_search .= "?start=$start" if ($start > 0);
1799 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
1800 return () unless $body;
1802 $body =~ s/[\r\n]/ /gs;
1803 $body =~ s/(<a)\b/\n$1/gsi;
1807 foreach (split (/\n/, $body)) {
1808 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
1809 <IMG \s [^<>]* \b SRC=\"([^<>\"]+)\" @xsi;
1810 next unless defined ($thumb);
1811 $page = html_unquote ($page);
1812 $thumb = html_unquote ($thumb);
1814 next unless ($thumb =~ m@^http://photos\d*\.flickr\.com/@);
1816 my $base = "http://www.flickr.com/";
1817 $page =~ s@^/@$base@;
1818 $thumb =~ s@^/@$base@;
1821 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
1824 next if ($flickr_cache{$img}); # already have it
1826 my @pair = ($img, $page, $start);
1827 LOG ($verbose_filter, " candidate: $img");
1828 push @flickr_cache, \@pair;
1829 $flickr_cache{$img} = \@pair;
1833 return () if ($#flickr_cache == -1);
1835 my $n = $#flickr_cache+1;
1836 my $i = int(rand($n));
1837 my ($img, $page) = @{$flickr_cache[$i]};
1839 # delete this one from @flickr_cache and from %flickr_cache.
1841 @flickr_cache = ( @flickr_cache[0 .. $i-1],
1842 @flickr_cache[$i+1 .. $#flickr_cache] );
1843 delete $flickr_cache{$img};
1845 # Keep the size of the cache under the limit by nuking older entries
1847 while ($#flickr_cache >= $flickr_cache_size) {
1848 my $pairP = shift @flickr_cache;
1849 my $img = $pairP->[0];
1850 delete $flickr_cache{$img};
1853 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1855 return ($page, $img);
1859 ############################################################################
1861 # Pick images from a random RSS feed on Flickr.
1863 ############################################################################
1865 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne" .
1866 "?format=rss_200_enc&tags=");
1868 # Picks a random RSS feed; picks a random image from that feed;
1869 # returns 2 URLs: the page containing the image, and the image.
1870 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
1873 sub pick_from_flickr_random($) {
1874 my $timeout = shift;
1876 my $rss = $flickr_rss_base . random_word();
1877 $last_search = $rss;
1879 print STDERR "\n\n" if ($verbose_load);
1880 LOG ($verbose_load, "URL: $last_search");
1882 $suppress_audit = 1;
1884 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
1885 if (!$base || !$body) {
1891 ($base, $img) = pick_image_from_rss ($base, $body);
1893 return () unless defined ($img);
1895 LOG ($verbose_load, "redirected to: $base");
1896 return ($base, $img);
1900 ############################################################################
1902 # Pick images by waiting for driftnet to populate a temp dir with files.
1903 # Requires driftnet version 0.1.5 or later.
1904 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1905 # for images being downloaded by others.)
1906 # Driftnet/webcollage integration by jwz.
1908 ############################################################################
1911 sub pick_from_driftnet($) {
1914 my $id = $driftnet_magic;
1915 my $dir = $driftnet_dir;
1919 error ("\$driftnet_dir unset?") unless ($dir);
1922 error ("$dir unreadable") unless (-d "$dir/.");
1924 $timeout = $http_timeout unless ($timeout);
1927 while ($now = time, $now < $start + $timeout) {
1929 opendir (DIR, $dir) || error ("$dir: $!");
1930 while (my $file = readdir(DIR)) {
1931 next if ($file =~ m/^\./);
1932 $file = "$dir/$file";
1934 LOG ($verbose_load, "picked file $file ($id)");
1935 return ($id, $file);
1939 LOG (($verbose_net || $verbose_load), "timed out for $id");
1944 sub get_driftnet_file($) {
1947 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1949 my $id = $driftnet_magic;
1950 my $re = qr/$driftnet_dir/;
1951 error ("$id: $file not in $driftnet_dir?")
1952 unless ($file =~ m@^$re@o);
1955 open (IN, $file) || error ("$id: $file: $!");
1957 while (<IN>) { $body .= $_; }
1958 close IN || error ("$id: $file: $!");
1959 unlink ($file) || error ("$id: $file: rm: $!");
1960 return ($id, $body);
1964 sub spawn_driftnet($) {
1967 # make a directory to use.
1969 my $tmp = $ENV{TEMPDIR} || "/tmp";
1970 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1971 LOG ($verbose_exec, "mkdir $driftnet_dir");
1972 last if mkdir ($driftnet_dir, 0700);
1975 if (! ($cmd =~ m/\s/)) {
1976 # if the command didn't have any arguments in it, then it must be just
1977 # a pointer to the executable. Append the default args to it.
1978 my $dargs = $default_driftnet_cmd;
1979 $dargs =~ s/^[^\s]+//;
1983 # point the driftnet command at our newly-minted private directory.
1985 $cmd .= " -d $driftnet_dir";
1986 $cmd .= ">/dev/null" unless ($verbose_exec);
1989 if ($pid < 0) { error ("fork: $!\n"); }
1992 push @pids_to_kill, $pid;
1993 LOG ($verbose_exec, "forked for \"$cmd\"");
1996 nontrapping_system ($cmd) || error ("exec: $!");
1999 # wait a bit, then make sure the process actually started up.
2002 error ("pid $pid failed to start \"$cmd\"")
2003 unless (1 == kill (0, $pid));
2007 ############################################################################
2009 # Pick a random image in a random way
2011 ############################################################################
2014 # Picks a random image on a random page, and returns two URLs:
2015 # the page containing the image, and the image.
2016 # Returns () if nothing found this time.
2019 sub pick_image(;$) {
2022 $current_state = "select";
2023 $load_method = "none";
2025 my $n = int(rand(100));
2028 my @rest = @search_methods;
2031 my $pct = shift @rest;
2032 my $name = shift @rest;
2033 my $tfn = shift @rest;
2035 if ($total > $n && !defined($fn)) {
2037 $current_state = $name;
2038 $load_method = $current_state;
2042 if ($total != 100) {
2043 error ("internal error: \@search_methods totals to $total%!");
2046 record_attempt ($current_state);
2047 return $fn->($timeout);
2052 ############################################################################
2054 # Statistics and logging
2056 ############################################################################
2059 return strftime ("%H:%M:%S: ", localtime);
2063 return "$progname: " . timestr() . "$current_state: ";
2068 print STDERR blurb() . "$err\n";
2074 print STDERR "$progname: stack trace:\n";
2076 my ($package, $filename, $line, $subroutine) = caller($i++);
2077 last unless defined($package);
2078 $filename =~ s@^.*/@@;
2079 print STDERR " $filename#$line, $subroutine\n";
2091 my $head = "$progname: DEBUG: ";
2092 foreach (split (/\n/, $lastlog)) {
2093 print STDERR "$head$_\n";
2099 my ($print, $msg) = @_;
2100 my $blurb = timestr() . "$current_state: ";
2101 $lastlog .= "$blurb$msg\n";
2102 print STDERR "$progname: $blurb$msg\n" if $print;
2107 my %stats_successes;
2110 my $last_state = undef;
2111 sub record_attempt($) {
2115 record_failure($last_state) unless ($image_succeeded > 0);
2117 $last_state = $name;
2120 report_performance();
2123 $image_succeeded = 0;
2124 $suppress_audit = 0;
2127 sub record_success($$$) {
2128 my ($name, $url, $base) = @_;
2129 if (defined($stats_successes{$name})) {
2130 $stats_successes{$name}++;
2132 $stats_successes{$name} = 1;
2135 stop_timer ($name, 1);
2136 my $o = $current_state;
2137 $current_state = $name;
2138 save_recent_url ($url, $base);
2139 $current_state = $o;
2140 $image_succeeded = 1;
2145 sub record_failure($) {
2148 return if $image_succeeded;
2150 stop_timer ($name, 0);
2151 if ($verbose_load && !$verbose_exec) {
2153 if ($suppress_audit) {
2154 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2158 my $o = $current_state;
2159 $current_state = "DEBUG";
2161 my $line = "#" x 78;
2162 print STDERR "\n\n\n";
2163 print STDERR ("#" x 78) . "\n";
2164 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2167 print STDERR ("-" x 78) . "\n";
2168 print STDERR "\n\n";
2170 $current_state = $o;
2172 $image_succeeded = 0;
2179 my $i = $stats_successes{$name};
2180 my $j = $stats_attempts{$name};
2183 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2187 my $current_start_time = 0;
2189 sub start_timer($) {
2191 $current_start_time = time;
2193 if (defined($stats_attempts{$name})) {
2194 $stats_attempts{$name}++;
2196 $stats_attempts{$name} = 1;
2198 if (!defined($stats_elapsed{$name})) {
2199 $stats_elapsed{$name} = 0;
2203 sub stop_timer($$) {
2204 my ($name, $success) = @_;
2205 $stats_elapsed{$name} += time - $current_start_time;
2209 my $last_report_time = 0;
2210 sub report_performance() {
2212 return unless $verbose_warnings;
2215 return unless ($now >= $last_report_time + $report_performance_interval);
2216 my $ot = $last_report_time;
2217 $last_report_time = $now;
2219 return if ($ot == 0);
2221 my $blurb = "$progname: " . timestr();
2224 print STDERR "${blurb}Current standings:\n";
2226 foreach my $name (sort keys (%stats_attempts)) {
2227 my $try = $stats_attempts{$name};
2228 my $suc = $stats_successes{$name} || 0;
2229 my $pct = int($suc * 100 / $try);
2230 my $secs = $stats_elapsed{$name};
2231 my $secs_link = int($secs / $try);
2232 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
2233 "$name:", "$pct%", $suc, $try, $secs_link);
2239 my $max_recent_images = 400;
2240 my $max_recent_sites = 20;
2241 my @recent_images = ();
2242 my @recent_sites = ();
2244 sub save_recent_url($$) {
2245 my ($url, $base) = @_;
2247 return unless ($verbose_warnings);
2250 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2251 return unless defined ($site);
2253 if ($base eq $driftnet_magic) {
2254 $site = $driftnet_magic;
2255 @recent_images = ();
2259 foreach (@recent_images) {
2261 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2262 " (on $base via $last_search)\n";
2268 # suppress "duplicate site" warning via %warningless_sites.
2270 if ($warningless_sites{$site}) {
2272 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2273 $warningless_sites{$1}) {
2275 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2276 $warningless_sites{$1}) {
2281 foreach (@recent_sites) {
2283 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2284 " ($url on $base via $last_search)\n";
2290 push @recent_images, $url;
2291 push @recent_sites, $site;
2292 shift @recent_images if ($#recent_images >= $max_recent_images);
2293 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2298 ##############################################################################
2302 ##############################################################################
2309 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2314 # Given the raw body of a GIF document, returns the dimensions of the image.
2318 my $type = substr($body, 0, 6);
2320 return () unless ($type =~ /GIF8[7,9]a/);
2321 $s = substr ($body, 6, 10);
2322 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2323 return (($b<<8|$a), ($d<<8|$c));
2326 # Given the raw body of a JPEG document, returns the dimensions of the image.
2331 my $L = length($body);
2333 my $c1 = substr($body, $i, 1); $i++;
2334 my $c2 = substr($body, $i, 1); $i++;
2335 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2338 while (ord($ch) != 0xDA && $i < $L) {
2339 # Find next marker, beginning with 0xFF.
2340 while (ord($ch) != 0xFF) {
2341 return () if (length($body) <= $i);
2342 $ch = substr($body, $i, 1); $i++;
2344 # markers can be padded with any number of 0xFF.
2345 while (ord($ch) == 0xFF) {
2346 return () if (length($body) <= $i);
2347 $ch = substr($body, $i, 1); $i++;
2350 # $ch contains the value of the marker.
2351 my $marker = ord($ch);
2353 if (($marker >= 0xC0) &&
2354 ($marker <= 0xCF) &&
2355 ($marker != 0xC4) &&
2356 ($marker != 0xCC)) { # it's a SOFn marker
2358 return () if (length($body) <= $i);
2359 my $s = substr($body, $i, 4); $i += 4;
2360 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2361 return (($c<<8|$d), ($a<<8|$b));
2364 # We must skip variables, since FFs in variable names aren't
2365 # valid JPEG markers.
2366 return () if (length($body) <= $i);
2367 my $s = substr($body, $i, 2); $i += 2;
2368 my ($c1, $c2) = unpack ("C"x2, $s);
2369 my $length = ($c1 << 8) | $c2;
2370 return () if ($length < 2);
2377 # Given the raw body of a PNG document, returns the dimensions of the image.
2381 return () unless ($body =~ m/^\211PNG\r/);
2382 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2383 return () unless defined ($bits);
2384 return () unless ($bits =~ /^IHDR/);
2385 my ($ign, $w, $h) = unpack("a4N2", $bits);
2390 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2395 my ($w, $h) = gif_size ($body);
2396 if ($w && $h) { return ($w, $h); }
2397 ($w, $h) = jpeg_size ($body);
2398 if ($w && $h) { return ($w, $h); }
2399 return png_size ($body);
2403 # returns the full path of the named program, or undef.
2407 foreach (split (/:/, $ENV{PATH})) {
2408 if (-x "$_/$prog") {
2416 # Like rand(), but chooses numbers with a bell curve distribution.
2419 $_ = 1.0 unless defined($_);
2421 return (rand($_) + rand($_) + rand($_));
2425 sub exit_cleanup() {
2427 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2428 if (@pids_to_kill) {
2429 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2430 kill ('TERM', @pids_to_kill);
2434 sub signal_cleanup($) {
2436 print STDERR blurb() . (defined($sig)
2437 ? "caught signal $sig."
2440 if ($verbose_exec || $verbose_warnings);
2446 ##############################################################################
2448 # Generating a list of urls only
2450 ##############################################################################
2452 sub url_only_output() {
2454 my ($base, $img) = pick_image;
2458 print "$img $base\n";
2463 ##############################################################################
2465 # Running as an xscreensaver module, or as a web page imagemap
2467 ##############################################################################
2469 my $image_ppm = sprintf ("%s/webcollage-%08x",
2470 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2472 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x",
2473 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2475 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x",
2476 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2479 my $filter_cmd = undef;
2480 my $post_filter_cmd = undef;
2481 my $background = undef;
2483 my @imagemap_areas = ();
2484 my $imagemap_html_tmp = undef;
2485 my $imagemap_jpg_tmp = undef;
2488 my $img_width; # size of the image being generated.
2494 unlink $image_ppm, $image_tmp1, $image_tmp2;
2495 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2496 if (defined ($imagemap_html_tmp));
2500 # Like system, but prints status about exit codes, and kills this process
2501 # with whatever signal killed the sub-process, if any.
2503 sub nontrapping_system(@) {
2507 s/\"[^\"]+\"/\"...\"/g;
2509 LOG ($verbose_exec, "executing \"$_\"");
2514 LOG ($verbose_exec, "subproc exited normally.");
2515 } elsif (($rc & 0xff) == 0) {
2517 LOG ($verbose_exec, "subproc exited with status $rc.");
2520 LOG ($verbose_exec, "subproc dumped core.");
2523 LOG ($verbose_exec, "subproc died with signal $rc.");
2524 # die that way ourselves.
2532 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2533 # writes a PPM to the given output file. Returns the width/height of the
2534 # image if successful.
2536 sub image_to_pnm($$$) {
2537 my ($url, $body, $output) = @_;
2538 my ($cmd, $cmd2, $w, $h);
2540 if ((@_ = gif_size ($body))) {
2543 } elsif ((@_ = jpeg_size ($body))) {
2546 } elsif ((@_ = png_size ($body))) {
2550 LOG (($verbose_pbm || $verbose_load),
2551 "not a GIF, JPG, or PNG" .
2552 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2553 ? " (looks like HTML)" : "") .
2555 $suppress_audit = 1;
2559 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2560 # do this, the process doesn't die properly.
2561 if (!$verbose_pbm) {
2563 # We get a "giftopnm: got a 'Application Extension' extension"
2564 # warning any time it's an animgif.
2566 # Note that "giftopnm: EOF / read error on image data" is not
2567 # always a fatal error -- sometimes the image looks fine anyway.
2569 $cmd2 .= " 2>/dev/null";
2572 # There exist corrupted GIF and JPEG files that can make giftopnm and
2573 # djpeg lose their minds and go into a loop. So this gives those programs
2574 # a small timeout -- if they don't complete in time, kill them.
2580 local $SIG{ALRM} = sub {
2582 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2583 kill ('TERM', $pid) if ($pid);
2588 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2595 LOG ($verbose_exec, "awaiting $pid");
2597 LOG ($verbose_exec, "$pid completed");
2599 my $size = (stat($output))[7];
2600 $size = -1 unless defined($size);
2602 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2606 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2609 print STDERR blurb() . "$cmd failed: $!\n";
2613 die if ($@ && $@ ne "alarm\n"); # propagate errors
2626 sub pick_root_displayer() {
2629 foreach my $cmd (@root_displayers) {
2631 my ($name) = m/^([^ ]+)/;
2632 push @names, "\"$name\"";
2633 LOG ($verbose_exec, "looking for $name...");
2634 foreach my $dir (split (/:/, $ENV{PATH})) {
2635 LOG ($verbose_exec, " checking $dir/$name");
2636 return $cmd if (-x "$dir/$name");
2640 $names[$#names] = "or " . $names[$#names];
2641 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2645 my $ppm_to_root_window_cmd = undef;
2648 sub x_or_pbm_output($) {
2649 my ($window_id) = @_;
2651 # Check for our helper program, to see whether we need to use PPM pipelines.
2653 $_ = "webcollage-helper";
2654 if (defined ($webcollage_helper) || which ($_)) {
2655 $webcollage_helper = $_ unless (defined($webcollage_helper));
2656 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2657 $webcollage_helper .= " -v";
2659 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2662 # make sure the various programs we execute exist, right up front.
2664 my @progs = ("ppmmake"); # always need this one
2666 if (!defined($webcollage_helper)) {
2667 # Only need these others if we don't have the helper.
2669 "giftopnm", "pngtopnm", "djpeg",
2670 "pnmpaste", "pnmscale", "pnmcut");
2674 which ($_) || error "$_ not found on \$PATH.";
2677 # find a root-window displayer program.
2679 $ppm_to_root_window_cmd = pick_root_displayer();
2681 if (defined ($window_id)) {
2682 error ("-window-id only works if xscreensaver-getimage is installed")
2683 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
2685 error ("unparsable window id: $window_id")
2686 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
2687 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
2688 error ("unable to munge displayer: $ppm_to_root_window_cmd");
2691 if (!$img_width || !$img_height) {
2693 if (!defined ($window_id) &&
2694 defined ($ENV{XSCREENSAVER_WINDOW})) {
2695 $window_id = $ENV{XSCREENSAVER_WINDOW};
2698 if (!defined ($window_id)) {
2700 which ($_) || error "$_ not found on \$PATH.";
2702 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2703 if (!defined($img_height)) {
2704 error "xdpyinfo failed.";
2706 } else { # we have a window id
2708 which ($_) || error "$_ not found on \$PATH.";
2709 $_ .= " -id $window_id";
2711 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
2713 if (!defined($img_height)) {
2714 error "xwininfo failed.";
2719 my $bgcolor = "#000000";
2720 my $bgimage = undef;
2723 if ($background =~ m/^\#[0-9a-f]+$/i) {
2724 $bgcolor = $background;
2726 } elsif (-r $background) {
2727 $bgimage = $background;
2729 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2730 error "not a color or readable file: $background";
2733 # default to assuming it's a color
2734 $bgcolor = $background;
2738 # Create the sold-colored base image.
2740 $_ = "ppmmake '$bgcolor' $img_width $img_height";
2741 LOG ($verbose_pbm, "creating base image: $_");
2742 nontrapping_system "$_ > $image_ppm";
2744 # Paste the default background image in the middle of it.
2751 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2753 while (<IMG>) { $body .= $_; }
2756 if ((@_ = gif_size ($body))) {
2758 $cmd = "giftopnm |";
2760 } elsif ((@_ = jpeg_size ($body))) {
2764 } elsif ((@_ = png_size ($body))) {
2766 $cmd = "pngtopnm |";
2768 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2774 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
2777 my $x = int (($img_width - $iw) / 2);
2778 my $y = int (($img_height - $ih) / 2);
2780 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2782 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2783 open (IMG, "| $cmd") || error "running $cmd: $!";
2787 LOG ($verbose_exec, "subproc exited normally.");
2788 rename ($image_tmp1, $image_ppm) ||
2789 error "renaming $image_tmp1 to $image_ppm: $!";
2795 my ($base, $img) = pick_image();
2796 my $source = $current_state;
2797 $current_state = "loadimage";
2799 my ($headers, $body) = get_document ($img, $base);
2801 paste_image ($base, $img, $body, $source);
2805 $current_state = "idle";
2806 $load_method = "none";
2808 unlink $image_tmp1, $image_tmp2;
2813 sub paste_image($$$$) {
2814 my ($base, $img, $body, $source) = @_;
2816 $current_state = "paste";
2818 $suppress_audit = 0;
2820 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2824 # If we are using the webcollage-helper, then we do not need to convert this
2825 # image to a PPM. But, if we're using a filter command, we still must, since
2826 # that's what the filters expect (webcollage-helper can read PPMs, so that's
2829 if (defined ($webcollage_helper) &&
2830 !defined ($filter_cmd)) {
2832 ($iw, $ih) = image_size ($body);
2834 LOG (($verbose_pbm || $verbose_load),
2835 "not a GIF, JPG, or PNG" .
2836 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2837 ? " (looks like HTML)" : "") .
2839 $suppress_audit = 1;
2845 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2846 print OUT $body || error ("writing $image_tmp1: $!");
2847 close OUT || error ("writing $image_tmp1: $!");
2850 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2853 LOG ($verbose_pbm, "unable to make PBM from $img");
2858 record_success ($load_method, $img, $base);
2861 my $ow = $iw; # used only for error messages
2864 # don't just tack this onto the front of the pipeline -- we want it to
2865 # be able to change the size of the input image.
2868 LOG ($verbose_pbm, "running $filter_cmd");
2870 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2872 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2873 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2876 rename ($image_tmp2, $image_tmp1);
2878 # re-get the width/height in case the filter resized it.
2880 open(IMG, "<$image_tmp1") || return 0;
2883 ($iw, $ih) = m/^(\d+) (\d+)$/;
2885 return 0 unless ($iw && $ih);
2888 my $target_w = $img_width; # max rectangle into which the image must fit
2889 my $target_h = $img_height;
2895 # Usually scale the image to fit on the screen -- but sometimes scale it
2896 # to fit on half or a quarter of the screen. (We do this by reducing the
2897 # size of the target rectangle.) Note that the image is not merely scaled
2898 # to fit; we instead cut the image in half repeatedly until it fits in the
2899 # target rectangle -- that gives a wider distribution of sizes.
2901 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
2902 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
2904 if ($iw > $target_w || $ih > $target_h) {
2905 while ($iw > $target_w ||
2911 if ($iw <= 10 || $ih <= 10) {
2912 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2916 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
2918 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2922 my $src = $image_tmp1;
2924 my $crop_x = 0; # the sub-rectangle of the image
2925 my $crop_y = 0; # that we will actually paste.
2929 # The chance that we will randomly crop out a section of an image starts
2930 # out fairly low, but goes up for images that are very large, or images
2931 # that have ratios that make them look like banners (we try to avoid
2932 # banner images entirely, but they slip through when the IMG tags didn't
2933 # have WIDTH and HEIGHT specified.)
2935 my $crop_chance = 0.2;
2936 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2937 $crop_chance += 0.2;
2939 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2940 $crop_chance += 0.2;
2942 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2943 $crop_chance += 0.7;
2946 if ($crop_chance > 0.1) {
2947 LOG ($verbose_pbm, "crop chance: $crop_chance");
2950 if (rand() < $crop_chance) {
2955 if ($crop_w > $min_width) {
2956 # if it's a banner, select the width linearly.
2957 # otherwise, select a bell.
2958 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2961 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2962 $crop_x = int (rand() * ($ow - $crop_w));
2964 if ($crop_h > $min_height) {
2965 # height always selects as a bell.
2966 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2967 $crop_y = int (rand() * ($oh - $crop_h));
2970 if ($crop_x != 0 || $crop_y != 0 ||
2971 $crop_w != $iw || $crop_h != $ih) {
2973 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2977 # Where the image should logically land -- this might be negative.
2979 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2980 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2982 # if we have chosen to paste the image outside of the rectangle of the
2983 # screen, then we need to crop it.
2987 $x + $crop_w > $img_width ||
2988 $y + $crop_h > $img_height) {
2991 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2993 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2994 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2996 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2997 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3000 # If any cropping needs to happen, add pnmcut.
3002 if ($crop_x != 0 || $crop_y != 0 ||
3003 $crop_w != $iw || $crop_h != $ih) {
3006 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3007 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3010 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3012 $cmd .= " | pnmpaste - $x $y $image_ppm";
3014 $cmd =~ s@^ *\| *@@;
3016 if (defined ($webcollage_helper)) {
3017 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3018 "$scale $opacity " .
3019 "$crop_x $crop_y $x $y " .
3024 # use a PPM pipeline
3026 $_ .= " < $image_tmp1 > $image_tmp2";
3030 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3032 $_ .= " 2> /dev/null";
3035 my $rc = nontrapping_system ($_);
3037 if (defined ($webcollage_helper) && -z $image_ppm) {
3038 LOG (1, "failed command: \"$cmd\"");
3039 print STDERR "\naudit log:\n\n\n";
3040 print STDERR ("#" x 78) . "\n";
3041 print STDERR blurb() . "$image_ppm has zero size\n";
3043 print STDERR "\n\n";
3048 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3049 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3053 if (!defined ($webcollage_helper)) {
3054 rename ($image_tmp2, $image_ppm) || return;
3057 my $target = "$image_ppm";
3059 # don't just tack this onto the end of the pipeline -- we don't want it
3060 # to end up in $image_ppm, because we don't want the results to be
3063 if ($post_filter_cmd) {
3067 $target = $image_tmp1;
3068 if (!defined ($webcollage_helper)) {
3069 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3071 # Blah, my scripts need the JPEG data, but some other folks need
3072 # the PPM data -- what to do? Ignore the problem, that's what!
3073 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3074 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3077 $rc = nontrapping_system ($cmd);
3079 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3084 if (!$no_output_p) {
3085 my $tsize = (stat($target))[7];
3087 $cmd = "$ppm_to_root_window_cmd $target";
3089 # xv seems to hate being killed. it tends to forget to clean
3090 # up after itself, and leaves windows around and colors allocated.
3091 # I had this same problem with vidwhacker, and I'm not entirely
3092 # sure what I did to fix it. But, let's try this: launch xv
3093 # in the background, so that killing this process doesn't kill it.
3094 # it will die of its own accord soon enough. So this means we
3095 # start pumping bits to the root window in parallel with starting
3096 # the next network retrieval, which is probably a better thing
3101 $rc = nontrapping_system ($cmd);
3104 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3109 LOG ($verbose_pbm, "$target size is $tsize");
3113 $source .= "-" . stats_of($source);
3114 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3115 if ($verbose_imgmap);
3116 if ($imagemap_base) {
3117 update_imagemap ($base, $x, $y, $iw, $ih,
3118 $image_ppm, $img_width, $img_height);
3127 sub update_imagemap($$$$$$$$) {
3128 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3130 $current_state = "imagemap";
3132 my $max_areas = 200;
3134 $url = html_quote ($url);
3137 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3138 unshift @imagemap_areas, $area; # put one on the front
3139 if ($#imagemap_areas >= $max_areas) {
3140 pop @imagemap_areas; # take one off the back.
3143 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3145 my $map_name = $imagemap_base;
3146 $map_name =~ s@^.*/@@;
3147 $map_name = 'collage' if ($map_name eq '');
3149 my $imagemap_html = $imagemap_base . ".html";
3150 my $imagemap_jpg = $imagemap_base . ".jpg";
3152 if (!defined ($imagemap_html_tmp)) {
3153 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3154 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3157 # Read the imagemap html file (if any) to get a template.
3159 my $template_html = '';
3162 if (open (IN, "<$imagemap_html")) {
3163 while (<IN>) { $template_html .= $_; }
3165 LOG ($verbose_pbm, "read template $imagemap_html");
3168 if ($template_html =~ m/^\s*$/s) {
3169 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3170 "<IMG SRC=\"$imagemap_base.jpg\"" .
3171 " USEMAP=\"$map_name\">\n");
3172 LOG ($verbose_pbm, "created dummy template");
3176 # Write the jpg to a tmp file
3180 if (defined ($webcollage_helper)) {
3181 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3183 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3185 my $rc = nontrapping_system ($cmd);
3187 error ("imagemap jpeg failed: \"$cmd\"\n");
3191 # Write the html to a tmp file
3194 my $body = $template_html;
3195 my $areas = join ("\n\t", @imagemap_areas);
3196 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3197 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
3199 "WIDTH=$image_width HEIGHT=$image_height " .
3200 "USEMAP=\"#$map_name\">");
3201 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3202 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3204 # if there are magic webcollage spans in the html, update those too.
3207 my @st = stat ($imagemap_jpg_tmp);
3208 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3209 my $size = int(($st[7] / 1024) + 0.5) . "K";
3210 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3211 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3215 open (OUT, ">$imagemap_html_tmp") || error ("$imagemap_html_tmp: $!");
3216 print OUT $body || error ("$imagemap_html_tmp: $!");
3217 close OUT || error ("$imagemap_html_tmp: $!");
3218 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3221 # Rename the two tmp files to the real files
3223 rename ($imagemap_html_tmp, $imagemap_html) ||
3224 error "renaming $imagemap_html_tmp to $imagemap_html";
3225 LOG ($verbose_pbm, "wrote $imagemap_html");
3226 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3227 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3228 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3232 sub init_signals() {
3234 $SIG{HUP} = \&signal_cleanup;
3235 $SIG{INT} = \&signal_cleanup;
3236 $SIG{QUIT} = \&signal_cleanup;
3237 $SIG{ABRT} = \&signal_cleanup;
3238 $SIG{KILL} = \&signal_cleanup;
3239 $SIG{TERM} = \&signal_cleanup;
3241 # Need this so that if giftopnm dies, we don't die.
3242 $SIG{PIPE} = 'IGNORE';
3245 END { exit_cleanup(); }
3254 my $driftnet_cmd = 0;
3256 $current_state = "init";
3257 $load_method = "none";
3260 my $window_id = undef;
3262 # historical suckage: the environment variable name is lower case.
3263 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3265 while ($_ = $ARGV[0]) {
3267 if ($_ eq "-display" ||
3273 $ENV{DISPLAY} = shift @ARGV;
3274 } elsif ($_ eq "-root") {
3276 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3277 $window_id = shift @ARGV;
3279 } elsif ($_ eq "-no-output") {
3281 } elsif ($_ eq "-urls-only") {
3284 } elsif ($_ eq "-imagemap") {
3285 $imagemap_base = shift @ARGV;
3287 } elsif ($_ eq "-verbose") {
3289 } elsif (m/^-v+$/) {
3290 $verbose += length($_)-1;
3291 } elsif ($_ eq "-delay") {
3292 $delay = shift @ARGV;
3293 } elsif ($_ eq "-timeout") {
3294 $http_timeout = shift @ARGV;
3295 } elsif ($_ eq "-filter") {
3296 $filter_cmd = shift @ARGV;
3297 } elsif ($_ eq "-filter2") {
3298 $post_filter_cmd = shift @ARGV;
3299 } elsif ($_ eq "-background" || $_ eq "-bg") {
3300 $background = shift @ARGV;
3301 } elsif ($_ eq "-size") {
3303 if (m@^(\d+)x(\d+)$@) {
3307 error "argument to \"-size\" must be of the form \"640x400\"";
3309 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3310 $http_proxy = shift @ARGV;
3311 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3312 $dict = shift @ARGV;
3313 } elsif ($_ eq "-opacity") {
3314 $opacity = shift @ARGV;
3315 error ("opacity must be between 0.0 and 1.0")
3316 if ($opacity <= 0 || $opacity > 1);
3317 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3318 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3319 if (! ($ARGV[0] =~ m/^-/)) {
3320 $driftnet_cmd = shift @ARGV;
3322 $driftnet_cmd = $default_driftnet_cmd;
3324 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3325 my $which = shift @ARGV;
3326 my @rest = @search_methods;
3329 my $pct = shift @rest;
3330 my $name = shift @rest;
3331 my $tfn = shift @rest;
3333 if ($name eq $which) {
3334 @search_methods = (100, $name, $tfn);
3339 error "no such search method as \"$which\"" unless ($ok);
3340 LOG (1, "DEBUG: using only \"$which\"");
3343 print STDERR "$copyright\nusage: $progname " .
3344 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3345 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3346 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3347 "\t\t [-filter cmd] [-filter2 cmd] [-background color]\n" .
3348 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3349 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3355 if ($http_proxy && $http_proxy eq "") {
3356 $http_proxy = undef;
3358 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3359 # historical suckage: allow "http://host:port" as well as "host:port".
3363 if (!$root_p && !$no_output_p) {
3364 print STDERR $copyright;
3365 error "the -root argument is mandatory (for now.)";
3368 if (!$no_output_p && !$ENV{DISPLAY}) {
3369 error "\$DISPLAY is not set.";
3373 if ($verbose == 1) {
3374 $verbose_imgmap = 1;
3375 $verbose_warnings = 1;
3377 } elsif ($verbose == 2) {
3378 $verbose_imgmap = 1;
3379 $verbose_warnings = 1;
3382 } elsif ($verbose == 3) {
3383 $verbose_imgmap = 1;
3384 $verbose_warnings = 1;
3386 $verbose_filter = 1;
3388 } elsif ($verbose == 4) {
3389 $verbose_imgmap = 1;
3390 $verbose_warnings = 1;
3392 $verbose_filter = 1;
3395 } elsif ($verbose == 5) {
3396 $verbose_imgmap = 1;
3397 $verbose_warnings = 1;
3399 $verbose_filter = 1;
3403 } elsif ($verbose == 6) {
3404 $verbose_imgmap = 1;
3405 $verbose_warnings = 1;
3407 $verbose_filter = 1;
3412 } elsif ($verbose >= 7) {
3413 $verbose_imgmap = 1;
3414 $verbose_warnings = 1;
3416 $verbose_filter = 1;
3424 error ("$dict does not exist") unless (-f $dict);
3430 if ($imagemap_base && !($img_width && $img_height)) {
3431 error ("-size WxH is required with -imagemap");
3436 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3441 x_or_pbm_output ($window_id);