3 # webcollage, Copyright (c) 1999-2011 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.156 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
64 my $copyright = "WebCollage $version, Copyright (c) 1999-2011" .
65 " Jamie Zawinski <jwz\@jwz.org>\n" .
66 " http://www.jwz.org/webcollage/\n";
70 my @search_methods = ( 24, "googlephotos", \&pick_from_google_image_photos,
71 13, "googleimgs", \&pick_from_google_images,
72 13, "googlenums", \&pick_from_google_image_numbers,
73 16, "flickr_recent", \&pick_from_flickr_recent,
74 13, "flickr_random", \&pick_from_flickr_random,
75 10, "twitpic", \&pick_from_twitpic_images,
76 8, "livejournal", \&pick_from_livejournal_images,
77 3, "yahoorand", \&pick_from_yahoo_random_link,
79 # This one doesn't work very well: too many non-img links.
80 0, "twitter", \&pick_from_twitter_images,
82 # This is a cute way to search for a certain webcams.
83 # Not included in default methods, since these images
84 # aren't terribly interesting by themselves.
85 # See also "SurveillanceSaver".
87 0, "securitycam", \&pick_from_security_camera,
89 # Nonfunctional as of June 2011.
90 # 0, "altavista", \&pick_from_alta_vista_random_link,
92 # In Apr 2002, Google asked me to stop searching them.
93 # I asked them to add a "random link" url. They said
94 # "that would be easy, we'll think about it" and then
95 # never wrote back. Booo Google! Booooo! So, screw
96 # those turkeys, I've turned Google searching back on.
97 # I'm sure they can take it. (Jan 2005.)
99 # Jan 2005: Yahoo fucked up their search form so that
100 # it's no longer possible to do "or" searches on news
101 # images, so we rarely get any hits there any more.
103 # 0, "yahoonews", \&pick_from_yahoo_news_text,
105 # Dec 2004: the ircimages guy's server can't take the
106 # heat, so he started banning the webcollage user agent.
107 # I tried to convince him to add a lighter-weight page to
108 # support webcollage better, but he doesn't care.
110 # 0, "ircimages", \&pick_from_ircimages,
112 # Dec 2002: Alta Vista has a new "random link" URL now.
113 # They added it specifically to better support webcollage!
114 # That was super cool of them. This is how we used to do
117 # 0, "avimages", \&pick_from_alta_vista_images,
118 # 0, "avtext", \&pick_from_alta_vista_text,
120 # This broke in 2004. Eh, Lycos sucks anyway.
122 # 0, "lycos", \&pick_from_lycos_text,
124 # This broke in 2003, I think. I suspect Hotbot is
125 # actually the same search engine data as Lycos.
127 # 0, "hotbot", \&pick_from_hotbot_text,
130 # programs we can use to write to the root window (tried in ascending order.)
132 my @root_displayers = (
133 "xscreensaver-getimage -root -file",
134 "chbg -once -xscreensaver -max_size 100",
135 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
136 " -rfg black -rbg black",
137 "xli -quiet -onroot -center -border black",
138 "xloadimage -quiet -onroot -center -border black",
140 # this lame program wasn't built with vroot.h:
141 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
145 # Some sites need cookies to work properly. These are they.
148 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
149 "web.altavista.com" => "AV_ALL=1",
151 # log in as "cipherpunk"
152 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
153 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
154 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
156 "ircimages.com" => 'disclaimer=1',
160 # If this is set, it's a helper program to use for pasting images together:
161 # this is a lot faster and more efficient than using PPM pipelines, which is
162 # what we do if this program doesn't exist. (We check for "webcollage-helper"
163 # on $PATH at startup, and set this variable appropriately.)
165 my $webcollage_helper = undef;
168 # If we have the webcollage-helper program, then it will paste the images
169 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
174 # Some sites have managed to poison the search engines. These are they.
175 # (We auto-detect sites that have poisoned the search engines via excessive
176 # keywords or dictionary words, but these are ones that slip through
179 # This can contain full host names, or 2 or 3 component domains.
182 "die.net" => 1, # 'l33t h4ck3r d00dz.
183 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
184 "rootsweb.com" => 1, # Cluttering avtext with human names.
185 "akamai.net" => 1, # Lots of sites have their images on Akamai.
186 "akamaitech.net" => 1, # But those are pretty much all banners.
187 # Since Akamai is super-expensive, let's
188 # go out on a limb and assume that all of
189 # their customers are rich-and-boring.
190 "bartleby.com" => 1, # Dictionary, cluttering avtext.
191 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
192 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
193 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
194 # (I don't see how they did it, though!)
195 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
196 "nextag.com" => 1, # Poisoned Alta Vista real good.
197 "ghettodriveby.com" => 1, # Poisoned Google Images.
198 "crosswordsolver.org" => 1, # Poisoned Google Images.
199 "xona.com" => 1, # Poisoned Google Images.
200 "freepatentsonline.com" => 1, # Poisoned Google Images.
201 "herbdatanz.com" => 1, # Poisoned Google Images.
205 # When verbosity is turned on, we warn about sites that we seem to be hitting
206 # a lot: usually this means some new poisoner has made it into the search
207 # engines. But sometimes, the warning is just because that site has a lot
208 # of stuff on it. So these are the sites that are immune to the "frequent
209 # site" diagnostic message.
211 my %warningless_sites = (
212 "home.earthlink.net" => 1,
213 "www.angelfire.com" => 1,
214 "members.aol.com" => 1,
215 "img.photobucket.com" => 1,
216 "pics.livejournal.com" => 1,
222 "wikimedia.org" => 1,
224 "amazonaws.com" => 1,
226 "photoshelter.com" => 1,
227 "myspacecdn.com" => 1,
228 "feedburner.com" => 1,
234 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
235 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
236 # hits this every time.
238 "images.quizfarm.com" => 1, # damn those LJ quizzes...
239 "images.quizilla.com" => 1,
240 "images.quizdiva.net" => 1,
242 "driftnet" => 1, # builtin...
243 "local-directory" => 1, # builtin...
247 # For decoding HTML-encoded character entities to URLs.
251 "quot" => '"', "amp" => '&', "lt" => '<', "gt" => '>',
252 "nbsp" => ' ', "iexcl" => '¡', "cent" => '¢', "pound" => '£',
253 "curren" => '¤', "yen" => '¥', "brvbar" => '¦', "sect" => '§',
254 "uml" => '¨', "copy" => '©', "ordf" => 'ª', "laquo" => '«',
255 "not" => '¬', "shy" => '', "reg" => '®', "macr" => '¯',
256 "deg" => '°', "plusmn" => '±', "sup2" => '²', "sup3" => '³',
257 "acute" => '´', "micro" => 'µ', "para" => '¶', "middot" => '·',
258 "cedil" => '¸', "sup1" => '¹', "ordm" => 'º', "raquo" => '»',
259 "frac14" => '¼', "frac12" => '½', "frac34" => '¾', "iquest" => '¿',
260 "Agrave" => 'À', "Aacute" => 'Á', "Acirc" => 'Â', "Atilde" => 'Ã',
261 "Auml" => 'Ä', "Aring" => 'Å', "AElig" => 'Æ', "Ccedil" => 'Ç',
262 "Egrave" => 'È', "Eacute" => 'É', "Ecirc" => 'Ê', "Euml" => 'Ë',
263 "Igrave" => 'Ì', "Iacute" => 'Í', "Icirc" => 'Î', "Iuml" => 'Ï',
264 "ETH" => 'Ð', "Ntilde" => 'Ñ', "Ograve" => 'Ò', "Oacute" => 'Ó',
265 "Ocirc" => 'Ô', "Otilde" => 'Õ', "Ouml" => 'Ö', "times" => '×',
266 "Oslash" => 'Ø', "Ugrave" => 'Ù', "Uacute" => 'Ú', "Ucirc" => 'Û',
267 "Uuml" => 'Ü', "Yacute" => 'Ý', "THORN" => 'Þ', "szlig" => 'ß',
268 "agrave" => 'à', "aacute" => 'á', "acirc" => 'â', "atilde" => 'ã',
269 "auml" => 'ä', "aring" => 'å', "aelig" => 'æ', "ccedil" => 'ç',
270 "egrave" => 'è', "eacute" => 'é', "ecirc" => 'ê', "euml" => 'ë',
271 "igrave" => 'ì', "iacute" => 'í', "icirc" => 'î', "iuml" => 'ï',
272 "eth" => 'ð', "ntilde" => 'ñ', "ograve" => 'ò', "oacute" => 'ó',
273 "ocirc" => 'ô', "otilde" => 'õ', "ouml" => 'ö', "divide" => '÷',
274 "oslash" => 'ø', "ugrave" => 'ù', "uacute" => 'ú', "ucirc" => 'û',
275 "uuml" => 'ü', "yacute" => 'ý', "thorn" => 'þ', "yuml" => 'ÿ',
277 # HTML 4 entities that do not have 1:1 Latin1 mappings.
278 "bull" => "*", "hellip"=> "...", "prime" => "'", "Prime" => "\"",
279 "frasl" => "/", "trade" => "[tm]", "larr" => "<-", "rarr" => "->",
280 "harr" => "<->", "lArr" => "<=", "rArr" => "=>", "hArr" => "<=>",
281 "empty" => "Ø", "minus" => "-", "lowast"=> "*", "sim" => "~",
282 "cong" => "=~", "asymp" => "~", "ne" => "!=", "equiv" => "==",
283 "le" => "<=", "ge" => ">=", "lang" => "<", "rang" => ">",
284 "loz" => "<>", "OElig" => "OE", "oelig" => "oe", "Yuml" => "Y",
285 "circ" => "^", "tilde" => "~", "ensp" => " ", "emsp" => " ",
286 "thinsp"=> " ", "ndash" => "-", "mdash" => "--", "lsquo" => "`",
287 "rsquo" => "'", "sbquo" => "'", "ldquo" => "\"", "rdquo" => "\"",
288 "bdquo" => "\"", "lsaquo"=> "<", "rsaquo"=> ">",
292 ##############################################################################
294 # Various global flags set by command line parameters, or computed
296 ##############################################################################
299 my $current_state = "???"; # for diagnostics
302 my $image_succeeded = -1;
303 my $suppress_audit = 0;
305 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
306 my $verbose_warnings = 0; # print out warnings when things go wrong
307 my $verbose_load = 0; # diagnostics about loading of URLs
308 my $verbose_filter = 0; # diagnostics about page selection/rejection
309 my $verbose_net = 0; # diagnostics about network I/O
310 my $verbose_pbm = 0; # diagnostics about PBM pipelines
311 my $verbose_http = 0; # diagnostics about all HTTP activity
312 my $verbose_exec = 0; # diagnostics about executing programs
314 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
316 my $http_proxy = undef;
317 my $http_timeout = 20;
318 my $cvt_timeout = 10;
324 my $min_gif_area = (120 * 120);
330 my $imagemap_base = undef;
332 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
334 my $driftnet_magic = 'driftnet';
335 my $driftnet_dir = undef;
336 my $default_driftnet_cmd = "driftnet -a -m 100";
338 my $local_magic = 'local-directory';
339 my $local_dir = undef;
344 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
345 "arrhenius", "arteriole", "blanket", "brainchild",
346 "burdensome", "carnival", "cherub", "chord", "clever",
347 "dedicate", "dilogarithm", "dolan", "dryden",
351 ##############################################################################
355 ##############################################################################
357 # returns three values: the HTTP response line; the document headers;
358 # and the document body.
360 sub get_document_1($$$) {
361 my ($url, $referer, $timeout) = @_;
363 if (!defined($timeout)) { $timeout = $http_timeout; }
364 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
367 LOG (($verbose_net || $verbose_load), "timed out for $url");
371 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
373 if (! ($url =~ m@^http://@i)) {
374 LOG ($verbose_net, "not an HTTP URL: $url");
378 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
379 $path = "" unless $path;
381 if (!$url_proto || !$serverstring) {
382 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
386 my ($them,$port) = split(/:/, $serverstring);
387 $port = 80 unless $port;
392 $serverstring = $http_proxy if $http_proxy;
393 $serverstring =~ s@^[a-z]+://@@;
394 ($them2,$port2) = split(/:/, $serverstring);
395 $port2 = 80 unless $port2;
398 my ($remote, $iaddr, $paddr, $proto, $line);
400 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
402 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
405 $iaddr = inet_aton($remote);
407 LOG (($verbose_net || $verbose_load), "host not found: $remote");
410 $paddr = sockaddr_in($port2, $iaddr);
418 local $SIG{ALRM} = sub {
419 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
424 $proto = getprotobyname('tcp');
425 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
426 LOG (($verbose_net || $verbose_load), "socket: $!");
429 if (!connect(S, $paddr)) {
430 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
434 select(S); $| = 1; select(STDOUT);
436 my $cookie = $cookies{$them};
438 my $user_agent = "$progname/$version";
440 if ($url =~ m@^http://www\.altavista\.com/@ ||
441 $url =~ m@^http://random\.yahoo\.com/@ ||
442 $url =~ m@^http://images\.google\.com/@ ||
443 $url =~ m@^http://www\.google\.com/@) {
444 # block this, you turkeys.
445 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)" .
446 " Gecko/20070914 Firefox/2.0.0.7";
448 # 28-Jun-2007: Google Images now emits the entire page in JS if
449 # you claim to be Gecko. They also still block "webcollage".
450 # They serve non-JS for unrecognised agents, so let's try this...
451 $user_agent = "NoJavascriptPlease/1.0"
452 if ($url =~ m@^http://[a-z]+\.google\.com/@);
455 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
457 "User-Agent: $user_agent\r\n";
459 $hdrs .= "Referer: $referer\r\n";
462 my @cc = split(/\r?\n/, $cookie);
463 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
467 foreach (split('\r?\n', $hdrs)) {
468 LOG ($verbose_http, " ==> $_");
471 my $http = <S> || "";
473 # Kludge: the Yahoo Random Link is now returning as its first
474 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
476 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
480 LOG ($verbose_http, " <== $_");
486 LOG ($verbose_http, " <== $_");
488 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
489 set_cookie($them, $1)
500 " <== [ body ]: $lines lines, " . length($body) . " bytes");
505 LOG (($verbose_net || $verbose_load), "null response: $url");
509 $SIG{ALRM} = 'DEFAULT'; # seem to be suffering a race?
510 return ( $http, $head, $body );
512 die if ($@ && $@ ne "alarm\n"); # propagate errors
514 if ($@ && $@ ne "alarm\n") {
515 print STDERR blurb() . "DIE " . join(" ", $@) . "\n";
533 # returns two values: the document headers; and the document body.
534 # if the given URL did a redirect, returns the redirected-to document.
536 sub get_document($$;$) {
537 my ($url, $referer, $timeout) = @_;
540 if (defined($referer) && $referer eq $driftnet_magic) {
541 return get_driftnet_file ($url);
544 if (defined($referer) && $referer eq $local_magic) {
545 return get_local_file ($url);
550 my $max_loop_count = 4;
553 if (defined($timeout) && $timeout <= 0) {
554 LOG (($verbose_net || $verbose_load), "timed out for $url");
559 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
561 if (defined ($timeout)) {
563 my $elapsed = $now - $start;
564 $timeout -= $elapsed;
568 return () unless $http; # error message already printed
570 $http =~ s/[\r\n]+$//s;
572 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
575 my ( $location ) = m@^location:[ \t]*(.*)$@im;
577 $location =~ s/[\r\n]$//;
579 LOG ($verbose_net, "redirect from $url to $location");
584 $referer =~ m@^(http://[^/]+)@i;
586 } elsif (! ($url =~ m@^[a-z]+:@i)) {
588 s@[^/]+$@@g if m@^http://[^/]+/@i;
589 $_ .= "/" if m@^http://[^/]+$@i;
594 LOG ($verbose_net, "no Location with \"$http\"");
595 return ( $url, $body );
598 if ($loop_count++ > $max_loop_count) {
600 "too many redirects ($max_loop_count) from $orig_url");
605 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
607 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
609 # http errors -- return nothing.
615 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
621 return ( $url, $body );
627 # If we already have a cookie defined for this site, and the site is trying
628 # to overwrite that very same cookie, let it do so. This is because nytimes
629 # expires its cookies - it lets you upgrade to a new cookie without logging
630 # in again, but you have to present the old cookie to get the new cookie.
631 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
634 my ($host, $cookie) = @_;
635 my $oc = $cookies{$host};
638 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
640 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
642 if ($oc_name eq $nc_name &&
643 $oc_value ne $nc_value) {
644 $cookies{$host} = $cookie;
645 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
650 ############################################################################
652 # Extracting image URLs from HTML
654 ############################################################################
656 # given a URL and the body text at that URL, selects and returns a random
657 # image from it. returns () if no suitable images found.
659 sub pick_image_from_body($$) {
660 my ($url, $body) = @_;
665 # if there's at least one slash after the host, take off the last
667 if ( m@^http://[^/]+/@io ) {
668 $base =~ s@[^/]+$@@go;
671 # if there are no slashes after the host at all, put one on the end.
672 if ( m@^http://[^/]+$@io ) {
678 # strip out newlines, compress whitespace
685 # There are certain web sites that list huge numbers of dictionary
686 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
687 # Porn sites tend not to be reputable!)
689 # I do not want webcollage to filter on content: I want it to select
690 # randomly from the set of images on the web. All the logic here for
691 # rejecting some images is really a set of heuristics for rejecting
692 # images that are not really images: for rejecting *text* that is in
693 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
694 # the content of the pictures to be randomly selected from among all
695 # the available content.
697 # So, filtering out "dirty" pictures by looking for "dirty" keywords
698 # would be wrong: dirty pictures exist, like it or not, so webcollage
699 # should be able to select them.
701 # However, picking a random URL is a hard thing to do. The mechanism I'm
702 # using is to search for a selection of random words. This is not
703 # perfect, but works ok most of the time. The way it breaks down is when
704 # some URLs get precedence because their pages list *every word* as
705 # related -- those URLs come up more often than others.
707 # So, after we've retrieved a URL, if it has too many keywords, reject
708 # it. We reject it not on the basis of what those keywords are, but on
709 # the basis that by having so many, the page has gotten an unfair
710 # advantage against our randomizer.
713 foreach my $trip (@tripwire_words) {
714 $trip_count++ if m/$trip/i;
717 if ($trip_count >= $#tripwire_words - 2) {
718 LOG (($verbose_filter || $verbose_load),
719 "there is probably a dictionary in \"$url\": rejecting.");
720 $rejected_urls{$url} = -1;
730 foreach (split(/ *</)) {
731 if ( m/^meta.*["']keywords["']/i ) {
733 # Likewise, reject any web pages that have a KEYWORDS meta tag
738 LOG (($verbose_filter || $verbose_load),
739 "excessive keywords ($L bytes) in $url: rejecting.");
740 $rejected_urls{$url} = $L;
745 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
748 } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
749 m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
750 ["']? (image_src|og:image) ["']? /six) {
752 my $was_inline = (lc($1) eq 'img');
753 my $was_meta = (lc($1) eq 'link' || lc($1) eq 'meta');
756 # For <link rel="image_src" href="...">
757 # and <meta property="og:image" content="...">
760 next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
764 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
765 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
770 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
772 } elsif ( ! m@^[^/:?]+:@ ) {
775 1 while (s@/[^/]+/\.\./@/@g);
779 if ( ! m@^http://@io ) {
784 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
788 # skip really short or really narrow images
789 if ( $width && $width < $min_width) {
790 if (!$height) { $height = "?"; }
791 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
795 if ( $height && $height < $min_height) {
796 if (!$width) { $width = "?"; }
797 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
801 # skip images with ratios that make them look like banners.
802 if ($min_ratio && $width && $height &&
803 ($width * $min_ratio ) > $height) {
804 if (!$height) { $height = "?"; }
805 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
809 # skip GIFs with a small number of pixels -- those usually suck.
810 if ($width && $height &&
812 ($width * $height) < $min_gif_area) {
813 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
817 # skip images with a URL that indicates a Yahoo thumbnail.
818 if (m@\.yimg\.com/.*/t/@) {
819 if (!$width) { $width = "?"; }
820 if (!$height) { $height = "?"; }
821 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
827 if ($unique_urls{$url}) {
828 LOG ($verbose_filter, " skip duplicate image $_");
832 LOG ($verbose_filter,
834 ($width && $height ? " (${width}x${height})" : "") .
835 ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
841 $weight = 20; # meta tag images are far preferable to inline images.
843 if ($url !~ m@[.](gif|png)$@io ) {
844 $weight += 2; # JPEGs are preferable to GIFs and PNGs.
847 $weight += 4; # pointers to images are preferable to inlined images.
851 $unique_urls{$url}++;
852 for (my $i = 0; $i < $weight; $i++) {
853 $urls[++$#urls] = $url;
858 my $fsp = ($body =~ m@<frameset@i);
863 @urls = depoison (@urls);
866 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
870 # pick a random element of the table
871 my $i = int(rand($#urls+1));
874 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
880 # Given a URL and the RSS feed from that URL, pick a random image from
881 # the feed. This is a lot simpler than extracting images out of a page:
882 # we already know we have reasonable images, so we just pick one.
883 # Returns: the real URL of the page (preferably not the RSS version),
886 sub pick_image_from_rss($$) {
887 my ( $url, $body ) = @_;
888 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
890 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
891 $base = $url unless $base;
893 # pick a random element of the table
895 my $i = int(rand(scalar @suitable));
896 my $url = $suitable[$i];
897 LOG ($verbose_load, "picked image " .($i+1) . "/" .
898 ($#suitable+1) . ": $url");
899 return ($base, $url);
905 ############################################################################
907 # Subroutines for getting pages and images out of search engines
909 ############################################################################
912 sub pick_dictionary() {
913 my @dicts = ("/usr/dict/words",
914 "/usr/share/dict/words",
915 "/usr/share/lib/dict/words",
916 "/usr/share/dict/cracklib-small",
917 "/usr/share/dict/cracklib-words"
919 foreach my $f (@dicts) {
925 error ("$dicts[0] does not exist") unless defined($wordlist);
928 # returns a random word from the dictionary
932 return undef unless open (my $in, '<', $wordlist);
934 my $size = (stat($in))[7];
939 error ("looping ($count) while reading $wordlist")
942 my $pos = int (rand ($size));
943 if (seek ($in, $pos, 0)) {
944 $word = <$in>; # toss partial line
945 $word = <$in>; # keep next line
949 next if ($word =~ m/^[-\']/);
953 $word =~ s/^[^a-z]+//s;
954 $word =~ s/[^a-z]+$//s;
960 $word =~ s/ally$/al/s;
961 $word =~ s/izes$/ize/s;
962 $word =~ s/esses$/ess/s;
963 $word =~ s/(.{5})ing$/$1/s;
965 next if (length ($word) > 14);
971 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
972 $word = "\%22$word\%22"; # And put quotes (%22) around it.
979 sub random_words($) {
981 return (random_word() . $sep .
982 random_word() . $sep .
983 random_word() . $sep .
984 random_word() . $sep .
991 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
998 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
1007 $s =~ s/\"/"/gi;
1011 sub html_unquote($) {
1013 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
1014 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
1019 # Loads the given URL (a search on some search engine) and returns:
1020 # - the total number of hits the search engine claimed it had;
1021 # - a list of URLs from the page that the search engine returned;
1022 # Note that this list contains all kinds of internal search engine
1023 # junk URLs too -- caller must prune them.
1025 sub pick_from_search_engine($$$) {
1026 my ( $timeout, $search_url, $words ) = @_;
1031 print STDERR "\n\n" if ($verbose_load);
1033 LOG ($verbose_load, "words: $_");
1034 LOG ($verbose_load, "URL: $search_url");
1036 $last_search = $search_url; # for warnings
1039 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1040 if (defined ($timeout)) {
1041 $timeout -= (time - $start);
1042 if ($timeout <= 0) {
1044 LOG (($verbose_net || $verbose_load),
1045 "timed out (late) for $search_url");
1046 $suppress_audit = 1;
1051 return () if (! $body);
1056 my $search_count = "?";
1057 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
1059 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
1061 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
1063 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1065 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1067 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1069 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1071 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1073 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1074 $search_count = $1; # lycos
1075 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1076 $search_count = $1; # hotbot
1077 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1078 $search_count = "0";
1079 } elsif ($body =~ m@found no document matching@i) { # avtext
1080 $search_count = "0";
1082 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1084 # if ($search_count eq "?" || $search_count eq "0") {
1085 # my $file = "/tmp/wc.html";
1086 # open (my $out, '>', $file) || error ("writing $file: $!");
1089 # print STDERR blurb() . "###### wrote $file\n";
1093 my $length = length($body);
1102 foreach (split(/\n/)) {
1104 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1107 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1108 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1110 if ( $rejected_urls{$u} ) {
1111 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1115 LOG ($verbose_http, " HREF: $u");
1117 $subpages[++$#subpages] = $u;
1120 if ( $#subpages < 0 ) {
1121 LOG ($verbose_filter,
1122 "found nothing on $base ($length bytes, $href_count links).");
1126 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1128 return ($search_count, @subpages);
1136 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1138 next unless defined($h);
1140 if ($poisoners{$h}) {
1141 LOG (($verbose_filter), " rejecting poisoner: $_");
1144 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1146 LOG (($verbose_filter), " rejecting poisoner: $_");
1149 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1151 LOG (($verbose_filter), " rejecting poisoner: $_");
1161 # given a list of URLs, picks one at random; loads it; and returns a
1162 # random image from it.
1163 # returns the url of the page loaded; the url of the image chosen.
1165 sub pick_image_from_pages($$$$@) {
1166 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1168 $total_hit_count = "?" unless defined($total_hit_count);
1170 @pages = depoison (@pages);
1172 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1173 " ($total_hit_count total)");
1175 return () if ($#pages < 0);
1177 my $i = int(rand($#pages+1));
1178 my $page = $pages[$i];
1180 LOG ($verbose_load, "picked page $page");
1182 $suppress_audit = 1;
1184 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1186 if (!$base2 || !$body2) {
1191 my $img = pick_image_from_body ($base2, $body2);
1195 return ($base2, $img);
1202 ############################################################################
1204 # Pick images from random pages returned by the Yahoo Random Link
1206 ############################################################################
1209 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1212 # Picks a random page; picks a random image on that page;
1213 # returns two URLs: the page containing the image, and the image.
1214 # Returns () if nothing found this time.
1216 sub pick_from_yahoo_random_link($) {
1219 print STDERR "\n\n" if ($verbose_load);
1220 LOG ($verbose_load, "URL: $yahoo_random_link");
1222 $last_search = $yahoo_random_link; # for warnings
1224 $suppress_audit = 1;
1226 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1227 if (!$base || !$body) {
1232 LOG ($verbose_load, "redirected to: $base");
1234 my $img = pick_image_from_body ($base, $body);
1238 return ($base, $img);
1245 ############################################################################
1247 # Pick images from random pages returned by the Alta Vista Random Link
1248 # Note: this seems to have gotten a *lot* less random lately (2007).
1250 ############################################################################
1253 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1256 # Picks a random page; picks a random image on that page;
1257 # returns two URLs: the page containing the image, and the image.
1258 # Returns () if nothing found this time.
1260 sub pick_from_alta_vista_random_link($) {
1263 print STDERR "\n\n" if ($verbose_load);
1264 LOG ($verbose_load, "URL: $alta_vista_random_link");
1266 $last_search = $alta_vista_random_link; # for warnings
1268 $suppress_audit = 1;
1270 my ( $base, $body ) = get_document ($alta_vista_random_link,
1272 if (!$base || !$body) {
1277 LOG ($verbose_load, "redirected to: $base");
1279 my $img = pick_image_from_body ($base, $body);
1283 return ($base, $img);
1290 ############################################################################
1292 # Pick images by feeding random words into Alta Vista Image Search
1294 ############################################################################
1297 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1298 "?ipht=1" . # photos
1299 "&igrph=1" . # graphics
1302 "&micat=1" . # no partner sites
1303 "&sc=on" . # "site collapse"
1307 sub pick_from_alta_vista_images($) {
1310 my $words = random_word();
1311 my $page = (int(rand(9)) + 1);
1312 my $search_url = $alta_vista_images_url . $words;
1315 $search_url .= "&pgno=" . $page; # page number
1316 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1319 my ($search_hit_count, @subpages) =
1320 pick_from_search_engine ($timeout, $search_url, $words);
1322 my @candidates = ();
1323 foreach my $u (@subpages) {
1325 # avimages is encoding their URLs now.
1326 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1327 $u = url_unquote($u);
1329 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1330 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1331 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1332 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1333 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1335 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1336 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1338 LOG ($verbose_filter, " candidate: $u");
1339 push @candidates, $u;
1342 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1343 $timeout, @candidates);
1348 ############################################################################
1350 # Pick images from Aptix security cameras
1351 # Cribbed liberally from google image search code.
1352 # By Jason Sullivan <jasonsul@us.ibm.com>
1354 ############################################################################
1356 my $aptix_images_url = ("http://www.google.com/search" .
1357 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1360 sub pick_from_security_camera($) {
1363 my $page = (int(rand(9)) + 1);
1364 my $num = 20; # 20 images per page
1365 my $search_url = $aptix_images_url;
1368 $search_url .= "&start=" . $page*$num; # page number
1369 $search_url .= "&num=" . $num; #images per page
1372 my ($search_hit_count, @subpages) =
1373 pick_from_search_engine ($timeout, $search_url, '');
1375 my @candidates = ();
1377 foreach my $u (@subpages) {
1378 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1379 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1381 LOG ($verbose_filter, " candidate: $u");
1382 push @candidates, $u;
1386 @candidates = depoison (@candidates);
1387 return () if ($#candidates < 0);
1388 my $i = int(rand($#candidates+1));
1389 my $img = $candidates[$i];
1390 my $ref = $referers{$img};
1392 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1393 return ($ref, $img);
1397 ############################################################################
1399 # Pick images by feeding random words into Google Image Search.
1400 # By Charles Gales <gales@us.ibm.com>
1402 ############################################################################
1405 my $google_images_url = "http://images.google.com/images" .
1406 "?site=images" . # photos
1407 "&btnG=Search" . # graphics
1408 "&safe=off" . # no screening
1413 sub pick_from_google_images($;$$) {
1414 my ($timeout, $words, $max_page) = @_;
1416 if (!defined($words)) {
1417 $words = random_word(); # only one word for Google
1420 my $page = (int(rand(9)) + 1);
1421 my $num = 20; # 20 images per page
1422 my $search_url = $google_images_url . $words;
1425 $search_url .= "&start=" . $page*$num; # page number
1426 $search_url .= "&num=" . $num; #images per page
1429 my ($search_hit_count, @subpages) =
1430 pick_from_search_engine ($timeout, $search_url, $words);
1432 my @candidates = ();
1434 foreach my $u (@subpages) {
1435 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1436 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1438 $u = html_unquote($u);
1439 if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1442 $img = "http://$img" unless ($img =~ m/^http:/i);
1444 $ref = url_decode($ref);
1445 $img = url_decode($img);
1447 LOG ($verbose_filter, " candidate: $ref");
1448 push @candidates, $img;
1449 $referers{$img} = $ref;
1453 @candidates = depoison (@candidates);
1454 return () if ($#candidates < 0);
1455 my $i = int(rand($#candidates+1));
1456 my $img = $candidates[$i];
1457 my $ref = $referers{$img};
1459 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1460 return ($ref, $img);
1465 ############################################################################
1467 # Pick images by feeding random numbers into Google Image Search.
1468 # By jwz, suggested by Ian O'Donnell.
1470 ############################################################################
1474 sub pick_from_google_image_numbers($) {
1478 my $number = int(rand($max));
1480 $number = sprintf("%04d", $number)
1483 pick_from_google_images ($timeout, "$number");
1488 ############################################################################
1490 # Pick images by feeding random digital camera file names into
1491 # Google Image Search.
1492 # By jwz, inspired by the excellent Random Personal Picture Finder
1493 # at http://www.diddly.com/random/
1495 ############################################################################
1499 # Common digital camera file name formats, as described at
1500 # http://www.diddly.com/random/about.html
1502 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1503 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1504 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1505 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1506 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1507 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1508 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1509 int(rand(0xC)), int(rand(30))+1,
1511 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1512 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1513 sub { my $n = int(rand(9999)); # Canon
1514 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1515 sub { my $n = int(rand(9999)); # Canon
1516 sprintf ("1%02d-%04d_IMG.jpg",
1517 int($n/100), $n); },
1518 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1519 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1520 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1521 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1522 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1523 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1524 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1525 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1526 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1527 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1528 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1529 # int(rand(12))+1, int(rand(31))+1,
1530 # int(rand(999))); },
1531 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1532 # int(rand(6)), # year
1533 # int(rand(12))+1, int(rand(31))+1,
1534 # int(rand(999))); },
1535 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1536 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1537 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1538 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1543 sub pick_from_google_image_photos($) {
1546 my $i = int(rand($#photomakers + 1));
1547 my $fn = $photomakers[$i];
1549 my $words .= $file . "%20filetype:jpg";
1551 pick_from_google_images ($timeout, $words);
1556 ############################################################################
1558 # Pick images by feeding random words into Alta Vista Text Search
1560 ############################################################################
1563 my $alta_vista_url = "http://www.altavista.com/web/results" .
1567 "&sc=on" . # "site collapse"
1572 sub pick_from_alta_vista_text($) {
1575 my $words = random_words('%20');
1576 my $page = (int(rand(9)) + 1);
1577 my $search_url = $alta_vista_url . $words;
1580 $search_url .= "&pgno=" . $page;
1581 $search_url .= "&stq=" . (($page-1) * 10);
1584 my ($search_hit_count, @subpages) =
1585 pick_from_search_engine ($timeout, $search_url, $words);
1587 my @candidates = ();
1588 foreach my $u (@subpages) {
1590 # Those altavista fuckers are playing really nasty redirection games
1591 # these days: the filter your clicks through their site, but use
1592 # onMouseOver to make it look like they're not! Well, it makes it
1593 # easier for us to identify search results...
1595 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1596 $u = url_unquote($u);
1598 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1599 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1600 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1602 LOG ($verbose_filter, " candidate: $u");
1603 push @candidates, $u;
1606 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1607 $timeout, @candidates);
1612 ############################################################################
1614 # Pick images by feeding random words into Hotbot
1616 ############################################################################
1618 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1620 "&descriptiontype=0" .
1627 "&cobrand=undefined" .
1630 sub pick_from_hotbot_text($) {
1633 $last_search = $hotbot_search_url; # for warnings
1635 # lycos seems to always give us back dictionaries and word lists if
1636 # we search for more than one word...
1638 my $words = random_word();
1640 my $start = int(rand(8)) * 10 + 1;
1641 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1643 my ($search_hit_count, @subpages) =
1644 pick_from_search_engine ($timeout, $search_url, $words);
1646 my @candidates = ();
1647 foreach my $u (@subpages) {
1649 # Hotbot plays redirection games too
1651 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1652 # $u = url_decode($1);
1654 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1655 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1656 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1657 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1659 LOG ($verbose_filter, " candidate: $u");
1660 push @candidates, $u;
1663 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1664 $timeout, @candidates);
1669 ############################################################################
1671 # Pick images by feeding random words into Lycos
1673 ############################################################################
1675 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1681 sub pick_from_lycos_text($) {
1684 $last_search = $lycos_search_url; # for warnings
1686 # lycos seems to always give us back dictionaries and word lists if
1687 # we search for more than one word...
1689 my $words = random_word();
1691 my $start = int(rand(8)) * 10 + 1;
1692 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1694 my ($search_hit_count, @subpages) =
1695 pick_from_search_engine ($timeout, $search_url, $words);
1697 my @candidates = ();
1698 foreach my $u (@subpages) {
1700 # Lycos plays redirection games.
1702 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1707 # $u = url_decode($1);
1709 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1710 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1711 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1712 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1713 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1716 LOG ($verbose_filter, " candidate: $u");
1717 push @candidates, $u;
1720 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1721 $timeout, @candidates);
1726 ############################################################################
1728 # Pick images by feeding random words into news.yahoo.com
1730 ############################################################################
1732 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1737 sub pick_from_yahoo_news_text($) {
1740 $last_search = $yahoo_news_url; # for warnings
1742 my $words = random_word();
1743 my $search_url = $yahoo_news_url . $words;
1745 my ($search_hit_count, @subpages) =
1746 pick_from_search_engine ($timeout, $search_url, $words);
1748 my @candidates = ();
1749 foreach my $u (@subpages) {
1751 # de-redirectize the URLs
1752 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1754 # only accept URLs on Yahoo's news site
1755 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1756 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1757 next unless ($u =~ m@&u=/@);
1759 LOG ($verbose_filter, " candidate: $u");
1760 push @candidates, $u;
1763 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1764 $timeout, @candidates);
1769 ############################################################################
1771 # Pick images from LiveJournal's list of recently-posted images.
1773 ############################################################################
1775 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1777 # With most of our image sources, we get a random page and then select
1778 # from the images on it. However, in the case of LiveJournal, the page
1779 # of images tends to update slowly; so we'll remember the last N entries
1780 # on it and randomly select from those, to get a wider variety each time.
1782 my $lj_cache_size = 1000;
1783 my @lj_cache = (); # fifo, for ordering by age
1784 my %lj_cache = (); # hash, for detecting dups
1787 sub pick_from_livejournal_images($) {
1790 $last_search = $livejournal_img_url; # for warnings
1792 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1793 return () unless $body;
1796 $body =~ s/(<recent-image)\b/\n$1/gsi;
1798 foreach (split (/\n/, $body)) {
1799 next unless (m/^<recent-image\b/);
1800 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1801 my $img = html_unquote ($1);
1803 next if ($lj_cache{$img}); # already have it
1805 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1806 my $page = html_unquote ($1);
1807 my @pair = ($img, $page);
1808 LOG ($verbose_filter, " candidate: $img");
1809 push @lj_cache, \@pair;
1810 $lj_cache{$img} = \@pair;
1813 return () if ($#lj_cache == -1);
1815 my $n = $#lj_cache+1;
1816 my $i = int(rand($n));
1817 my ($img, $page) = @{$lj_cache[$i]};
1819 # delete this one from @lj_cache and from %lj_cache.
1821 @lj_cache = ( @lj_cache[0 .. $i-1],
1822 @lj_cache[$i+1 .. $#lj_cache] );
1823 delete $lj_cache{$img};
1825 # Keep the size of the cache under the limit by nuking older entries
1827 while ($#lj_cache >= $lj_cache_size) {
1828 my $pairP = shift @lj_cache;
1829 my $img = $pairP->[0];
1830 delete $lj_cache{$img};
1833 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1835 return ($page, $img);
1839 ############################################################################
1841 # Pick images from ircimages.com (images that have been in the /topic of
1842 # various IRC channels.)
1844 ############################################################################
1846 my $ircimages_url = "http://ircimages.com/";
1849 sub pick_from_ircimages($) {
1852 $last_search = $ircimages_url; # for warnings
1854 my $n = int(rand(2900));
1855 my $search_url = $ircimages_url . "page-$n";
1857 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1858 return () unless $body;
1860 my @candidates = ();
1863 $body =~ s/(<A)\b/\n$1/gsi;
1865 foreach (split (/\n/, $body)) {
1867 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1870 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1871 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1873 next unless ($u =~ m/^http:/i);
1874 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1875 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1877 LOG ($verbose_http, " HREF: $u");
1878 push @candidates, $u;
1881 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1883 return () if ($#candidates == -1);
1885 my $i = int(rand($#candidates+1));
1886 my $img = $candidates[$i];
1888 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1891 $search_url = $img; # hmm...
1892 return ($search_url, $img);
1896 ############################################################################
1898 # Pick images from Twitpic's list of recently-posted images.
1900 ############################################################################
1902 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1904 # With most of our image sources, we get a random page and then select
1905 # from the images on it. However, in the case of Twitpic, the page
1906 # of images tends to update slowly; so we'll remember the last N entries
1907 # on it and randomly select from those, to get a wider variety each time.
1909 my $twitpic_cache_size = 1000;
1910 my @twitpic_cache = (); # fifo, for ordering by age
1911 my %twitpic_cache = (); # hash, for detecting dups
1914 sub pick_from_twitpic_images($) {
1917 $last_search = $twitpic_img_url; # for warnings
1919 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1925 $body =~ s/(<item)\b/\n$1/gsi;
1927 my @items = split (/\n/, $body);
1930 next unless (m@<link>([^<>]*)</link>@si);
1931 my $page = html_unquote ($1);
1936 next if ($twitpic_cache{$page}); # already have it
1938 LOG ($verbose_filter, " candidate: $page");
1939 push @twitpic_cache, $page;
1940 $twitpic_cache{$page} = $page;
1944 # Pull from the cache.
1946 return () if ($#twitpic_cache == -1);
1948 my $n = $#twitpic_cache+1;
1949 my $i = int(rand($n));
1950 my $page = $twitpic_cache[$i];
1952 # delete this one from @twitpic_cache and from %twitpic_cache.
1954 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1955 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1956 delete $twitpic_cache{$page};
1958 # Keep the size of the cache under the limit by nuking older entries
1960 while ($#twitpic_cache >= $twitpic_cache_size) {
1961 my $page = shift @twitpic_cache;
1962 delete $twitpic_cache{$page};
1965 ( $base, $body ) = get_document ($page, undef, $timeout);
1967 $body = '' unless defined($body);
1969 foreach (split (/<img\s+/, $body)) {
1970 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1973 next if m@/images/@s;
1977 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
1978 if ($img =~ m@^/@) {
1979 $base =~ s@^(https?://[^/]+)/.*@$1@s;
1980 $img = $base . $img;
1986 LOG ($verbose_load, "no matching images on $page\n");
1990 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1992 return ($page, $img);
1996 ############################################################################
1998 # Pick images from Twitter's list of recently-posted updates.
2000 ############################################################################
2002 # With most of our image sources, we get a random page and then select
2003 # from the images on it. However, in the case of Twitter, the page
2004 # of images only updates once a minute; so we'll remember the last N entries
2005 # on it and randomly select from those, to get a wider variety each time.
2007 my $twitter_img_url = "http://twitter.com/statuses/public_timeline.rss";
2009 my $twitter_cache_size = 1000;
2010 my @twitter_cache = (); # fifo, for ordering by age
2011 my %twitter_cache = (); # hash, for detecting dups
2015 sub pick_from_twitter_images($) {
2018 $last_search = $twitter_img_url; # for warnings
2020 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2026 $body =~ s/(<item)\b/\n$1/gsi;
2028 my @items = split (/\n/, $body);
2031 next unless (m@<link>([^<>]*)</link>@si);
2032 my $page = html_unquote ($1);
2034 next if ($twitter_cache{$page}); # already have it
2036 my ($title) = m@<title\b[^<>]*>(.*?)</title>@si;
2039 my ($url) = ($title =~ m@\b(https?://[^\s\[\]()<>\"\']+[a-z\d/])@si);
2042 LOG ($verbose_filter, " candidate: $page - $url");
2043 push @twitter_cache, $page;
2044 $twitter_cache{$page} = $url;
2048 # Pull from the cache.
2050 return () if ($#twitter_cache == -1);
2052 my $n = $#twitter_cache+1;
2053 my $i = int(rand($n));
2054 my $page = $twitter_cache[$i];
2055 my $url = $twitter_cache{$page};
2057 # delete this one from @twitter_cache and from %twitter_cache.
2059 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2060 @twitter_cache[$i+1 .. $#twitter_cache] );
2061 delete $twitter_cache{$page};
2063 # Keep the size of the cache under the limit by nuking older entries
2065 while ($#twitter_cache >= $twitter_cache_size) {
2066 my $page = shift @twitter_cache;
2067 delete $twitter_cache{$page};
2070 LOG ($verbose_load, "picked page $url");
2072 $suppress_audit = 1;
2074 my ( $base2, $body2 ) = get_document ($url, $base, $timeout);
2076 if (!$base2 || !$body2) {
2081 my $img = pick_image_from_body ($base2, $body2);
2085 return ($base2, $img);
2092 ############################################################################
2094 # Pick images from Flickr's page of recently-posted photos.
2096 ############################################################################
2098 my $flickr_img_url = "http://www.flickr.com/photos/";
2100 # Like LiveJournal, the Flickr page of images tends to update slowly,
2101 # so remember the last N entries on it and randomly select from those.
2103 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2104 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2106 my $flickr_cache_size = 1000;
2107 my @flickr_cache = (); # fifo, for ordering by age
2108 my %flickr_cache = (); # hash, for detecting dups
2112 sub pick_from_flickr_recent($) {
2115 my $start = 16 * int(rand(100));
2117 $last_search = $flickr_img_url; # for warnings
2118 $last_search .= "?start=$start" if ($start > 0);
2120 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2121 return () unless $body;
2123 $body =~ s/[\r\n]/ /gs;
2124 $body =~ s/(<a)\b/\n$1/gsi;
2128 foreach (split (/\n/, $body)) {
2129 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2130 <IMG \s [^<>]* \b SRC=\"([^<>\"]+)\" @xsi;
2131 next unless defined ($thumb);
2132 $page = html_unquote ($page);
2133 $thumb = html_unquote ($thumb);
2135 next unless ($thumb =~ m@^http://farm\d*\.static\.flickr\.com/@);
2137 my $base = "http://www.flickr.com/";
2138 $page =~ s@^/@$base@;
2139 $thumb =~ s@^/@$base@;
2142 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2145 next if ($flickr_cache{$img}); # already have it
2147 my @pair = ($img, $page, $start);
2148 LOG ($verbose_filter, " candidate: $img");
2149 push @flickr_cache, \@pair;
2150 $flickr_cache{$img} = \@pair;
2154 return () if ($#flickr_cache == -1);
2156 my $n = $#flickr_cache+1;
2157 my $i = int(rand($n));
2158 my ($img, $page) = @{$flickr_cache[$i]};
2160 # delete this one from @flickr_cache and from %flickr_cache.
2162 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2163 @flickr_cache[$i+1 .. $#flickr_cache] );
2164 delete $flickr_cache{$img};
2166 # Keep the size of the cache under the limit by nuking older entries
2168 while ($#flickr_cache >= $flickr_cache_size) {
2169 my $pairP = shift @flickr_cache;
2170 my $img = $pairP->[0];
2171 delete $flickr_cache{$img};
2174 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2176 return ($page, $img);
2180 ############################################################################
2182 # Pick images from a random RSS feed on Flickr.
2184 ############################################################################
2186 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2187 "?format=rss_200_enc&tagmode=any&tags=");
2189 # Picks a random RSS feed; picks a random image from that feed;
2190 # returns 2 URLs: the page containing the image, and the image.
2191 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2194 sub pick_from_flickr_random($) {
2195 my $timeout = shift;
2197 my $words = random_words(',');
2198 my $rss = $flickr_rss_base . $words;
2199 $last_search = $rss;
2204 print STDERR "\n\n" if ($verbose_load);
2205 LOG ($verbose_load, "words: $_");
2206 LOG ($verbose_load, "URL: $last_search");
2208 $suppress_audit = 1;
2210 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2211 if (!$base || !$body) {
2217 ($base, $img) = pick_image_from_rss ($base, $body);
2219 return () unless defined ($img);
2221 LOG ($verbose_load, "redirected to: $base");
2222 return ($base, $img);
2226 ############################################################################
2228 # Pick images by waiting for driftnet to populate a temp dir with files.
2229 # Requires driftnet version 0.1.5 or later.
2230 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2231 # for images being downloaded by others.)
2232 # Driftnet/webcollage integration by jwz.
2234 ############################################################################
2237 sub pick_from_driftnet($) {
2240 my $id = $driftnet_magic;
2241 my $dir = $driftnet_dir;
2245 error ("\$driftnet_dir unset?") unless ($dir);
2248 error ("$dir unreadable") unless (-d "$dir/.");
2250 $timeout = $http_timeout unless ($timeout);
2253 while ($now = time, $now < $start + $timeout) {
2254 opendir (my $dir, $dir) || error ("$dir: $!");
2255 while (my $file = readdir($dir)) {
2256 next if ($file =~ m/^\./);
2257 $file = "$dir/$file";
2259 LOG ($verbose_load, "picked file $file ($id)");
2260 return ($id, $file);
2264 LOG (($verbose_net || $verbose_load), "timed out for $id");
2269 sub get_driftnet_file($) {
2272 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2274 my $id = $driftnet_magic;
2275 my $re = qr/$driftnet_dir/;
2276 error ("$id: $file not in $driftnet_dir?")
2277 unless ($file =~ m@^$re@o);
2279 open (my $in, '<', $file) || error ("$id: $file: $!");
2281 local $/ = undef; # read entire file
2283 close ($in) || error ("$id: $file: $!");
2284 unlink ($file) || error ("$id: $file: rm: $!");
2285 return ($id, $body);
2289 sub spawn_driftnet($) {
2292 # make a directory to use.
2294 my $tmp = $ENV{TEMPDIR} || "/tmp";
2295 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2296 LOG ($verbose_exec, "mkdir $driftnet_dir");
2297 last if mkdir ($driftnet_dir, 0700);
2300 if (! ($cmd =~ m/\s/)) {
2301 # if the command didn't have any arguments in it, then it must be just
2302 # a pointer to the executable. Append the default args to it.
2303 my $dargs = $default_driftnet_cmd;
2304 $dargs =~ s/^[^\s]+//;
2308 # point the driftnet command at our newly-minted private directory.
2310 $cmd .= " -d $driftnet_dir";
2311 $cmd .= ">/dev/null" unless ($verbose_exec);
2314 if ($pid < 0) { error ("fork: $!\n"); }
2317 push @pids_to_kill, $pid;
2318 LOG ($verbose_exec, "forked for \"$cmd\"");
2321 nontrapping_system ($cmd) || error ("exec: $!");
2324 # wait a bit, then make sure the process actually started up.
2327 error ("pid $pid failed to start \"$cmd\"")
2328 unless (1 == kill (0, $pid));
2332 sub pick_from_local_dir($) {
2335 my $id = $local_magic;
2338 my $dir = $local_dir;
2339 error ("\$local_dir unset?") unless ($dir);
2342 error ("$dir unreadable") unless (-d "$dir/.");
2344 my $v = ($verbose_exec ? "-v" : "");
2345 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2346 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2348 LOG ($verbose_load, "picked file $pick ($id)");
2349 return ($id, $pick);
2353 sub get_local_file($) {
2356 error ("\$local_dir unset?") unless ($local_dir);
2358 my $id = $local_magic;
2359 my $re = qr/$local_dir/;
2360 error ("$id: $file not in $local_dir?")
2361 unless ($file =~ m@^$re@o);
2363 open (my $in, '<', $file) || error ("$id: $file: $!");
2364 local $/ = undef; # read entire file
2366 close ($in) || error ("$id: $file: $!");
2367 return ($id, $body);
2372 ############################################################################
2374 # Pick a random image in a random way
2376 ############################################################################
2379 # Picks a random image on a random page, and returns two URLs:
2380 # the page containing the image, and the image.
2381 # Returns () if nothing found this time.
2384 sub pick_image(;$) {
2387 $current_state = "select";
2388 $load_method = "none";
2390 my $n = int(rand(100));
2393 my @rest = @search_methods;
2396 my $pct = shift @rest;
2397 my $name = shift @rest;
2398 my $tfn = shift @rest;
2400 if ($total > $n && !defined($fn)) {
2402 $current_state = $name;
2403 $load_method = $current_state;
2407 if ($total != 100) {
2408 error ("internal error: \@search_methods totals to $total%!");
2411 record_attempt ($current_state);
2412 return $fn->($timeout);
2417 ############################################################################
2419 # Statistics and logging
2421 ############################################################################
2424 return strftime ("%H:%M:%S: ", localtime);
2428 return "$progname: " . timestr() . "$current_state: ";
2433 print STDERR blurb() . "$err\n";
2439 print STDERR "$progname: stack trace:\n";
2441 my ($package, $filename, $line, $subroutine) = caller($i++);
2442 last unless defined($package);
2443 $filename =~ s@^.*/@@;
2444 print STDERR " $filename#$line, $subroutine\n";
2456 my $head = "$progname: DEBUG: ";
2457 foreach (split (/\n/, $lastlog)) {
2458 print STDERR "$head$_\n";
2464 my ($print, $msg) = @_;
2465 my $blurb = timestr() . "$current_state: ";
2466 $lastlog .= "$blurb$msg\n";
2467 print STDERR "$progname: $blurb$msg\n" if $print;
2472 my %stats_successes;
2475 my $last_state = undef;
2476 sub record_attempt($) {
2480 record_failure($last_state) unless ($image_succeeded > 0);
2482 $last_state = $name;
2485 report_performance();
2488 $image_succeeded = 0;
2489 $suppress_audit = 0;
2492 sub record_success($$$) {
2493 my ($name, $url, $base) = @_;
2494 if (defined($stats_successes{$name})) {
2495 $stats_successes{$name}++;
2497 $stats_successes{$name} = 1;
2500 stop_timer ($name, 1);
2501 my $o = $current_state;
2502 $current_state = $name;
2503 save_recent_url ($url, $base);
2504 $current_state = $o;
2505 $image_succeeded = 1;
2510 sub record_failure($) {
2513 return if $image_succeeded;
2515 stop_timer ($name, 0);
2516 if ($verbose_load && !$verbose_exec) {
2518 if ($suppress_audit) {
2519 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2523 my $o = $current_state;
2524 $current_state = "DEBUG";
2526 my $line = "#" x 78;
2527 print STDERR "\n\n\n";
2528 print STDERR ("#" x 78) . "\n";
2529 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2532 print STDERR ("-" x 78) . "\n";
2533 print STDERR "\n\n";
2535 $current_state = $o;
2537 $image_succeeded = 0;
2544 my $i = $stats_successes{$name};
2545 my $j = $stats_attempts{$name};
2548 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2552 my $current_start_time = 0;
2554 sub start_timer($) {
2556 $current_start_time = time;
2558 if (defined($stats_attempts{$name})) {
2559 $stats_attempts{$name}++;
2561 $stats_attempts{$name} = 1;
2563 if (!defined($stats_elapsed{$name})) {
2564 $stats_elapsed{$name} = 0;
2568 sub stop_timer($$) {
2569 my ($name, $success) = @_;
2570 $stats_elapsed{$name} += time - $current_start_time;
2574 my $last_report_time = 0;
2575 sub report_performance() {
2577 return unless $verbose_warnings;
2580 return unless ($now >= $last_report_time + $report_performance_interval);
2581 my $ot = $last_report_time;
2582 $last_report_time = $now;
2584 return if ($ot == 0);
2586 my $blurb = "$progname: " . timestr();
2589 print STDERR "${blurb}Current standings:\n";
2591 foreach my $name (sort keys (%stats_attempts)) {
2592 my $try = $stats_attempts{$name};
2593 my $suc = $stats_successes{$name} || 0;
2594 my $pct = int($suc * 100 / $try);
2595 my $secs = $stats_elapsed{$name};
2596 my $secs_link = $secs / $try;
2597 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2598 " \t %.1f secs/link\n",
2599 "$name:", "$pct%", $suc, $try, $secs_link);
2605 my $max_recent_images = 400;
2606 my $max_recent_sites = 20;
2607 my @recent_images = ();
2608 my @recent_sites = ();
2610 sub save_recent_url($$) {
2611 my ($url, $base) = @_;
2613 return unless ($verbose_warnings);
2616 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2617 return unless defined ($site);
2619 if ($base eq $driftnet_magic || $base eq $local_magic) {
2621 @recent_images = ();
2625 foreach (@recent_images) {
2627 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2628 " (on $base via $last_search)\n";
2634 # suppress "duplicate site" warning via %warningless_sites.
2636 if ($warningless_sites{$site}) {
2638 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2639 $warningless_sites{$1}) {
2641 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2642 $warningless_sites{$1}) {
2647 foreach (@recent_sites) {
2649 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2650 " ($url on $base via $last_search)\n";
2656 push @recent_images, $url;
2657 push @recent_sites, $site;
2658 shift @recent_images if ($#recent_images >= $max_recent_images);
2659 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2664 ##############################################################################
2668 ##############################################################################
2675 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2680 # Given the raw body of a GIF document, returns the dimensions of the image.
2684 my $type = substr($body, 0, 6);
2686 return () unless ($type =~ /GIF8[7,9]a/);
2687 $s = substr ($body, 6, 10);
2688 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2689 return () unless defined ($d);
2690 return (($b<<8|$a), ($d<<8|$c));
2693 # Given the raw body of a JPEG document, returns the dimensions of the image.
2698 my $L = length($body);
2700 my $c1 = substr($body, $i, 1); $i++;
2701 my $c2 = substr($body, $i, 1); $i++;
2702 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2705 while (ord($ch) != 0xDA && $i < $L) {
2706 # Find next marker, beginning with 0xFF.
2707 while (ord($ch) != 0xFF) {
2708 return () if (length($body) <= $i);
2709 $ch = substr($body, $i, 1); $i++;
2711 # markers can be padded with any number of 0xFF.
2712 while (ord($ch) == 0xFF) {
2713 return () if (length($body) <= $i);
2714 $ch = substr($body, $i, 1); $i++;
2717 # $ch contains the value of the marker.
2718 my $marker = ord($ch);
2720 if (($marker >= 0xC0) &&
2721 ($marker <= 0xCF) &&
2722 ($marker != 0xC4) &&
2723 ($marker != 0xCC)) { # it's a SOFn marker
2725 return () if (length($body) <= $i);
2726 my $s = substr($body, $i, 4); $i += 4;
2727 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2728 return (($c<<8|$d), ($a<<8|$b));
2731 # We must skip variables, since FFs in variable names aren't
2732 # valid JPEG markers.
2733 return () if (length($body) <= $i);
2734 my $s = substr($body, $i, 2); $i += 2;
2735 my ($c1, $c2) = unpack ("C"x2, $s);
2736 my $length = ($c1 << 8) | $c2;
2737 return () if ($length < 2);
2744 # Given the raw body of a PNG document, returns the dimensions of the image.
2748 return () unless ($body =~ m/^\211PNG\r/);
2749 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2750 return () unless defined ($bits);
2751 return () unless ($bits =~ /^IHDR/);
2752 my ($ign, $w, $h) = unpack("a4N2", $bits);
2757 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2762 my ($w, $h) = gif_size ($body);
2763 if ($w && $h) { return ($w, $h); }
2764 ($w, $h) = jpeg_size ($body);
2765 if ($w && $h) { return ($w, $h); }
2766 return png_size ($body);
2770 # returns the full path of the named program, or undef.
2774 foreach (split (/:/, $ENV{PATH})) {
2775 if (-x "$_/$prog") {
2783 # Like rand(), but chooses numbers with a bell curve distribution.
2786 $_ = 1.0 unless defined($_);
2788 return (rand($_) + rand($_) + rand($_));
2792 sub exit_cleanup() {
2794 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2795 if (@pids_to_kill) {
2796 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2797 kill ('TERM', @pids_to_kill);
2801 sub signal_cleanup($) {
2803 print STDERR blurb() . (defined($sig)
2804 ? "caught signal $sig."
2807 if ($verbose_exec || $verbose_warnings);
2813 ##############################################################################
2815 # Generating a list of urls only
2817 ##############################################################################
2819 sub url_only_output() {
2821 my ($base, $img) = pick_image;
2825 print "$img $base\n";
2830 ##############################################################################
2832 # Running as an xscreensaver module, or as a web page imagemap
2834 ##############################################################################
2836 my $image_ppm = sprintf ("%s/webcollage-%08x.ppm",
2837 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2839 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x.ppm",
2840 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2842 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x.ppm",
2843 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2846 my $filter_cmd = undef;
2847 my $post_filter_cmd = undef;
2848 my $background = undef;
2850 my @imagemap_areas = ();
2851 my $imagemap_html_tmp = undef;
2852 my $imagemap_jpg_tmp = undef;
2855 my $img_width; # size of the image being generated.
2861 unlink $image_ppm, $image_tmp1, $image_tmp2;
2862 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2863 if (defined ($imagemap_html_tmp));
2867 # Like system, but prints status about exit codes, and kills this process
2868 # with whatever signal killed the sub-process, if any.
2870 sub nontrapping_system(@) {
2874 s/\"[^\"]+\"/\"...\"/g;
2876 LOG ($verbose_exec, "executing \"$_\"");
2881 LOG ($verbose_exec, "subproc exited normally.");
2882 } elsif (($rc & 0xff) == 0) {
2884 LOG ($verbose_exec, "subproc exited with status $rc.");
2887 LOG ($verbose_exec, "subproc dumped core.");
2890 LOG ($verbose_exec, "subproc died with signal $rc.");
2891 # die that way ourselves.
2899 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2900 # writes a PPM to the given output file. Returns the width/height of the
2901 # image if successful.
2903 sub image_to_pnm($$$) {
2904 my ($url, $body, $output) = @_;
2905 my ($cmd, $cmd2, $w, $h);
2907 if ((@_ = gif_size ($body))) {
2910 } elsif ((@_ = jpeg_size ($body))) {
2913 } elsif ((@_ = png_size ($body))) {
2917 LOG (($verbose_pbm || $verbose_load),
2918 "not a GIF, JPG, or PNG" .
2919 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2920 ? " (looks like HTML)" : "") .
2922 $suppress_audit = 1;
2926 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2927 # do this, the process doesn't die properly.
2928 if (!$verbose_pbm) {
2930 # We get a "giftopnm: got a 'Application Extension' extension"
2931 # warning any time it's an animgif.
2933 # Note that "giftopnm: EOF / read error on image data" is not
2934 # always a fatal error -- sometimes the image looks fine anyway.
2936 $cmd2 .= " 2>/dev/null";
2939 # There exist corrupted GIF and JPEG files that can make giftopnm and
2940 # djpeg lose their minds and go into a loop. So this gives those programs
2941 # a small timeout -- if they don't complete in time, kill them.
2947 local $SIG{ALRM} = sub {
2949 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2950 kill ('TERM', $pid) if ($pid);
2955 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
2962 LOG ($verbose_exec, "awaiting $pid");
2964 LOG ($verbose_exec, "$pid completed");
2966 my $size = (stat($output))[7];
2967 $size = -1 unless defined($size);
2969 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2973 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2976 print STDERR blurb() . "$cmd failed: $!\n";
2980 die if ($@ && $@ ne "alarm\n"); # propagate errors
2994 # Same as the "ppmmake" command: creates a solid-colored PPM.
2995 # Does not understand the rgb.txt color names except "black" and "white".
2998 my ($outfile, $bgcolor, $w, $h) = @_;
3001 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3002 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3003 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3004 } elsif ($bgcolor =~ m/^black$/i) {
3005 ($r, $g, $b) = (0, 0, 0);
3006 } elsif ($bgcolor =~ m/^white$/i) {
3007 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3009 error ("unparsable color name: $bgcolor");
3012 my $pixel = pack('CCC', $r, $g, $b);
3013 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3015 open (my $out, '>', $outfile) || error ("$outfile: $!");
3021 sub pick_root_displayer() {
3025 # see "xscreensaver/hacks/webcollage-cocoa.m"
3026 return "echo COCOA LOAD ";
3029 foreach my $cmd (@root_displayers) {
3031 my ($name) = m/^([^ ]+)/;
3032 push @names, "\"$name\"";
3033 LOG ($verbose_exec, "looking for $name...");
3034 foreach my $dir (split (/:/, $ENV{PATH})) {
3035 LOG ($verbose_exec, " checking $dir/$name");
3036 return $cmd if (-x "$dir/$name");
3040 $names[$#names] = "or " . $names[$#names];
3041 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3045 my $ppm_to_root_window_cmd = undef;
3048 sub x_or_pbm_output($) {
3049 my ($window_id) = @_;
3051 # Check for our helper program, to see whether we need to use PPM pipelines.
3053 $_ = "webcollage-helper";
3054 if (defined ($webcollage_helper) || which ($_)) {
3055 $webcollage_helper = $_ unless (defined($webcollage_helper));
3056 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3057 $webcollage_helper .= " -v";
3059 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3062 if ($cocoa_p && !defined ($webcollage_helper)) {
3063 error ("webcollage-helper not found in Cocoa-mode!");
3067 # make sure the various programs we execute exist, right up front.
3071 if (!defined($webcollage_helper)) {
3072 # Only need these others if we don't have the helper.
3074 "giftopnm", "pngtopnm", "djpeg",
3075 "pnmpaste", "pnmscale", "pnmcut");
3079 which ($_) || error "$_ not found on \$PATH.";
3082 # find a root-window displayer program.
3084 if (!$no_output_p) {
3085 $ppm_to_root_window_cmd = pick_root_displayer();
3088 if (defined ($window_id)) {
3089 error ("-window-id only works if xscreensaver-getimage is installed")
3090 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3092 error ("unparsable window id: $window_id")
3093 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3094 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3095 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3098 if (!$img_width || !$img_height) {
3100 if (!defined ($window_id) &&
3101 defined ($ENV{XSCREENSAVER_WINDOW})) {
3102 $window_id = $ENV{XSCREENSAVER_WINDOW};
3105 if (!defined ($window_id)) {
3107 which ($_) || error "$_ not found on \$PATH.";
3109 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3110 if (!defined($img_height)) {
3111 error "xdpyinfo failed.";
3113 } else { # we have a window id
3115 which ($_) || error "$_ not found on \$PATH.";
3116 $_ .= " -id $window_id";
3118 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3120 if (!defined($img_height)) {
3121 error "xwininfo failed.";
3126 my $bgcolor = "#000000";
3127 my $bgimage = undef;
3130 if ($background =~ m/^\#[0-9a-f]+$/i) {
3131 $bgcolor = $background;
3133 } elsif (-r $background) {
3134 $bgimage = $background;
3136 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3137 error "not a color or readable file: $background";
3140 # default to assuming it's a color
3141 $bgcolor = $background;
3145 # Create the sold-colored base image.
3147 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3148 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3150 # Paste the default background image in the middle of it.
3156 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3157 local $/ = undef; # read entire file
3162 if ((@_ = gif_size ($body))) {
3164 $cmd = "giftopnm |";
3166 } elsif ((@_ = jpeg_size ($body))) {
3170 } elsif ((@_ = png_size ($body))) {
3172 $cmd = "pngtopnm |";
3174 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3180 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3183 my $x = int (($img_width - $iw) / 2);
3184 my $y = int (($img_height - $ih) / 2);
3186 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3188 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3189 open ($imgf, "| $cmd") || error "running $cmd: $!";
3193 LOG ($verbose_exec, "subproc exited normally.");
3194 rename ($image_tmp1, $image_ppm) ||
3195 error "renaming $image_tmp1 to $image_ppm: $!";
3201 my ($base, $img) = pick_image();
3202 my $source = $current_state;
3203 $current_state = "loadimage";
3205 my ($headers, $body) = get_document ($img, $base);
3207 paste_image ($base, $img, $body, $source);
3211 $current_state = "idle";
3212 $load_method = "none";
3214 unlink $image_tmp1, $image_tmp2;
3219 sub paste_image($$$$) {
3220 my ($base, $img, $body, $source) = @_;
3222 $current_state = "paste";
3224 $suppress_audit = 0;
3226 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3230 # If we are using the webcollage-helper, then we do not need to convert this
3231 # image to a PPM. But, if we're using a filter command, we still must, since
3232 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3235 if (defined ($webcollage_helper) &&
3236 !defined ($filter_cmd)) {
3238 ($iw, $ih) = image_size ($body);
3240 LOG (($verbose_pbm || $verbose_load),
3241 "not a GIF, JPG, or PNG" .
3242 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3243 ? " (looks like HTML)" : "") .
3245 $suppress_audit = 1;
3250 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3251 (print $out $body) || error ("writing $image_tmp1: $!");
3252 close ($out) || error ("writing $image_tmp1: $!");
3255 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3258 LOG ($verbose_pbm, "unable to make PBM from $img");
3263 record_success ($load_method, $img, $base);
3266 my $ow = $iw; # used only for error messages
3269 # don't just tack this onto the front of the pipeline -- we want it to
3270 # be able to change the size of the input image.
3273 LOG ($verbose_pbm, "running $filter_cmd");
3275 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3277 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3278 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3281 rename ($image_tmp2, $image_tmp1);
3283 # re-get the width/height in case the filter resized it.
3284 open (my $imgf, '<', $image_tmp1) || return 0;
3287 ($iw, $ih) = m/^(\d+) (\d+)$/;
3289 return 0 unless ($iw && $ih);
3292 my $target_w = $img_width; # max rectangle into which the image must fit
3293 my $target_h = $img_height;
3299 # Usually scale the image to fit on the screen -- but sometimes scale it
3300 # to fit on half or a quarter of the screen. (We do this by reducing the
3301 # size of the target rectangle.) Note that the image is not merely scaled
3302 # to fit; we instead cut the image in half repeatedly until it fits in the
3303 # target rectangle -- that gives a wider distribution of sizes.
3305 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3306 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3308 if ($iw > $target_w || $ih > $target_h) {
3309 while ($iw > $target_w ||
3315 if ($iw <= 10 || $ih <= 10) {
3316 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3320 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3322 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3326 my $src = $image_tmp1;
3328 my $crop_x = 0; # the sub-rectangle of the image
3329 my $crop_y = 0; # that we will actually paste.
3333 # The chance that we will randomly crop out a section of an image starts
3334 # out fairly low, but goes up for images that are very large, or images
3335 # that have ratios that make them look like banners (we try to avoid
3336 # banner images entirely, but they slip through when the IMG tags didn't
3337 # have WIDTH and HEIGHT specified.)
3339 my $crop_chance = 0.2;
3340 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3341 $crop_chance += 0.2;
3343 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3344 $crop_chance += 0.2;
3346 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3347 $crop_chance += 0.7;
3350 if ($crop_chance > 0.1) {
3351 LOG ($verbose_pbm, "crop chance: $crop_chance");
3354 if (rand() < $crop_chance) {
3359 if ($crop_w > $min_width) {
3360 # if it's a banner, select the width linearly.
3361 # otherwise, select a bell.
3362 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3365 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3366 $crop_x = int (rand() * ($ow - $crop_w));
3368 if ($crop_h > $min_height) {
3369 # height always selects as a bell.
3370 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3371 $crop_y = int (rand() * ($oh - $crop_h));
3374 if ($crop_x != 0 || $crop_y != 0 ||
3375 $crop_w != $iw || $crop_h != $ih) {
3377 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3381 # Where the image should logically land -- this might be negative.
3383 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3384 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3386 # if we have chosen to paste the image outside of the rectangle of the
3387 # screen, then we need to crop it.
3391 $x + $crop_w > $img_width ||
3392 $y + $crop_h > $img_height) {
3395 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3397 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3398 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3400 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3401 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3404 # If any cropping needs to happen, add pnmcut.
3406 if ($crop_x != 0 || $crop_y != 0 ||
3407 $crop_w != $iw || $crop_h != $ih) {
3410 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3411 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3414 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3416 $cmd .= " | pnmpaste - $x $y $image_ppm";
3418 $cmd =~ s@^ *\| *@@;
3420 if (defined ($webcollage_helper)) {
3421 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3422 "$scale $opacity " .
3423 "$crop_x $crop_y $x $y " .
3428 # use a PPM pipeline
3430 $_ .= " < $image_tmp1 > $image_tmp2";
3434 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3436 $_ .= " 2> /dev/null";
3439 my $rc = nontrapping_system ($_);
3441 if (defined ($webcollage_helper) && -z $image_ppm) {
3442 LOG (1, "failed command: \"$cmd\"");
3443 print STDERR "\naudit log:\n\n\n";
3444 print STDERR ("#" x 78) . "\n";
3445 print STDERR blurb() . "$image_ppm has zero size\n";
3447 print STDERR "\n\n";
3452 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3453 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3457 if (!defined ($webcollage_helper)) {
3458 rename ($image_tmp2, $image_ppm) || return;
3461 my $target = "$image_ppm";
3463 # don't just tack this onto the end of the pipeline -- we don't want it
3464 # to end up in $image_ppm, because we don't want the results to be
3467 if ($post_filter_cmd) {
3471 $target = $image_tmp1;
3472 if (!defined ($webcollage_helper)) {
3473 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3475 # Blah, my scripts need the JPEG data, but some other folks need
3476 # the PPM data -- what to do? Ignore the problem, that's what!
3477 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3478 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3481 $rc = nontrapping_system ($cmd);
3483 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3488 if (!$no_output_p) {
3489 my $tsize = (stat($target))[7];
3491 $cmd = "$ppm_to_root_window_cmd $target";
3493 # xv seems to hate being killed. it tends to forget to clean
3494 # up after itself, and leaves windows around and colors allocated.
3495 # I had this same problem with vidwhacker, and I'm not entirely
3496 # sure what I did to fix it. But, let's try this: launch xv
3497 # in the background, so that killing this process doesn't kill it.
3498 # it will die of its own accord soon enough. So this means we
3499 # start pumping bits to the root window in parallel with starting
3500 # the next network retrieval, which is probably a better thing
3503 $cmd .= " &" unless ($cocoa_p);
3505 $rc = nontrapping_system ($cmd);
3508 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3513 LOG ($verbose_pbm, "$target size is $tsize");
3517 $source .= "-" . stats_of($source);
3518 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3519 if ($verbose_imgmap);
3520 if ($imagemap_base) {
3521 update_imagemap ($base, $x, $y, $iw, $ih,
3522 $image_ppm, $img_width, $img_height);
3531 sub update_imagemap($$$$$$$$) {
3532 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3534 $current_state = "imagemap";
3536 my $max_areas = 200;
3538 $url = html_quote ($url);
3541 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3542 unshift @imagemap_areas, $area; # put one on the front
3543 if ($#imagemap_areas >= $max_areas) {
3544 pop @imagemap_areas; # take one off the back.
3547 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3549 my $map_name = $imagemap_base;
3550 $map_name =~ s@^.*/@@;
3551 $map_name = 'collage' if ($map_name eq '');
3553 my $imagemap_html = $imagemap_base . ".html";
3554 my $imagemap_jpg = $imagemap_base . ".jpg";
3556 if (!defined ($imagemap_html_tmp)) {
3557 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3558 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3561 # Read the imagemap html file (if any) to get a template.
3563 my $template_html = '';
3565 if (open (my $in, '<', $imagemap_html)) {
3566 local $/ = undef; # read entire file
3567 $template_html = <$in>;
3569 LOG ($verbose_pbm, "read template $imagemap_html");
3572 if ($template_html =~ m/^\s*$/s) {
3573 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3574 "<IMG SRC=\"$imagemap_base.jpg\"" .
3575 " USEMAP=\"$map_name\">\n");
3576 LOG ($verbose_pbm, "created dummy template");
3580 # Write the jpg to a tmp file
3584 if (defined ($webcollage_helper)) {
3585 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3587 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3589 my $rc = nontrapping_system ($cmd);
3591 error ("imagemap jpeg failed: \"$cmd\"\n");
3595 # Write the html to a tmp file
3598 my $body = $template_html;
3599 my $areas = join ("\n\t", @imagemap_areas);
3600 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3601 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
3603 "WIDTH=$image_width HEIGHT=$image_height " .
3604 "USEMAP=\"#$map_name\">");
3605 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3606 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3608 # if there are magic webcollage spans in the html, update those too.
3611 my @st = stat ($imagemap_jpg_tmp);
3612 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3613 my $size = int(($st[7] / 1024) + 0.5) . "K";
3614 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3615 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3618 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3619 (print $out $body) || error ("$imagemap_html_tmp: $!");
3620 close ($out) || error ("$imagemap_html_tmp: $!");
3621 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3624 # Rename the two tmp files to the real files
3626 rename ($imagemap_html_tmp, $imagemap_html) ||
3627 error "renaming $imagemap_html_tmp to $imagemap_html";
3628 LOG ($verbose_pbm, "wrote $imagemap_html");
3629 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3630 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3631 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3635 # Figure out what the proxy server should be, either from environment
3636 # variables or by parsing the output of the (MacOS) program "scutil",
3637 # which tells us what the system-wide proxy settings are.
3641 if (! $http_proxy) {
3642 # historical suckage: the environment variable name is lower case.
3643 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3646 if (defined ($http_proxy)) {
3647 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3648 # historical suckage: allow "http://host:port" as well as "host:port".
3653 my $proxy_data = `scutil --proxy 2>/dev/null`;
3654 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3655 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3656 # Note: this ignores the "ExceptionsList".
3658 $http_proxy = $server;
3659 $http_proxy .= ":$port" if $port;
3664 LOG ($verbose_net, "proxy server: $http_proxy");
3669 sub init_signals() {
3671 $SIG{HUP} = \&signal_cleanup;
3672 $SIG{INT} = \&signal_cleanup;
3673 $SIG{QUIT} = \&signal_cleanup;
3674 $SIG{ABRT} = \&signal_cleanup;
3675 $SIG{KILL} = \&signal_cleanup;
3676 $SIG{TERM} = \&signal_cleanup;
3678 # Need this so that if giftopnm dies, we don't die.
3679 $SIG{PIPE} = 'IGNORE';
3682 END { exit_cleanup(); }
3691 my $driftnet_cmd = 0;
3693 $current_state = "init";
3694 $load_method = "none";
3697 my $window_id = undef;
3699 while ($_ = $ARGV[0]) {
3701 if ($_ eq "-display" ||
3707 $ENV{DISPLAY} = shift @ARGV;
3708 } elsif ($_ eq "-root") {
3710 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3711 $window_id = shift @ARGV;
3713 } elsif ($_ eq "-no-output") {
3715 } elsif ($_ eq "-urls-only") {
3718 } elsif ($_ eq "-cocoa") {
3720 } elsif ($_ eq "-imagemap") {
3721 $imagemap_base = shift @ARGV;
3723 } elsif ($_ eq "-verbose") {
3725 } elsif (m/^-v+$/) {
3726 $verbose += length($_)-1;
3727 } elsif ($_ eq "-delay") {
3728 $delay = shift @ARGV;
3729 } elsif ($_ eq "-timeout") {
3730 $http_timeout = shift @ARGV;
3731 } elsif ($_ eq "-filter") {
3732 $filter_cmd = shift @ARGV;
3733 } elsif ($_ eq "-filter2") {
3734 $post_filter_cmd = shift @ARGV;
3735 } elsif ($_ eq "-background" || $_ eq "-bg") {
3736 $background = shift @ARGV;
3737 } elsif ($_ eq "-size") {
3739 if (m@^(\d+)x(\d+)$@) {
3743 error "argument to \"-size\" must be of the form \"640x400\"";
3745 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3746 $http_proxy = shift @ARGV;
3747 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3748 $dict = shift @ARGV;
3749 } elsif ($_ eq "-opacity") {
3750 $opacity = shift @ARGV;
3751 error ("opacity must be between 0.0 and 1.0")
3752 if ($opacity <= 0 || $opacity > 1);
3753 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3754 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3755 if (! ($ARGV[0] =~ m/^-/)) {
3756 $driftnet_cmd = shift @ARGV;
3758 $driftnet_cmd = $default_driftnet_cmd;
3760 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3761 @search_methods = ( 100, "local", \&pick_from_local_dir );
3762 if (! ($ARGV[0] =~ m/^-/)) {
3763 $local_dir = shift @ARGV;
3765 error ("local directory path must be set")
3767 } elsif ($_ eq "-fps") {
3768 # -fps only works on MacOS, via "webcollage-cocoa.m".
3769 # Ignore it if passed to this script in an X11 context.
3770 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3771 my $which = shift @ARGV;
3772 my @rest = @search_methods;
3775 my $pct = shift @rest;
3776 my $name = shift @rest;
3777 my $tfn = shift @rest;
3779 if ($name eq $which) {
3780 @search_methods = (100, $name, $tfn);
3785 error "no such search method as \"$which\"" unless ($ok);
3786 LOG (1, "DEBUG: using only \"$which\"");
3789 print STDERR "$copyright\nusage: $progname " .
3790 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3791 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3792 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3793 "\t\t [-background color] [-opacity f]\n" .
3794 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3795 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3796 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3797 "\t\t [-directory local-image-directory]\n" .
3803 if (!$root_p && !$no_output_p && !$cocoa_p) {
3804 print STDERR $copyright;
3805 error "the -root argument is mandatory (for now.)";
3808 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3809 error "\$DISPLAY is not set.";
3813 if ($verbose == 1) {
3814 $verbose_imgmap = 1;
3815 $verbose_warnings = 1;
3817 } elsif ($verbose == 2) {
3818 $verbose_imgmap = 1;
3819 $verbose_warnings = 1;
3822 } elsif ($verbose == 3) {
3823 $verbose_imgmap = 1;
3824 $verbose_warnings = 1;
3826 $verbose_filter = 1;
3828 } elsif ($verbose == 4) {
3829 $verbose_imgmap = 1;
3830 $verbose_warnings = 1;
3832 $verbose_filter = 1;
3835 } elsif ($verbose == 5) {
3836 $verbose_imgmap = 1;
3837 $verbose_warnings = 1;
3839 $verbose_filter = 1;
3843 } elsif ($verbose == 6) {
3844 $verbose_imgmap = 1;
3845 $verbose_warnings = 1;
3847 $verbose_filter = 1;
3852 } elsif ($verbose >= 7) {
3853 $verbose_imgmap = 1;
3854 $verbose_warnings = 1;
3856 $verbose_filter = 1;
3864 error ("$dict does not exist") unless (-f $dict);
3870 if ($imagemap_base && !($img_width && $img_height)) {
3871 error ("-size WxH is required with -imagemap");
3874 if (defined ($local_dir)) {
3875 $_ = "xscreensaver-getimage-file";
3876 which ($_) || error "$_ not found on \$PATH.";
3882 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3887 x_or_pbm_output ($window_id);