3 # webcollage, Copyright (c) 1999-2004 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.117 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
64 my $copyright = "WebCollage $version, Copyright (c) 1999-2004" .
65 " Jamie Zawinski <jwz\@jwz.org>\n" .
66 " http://www.jwz.org/webcollage/\n";
70 my @search_methods = ( 71, "altavista", \&pick_from_alta_vista_random_link,
71 10, "livejournal", \&pick_from_livejournal_images,
72 8, "yahoorand", \&pick_from_yahoo_random_link,
73 6, "yahoonews", \&pick_from_yahoo_news_text,
74 5, "ircimages", \&pick_from_ircimages,
76 # Alta Vista has a new "random link" URL now.
77 # They added it specifically to better support webcollage!
78 # That was super cool of them. This is how we used to do
81 # 0, "avimages", \&pick_from_alta_vista_images,
82 # 0, "avtext", \&pick_from_alta_vista_text,
84 # Google asked (nicely) for me to stop searching them.
85 # I asked them to add a "random link" url. They said
86 # "that would be easy, we'll think about it" and then
87 # never wrote back. Booo Google! Booooo!
89 # 0, "googlenums", \&pick_from_google_image_numbers,
90 # 0, "googleimgs", \&pick_from_google_images,
92 # I suspect Hotbot is actually the same search engine
95 # 0, "hotbot", \&pick_from_hotbot_text,
97 # Eh, Lycos sucks anyway.
98 # 0, "lycos", \&pick_from_lycos_text,
101 # programs we can use to write to the root window (tried in ascending order.)
103 my @root_displayers = (
104 "xscreensaver-getimage -root -file",
105 "chbg -once -xscreensaver -max_size 100",
106 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
107 " -rfg black -rbg black",
108 "xli -quiet -onroot -center -border black",
109 "xloadimage -quiet -onroot -center -border black",
111 # this lame program wasn't built with vroot.h:
112 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
116 # Some sites need cookies to work properly. These are they.
119 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
120 "web.altavista.com" => "AV_ALL=1",
122 # log in as "cipherpunk"
123 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
124 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
125 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
127 "ircimages.com" => 'disclaimer=1',
131 # If this is set, it's a helper program to use for pasting images together:
132 # this is a lot faster and more efficient than using PPM pipelines, which is
133 # what we do if this program doesn't exist. (We check for "webcollage-helper"
134 # on $PATH at startup, and set this variable appropriately.)
136 my $webcollage_helper = undef;
139 # If we have the webcollage-helper program, then it will paste the images
140 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
145 # Some sites have managed to poison the search engines. These are they.
146 # (We auto-detect sites that have poisoned the search engines via excessive
147 # keywords or dictionary words, but these are ones that slip through
150 # This can contain full host names, or 2 or 3 component domains.
153 "die.net" => 1, # 'l33t h4ck3r d00dz.
154 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
155 "rootsweb.com" => 1, # Cluttering avtext with human names.
156 "akamai.net" => 1, # Lots of sites have their images on Akamai.
157 "akamaitech.net" => 1, # But those are pretty much all banners.
158 # Since Akamai is super-expensive, let's
159 # go out on a limb and assume that all of
160 # their customers are rich-and-boring.
161 "bartleby.com" => 1, # Dictionary, cluttering avtext.
162 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
163 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
164 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
165 # (I don't see how they did it, though!)
166 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
167 "nextag.com" => 1, # Poisoned Alta Vista real good.
171 # When verbosity is turned on, we warn about sites that we seem to be hitting
172 # a lot: usually this means some new poisoner has made it into the search
173 # engines. But sometimes, the warning is just because that site has a lot
174 # of stuff on it. So these are the sites that are immune to the "frequent
175 # site" diagnostic message.
177 my %warningless_sites = (
178 "home.earthlink.net" => 1, # Lots of home pages here.
179 "www.geocities.com" => 1,
180 "www.angelfire.com" => 1,
181 "members.aol.com" => 1,
183 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
184 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
185 # hits this every time.
187 "driftnet" => 1, # builtin...
191 ##############################################################################
193 # Various global flags set by command line parameters, or computed
195 ##############################################################################
198 my $current_state = "???"; # for diagnostics
201 my $image_succeeded = -1;
202 my $suppress_audit = 0;
204 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
205 my $verbose_warnings = 0; # print out warnings when things go wrong
206 my $verbose_load = 0; # diagnostics about loading of URLs
207 my $verbose_filter = 0; # diagnostics about page selection/rejection
208 my $verbose_net = 0; # diagnostics about network I/O
209 my $verbose_pbm = 0; # diagnostics about PBM pipelines
210 my $verbose_http = 0; # diagnostics about all HTTP activity
211 my $verbose_exec = 0; # diagnostics about executing programs
213 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
215 my $http_proxy = undef;
216 my $http_timeout = 30;
217 my $cvt_timeout = 10;
223 my $min_gif_area = (120 * 120);
228 my $imagemap_base = undef;
230 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
232 my $driftnet_magic = 'driftnet';
233 my $driftnet_dir = undef;
234 my $default_driftnet_cmd = "driftnet -a -m 100";
239 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
240 "arrhenius", "arteriole", "blanket", "brainchild",
241 "burdensome", "carnival", "cherub", "chord", "clever",
242 "dedicate", "dilogarithm", "dolan", "dryden",
246 ##############################################################################
250 ##############################################################################
252 # returns three values: the HTTP response line; the document headers;
253 # and the document body.
256 my ( $url, $referer, $timeout ) = @_;
258 if (!defined($timeout)) { $timeout = $http_timeout; }
259 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
262 LOG (($verbose_net || $verbose_load), "timed out for $url");
266 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
268 if (! ($url =~ m@^http://@i)) {
269 LOG ($verbose_net, "not an HTTP URL: $url");
273 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
274 $path = "" unless $path;
276 if (!$url_proto || !$serverstring) {
277 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
281 my ($them,$port) = split(/:/, $serverstring);
282 $port = 80 unless $port;
287 $serverstring = $http_proxy if $http_proxy;
288 $serverstring =~ s@^[a-z]+://@@;
289 ($them2,$port2) = split(/:/, $serverstring);
290 $port2 = 80 unless $port2;
293 my ($remote, $iaddr, $paddr, $proto, $line);
295 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
297 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
300 $iaddr = inet_aton($remote);
302 LOG (($verbose_net || $verbose_load), "host not found: $remote");
305 $paddr = sockaddr_in($port2, $iaddr);
313 local $SIG{ALRM} = sub {
314 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
319 $proto = getprotobyname('tcp');
320 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
321 LOG (($verbose_net || $verbose_load), "socket: $!");
324 if (!connect(S, $paddr)) {
325 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
329 select(S); $| = 1; select(STDOUT);
331 my $cookie = $cookies{$them};
333 my $user_agent = "$progname/$version";
335 if ($url =~ m@^http://www\.altavista\.com/@ ||
336 $url =~ m@^http://random\.yahoo\.com/@ ||
337 $url =~ m@^http://images\.google\.com/@) {
338 # block this, you turkeys.
339 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
342 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
344 "User-Agent: $user_agent\r\n";
346 $hdrs .= "Referer: $referer\r\n";
349 my @cc = split(/\r?\n/, $cookie);
350 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
354 foreach (split('\r?\n', $hdrs)) {
355 LOG ($verbose_http, " ==> $_");
358 my $http = <S> || "";
360 # Kludge: the Yahoo Random Link is now returning as its first
361 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
363 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
367 LOG ($verbose_http, " <== $_");
373 LOG ($verbose_http, " <== $_");
375 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
376 set_cookie($them, $1)
387 " <== [ body ]: $lines lines, " . length($body) . " bytes");
392 LOG (($verbose_net || $verbose_load), "null response: $url");
396 return ( $http, $head, $body );
398 die if ($@ && $@ ne "alarm\n"); # propagate errors
413 # returns two values: the document headers; and the document body.
414 # if the given URL did a redirect, returns the redirected-to document.
417 my ( $url, $referer, $timeout ) = @_;
420 if (defined($referer) && $referer eq $driftnet_magic) {
421 return get_driftnet_file ($url);
426 my $max_loop_count = 4;
429 if (defined($timeout) && $timeout <= 0) {
430 LOG (($verbose_net || $verbose_load), "timed out for $url");
435 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
437 if (defined ($timeout)) {
439 my $elapsed = $now - $start;
440 $timeout -= $elapsed;
444 return () unless $http; # error message already printed
446 $http =~ s/[\r\n]+$//s;
448 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
451 my ( $location ) = m@^location:[ \t]*(.*)$@im;
453 $location =~ s/[\r\n]$//;
455 LOG ($verbose_net, "redirect from $url to $location");
460 $referer =~ m@^(http://[^/]+)@i;
462 } elsif (! ($url =~ m@^[a-z]+:@i)) {
464 s@[^/]+$@@g if m@^http://[^/]+/@i;
465 $_ .= "/" if m@^http://[^/]+$@i;
470 LOG ($verbose_net, "no Location with \"$http\"");
471 return ( $url, $body );
474 if ($loop_count++ > $max_loop_count) {
476 "too many redirects ($max_loop_count) from $orig_url");
481 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
483 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
485 # http errors -- return nothing.
491 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
497 return ( $url, $body );
503 # If we already have a cookie defined for this site, and the site is trying
504 # to overwrite that very same cookie, let it do so. This is because nytimes
505 # expires its cookies - it lets you upgrade to a new cookie without logging
506 # in again, but you have to present the old cookie to get the new cookie.
507 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
510 my ($host, $cookie) = @_;
511 my $oc = $cookies{$host};
514 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
516 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
518 if ($oc_name eq $nc_name &&
519 $oc_value ne $nc_value) {
520 $cookies{$host} = $cookie;
521 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
526 ############################################################################
528 # Extracting image URLs from HTML
530 ############################################################################
532 # given a URL and the body text at that URL, selects and returns a random
533 # image from it. returns () if no suitable images found.
535 sub pick_image_from_body {
536 my ( $url, $body ) = @_;
541 # if there's at least one slash after the host, take off the last
543 if ( m@^http://[^/]+/@io ) {
544 $base =~ s@[^/]+$@@go;
547 # if there are no slashes after the host at all, put one on the end.
548 if ( m@^http://[^/]+$@io ) {
554 # strip out newlines, compress whitespace
561 # There are certain web sites that list huge numbers of dictionary
562 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
563 # Porn sites tend not to be reputable!)
565 # I do not want webcollage to filter on content: I want it to select
566 # randomly from the set of images on the web. All the logic here for
567 # rejecting some images is really a set of heuristics for rejecting
568 # images that are not really images: for rejecting *text* that is in
569 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
570 # the content of the pictures to be randomly selected from among all
571 # the available content.
573 # So, filtering out "dirty" pictures by looking for "dirty" keywords
574 # would be wrong: dirty pictures exist, like it or not, so webcollage
575 # should be able to select them.
577 # However, picking a random URL is a hard thing to do. The mechanism I'm
578 # using is to search for a selection of random words. This is not
579 # perfect, but works ok most of the time. The way it breaks down is when
580 # some URLs get precedence because their pages list *every word* as
581 # related -- those URLs come up more often than others.
583 # So, after we've retrieved a URL, if it has too many keywords, reject
584 # it. We reject it not on the basis of what those keywords are, but on
585 # the basis that by having so many, the page has gotten an unfair
586 # advantage against our randomizer.
589 foreach my $trip (@tripwire_words) {
590 $trip_count++ if m/$trip/i;
593 if ($trip_count >= $#tripwire_words - 2) {
594 LOG (($verbose_filter || $verbose_load),
595 "there is probably a dictionary in \"$url\": rejecting.");
596 $rejected_urls{$url} = -1;
606 foreach (split(/ *</)) {
609 # Likewise, reject any web pages that have a KEYWORDS meta tag
612 if (m/name ?= ?\"?keywords\"?/i &&
613 m/content ?= ?\"([^\"]+)\"/) {
616 LOG (($verbose_filter || $verbose_load),
617 "excessive keywords ($L bytes) in $url: rejecting.");
618 $rejected_urls{$url} = $L;
623 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
627 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
629 my $was_inline = (! ( "$1" eq "a" || "$1" eq "A" ));
631 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
632 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
637 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
639 } elsif ( ! m@^[^/:?]+:@ ) {
642 1 while (s@/[^/]+/\.\./@/@g);
646 if ( ! m@^http://@io ) {
651 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
655 # skip really short or really narrow images
656 if ( $width && $width < $min_width) {
657 if (!$height) { $height = "?"; }
658 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
662 if ( $height && $height < $min_height) {
663 if (!$width) { $width = "?"; }
664 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
668 # skip images with ratios that make them look like banners.
669 if ($min_ratio && $width && $height &&
670 ($width * $min_ratio ) > $height) {
671 if (!$height) { $height = "?"; }
672 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
676 # skip GIFs with a small number of pixels -- those usually suck.
677 if ($width && $height &&
679 ($width * $height) < $min_gif_area) {
680 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
687 if ($unique_urls{$url}) {
688 LOG ($verbose_filter, " skip duplicate image $_");
692 LOG ($verbose_filter,
694 ($width && $height ? " (${width}x${height})" : "") .
695 ($was_inline ? " (inline)" : ""));
697 $urls[++$#urls] = $url;
698 $unique_urls{$url}++;
700 # JPEGs are preferable to GIFs and PNGs.
702 if ( ! m@[.](gif|png)$@io ) {
703 $urls[++$#urls] = $url;
706 # pointers to images are preferable to inlined images.
707 if ( ! $was_inline ) {
708 $urls[++$#urls] = $url;
709 $urls[++$#urls] = $url;
714 my $fsp = ($body =~ m@<frameset@i);
719 @urls = depoison (@urls);
722 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
726 # pick a random element of the table
727 my $i = int(rand($#urls+1));
730 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
737 ############################################################################
739 # Subroutines for getting pages and images out of search engines
741 ############################################################################
744 sub pick_dictionary {
745 my @dicts = ("/usr/dict/words",
746 "/usr/share/dict/words",
747 "/usr/share/lib/dict/words");
748 foreach my $f (@dicts) {
754 error ("$dicts[0] does not exist") unless defined($wordlist);
757 # returns a random word from the dictionary
761 if (open (IN, "<$wordlist")) {
762 my $size = (stat(IN))[7];
763 my $pos = rand $size;
764 if (seek (IN, $pos, 0)) {
765 $word = <IN>; # toss partial line
766 $word = <IN>; # keep next line
775 return 0 if (!$word);
777 $word =~ s/^[ \t\n\r]+//;
778 $word =~ s/[ \t\n\r]+$//;
783 $word =~ s/ally$/al/;
784 $word =~ s/izes$/ize/;
785 $word =~ tr/A-Z/a-z/;
787 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
788 $word = "\%22$word\%22"; # And put quotes (%22) around it.
796 my $sep = ($or_p ? "%20OR%20" : "%20");
797 return (random_word . $sep .
807 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
814 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
823 $s =~ s/\"/"/gi;
829 $s =~ s/</</gi; # far from exhaustive...
831 $s =~ s/"/\"/gi;
837 # Loads the given URL (a search on some search engine) and returns:
838 # - the total number of hits the search engine claimed it had;
839 # - a list of URLs from the page that the search engine returned;
840 # Note that this list contains all kinds of internal search engine
841 # junk URLs too -- caller must prune them.
843 sub pick_from_search_engine {
844 my ( $timeout, $search_url, $words ) = @_;
849 print STDERR "\n\n" if ($verbose_load);
851 LOG ($verbose_load, "words: $_");
852 LOG ($verbose_load, "URL: $search_url");
854 $last_search = $search_url; # for warnings
857 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
858 if (defined ($timeout)) {
859 $timeout -= (time - $start);
862 LOG (($verbose_net || $verbose_load),
863 "timed out (late) for $search_url");
869 return () if (! $body);
874 my $search_count = "?";
875 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
877 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
879 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
881 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
883 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
885 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
887 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
889 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
891 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
892 $search_count = $1; # lycos
893 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
894 $search_count = $1; # hotbot
895 } elsif ($body =~ m@no photos were found containing@i) { # avimages
897 } elsif ($body =~ m@found no document matching@i) { # avtext
900 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
902 # if ($search_count eq "?" || $search_count eq "0") {
904 # my $file = "/tmp/wc.html";
905 # open(OUT, ">$file") || error ("writing $file: $!");
908 # print STDERR blurb() . "###### wrote $file\n";
912 my $length = length($body);
921 foreach (split(/\n/)) {
923 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
926 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
927 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
929 if ( $rejected_urls{$u} ) {
930 LOG ($verbose_filter, " pre-rejecting candidate: $u");
934 LOG ($verbose_http, " HREF: $u");
936 $subpages[++$#subpages] = $u;
939 if ( $#subpages < 0 ) {
940 LOG ($verbose_filter,
941 "found nothing on $base ($length bytes, $href_count links).");
945 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
947 return ($search_count, @subpages);
955 my ($h) = m@^http://([^/: \t\r\n]+)@i;
957 next unless defined($h);
959 if ($poisoners{$h}) {
960 LOG (($verbose_filter), " rejecting poisoner: $_");
963 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
965 LOG (($verbose_filter), " rejecting poisoner: $_");
968 if ($h =~ m@([^.]+\.[^.]+)$@ &&
970 LOG (($verbose_filter), " rejecting poisoner: $_");
980 # given a list of URLs, picks one at random; loads it; and returns a
981 # random image from it.
982 # returns the url of the page loaded; the url of the image chosen;
983 # and a debugging description string.
985 sub pick_image_from_pages {
986 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
988 $total_hit_count = "?" unless defined($total_hit_count);
990 @pages = depoison (@pages);
992 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
993 " ($total_hit_count total)");
995 return () if ($#pages < 0);
997 my $i = int(rand($#pages+1));
998 my $page = $pages[$i];
1000 LOG ($verbose_load, "picked page $page");
1002 $suppress_audit = 1;
1004 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1006 if (!$base2 || !$body2) {
1011 my $img = pick_image_from_body ($base2, $body2);
1015 return ($base2, $img);
1022 ############################################################################
1024 # Pick images from random pages returned by the Yahoo Random Link
1026 ############################################################################
1029 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1032 # Picks a random page; picks a random image on that page;
1033 # returns two URLs: the page containing the image, and the image.
1034 # Returns () if nothing found this time.
1036 sub pick_from_yahoo_random_link {
1037 my ( $timeout ) = @_;
1039 print STDERR "\n\n" if ($verbose_load);
1040 LOG ($verbose_load, "URL: $yahoo_random_link");
1042 $last_search = $yahoo_random_link; # for warnings
1044 $suppress_audit = 1;
1046 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1047 if (!$base || !$body) {
1052 LOG ($verbose_load, "redirected to: $base");
1054 my $img = pick_image_from_body ($base, $body);
1058 return ($base, $img);
1065 ############################################################################
1067 # Pick images from random pages returned by the Alta Vista Random Link
1069 ############################################################################
1072 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1075 # Picks a random page; picks a random image on that page;
1076 # returns two URLs: the page containing the image, and the image.
1077 # Returns () if nothing found this time.
1079 sub pick_from_alta_vista_random_link {
1080 my ( $timeout ) = @_;
1082 print STDERR "\n\n" if ($verbose_load);
1083 LOG ($verbose_load, "URL: $alta_vista_random_link");
1085 $last_search = $alta_vista_random_link; # for warnings
1087 $suppress_audit = 1;
1089 my ( $base, $body ) = get_document ($alta_vista_random_link,
1091 if (!$base || !$body) {
1096 LOG ($verbose_load, "redirected to: $base");
1098 my $img = pick_image_from_body ($base, $body);
1102 return ($base, $img);
1109 ############################################################################
1111 # Pick images by feeding random words into Alta Vista Image Search
1113 ############################################################################
1116 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1117 "?ipht=1" . # photos
1118 "&igrph=1" . # graphics
1121 "&micat=1" . # no partner sites
1122 "&sc=on" . # "site collapse"
1126 sub pick_from_alta_vista_images {
1127 my ( $timeout ) = @_;
1129 my $words = random_word();
1130 my $page = (int(rand(9)) + 1);
1131 my $search_url = $alta_vista_images_url . $words;
1134 $search_url .= "&pgno=" . $page; # page number
1135 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1138 my ($search_hit_count, @subpages) =
1139 pick_from_search_engine ($timeout, $search_url, $words);
1141 my @candidates = ();
1142 foreach my $u (@subpages) {
1144 # avimages is encoding their URLs now.
1145 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1146 $u = url_unquote($u);
1148 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1149 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1150 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1151 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1152 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1154 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1155 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1157 LOG ($verbose_filter, " candidate: $u");
1158 push @candidates, $u;
1161 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1162 $timeout, @candidates);
1167 ############################################################################
1169 # Pick images by feeding random words into Google Image Search.
1170 # By Charles Gales <gales@us.ibm.com>
1172 ############################################################################
1175 my $google_images_url = "http://images.google.com/images" .
1176 "?site=images" . # photos
1177 "&btnG=Search" . # graphics
1178 "&safe=off" . # no screening
1183 sub pick_from_google_images {
1184 my ( $timeout ) = @_;
1186 my $words = random_word; # only one word for Google
1187 my $page = (int(rand(9)) + 1);
1188 my $num = 20; # 20 images per page
1189 my $search_url = $google_images_url . $words;
1192 $search_url .= "&start=" . $page*$num; # page number
1193 $search_url .= "&num=" . $num; #images per page
1196 my ($search_hit_count, @subpages) =
1197 pick_from_search_engine ($timeout, $search_url, $words);
1199 my @candidates = ();
1200 foreach my $u (@subpages) {
1201 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1202 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1204 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1206 LOG ($verbose_filter, " candidate: $urlf");
1207 push @candidates, $urlf;
1211 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1212 $timeout, @candidates);
1217 ############################################################################
1219 # Pick images by feeding random *numbers* into Google Image Search.
1220 # By jwz, suggested by Ian O'Donnell.
1222 ############################################################################
1226 sub pick_from_google_image_numbers {
1227 my ( $timeout ) = @_;
1230 my $number = int(rand($max));
1232 $number = sprintf("%04d", $number)
1235 my $words = "$number";
1236 my $page = (int(rand(40)) + 1);
1237 my $num = 20; # 20 images per page
1238 my $search_url = $google_images_url . $words;
1241 $search_url .= "&start=" . $page*$num; # page number
1242 $search_url .= "&num=" . $num; #images per page
1245 my ($search_hit_count, @subpages) =
1246 pick_from_search_engine ($timeout, $search_url, $words);
1248 my @candidates = ();
1250 foreach my $u (@subpages) {
1251 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1252 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1254 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1257 $img = "http://$img" unless ($img =~ m/^http:/i);
1259 LOG ($verbose_filter, " candidate: $ref");
1260 push @candidates, $img;
1261 $referers{$img} = $ref;
1265 @candidates = depoison (@candidates);
1266 return () if ($#candidates < 0);
1267 my $i = int(rand($#candidates+1));
1268 my $img = $candidates[$i];
1269 my $ref = $referers{$img};
1271 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1272 return ($ref, $img);
1277 ############################################################################
1279 # Pick images by feeding random words into Alta Vista Text Search
1281 ############################################################################
1284 my $alta_vista_url = "http://www.altavista.com/web/results" .
1288 "&sc=on" . # "site collapse"
1293 sub pick_from_alta_vista_text {
1294 my ( $timeout ) = @_;
1296 my $words = random_words(0);
1297 my $page = (int(rand(9)) + 1);
1298 my $search_url = $alta_vista_url . $words;
1301 $search_url .= "&pgno=" . $page;
1302 $search_url .= "&stq=" . (($page-1) * 10);
1305 my ($search_hit_count, @subpages) =
1306 pick_from_search_engine ($timeout, $search_url, $words);
1308 my @candidates = ();
1309 foreach my $u (@subpages) {
1311 # Those altavista fuckers are playing really nasty redirection games
1312 # these days: the filter your clicks through their site, but use
1313 # onMouseOver to make it look like they're not! Well, it makes it
1314 # easier for us to identify search results...
1316 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1317 $u = url_unquote($u);
1319 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1320 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1321 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1323 LOG ($verbose_filter, " candidate: $u");
1324 push @candidates, $u;
1327 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1328 $timeout, @candidates);
1333 ############################################################################
1335 # Pick images by feeding random words into Hotbot
1337 ############################################################################
1339 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1341 "&descriptiontype=0" .
1348 "&cobrand=undefined" .
1351 sub pick_from_hotbot_text {
1352 my ( $timeout ) = @_;
1354 $last_search = $hotbot_search_url; # for warnings
1356 # lycos seems to always give us back dictionaries and word lists if
1357 # we search for more than one word...
1359 my $words = random_word();
1361 my $start = int(rand(8)) * 10 + 1;
1362 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1364 my ($search_hit_count, @subpages) =
1365 pick_from_search_engine ($timeout, $search_url, $words);
1367 my @candidates = ();
1368 foreach my $u (@subpages) {
1370 # Hotbot plays redirection games too
1372 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1373 # $u = url_decode($1);
1375 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1376 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1377 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1378 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1380 LOG ($verbose_filter, " candidate: $u");
1381 push @candidates, $u;
1384 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1385 $timeout, @candidates);
1390 ############################################################################
1392 # Pick images by feeding random words into Lycos
1394 ############################################################################
1396 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1402 sub pick_from_lycos_text {
1403 my ( $timeout ) = @_;
1405 $last_search = $lycos_search_url; # for warnings
1407 # lycos seems to always give us back dictionaries and word lists if
1408 # we search for more than one word...
1410 my $words = random_word();
1412 my $start = int(rand(8)) * 10 + 1;
1413 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1415 my ($search_hit_count, @subpages) =
1416 pick_from_search_engine ($timeout, $search_url, $words);
1418 my @candidates = ();
1419 foreach my $u (@subpages) {
1421 # Lycos plays redirection games.
1423 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1428 # $u = url_decode($1);
1430 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1431 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1432 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1433 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1434 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1437 LOG ($verbose_filter, " candidate: $u");
1438 push @candidates, $u;
1441 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1442 $timeout, @candidates);
1447 ############################################################################
1449 # Pick images by feeding random words into news.yahoo.com
1451 ############################################################################
1453 my $yahoo_news_url = "http://search.news.yahoo.com/search/news" .
1456 "&s=-%24s%2C-date" .
1464 sub pick_from_yahoo_news_text {
1465 my ( $timeout ) = @_;
1467 $last_search = $yahoo_news_url; # for warnings
1469 my $words = random_words(0);
1470 my $search_url = $yahoo_news_url . $words;
1472 my ($search_hit_count, @subpages) =
1473 pick_from_search_engine ($timeout, $search_url, $words);
1475 my @candidates = ();
1476 foreach my $u (@subpages) {
1477 # only accept URLs on Yahoo's news site
1478 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1479 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1481 LOG ($verbose_filter, " candidate: $u");
1482 push @candidates, $u;
1485 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1486 $timeout, @candidates);
1491 ############################################################################
1493 # Pick images from LiveJournal's list of recently-posted images.
1495 ############################################################################
1497 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1500 sub pick_from_livejournal_images {
1501 my ( $timeout ) = @_;
1503 $last_search = $livejournal_img_url; # for warnings
1505 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1506 return () unless $body;
1508 my @candidates = ();
1511 $body =~ s/(<recent-image)\b/\n$1/gsi;
1513 foreach (split (/\n/, $body)) {
1514 next unless (m/^<recent-image\b/);
1515 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1516 my $img = html_unquote ($1);
1517 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1518 my $page = html_unquote ($1);
1519 my @pair = ($img, $page);
1520 LOG ($verbose_filter, " candidate: $img");
1521 push @candidates, \@pair;
1524 return () if ($#candidates == -1);
1526 my $i = int(rand($#candidates+1));
1527 my ($img, $page) = @{$candidates[$i]};
1529 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1532 return ($page, $img);
1536 ############################################################################
1538 # Pick images from ircimages.com (images that have been in the /topic of
1539 # various IRC channels.)
1541 ############################################################################
1543 my $ircimages_url = "http://ircimages.com/";
1546 sub pick_from_ircimages {
1547 my ( $timeout ) = @_;
1549 $last_search = $ircimages_url; # for warnings
1551 my $n = int(rand(2900));
1552 my $search_url = $ircimages_url . "page-$n";
1554 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1555 return () unless $body;
1557 my @candidates = ();
1560 $body =~ s/(<A)\b/\n$1/gsi;
1562 foreach (split (/\n/, $body)) {
1564 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1567 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1568 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1570 next unless ($u =~ m/^http:/i);
1571 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1572 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1574 LOG ($verbose_http, " HREF: $u");
1575 push @candidates, $u;
1578 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1580 return () if ($#candidates == -1);
1582 my $i = int(rand($#candidates+1));
1583 my $img = $candidates[$i];
1585 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1588 $search_url = $img; # hmm...
1589 return ($search_url, $img);
1593 ############################################################################
1595 # Pick images by waiting for driftnet to populate a temp dir with files.
1596 # Requires driftnet version 0.1.5 or later.
1597 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
1598 # for images being downloaded by others.)
1599 # Driftnet/webcollage integration by jwz.
1601 ############################################################################
1604 sub pick_from_driftnet {
1605 my ( $timeout ) = @_;
1607 my $id = $driftnet_magic;
1608 my $dir = $driftnet_dir;
1612 error ("\$driftnet_dir unset?") unless ($dir);
1615 error ("$dir unreadable") unless (-d "$dir/.");
1617 $timeout = $http_timeout unless ($timeout);
1620 while ($now = time, $now < $start + $timeout) {
1622 opendir (DIR, $dir) || error ("$dir: $!");
1623 while (my $file = readdir(DIR)) {
1624 next if ($file =~ m/^\./);
1625 $file = "$dir/$file";
1627 LOG ($verbose_load, "picked file $file ($id)");
1628 return ($id, $file);
1632 LOG (($verbose_net || $verbose_load), "timed out for $id");
1637 sub get_driftnet_file {
1640 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
1642 my $id = $driftnet_magic;
1643 my $re = qr/$driftnet_dir/;
1644 error ("$id: $file not in $driftnet_dir?")
1645 unless ($file =~ m@^$re@o);
1648 open (IN, $file) || error ("$id: $file: $!");
1650 while (<IN>) { $body .= $_; }
1651 close IN || error ("$id: $file: $!");
1652 unlink ($file) || error ("$id: $file: rm: $!");
1653 return ($id, $body);
1657 sub spawn_driftnet {
1660 # make a directory to use.
1662 my $tmp = $ENV{TEMPDIR} || "/tmp";
1663 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
1664 LOG ($verbose_exec, "mkdir $driftnet_dir");
1665 last if mkdir ($driftnet_dir, 0700);
1668 if (! ($cmd =~ m/\s/)) {
1669 # if the command didn't have any arguments in it, then it must be just
1670 # a pointer to the executable. Append the default args to it.
1671 my $dargs = $default_driftnet_cmd;
1672 $dargs =~ s/^[^\s]+//;
1676 # point the driftnet command at our newly-minted private directory.
1678 $cmd .= " -d $driftnet_dir";
1679 $cmd .= ">/dev/null" unless ($verbose_exec);
1682 if ($pid < 0) { error ("fork: $!\n"); }
1685 push @pids_to_kill, $pid;
1686 LOG ($verbose_exec, "forked for \"$cmd\"");
1689 nontrapping_system ($cmd) || error ("exec: $!");
1692 # wait a bit, then make sure the process actually started up.
1695 error ("pid $pid failed to start \"$cmd\"")
1696 unless (1 == kill (0, $pid));
1700 ############################################################################
1702 # Pick a random image in a random way
1704 ############################################################################
1707 # Picks a random image on a random page, and returns two URLs:
1708 # the page containing the image, and the image.
1709 # Returns () if nothing found this time.
1713 my ( $timeout ) = @_;
1715 $current_state = "select";
1716 $load_method = "none";
1718 my $n = int(rand(100));
1721 my @rest = @search_methods;
1724 my $pct = shift @rest;
1725 my $name = shift @rest;
1726 my $tfn = shift @rest;
1728 if ($total > $n && !defined($fn)) {
1730 $current_state = $name;
1731 $load_method = $current_state;
1735 if ($total != 100) {
1736 error ("internal error: \@search_methods totals to $total%!");
1739 record_attempt ($current_state);
1740 return $fn->($timeout);
1745 ############################################################################
1747 # Statistics and logging
1749 ############################################################################
1752 return strftime ("%H:%M:%S: ", localtime);
1756 return "$progname: " . timestr() . "$current_state: ";
1761 print STDERR blurb() . "$err\n";
1773 my $head = "$progname: DEBUG: ";
1774 foreach (split (/\n/, $lastlog)) {
1775 print STDERR "$head$_\n";
1781 my ($print, $msg) = @_;
1782 my $blurb = timestr() . "$current_state: ";
1783 $lastlog .= "$blurb$msg\n";
1784 print STDERR "$progname: $blurb$msg\n" if $print;
1789 my %stats_successes;
1792 my $last_state = undef;
1793 sub record_attempt {
1797 record_failure($last_state) unless ($image_succeeded > 0);
1799 $last_state = $name;
1802 report_performance();
1805 $image_succeeded = 0;
1806 $suppress_audit = 0;
1809 sub record_success {
1810 my ($name, $url, $base) = @_;
1811 if (defined($stats_successes{$name})) {
1812 $stats_successes{$name}++;
1814 $stats_successes{$name} = 1;
1817 stop_timer ($name, 1);
1818 my $o = $current_state;
1819 $current_state = $name;
1820 save_recent_url ($url, $base);
1821 $current_state = $o;
1822 $image_succeeded = 1;
1827 sub record_failure {
1830 return if $image_succeeded;
1832 stop_timer ($name, 0);
1833 if ($verbose_load && !$verbose_exec) {
1835 if ($suppress_audit) {
1836 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1840 my $o = $current_state;
1841 $current_state = "DEBUG";
1843 my $line = "#" x 78;
1844 print STDERR "\n\n\n";
1845 print STDERR ("#" x 78) . "\n";
1846 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1849 print STDERR ("-" x 78) . "\n";
1850 print STDERR "\n\n";
1852 $current_state = $o;
1854 $image_succeeded = 0;
1861 my $i = $stats_successes{$name};
1862 my $j = $stats_attempts{$name};
1865 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1869 my $current_start_time = 0;
1873 $current_start_time = time;
1875 if (defined($stats_attempts{$name})) {
1876 $stats_attempts{$name}++;
1878 $stats_attempts{$name} = 1;
1880 if (!defined($stats_elapsed{$name})) {
1881 $stats_elapsed{$name} = 0;
1886 my ($name, $success) = @_;
1887 $stats_elapsed{$name} += time - $current_start_time;
1891 my $last_report_time = 0;
1892 sub report_performance {
1894 return unless $verbose_warnings;
1897 return unless ($now >= $last_report_time + $report_performance_interval);
1898 my $ot = $last_report_time;
1899 $last_report_time = $now;
1901 return if ($ot == 0);
1903 my $blurb = "$progname: " . timestr();
1906 print STDERR "${blurb}Current standings:\n";
1908 foreach my $name (sort keys (%stats_attempts)) {
1909 my $try = $stats_attempts{$name};
1910 my $suc = $stats_successes{$name} || 0;
1911 my $pct = int($suc * 100 / $try);
1912 my $secs = $stats_elapsed{$name};
1913 my $secs_link = int($secs / $try);
1914 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1915 "$name:", "$pct%", $suc, $try, $secs_link);
1921 my $max_recent_images = 400;
1922 my $max_recent_sites = 20;
1923 my @recent_images = ();
1924 my @recent_sites = ();
1926 sub save_recent_url {
1927 my ($url, $base) = @_;
1929 return unless ($verbose_warnings);
1932 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1933 return unless defined ($site);
1935 if ($base eq $driftnet_magic) {
1936 $site = $driftnet_magic;
1937 @recent_images = ();
1941 foreach (@recent_images) {
1943 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1944 " (on $base via $last_search)\n";
1950 # suppress "duplicate site" warning via %warningless_sites.
1952 if ($warningless_sites{$site}) {
1954 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1955 $warningless_sites{$1}) {
1957 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1958 $warningless_sites{$1}) {
1963 foreach (@recent_sites) {
1965 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1966 " ($url on $base via $last_search)\n";
1972 push @recent_images, $url;
1973 push @recent_sites, $site;
1974 shift @recent_images if ($#recent_images >= $max_recent_images);
1975 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1980 ##############################################################################
1984 ##############################################################################
1991 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1996 # Given the raw body of a GIF document, returns the dimensions of the image.
2000 my $type = substr($body, 0, 6);
2002 return () unless ($type =~ /GIF8[7,9]a/);
2003 $s = substr ($body, 6, 10);
2004 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2005 return (($b<<8|$a), ($d<<8|$c));
2008 # Given the raw body of a JPEG document, returns the dimensions of the image.
2013 my $L = length($body);
2015 my $c1 = substr($body, $i, 1); $i++;
2016 my $c2 = substr($body, $i, 1); $i++;
2017 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2020 while (ord($ch) != 0xDA && $i < $L) {
2021 # Find next marker, beginning with 0xFF.
2022 while (ord($ch) != 0xFF) {
2023 return () if (length($body) <= $i);
2024 $ch = substr($body, $i, 1); $i++;
2026 # markers can be padded with any number of 0xFF.
2027 while (ord($ch) == 0xFF) {
2028 return () if (length($body) <= $i);
2029 $ch = substr($body, $i, 1); $i++;
2032 # $ch contains the value of the marker.
2033 my $marker = ord($ch);
2035 if (($marker >= 0xC0) &&
2036 ($marker <= 0xCF) &&
2037 ($marker != 0xC4) &&
2038 ($marker != 0xCC)) { # it's a SOFn marker
2040 return () if (length($body) <= $i);
2041 my $s = substr($body, $i, 4); $i += 4;
2042 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2043 return (($c<<8|$d), ($a<<8|$b));
2046 # We must skip variables, since FFs in variable names aren't
2047 # valid JPEG markers.
2048 return () if (length($body) <= $i);
2049 my $s = substr($body, $i, 2); $i += 2;
2050 my ($c1, $c2) = unpack ("C"x2, $s);
2051 my $length = ($c1 << 8) | $c2;
2052 return () if ($length < 2);
2059 # Given the raw body of a PNG document, returns the dimensions of the image.
2063 return () unless ($body =~ m/^\211PNG\r/);
2064 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2065 return () unless defined ($bits);
2066 return () unless ($bits =~ /^IHDR/);
2067 my ($ign, $w, $h) = unpack("a4N2", $bits);
2072 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2077 my ($w, $h) = gif_size ($body);
2078 if ($w && $h) { return ($w, $h); }
2079 ($w, $h) = jpeg_size ($body);
2080 if ($w && $h) { return ($w, $h); }
2081 return png_size ($body);
2085 # returns the full path of the named program, or undef.
2089 foreach (split (/:/, $ENV{PATH})) {
2090 if (-x "$_/$prog") {
2098 # Like rand(), but chooses numbers with a bell curve distribution.
2101 $_ = 1.0 unless defined($_);
2103 return (rand($_) + rand($_) + rand($_));
2109 if (@pids_to_kill) {
2110 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2111 kill ('TERM', @pids_to_kill);
2115 sub signal_cleanup {
2117 print STDERR blurb() . (defined($sig)
2118 ? "caught signal $sig."
2127 ##############################################################################
2129 # Generating a list of urls only
2131 ##############################################################################
2133 sub url_only_output {
2135 my ($base, $img) = pick_image;
2139 print "$img $base\n";
2144 ##############################################################################
2146 # Running as an xscreensaver module
2148 ##############################################################################
2150 my $image_ppm = sprintf ("%s/webcollage-%08x",
2151 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2153 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x",
2154 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2156 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x",
2157 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2160 my $filter_cmd = undef;
2161 my $post_filter_cmd = undef;
2162 my $background = undef;
2164 my @imagemap_areas = ();
2165 my $imagemap_html_tmp = undef;
2166 my $imagemap_jpg_tmp = undef;
2169 my $img_width; # size of the image being generated.
2175 unlink $image_ppm, $image_tmp1, $image_tmp2;
2176 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2177 if (defined ($imagemap_html_tmp));
2181 # Like system, but prints status about exit codes, and kills this process
2182 # with whatever signal killed the sub-process, if any.
2184 sub nontrapping_system {
2188 s/\"[^\"]+\"/\"...\"/g;
2190 LOG ($verbose_exec, "executing \"$_\"");
2195 LOG ($verbose_exec, "subproc exited normally.");
2196 } elsif (($rc & 0xff) == 0) {
2198 LOG ($verbose_exec, "subproc exited with status $rc.");
2201 LOG ($verbose_exec, "subproc dumped core.");
2204 LOG ($verbose_exec, "subproc died with signal $rc.");
2205 # die that way ourselves.
2213 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2214 # writes a PPM to the given output file. Returns the width/height of the
2215 # image if successful.
2218 my ($url, $body, $output) = @_;
2219 my ($cmd, $cmd2, $w, $h);
2221 if ((@_ = gif_size ($body))) {
2224 } elsif ((@_ = jpeg_size ($body))) {
2227 } elsif ((@_ = png_size ($body))) {
2231 LOG (($verbose_pbm || $verbose_load),
2232 "not a GIF, JPG, or PNG" .
2233 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2234 ? " (looks like HTML)" : "") .
2236 $suppress_audit = 1;
2240 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2241 # do this, the process doesn't die properly.
2242 if (!$verbose_pbm) {
2244 # We get a "giftopnm: got a 'Application Extension' extension"
2245 # warning any time it's an animgif.
2247 # Note that "giftopnm: EOF / read error on image data" is not
2248 # always a fatal error -- sometimes the image looks fine anyway.
2250 $cmd2 .= " 2>/dev/null";
2253 # There exist corrupted GIF and JPEG files that can make giftopnm and
2254 # djpeg lose their minds and go into a loop. So this gives those programs
2255 # a small timeout -- if they don't complete in time, kill them.
2261 local $SIG{ALRM} = sub {
2263 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2264 kill ('TERM', $pid) if ($pid);
2269 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
2276 LOG ($verbose_exec, "awaiting $pid");
2278 LOG ($verbose_exec, "$pid completed");
2280 my $size = (stat($output))[7];
2281 $size = -1 unless defined($size);
2283 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2287 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2290 print STDERR blurb() . "$cmd failed: $!\n";
2294 die if ($@ && $@ ne "alarm\n"); # propagate errors
2307 sub pick_root_displayer {
2310 foreach my $cmd (@root_displayers) {
2312 my ($name) = m/^([^ ]+)/;
2313 push @names, "\"$name\"";
2314 LOG ($verbose_exec, "looking for $name...");
2315 foreach my $dir (split (/:/, $ENV{PATH})) {
2316 LOG ($verbose_exec, " checking $dir/$name");
2317 return $cmd if (-x "$dir/$name");
2321 $names[$#names] = "or " . $names[$#names];
2322 error "none of: " . join (", ", @names) . " were found on \$PATH.";
2326 my $ppm_to_root_window_cmd = undef;
2329 sub x_or_pbm_output {
2330 my ($window_id) = @_;
2332 # Check for our helper program, to see whether we need to use PPM pipelines.
2334 $_ = "webcollage-helper";
2335 if (defined ($webcollage_helper) || which ($_)) {
2336 $webcollage_helper = $_ unless (defined($webcollage_helper));
2337 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
2338 $webcollage_helper .= " -v";
2340 LOG (($verbose_pbm || $verbose_load), "no $_ program");
2343 # make sure the various programs we execute exist, right up front.
2345 my @progs = ("ppmmake"); # always need this one
2347 if (!defined($webcollage_helper)) {
2348 # Only need these others if we don't have the helper.
2350 "giftopnm", "pngtopnm", "djpeg",
2351 "pnmpaste", "pnmscale", "pnmcut");
2355 which ($_) || error "$_ not found on \$PATH.";
2358 # find a root-window displayer program.
2360 $ppm_to_root_window_cmd = pick_root_displayer();
2362 if (defined ($window_id)) {
2363 error ("-window-id only works if xscreensaver-getimage is installed")
2364 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
2366 error ("unparsable window id: $window_id")
2367 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
2368 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
2369 error ("unable to munge displayer: $ppm_to_root_window_cmd");
2372 if (!$img_width || !$img_height) {
2374 if (!defined ($window_id) &&
2375 defined ($ENV{XSCREENSAVER_WINDOW})) {
2376 $window_id = $ENV{XSCREENSAVER_WINDOW};
2379 if (!defined ($window_id)) {
2381 which ($_) || error "$_ not found on \$PATH.";
2383 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
2384 if (!defined($img_height)) {
2385 error "xdpyinfo failed.";
2387 } else { # we have a window id
2389 which ($_) || error "$_ not found on \$PATH.";
2390 $_ .= " -id $window_id";
2392 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
2394 if (!defined($img_height)) {
2395 error "xwininfo failed.";
2400 my $bgcolor = "#000000";
2401 my $bgimage = undef;
2404 if ($background =~ m/^\#[0-9a-f]+$/i) {
2405 $bgcolor = $background;
2407 } elsif (-r $background) {
2408 $bgimage = $background;
2410 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
2411 error "not a color or readable file: $background";
2414 # default to assuming it's a color
2415 $bgcolor = $background;
2419 # Create the sold-colored base image.
2421 $_ = "ppmmake '$bgcolor' $img_width $img_height";
2422 LOG ($verbose_pbm, "creating base image: $_");
2423 nontrapping_system "$_ > $image_ppm";
2425 # Paste the default background image in the middle of it.
2432 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
2434 while (<IMG>) { $body .= $_; }
2437 if ((@_ = gif_size ($body))) {
2439 $cmd = "giftopnm |";
2441 } elsif ((@_ = jpeg_size ($body))) {
2445 } elsif ((@_ = png_size ($body))) {
2447 $cmd = "pngtopnm |";
2449 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
2455 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
2458 my $x = int (($img_width - $iw) / 2);
2459 my $y = int (($img_height - $ih) / 2);
2461 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
2463 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
2464 open (IMG, "| $cmd") || error "running $cmd: $!";
2468 LOG ($verbose_exec, "subproc exited normally.");
2469 rename ($image_tmp1, $image_ppm) ||
2470 error "renaming $image_tmp1 to $image_ppm: $!";
2476 my ($base, $img) = pick_image();
2477 my $source = $current_state;
2478 $current_state = "loadimage";
2480 my ($headers, $body) = get_document ($img, $base);
2482 paste_image ($base, $img, $body, $source);
2486 $current_state = "idle";
2487 $load_method = "none";
2489 unlink $image_tmp1, $image_tmp2;
2495 my ($base, $img, $body, $source) = @_;
2497 $current_state = "paste";
2499 $suppress_audit = 0;
2501 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
2505 # If we are using the webcollage-helper, then we do not need to convert this
2506 # image to a PPM. But, if we're using a filter command, we still must, since
2507 # that's what the filters expect (webcollage-helper can read PPMs, so that's
2510 if (defined ($webcollage_helper) &&
2511 !defined ($filter_cmd)) {
2513 ($iw, $ih) = image_size ($body);
2515 LOG (($verbose_pbm || $verbose_load),
2516 "not a GIF, JPG, or PNG" .
2517 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
2518 ? " (looks like HTML)" : "") .
2520 $suppress_audit = 1;
2526 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
2527 print OUT $body || error ("writing $image_tmp1: $!");
2528 close OUT || error ("writing $image_tmp1: $!");
2531 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2534 LOG ($verbose_pbm, "unable to make PBM from $img");
2539 record_success ($load_method, $img, $base);
2542 my $ow = $iw; # used only for error messages
2545 # don't just tack this onto the front of the pipeline -- we want it to
2546 # be able to change the size of the input image.
2549 LOG ($verbose_pbm, "running $filter_cmd");
2551 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2553 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2554 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2557 rename ($image_tmp2, $image_tmp1);
2559 # re-get the width/height in case the filter resized it.
2561 open(IMG, "<$image_tmp1") || return 0;
2564 ($iw, $ih) = m/^(\d+) (\d+)$/;
2566 return 0 unless ($iw && $ih);
2569 my $target_w = $img_width; # max rectangle into which the image must fit
2570 my $target_h = $img_height;
2576 # Usually scale the image to fit on the screen -- but sometimes scale it
2577 # to fit on half or a quarter of the screen. (We do this by reducing the
2578 # size of the target rectangle.) Note that the image is not merely scaled
2579 # to fit; we instead cut the image in half repeatedly until it fits in the
2580 # target rectangle -- that gives a wider distribution of sizes.
2582 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
2583 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
2585 if ($iw > $target_w || $ih > $target_h) {
2586 while ($iw > $target_w ||
2592 if ($iw <= 10 || $ih <= 10) {
2593 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2597 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
2599 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2603 my $src = $image_tmp1;
2605 my $crop_x = 0; # the sub-rectangle of the image
2606 my $crop_y = 0; # that we will actually paste.
2610 # The chance that we will randomly crop out a section of an image starts
2611 # out fairly low, but goes up for images that are very large, or images
2612 # that have ratios that make them look like banners (we try to avoid
2613 # banner images entirely, but they slip through when the IMG tags didn't
2614 # have WIDTH and HEIGHT specified.)
2616 my $crop_chance = 0.2;
2617 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2618 $crop_chance += 0.2;
2620 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2621 $crop_chance += 0.2;
2623 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2624 $crop_chance += 0.7;
2627 if ($crop_chance > 0.1) {
2628 LOG ($verbose_pbm, "crop chance: $crop_chance");
2631 if (rand() < $crop_chance) {
2636 if ($crop_w > $min_width) {
2637 # if it's a banner, select the width linearly.
2638 # otherwise, select a bell.
2639 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2642 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2643 $crop_x = int (rand() * ($ow - $crop_w));
2645 if ($crop_h > $min_height) {
2646 # height always selects as a bell.
2647 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2648 $crop_y = int (rand() * ($oh - $crop_h));
2651 if ($crop_x != 0 || $crop_y != 0 ||
2652 $crop_w != $iw || $crop_h != $ih) {
2654 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2658 # Where the image should logically land -- this might be negative.
2660 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2661 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2663 # if we have chosen to paste the image outside of the rectangle of the
2664 # screen, then we need to crop it.
2668 $x + $crop_w > $img_width ||
2669 $y + $crop_h > $img_height) {
2672 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2674 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2675 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2677 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2678 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2681 # If any cropping needs to happen, add pnmcut.
2683 if ($crop_x != 0 || $crop_y != 0 ||
2684 $crop_w != $iw || $crop_h != $ih) {
2687 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2688 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2691 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2693 $cmd .= " | pnmpaste - $x $y $image_ppm";
2695 $cmd =~ s@^ *\| *@@;
2697 if (defined ($webcollage_helper)) {
2698 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
2699 "$scale $opacity " .
2700 "$crop_x $crop_y $x $y " .
2705 # use a PPM pipeline
2707 $_ .= " < $image_tmp1 > $image_tmp2";
2711 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2713 $_ .= " 2> /dev/null";
2716 my $rc = nontrapping_system ($_);
2718 if (defined ($webcollage_helper) && -z $image_ppm) {
2719 LOG (1, "failed command: \"$cmd\"");
2720 print STDERR "\naudit log:\n\n\n";
2721 print STDERR ("#" x 78) . "\n";
2722 print STDERR blurb() . "$image_ppm has zero size\n";
2724 print STDERR "\n\n";
2729 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2730 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2734 if (!defined ($webcollage_helper)) {
2735 rename ($image_tmp2, $image_ppm) || return;
2738 my $target = "$image_ppm";
2740 # don't just tack this onto the end of the pipeline -- we don't want it
2741 # to end up in $image_ppm, because we don't want the results to be
2744 if ($post_filter_cmd) {
2748 $target = $image_tmp1;
2749 if (!defined ($webcollage_helper)) {
2750 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2752 # Blah, my scripts need the JPEG data, but some other folks need
2753 # the PPM data -- what to do? Ignore the problem, that's what!
2754 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
2755 $cmd = "($post_filter_cmd) < $image_ppm > $target";
2758 $rc = nontrapping_system ($cmd);
2760 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2765 if (!$no_output_p) {
2766 my $tsize = (stat($target))[7];
2768 $cmd = "$ppm_to_root_window_cmd $target";
2770 # xv seems to hate being killed. it tends to forget to clean
2771 # up after itself, and leaves windows around and colors allocated.
2772 # I had this same problem with vidwhacker, and I'm not entirely
2773 # sure what I did to fix it. But, let's try this: launch xv
2774 # in the background, so that killing this process doesn't kill it.
2775 # it will die of its own accord soon enough. So this means we
2776 # start pumping bits to the root window in parallel with starting
2777 # the next network retrieval, which is probably a better thing
2782 $rc = nontrapping_system ($cmd);
2785 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2790 LOG ($verbose_pbm, "$target size is $tsize");
2794 $source .= "-" . stats_of($source);
2795 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2796 if ($verbose_imgmap);
2798 if ($imagemap_base) {
2799 update_imagemap ($base, $x, $y, $iw, $ih,
2800 $image_ppm, $img_width, $img_height);
2809 sub update_imagemap {
2810 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
2812 $current_state = "imagemap";
2814 my $max_areas = 200;
2816 $url = html_quote ($url);
2819 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
2820 unshift @imagemap_areas, $area; # put one on the front
2821 if ($#imagemap_areas >= $max_areas) {
2822 pop @imagemap_areas; # take one off the back.
2825 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
2827 my $map_name = $imagemap_base;
2828 $map_name =~ s@^.*/@@;
2829 $map_name = 'collage' if ($map_name eq '');
2831 my $imagemap_html = $imagemap_base . ".html";
2832 my $imagemap_jpg = $imagemap_base . ".jpg";
2834 if (!defined ($imagemap_html_tmp)) {
2835 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
2836 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
2839 # Read the imagemap html file (if any) to get a template.
2841 my $template_html = '';
2844 if (open (IN, "<$imagemap_html")) {
2845 while (<IN>) { $template_html .= $_; }
2847 LOG ($verbose_pbm, "read template $imagemap_html");
2850 if ($template_html =~ m/^\s*$/s) {
2851 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
2852 "<IMG SRC=\"$imagemap_base.jpg\"" .
2853 " USEMAP=\"$map_name\">\n");
2854 LOG ($verbose_pbm, "created dummy template");
2858 # Write the jpg to a tmp file
2862 if (defined ($webcollage_helper)) {
2863 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
2865 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
2867 my $rc = nontrapping_system ($cmd);
2869 error ("imagemap jpeg failed: \"$cmd\"\n");
2873 # Write the html to a tmp file
2876 my $body = $template_html;
2877 my $areas = join ("\n\t", @imagemap_areas);
2878 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
2879 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
2881 "WIDTH=$image_width HEIGHT=$image_height " .
2882 "USEMAP=\"#$map_name\">");
2883 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
2884 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
2886 # if there are magic webcollage spans in the html, update those too.
2889 my @st = stat ($imagemap_jpg_tmp);
2890 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
2891 my $size = int(($st[7] / 1024) + 0.5) . "K";
2892 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
2893 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
2897 open (OUT, ">$imagemap_html_tmp") || error ("$imagemap_html_tmp: $!");
2898 print OUT $body || error ("$imagemap_html_tmp: $!");
2899 close OUT || error ("$imagemap_html_tmp: $!");
2900 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
2903 # Rename the two tmp files to the real files
2905 rename ($imagemap_html_tmp, $imagemap_html) ||
2906 error "renaming $imagemap_html_tmp to $imagemap_html";
2907 LOG ($verbose_pbm, "wrote $imagemap_html");
2908 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
2909 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
2910 LOG ($verbose_pbm, "wrote $imagemap_jpg");
2916 $SIG{HUP} = \&signal_cleanup;
2917 $SIG{INT} = \&signal_cleanup;
2918 $SIG{QUIT} = \&signal_cleanup;
2919 $SIG{ABRT} = \&signal_cleanup;
2920 $SIG{KILL} = \&signal_cleanup;
2921 $SIG{TERM} = \&signal_cleanup;
2923 # Need this so that if giftopnm dies, we don't die.
2924 $SIG{PIPE} = 'IGNORE';
2927 END { exit_cleanup(); }
2936 my $driftnet_cmd = 0;
2938 $current_state = "init";
2939 $load_method = "none";
2942 my $window_id = undef;
2944 # historical suckage: the environment variable name is lower case.
2945 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2947 while ($_ = $ARGV[0]) {
2949 if ($_ eq "-display" ||
2955 $ENV{DISPLAY} = shift @ARGV;
2956 } elsif ($_ eq "-root") {
2958 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
2959 $window_id = shift @ARGV;
2961 } elsif ($_ eq "-no-output") {
2963 } elsif ($_ eq "-urls-only") {
2966 } elsif ($_ eq "-imagemap") {
2967 $imagemap_base = shift @ARGV;
2969 } elsif ($_ eq "-verbose") {
2971 } elsif (m/^-v+$/) {
2972 $verbose += length($_)-1;
2973 } elsif ($_ eq "-delay") {
2974 $delay = shift @ARGV;
2975 } elsif ($_ eq "-timeout") {
2976 $http_timeout = shift @ARGV;
2977 } elsif ($_ eq "-filter") {
2978 $filter_cmd = shift @ARGV;
2979 } elsif ($_ eq "-filter2") {
2980 $post_filter_cmd = shift @ARGV;
2981 } elsif ($_ eq "-background" || $_ eq "-bg") {
2982 $background = shift @ARGV;
2983 } elsif ($_ eq "-size") {
2985 if (m@^(\d+)x(\d+)$@) {
2989 error "argument to \"-size\" must be of the form \"640x400\"";
2991 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2992 $http_proxy = shift @ARGV;
2993 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2994 $dict = shift @ARGV;
2995 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
2996 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
2997 if (! ($ARGV[0] =~ m/^-/)) {
2998 $driftnet_cmd = shift @ARGV;
3000 $driftnet_cmd = $default_driftnet_cmd;
3002 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3003 my $which = shift @ARGV;
3004 my @rest = @search_methods;
3007 my $pct = shift @rest;
3008 my $name = shift @rest;
3009 my $tfn = shift @rest;
3011 if ($name eq $which) {
3012 @search_methods = (100, $name, $tfn);
3017 error "no such search method as \"$which\"" unless ($ok);
3018 LOG (1, "DEBUG: using only \"$which\"");
3021 print STDERR "$copyright\nusage: $progname " .
3022 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3023 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3024 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3025 "\t\t [-filter cmd] [-filter2 cmd] [-background color]\n" .
3026 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3027 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3033 if ($http_proxy && $http_proxy eq "") {
3034 $http_proxy = undef;
3036 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3037 # historical suckage: allow "http://host:port" as well as "host:port".
3041 if (!$root_p && !$no_output_p) {
3042 print STDERR $copyright;
3043 error "the -root argument is mandatory (for now.)";
3046 if (!$no_output_p && !$ENV{DISPLAY}) {
3047 error "\$DISPLAY is not set.";
3051 if ($verbose == 1) {
3052 $verbose_imgmap = 1;
3053 $verbose_warnings = 1;
3055 } elsif ($verbose == 2) {
3056 $verbose_imgmap = 1;
3057 $verbose_warnings = 1;
3060 } elsif ($verbose == 3) {
3061 $verbose_imgmap = 1;
3062 $verbose_warnings = 1;
3064 $verbose_filter = 1;
3066 } elsif ($verbose == 4) {
3067 $verbose_imgmap = 1;
3068 $verbose_warnings = 1;
3070 $verbose_filter = 1;
3073 } elsif ($verbose == 5) {
3074 $verbose_imgmap = 1;
3075 $verbose_warnings = 1;
3077 $verbose_filter = 1;
3081 } elsif ($verbose == 6) {
3082 $verbose_imgmap = 1;
3083 $verbose_warnings = 1;
3085 $verbose_filter = 1;
3090 } elsif ($verbose >= 7) {
3091 $verbose_imgmap = 1;
3092 $verbose_warnings = 1;
3094 $verbose_filter = 1;
3102 error ("$dict does not exist") unless (-f $dict);
3110 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3115 x_or_pbm_output ($window_id);