3 # webcollage, Copyright © 1999-2013 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.160 $ }; $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 = ( 26, "googlephotos", \&pick_from_google_image_photos,
71 15, "googleimgs", \&pick_from_google_images,
72 15, "googlenums", \&pick_from_google_image_numbers,
73 17, "flickr_recent", \&pick_from_flickr_recent,
74 14, "flickr_random", \&pick_from_flickr_random,
75 # twitpic went stale. don't have time to fix it right now.
76 # 10, "twitpic", \&pick_from_twitpic_images,
77 9, "livejournal", \&pick_from_livejournal_images,
78 4, "yahoorand", \&pick_from_yahoo_random_link,
80 # This one doesn't work very well: too many non-img links.
81 0, "twitter", \&pick_from_twitter_images,
83 # This is a cute way to search for a certain webcams.
84 # Not included in default methods, since these images
85 # aren't terribly interesting by themselves.
86 # See also "SurveillanceSaver".
88 0, "securitycam", \&pick_from_security_camera,
90 # Nonfunctional as of June 2011.
91 # 0, "altavista", \&pick_from_alta_vista_random_link,
93 # In Apr 2002, Google asked me to stop searching them.
94 # I asked them to add a "random link" url. They said
95 # "that would be easy, we'll think about it" and then
96 # never wrote back. Booo Google! Booooo! So, screw
97 # those turkeys, I've turned Google searching back on.
98 # I'm sure they can take it. (Jan 2005.)
100 # Jan 2005: Yahoo fucked up their search form so that
101 # it's no longer possible to do "or" searches on news
102 # images, so we rarely get any hits there any more.
104 # 0, "yahoonews", \&pick_from_yahoo_news_text,
106 # Dec 2004: the ircimages guy's server can't take the
107 # heat, so he started banning the webcollage user agent.
108 # I tried to convince him to add a lighter-weight page to
109 # support webcollage better, but he doesn't care.
111 # 0, "ircimages", \&pick_from_ircimages,
113 # Dec 2002: Alta Vista has a new "random link" URL now.
114 # They added it specifically to better support webcollage!
115 # That was super cool of them. This is how we used to do
118 # 0, "avimages", \&pick_from_alta_vista_images,
119 # 0, "avtext", \&pick_from_alta_vista_text,
121 # This broke in 2004. Eh, Lycos sucks anyway.
123 # 0, "lycos", \&pick_from_lycos_text,
125 # This broke in 2003, I think. I suspect Hotbot is
126 # actually the same search engine data as Lycos.
128 # 0, "hotbot", \&pick_from_hotbot_text,
131 # programs we can use to write to the root window (tried in ascending order.)
133 my @root_displayers = (
134 "xscreensaver-getimage -root -file",
135 "chbg -once -xscreensaver -max_size 100",
136 "xv -root -quit -viewonly +noresetroot -quick24 -rmode 5" .
137 " -rfg black -rbg black",
138 "xli -quiet -onroot -center -border black",
139 "xloadimage -quiet -onroot -center -border black",
141 # this lame program wasn't built with vroot.h:
142 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
146 # Some sites need cookies to work properly. These are they.
149 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
150 "web.altavista.com" => "AV_ALL=1",
152 # log in as "cipherpunk"
153 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
154 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
155 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
157 "ircimages.com" => 'disclaimer=1',
161 # If this is set, it's a helper program to use for pasting images together:
162 # this is a lot faster and more efficient than using PPM pipelines, which is
163 # what we do if this program doesn't exist. (We check for "webcollage-helper"
164 # on $PATH at startup, and set this variable appropriately.)
166 my $webcollage_helper = undef;
169 # If we have the webcollage-helper program, then it will paste the images
170 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
175 # Some sites have managed to poison the search engines. These are they.
176 # (We auto-detect sites that have poisoned the search engines via excessive
177 # keywords or dictionary words, but these are ones that slip through
180 # This can contain full host names, or 2 or 3 component domains.
183 "die.net" => 1, # 'l33t h4ck3r d00dz.
184 "genforum.genealogy.com" => 1, # Cluttering avtext with human names.
185 "rootsweb.com" => 1, # Cluttering avtext with human names.
186 "akamai.net" => 1, # Lots of sites have their images on Akamai.
187 "akamaitech.net" => 1, # But those are pretty much all banners.
188 # Since Akamai is super-expensive, let's
189 # go out on a limb and assume that all of
190 # their customers are rich-and-boring.
191 "bartleby.com" => 1, # Dictionary, cluttering avtext.
192 "encyclopedia.com" => 1, # Dictionary, cluttering avtext.
193 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering avtext.
194 "hotlinkpics.com" => 1, # Porn site that has poisoned avimages
195 # (I don't see how they did it, though!)
196 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
197 "nextag.com" => 1, # Poisoned Alta Vista real good.
198 "ghettodriveby.com" => 1, # Poisoned Google Images.
199 "crosswordsolver.org" => 1, # Poisoned Google Images.
200 "xona.com" => 1, # Poisoned Google Images.
201 "freepatentsonline.com" => 1, # Poisoned Google Images.
202 "herbdatanz.com" => 1, # Poisoned Google Images.
206 # When verbosity is turned on, we warn about sites that we seem to be hitting
207 # a lot: usually this means some new poisoner has made it into the search
208 # engines. But sometimes, the warning is just because that site has a lot
209 # of stuff on it. So these are the sites that are immune to the "frequent
210 # site" diagnostic message.
212 my %warningless_sites = (
213 "home.earthlink.net" => 1,
214 "www.angelfire.com" => 1,
215 "members.aol.com" => 1,
216 "img.photobucket.com" => 1,
217 "pics.livejournal.com" => 1,
223 "wikimedia.org" => 1,
225 "amazonaws.com" => 1,
227 "photoshelter.com" => 1,
228 "myspacecdn.com" => 1,
229 "feedburner.com" => 1,
236 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
237 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
238 # hits this every time.
240 "images.quizfarm.com" => 1, # damn those LJ quizzes...
241 "images.quizilla.com" => 1,
242 "images.quizdiva.net" => 1,
244 "driftnet" => 1, # builtin...
245 "local-directory" => 1, # builtin...
249 # For decoding HTML-encoded character entities to URLs.
253 "quot" => '"', "amp" => '&', "lt" => '<',
254 "gt" => '>', "nbsp" => ' ', "iexcl" => '',
255 "cent" => "\xA2", "pound" => "\xA3", "curren" => "\xA4",
256 "yen" => "\xA5", "brvbar" => "\xA6", "sect" => "\xA7",
257 "uml" => "\xA8", "copy" => "\xA9", "ordf" => "\xAA",
258 "laquo" => "\xAB", "not" => "\xAC", "shy" => "\xAD",
259 "reg" => "\xAE", "macr" => "\xAF", "deg" => "\xB0",
260 "plusmn" => "\xB1", "sup2" => "\xB2", "sup3" => "\xB3",
261 "acute" => "\xB4", "micro" => "\xB5", "para" => "\xB6",
262 "middot" => "\xB7", "cedil" => "\xB8", "sup1" => "\xB9",
263 "ordm" => "\xBA", "raquo" => "\xBB", "frac14" => "\xBC",
264 "frac12" => "\xBD", "frac34" => "\xBE", "iquest" => "\xBF",
265 "Agrave" => "\xC0", "Aacute" => "\xC1", "Acirc" => "\xC2",
266 "Atilde" => "\xC3", "Auml" => "\xC4", "Aring" => "\xC5",
267 "AElig" => "\xC6", "Ccedil" => "\xC7", "Egrave" => "\xC8",
268 "Eacute" => "\xC9", "Ecirc" => "\xCA", "Euml" => "\xCB",
269 "Igrave" => "\xCC", "Iacute" => "\xCD", "Icirc" => "\xCE",
270 "Iuml" => "\xCF", "ETH" => "\xD0", "Ntilde" => "\xD1",
271 "Ograve" => "\xD2", "Oacute" => "\xD3", "Ocirc" => "\xD4",
272 "Otilde" => "\xD5", "Ouml" => "\xD6", "times" => "\xD7",
273 "Oslash" => "\xD8", "Ugrave" => "\xD9", "Uacute" => "\xDA",
274 "Ucirc" => "\xDB", "Uuml" => "\xDC", "Yacute" => "\xDD",
275 "THORN" => "\xDE", "szlig" => "\xDF", "agrave" => "\xE0",
276 "aacute" => "\xE1", "acirc" => "\xE2", "atilde" => "\xE3",
277 "auml" => "\xE4", "aring" => "\xE5", "aelig" => "\xE6",
278 "ccedil" => "\xE7", "egrave" => "\xE8", "eacute" => "\xE9",
279 "ecirc" => "\xEA", "euml" => "\xEB", "igrave" => "\xEC",
280 "iacute" => "\xED", "icirc" => "\xEE", "iuml" => "\xEF",
281 "eth" => "\xF0", "ntilde" => "\xF1", "ograve" => "\xF2",
282 "oacute" => "\xF3", "ocirc" => "\xF4", "otilde" => "\xF5",
283 "ouml" => "\xF6", "divide" => "\xF7", "oslash" => "\xF8",
284 "ugrave" => "\xF9", "uacute" => "\xFA", "ucirc" => "\xFB",
285 "uuml" => "\xFC", "yacute" => "\xFD", "thorn" => "\xFE",
288 # HTML 4 entities that do not have 1:1 Latin1 mappings.
289 "bull" => "*", "hellip"=> "...", "prime" => "'", "Prime" => "\"",
290 "frasl" => "/", "trade" => "[tm]", "larr" => "<-", "rarr" => "->",
291 "harr" => "<->", "lArr" => "<=", "rArr" => "=>", "hArr" => "<=>",
292 "empty" => "\xD8", "minus" => "-", "lowast"=> "*", "sim" => "~",
293 "cong" => "=~", "asymp" => "~", "ne" => "!=", "equiv" => "==",
294 "le" => "<=", "ge" => ">=", "lang" => "<", "rang" => ">",
295 "loz" => "<>", "OElig" => "OE", "oelig" => "oe", "Yuml" => "Y",
296 "circ" => "^", "tilde" => "~", "ensp" => " ", "emsp" => " ",
297 "thinsp"=> " ", "ndash" => "-", "mdash" => "--", "lsquo" => "`",
298 "rsquo" => "'", "sbquo" => "'", "ldquo" => "\"", "rdquo" => "\"",
299 "bdquo" => "\"", "lsaquo"=> "<", "rsaquo"=> ">",
303 ##############################################################################
305 # Various global flags set by command line parameters, or computed
307 ##############################################################################
310 my $current_state = "???"; # for diagnostics
313 my $image_succeeded = -1;
314 my $suppress_audit = 0;
316 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
317 my $verbose_warnings = 0; # print out warnings when things go wrong
318 my $verbose_load = 0; # diagnostics about loading of URLs
319 my $verbose_filter = 0; # diagnostics about page selection/rejection
320 my $verbose_net = 0; # diagnostics about network I/O
321 my $verbose_pbm = 0; # diagnostics about PBM pipelines
322 my $verbose_http = 0; # diagnostics about all HTTP activity
323 my $verbose_exec = 0; # diagnostics about executing programs
325 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
327 my $http_proxy = undef;
328 my $http_timeout = 20;
329 my $cvt_timeout = 10;
335 my $min_gif_area = (120 * 120);
341 my $imagemap_base = undef;
343 my @pids_to_kill = (); # forked pids we should kill when we exit, if any.
345 my $driftnet_magic = 'driftnet';
346 my $driftnet_dir = undef;
347 my $default_driftnet_cmd = "driftnet -a -m 100";
349 my $local_magic = 'local-directory';
350 my $local_dir = undef;
355 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
356 "arrhenius", "arteriole", "blanket", "brainchild",
357 "burdensome", "carnival", "cherub", "chord", "clever",
358 "dedicate", "dilogarithm", "dolan", "dryden",
362 ##############################################################################
366 ##############################################################################
368 # returns three values: the HTTP response line; the document headers;
369 # and the document body.
371 sub get_document_1($$$) {
372 my ($url, $referer, $timeout) = @_;
374 if (!defined($timeout)) { $timeout = $http_timeout; }
375 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
378 LOG (($verbose_net || $verbose_load), "timed out for $url");
382 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
384 if (! ($url =~ m@^http://@i)) {
385 LOG ($verbose_net, "not an HTTP URL: $url");
389 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
390 $path = "" unless $path;
392 if (!$url_proto || !$serverstring) {
393 LOG (($verbose_net || $verbose_load), "unparsable URL: $url");
397 my ($them,$port) = split(/:/, $serverstring);
398 $port = 80 unless $port;
403 $serverstring = $http_proxy if $http_proxy;
404 $serverstring =~ s@^[a-z]+://@@;
405 ($them2,$port2) = split(/:/, $serverstring);
406 $port2 = 80 unless $port2;
409 my ($remote, $iaddr, $paddr, $proto, $line);
411 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
413 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
416 $iaddr = inet_aton($remote);
418 LOG (($verbose_net || $verbose_load), "host not found: $remote");
421 $paddr = sockaddr_in($port2, $iaddr);
429 local $SIG{ALRM} = sub {
430 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
435 $proto = getprotobyname('tcp');
436 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
437 LOG (($verbose_net || $verbose_load), "socket: $!");
440 if (!connect(S, $paddr)) {
441 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
445 select(S); $| = 1; select(STDOUT);
447 my $cookie = $cookies{$them};
449 my $user_agent = "$progname/$version";
451 if ($url =~ m@^http://www\.altavista\.com/@ ||
452 $url =~ m@^http://random\.yahoo\.com/@ ||
453 $url =~ m@^http://images\.google\.com/@ ||
454 $url =~ m@^http://www\.google\.com/@) {
455 # block this, you turkeys.
456 $user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7)" .
457 " Gecko/20070914 Firefox/2.0.0.7";
459 # 28-Jun-2007: Google Images now emits the entire page in JS if
460 # you claim to be Gecko. They also still block "webcollage".
461 # They serve non-JS for unrecognised agents, so let's try this...
462 $user_agent = "NoJavascriptPlease/1.0"
463 if ($url =~ m@^http://[a-z]+\.google\.com/@);
466 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
468 "User-Agent: $user_agent\r\n";
470 $hdrs .= "Referer: $referer\r\n";
473 my @cc = split(/\r?\n/, $cookie);
474 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
478 foreach (split('\r?\n', $hdrs)) {
479 LOG ($verbose_http, " ==> $_");
482 my $http = <S> || "";
484 # Kludge: the Yahoo Random Link is now returning as its first
485 # line "Status: 301" instead of "HTTP/1.0 301 Found". Fix it...
487 $http =~ s@^Status:\s+(\d+)\b@HTTP/1.0 $1@i;
491 LOG ($verbose_http, " <== $_");
497 LOG ($verbose_http, " <== $_");
499 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
500 set_cookie($them, $1)
511 " <== [ body ]: $lines lines, " . length($body) . " bytes");
516 LOG (($verbose_net || $verbose_load), "null response: $url");
520 $SIG{ALRM} = 'DEFAULT'; # seem to be suffering a race?
521 return ( $http, $head, $body );
523 die if ($@ && $@ ne "alarm\n"); # propagate errors
525 if ($@ && $@ ne "alarm\n") {
526 print STDERR blurb() . "DIE " . join(" ", $@) . "\n";
544 # returns two values: the document headers; and the document body.
545 # if the given URL did a redirect, returns the redirected-to document.
547 sub get_document($$;$) {
548 my ($url, $referer, $timeout) = @_;
551 if (defined($referer) && $referer eq $driftnet_magic) {
552 return get_driftnet_file ($url);
555 if (defined($referer) && $referer eq $local_magic) {
556 return get_local_file ($url);
561 my $max_loop_count = 4;
564 if (defined($timeout) && $timeout <= 0) {
565 LOG (($verbose_net || $verbose_load), "timed out for $url");
570 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
572 if (defined ($timeout)) {
574 my $elapsed = $now - $start;
575 $timeout -= $elapsed;
579 return () unless $http; # error message already printed
581 $http =~ s/[\r\n]+$//s;
583 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
586 my ( $location ) = m@^location:[ \t]*(.*)$@im;
588 $location =~ s/[\r\n]$//;
590 LOG ($verbose_net, "redirect from $url to $location");
595 $referer =~ m@^(http://[^/]+)@i;
597 } elsif (! ($url =~ m@^[a-z]+:@i)) {
599 s@[^/]+$@@g if m@^http://[^/]+/@i;
600 $_ .= "/" if m@^http://[^/]+$@i;
605 LOG ($verbose_net, "no Location with \"$http\"");
606 return ( $url, $body );
609 if ($loop_count++ > $max_loop_count) {
611 "too many redirects ($max_loop_count) from $orig_url");
616 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
618 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
620 # http errors -- return nothing.
626 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
632 return ( $url, $body );
638 # If we already have a cookie defined for this site, and the site is trying
639 # to overwrite that very same cookie, let it do so. This is because nytimes
640 # expires its cookies - it lets you upgrade to a new cookie without logging
641 # in again, but you have to present the old cookie to get the new cookie.
642 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
645 my ($host, $cookie) = @_;
646 my $oc = $cookies{$host};
649 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
651 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
653 if ($oc_name eq $nc_name &&
654 $oc_value ne $nc_value) {
655 $cookies{$host} = $cookie;
656 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
661 ############################################################################
663 # Extracting image URLs from HTML
665 ############################################################################
667 # given a URL and the body text at that URL, selects and returns a random
668 # image from it. returns () if no suitable images found.
670 sub pick_image_from_body($$) {
671 my ($url, $body) = @_;
676 # if there's at least one slash after the host, take off the last
678 if ( m@^http://[^/]+/@io ) {
679 $base =~ s@[^/]+$@@go;
682 # if there are no slashes after the host at all, put one on the end.
683 if ( m@^http://[^/]+$@io ) {
689 # strip out newlines, compress whitespace
696 # There are certain web sites that list huge numbers of dictionary
697 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
698 # Porn sites tend not to be reputable!)
700 # I do not want webcollage to filter on content: I want it to select
701 # randomly from the set of images on the web. All the logic here for
702 # rejecting some images is really a set of heuristics for rejecting
703 # images that are not really images: for rejecting *text* that is in
704 # GIF/JPEG/PNG form. I don't want text, I want pictures, and I want
705 # the content of the pictures to be randomly selected from among all
706 # the available content.
708 # So, filtering out "dirty" pictures by looking for "dirty" keywords
709 # would be wrong: dirty pictures exist, like it or not, so webcollage
710 # should be able to select them.
712 # However, picking a random URL is a hard thing to do. The mechanism I'm
713 # using is to search for a selection of random words. This is not
714 # perfect, but works ok most of the time. The way it breaks down is when
715 # some URLs get precedence because their pages list *every word* as
716 # related -- those URLs come up more often than others.
718 # So, after we've retrieved a URL, if it has too many keywords, reject
719 # it. We reject it not on the basis of what those keywords are, but on
720 # the basis that by having so many, the page has gotten an unfair
721 # advantage against our randomizer.
724 foreach my $trip (@tripwire_words) {
725 $trip_count++ if m/$trip/i;
728 if ($trip_count >= $#tripwire_words - 2) {
729 LOG (($verbose_filter || $verbose_load),
730 "there is probably a dictionary in \"$url\": rejecting.");
731 $rejected_urls{$url} = -1;
741 foreach (split(/ *</)) {
742 if ( m/^meta.*["']keywords["']/i ) {
744 # Likewise, reject any web pages that have a KEYWORDS meta tag
749 LOG (($verbose_filter || $verbose_load),
750 "excessive keywords ($L bytes) in $url: rejecting.");
751 $rejected_urls{$url} = $L;
756 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
759 } elsif (m/^ (IMG|A) \b .* (SRC|HREF) \s* = \s* ["']? (.*?) [ "'<>] /six ||
760 m/^ (LINK|META) \b .* (REL|PROPERTY) \s* = \s*
761 ["']? (image_src|og:image) ["']? /six) {
763 my $was_inline = (lc($1) eq 'img');
764 my $was_meta = (lc($1) eq 'link' || lc($1) eq 'meta');
767 # For <link rel="image_src" href="...">
768 # and <meta property="og:image" content="...">
771 next unless (m/ (HREF|CONTENT) \s* = \s* ["']? (.*?) [ "'<>] /six);
775 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
776 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
781 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
783 } elsif ( ! m@^[^/:?]+:@ ) {
786 1 while (s@/[^/]+/\.\./@/@g);
790 if ( ! m@^http://@io ) {
795 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@io ) {
799 # skip really short or really narrow images
800 if ( $width && $width < $min_width) {
801 if (!$height) { $height = "?"; }
802 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
806 if ( $height && $height < $min_height) {
807 if (!$width) { $width = "?"; }
808 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
812 # skip images with ratios that make them look like banners.
813 if ($min_ratio && $width && $height &&
814 ($width * $min_ratio ) > $height) {
815 if (!$height) { $height = "?"; }
816 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
820 # skip GIFs with a small number of pixels -- those usually suck.
821 if ($width && $height &&
823 ($width * $height) < $min_gif_area) {
824 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
828 # skip images with a URL that indicates a Yahoo thumbnail.
829 if (m@\.yimg\.com/.*/t/@) {
830 if (!$width) { $width = "?"; }
831 if (!$height) { $height = "?"; }
832 LOG ($verbose_filter, " skip yahoo thumb $_ (${width}x$height)");
838 if ($unique_urls{$url}) {
839 LOG ($verbose_filter, " skip duplicate image $_");
843 LOG ($verbose_filter,
845 ($width && $height ? " (${width}x${height})" : "") .
846 ($was_meta ? " (meta)" : $was_inline ? " (inline)" : ""));
852 $weight = 20; # meta tag images are far preferable to inline images.
854 if ($url !~ m@[.](gif|png)$@io ) {
855 $weight += 2; # JPEGs are preferable to GIFs and PNGs.
858 $weight += 4; # pointers to images are preferable to inlined images.
862 $unique_urls{$url}++;
863 for (my $i = 0; $i < $weight; $i++) {
864 $urls[++$#urls] = $url;
869 my $fsp = ($body =~ m@<frameset@i);
874 @urls = depoison (@urls);
877 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
881 # pick a random element of the table
882 my $i = int(rand($#urls+1));
885 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
891 # Given a URL and the RSS feed from that URL, pick a random image from
892 # the feed. This is a lot simpler than extracting images out of a page:
893 # we already know we have reasonable images, so we just pick one.
894 # Returns: the real URL of the page (preferably not the RSS version),
897 sub pick_image_from_rss($$) {
898 my ( $url, $body ) = @_;
899 my @suitable = ($body =~ m/<enclosure url="(.*?)"/g);
901 my ($base) = ($body =~ m@<link>([^<>]+)</link>@i);
902 $base = $url unless $base;
904 # pick a random element of the table
906 my $i = int(rand(scalar @suitable));
907 my $url = $suitable[$i];
908 LOG ($verbose_load, "picked image " .($i+1) . "/" .
909 ($#suitable+1) . ": $url");
910 return ($base, $url);
916 ############################################################################
918 # Subroutines for getting pages and images out of search engines
920 ############################################################################
923 sub pick_dictionary() {
924 my @dicts = ("/usr/dict/words",
925 "/usr/share/dict/words",
926 "/usr/share/lib/dict/words",
927 "/usr/share/dict/cracklib-small",
928 "/usr/share/dict/cracklib-words"
930 foreach my $f (@dicts) {
936 error ("$dicts[0] does not exist") unless defined($wordlist);
939 # returns a random word from the dictionary
943 return undef unless open (my $in, '<', $wordlist);
945 my $size = (stat($in))[7];
950 error ("looping ($count) while reading $wordlist")
953 my $pos = int (rand ($size));
954 if (seek ($in, $pos, 0)) {
955 $word = <$in>; # toss partial line
956 $word = <$in>; # keep next line
960 next if ($word =~ m/^[-\']/);
964 $word =~ s/^[^a-z]+//s;
965 $word =~ s/[^a-z]+$//s;
971 $word =~ s/ally$/al/s;
972 $word =~ s/izes$/ize/s;
973 $word =~ s/esses$/ess/s;
974 $word =~ s/(.{5})ing$/$1/s;
976 next if (length ($word) > 14);
982 if ( $word =~ s/\s/\+/gs ) { # convert intra-word spaces to "+".
983 $word = "\%22$word\%22"; # And put quotes (%22) around it.
990 sub random_words($) {
992 return (random_word() . $sep .
993 random_word() . $sep .
994 random_word() . $sep .
995 random_word() . $sep .
1002 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
1006 sub url_unquote($) {
1009 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
1018 $s =~ s/\"/"/gi;
1022 sub html_unquote($) {
1024 $s =~ s/(&([a-z]+);)/{ $entity_table{$2} || $1; }/gexi; # e.g., '
1025 $s =~ s/(&\#(\d+);)/{ chr($2) }/gexi; # e.g., '
1030 # Loads the given URL (a search on some search engine) and returns:
1031 # - the total number of hits the search engine claimed it had;
1032 # - a list of URLs from the page that the search engine returned;
1033 # Note that this list contains all kinds of internal search engine
1034 # junk URLs too -- caller must prune them.
1036 sub pick_from_search_engine($$$) {
1037 my ( $timeout, $search_url, $words ) = @_;
1042 print STDERR "\n\n" if ($verbose_load);
1044 LOG ($verbose_load, "words: $_");
1045 LOG ($verbose_load, "URL: $search_url");
1047 $last_search = $search_url; # for warnings
1050 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1051 if (defined ($timeout)) {
1052 $timeout -= (time - $start);
1053 if ($timeout <= 0) {
1055 LOG (($verbose_net || $verbose_load),
1056 "timed out (late) for $search_url");
1057 $suppress_audit = 1;
1062 return () if (! $body);
1067 my $search_count = "?";
1068 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
1070 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
1072 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
1074 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
1076 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # avimages
1078 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # avimages
1080 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
1082 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
1084 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
1085 $search_count = $1; # lycos
1086 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
1087 $search_count = $1; # hotbot
1088 } elsif ($body =~ m@no photos were found containing@i) { # avimages
1089 $search_count = "0";
1090 } elsif ($body =~ m@found no document matching@i) { # avtext
1091 $search_count = "0";
1093 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
1095 # if ($search_count eq "?" || $search_count eq "0") {
1096 # my $file = "/tmp/wc.html";
1097 # open (my $out, '>', $file) || error ("writing $file: $!");
1100 # print STDERR blurb() . "###### wrote $file\n";
1104 my $length = length($body);
1113 foreach (split(/\n/)) {
1115 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1118 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1119 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1121 if ( $rejected_urls{$u} ) {
1122 LOG ($verbose_filter, " pre-rejecting candidate: $u");
1126 LOG ($verbose_http, " HREF: $u");
1128 $subpages[++$#subpages] = $u;
1131 if ( $#subpages < 0 ) {
1132 LOG ($verbose_filter,
1133 "found nothing on $base ($length bytes, $href_count links).");
1137 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
1139 return ($search_count, @subpages);
1147 my ($h) = m@^http://([^/: \t\r\n]+)@i;
1149 next unless defined($h);
1151 if ($poisoners{$h}) {
1152 LOG (($verbose_filter), " rejecting poisoner: $_");
1155 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1157 LOG (($verbose_filter), " rejecting poisoner: $_");
1160 if ($h =~ m@([^.]+\.[^.]+)$@ &&
1162 LOG (($verbose_filter), " rejecting poisoner: $_");
1172 # given a list of URLs, picks one at random; loads it; and returns a
1173 # random image from it.
1174 # returns the url of the page loaded; the url of the image chosen.
1176 sub pick_image_from_pages($$$$@) {
1177 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
1179 $total_hit_count = "?" unless defined($total_hit_count);
1181 @pages = depoison (@pages);
1183 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
1184 " ($total_hit_count total)");
1186 return () if ($#pages < 0);
1188 my $i = int(rand($#pages+1));
1189 my $page = $pages[$i];
1191 LOG ($verbose_load, "picked page $page");
1193 $suppress_audit = 1;
1195 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
1197 if (!$base2 || !$body2) {
1202 my $img = pick_image_from_body ($base2, $body2);
1206 return ($base2, $img);
1213 ############################################################################
1215 # Pick images from random pages returned by the Yahoo Random Link
1217 ############################################################################
1220 my $yahoo_random_link = "http://random.yahoo.com/fast/ryl";
1223 # Picks a random page; picks a random image on that page;
1224 # returns two URLs: the page containing the image, and the image.
1225 # Returns () if nothing found this time.
1227 sub pick_from_yahoo_random_link($) {
1230 print STDERR "\n\n" if ($verbose_load);
1231 LOG ($verbose_load, "URL: $yahoo_random_link");
1233 $last_search = $yahoo_random_link; # for warnings
1235 $suppress_audit = 1;
1237 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
1238 if (!$base || !$body) {
1243 LOG ($verbose_load, "redirected to: $base");
1245 my $img = pick_image_from_body ($base, $body);
1249 return ($base, $img);
1256 ############################################################################
1258 # Pick images from random pages returned by the Alta Vista Random Link
1259 # Note: this seems to have gotten a *lot* less random lately (2007).
1261 ############################################################################
1264 my $alta_vista_random_link = "http://www.altavista.com/image/randomlink";
1267 # Picks a random page; picks a random image on that page;
1268 # returns two URLs: the page containing the image, and the image.
1269 # Returns () if nothing found this time.
1271 sub pick_from_alta_vista_random_link($) {
1274 print STDERR "\n\n" if ($verbose_load);
1275 LOG ($verbose_load, "URL: $alta_vista_random_link");
1277 $last_search = $alta_vista_random_link; # for warnings
1279 $suppress_audit = 1;
1281 my ( $base, $body ) = get_document ($alta_vista_random_link,
1283 if (!$base || !$body) {
1288 LOG ($verbose_load, "redirected to: $base");
1290 my $img = pick_image_from_body ($base, $body);
1294 return ($base, $img);
1301 ############################################################################
1303 # Pick images by feeding random words into Alta Vista Image Search
1305 ############################################################################
1308 my $alta_vista_images_url = "http://www.altavista.com/image/results" .
1309 "?ipht=1" . # photos
1310 "&igrph=1" . # graphics
1313 "&micat=1" . # no partner sites
1314 "&sc=on" . # "site collapse"
1318 sub pick_from_alta_vista_images($) {
1321 my $words = random_word();
1322 my $page = (int(rand(9)) + 1);
1323 my $search_url = $alta_vista_images_url . $words;
1326 $search_url .= "&pgno=" . $page; # page number
1327 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1330 my ($search_hit_count, @subpages) =
1331 pick_from_search_engine ($timeout, $search_url, $words);
1333 my @candidates = ();
1334 foreach my $u (@subpages) {
1336 # avimages is encoding their URLs now.
1337 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1338 $u = url_unquote($u);
1340 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1341 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1342 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1343 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1344 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1346 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1347 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1349 LOG ($verbose_filter, " candidate: $u");
1350 push @candidates, $u;
1353 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1354 $timeout, @candidates);
1359 ############################################################################
1361 # Pick images from Aptix security cameras
1362 # Cribbed liberally from google image search code.
1363 # By Jason Sullivan <jasonsul@us.ibm.com>
1365 ############################################################################
1367 my $aptix_images_url = ("http://www.google.com/search" .
1368 "?q=inurl:%22jpg/image.jpg%3Fr%3D%22");
1371 sub pick_from_security_camera($) {
1374 my $page = (int(rand(9)) + 1);
1375 my $num = 20; # 20 images per page
1376 my $search_url = $aptix_images_url;
1379 $search_url .= "&start=" . $page*$num; # page number
1380 $search_url .= "&num=" . $num; #images per page
1383 my ($search_hit_count, @subpages) =
1384 pick_from_search_engine ($timeout, $search_url, '');
1386 my @candidates = ();
1388 foreach my $u (@subpages) {
1389 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins (most links)
1390 next unless ($u =~ m@jpg/image.jpg\?r=@i); # All pics contain this
1392 LOG ($verbose_filter, " candidate: $u");
1393 push @candidates, $u;
1397 @candidates = depoison (@candidates);
1398 return () if ($#candidates < 0);
1399 my $i = int(rand($#candidates+1));
1400 my $img = $candidates[$i];
1401 my $ref = $referers{$img};
1403 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1404 return ($ref, $img);
1408 ############################################################################
1410 # Pick images by feeding random words into Google Image Search.
1411 # By Charles Gales <gales@us.ibm.com>
1413 ############################################################################
1416 my $google_images_url = "http://images.google.com/images" .
1417 "?site=images" . # photos
1418 "&btnG=Search" . # graphics
1419 "&safe=off" . # no screening
1424 sub pick_from_google_images($;$$) {
1425 my ($timeout, $words, $max_page) = @_;
1427 if (!defined($words)) {
1428 $words = random_word(); # only one word for Google
1431 my $page = (int(rand(9)) + 1);
1432 my $num = 20; # 20 images per page
1433 my $search_url = $google_images_url . $words;
1436 $search_url .= "&start=" . $page*$num; # page number
1437 $search_url .= "&num=" . $num; #images per page
1440 my ($search_hit_count, @subpages) =
1441 pick_from_search_engine ($timeout, $search_url, $words);
1443 my @candidates = ();
1445 foreach my $u (@subpages) {
1446 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1447 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1449 $u = html_unquote($u);
1450 if ($u =~ m@^/imgres\?imgurl=(.*?)&imgrefurl=(.*?)\&@) {
1453 $img = "http://$img" unless ($img =~ m/^http:/i);
1455 $ref = url_decode($ref);
1456 $img = url_decode($img);
1458 LOG ($verbose_filter, " candidate: $ref");
1459 push @candidates, $img;
1460 $referers{$img} = $ref;
1464 @candidates = depoison (@candidates);
1465 return () if ($#candidates < 0);
1466 my $i = int(rand($#candidates+1));
1467 my $img = $candidates[$i];
1468 my $ref = $referers{$img};
1470 LOG ($verbose_load, "picked image " . ($i+1) . ": $img (on $ref)");
1471 return ($ref, $img);
1476 ############################################################################
1478 # Pick images by feeding random numbers into Google Image Search.
1479 # By jwz, suggested by Ian O'Donnell.
1481 ############################################################################
1485 sub pick_from_google_image_numbers($) {
1489 my $number = int(rand($max));
1491 $number = sprintf("%04d", $number)
1494 pick_from_google_images ($timeout, "$number");
1499 ############################################################################
1501 # Pick images by feeding random digital camera file names into
1502 # Google Image Search.
1503 # By jwz, inspired by the excellent Random Personal Picture Finder
1504 # at http://www.diddly.com/random/
1506 ############################################################################
1510 # Common digital camera file name formats, as described at
1511 # http://www.diddly.com/random/about.html
1513 sub { sprintf ("dcp%05d.jpg", int(rand(4000))); }, # Kodak
1514 sub { sprintf ("dsc%05d.jpg", int(rand(4000))); }, # Nikon
1515 sub { sprintf ("dscn%04d.jpg", int(rand(4000))); }, # Nikon
1516 sub { sprintf ("mvc-%03d.jpg", int(rand(999))); }, # Sony Mavica
1517 sub { sprintf ("mvc%05d.jpg", int(rand(9999))); }, # Sony Mavica
1518 sub { sprintf ("P101%04d.jpg", int(rand(9999))); }, # Olympus w/ date=101
1519 sub { sprintf ("P%x%02d%04d.jpg", # Olympus
1520 int(rand(0xC)), int(rand(30))+1,
1522 sub { sprintf ("IMG_%03d.jpg", int(rand(999))); }, # ?
1523 sub { sprintf ("IMAG%04d.jpg", int(rand(9999))); }, # RCA and Samsung
1524 sub { my $n = int(rand(9999)); # Canon
1525 sprintf ("1%02d-%04d.jpg", int($n/100), $n); },
1526 sub { my $n = int(rand(9999)); # Canon
1527 sprintf ("1%02d-%04d_IMG.jpg",
1528 int($n/100), $n); },
1529 sub { sprintf ("IMG_%04d.jpg", int(rand(9999))); }, # Canon
1530 sub { sprintf ("dscf%04d.jpg", int(rand(9999))); }, # Fuji Finepix
1531 sub { sprintf ("pdrm%04d.jpg", int(rand(9999))); }, # Toshiba PDR
1532 sub { sprintf ("IM%06d.jpg", int(rand(9999))); }, # HP Photosmart
1533 sub { sprintf ("EX%06d.jpg", int(rand(9999))); }, # HP Photosmart
1534 # sub { my $n = int(rand(3)); # Kodak DC-40,50,120
1535 # sprintf ("DC%04d%s.jpg", int(rand(9999)),
1536 # $n == 0 ? 'S' : $n == 1 ? 'M' : 'L'); },
1537 sub { sprintf ("pict%04d.jpg", int(rand(9999))); }, # Minolta Dimage
1538 sub { sprintf ("P%07d.jpg", int(rand(9999))); }, # Kodak DC290
1539 # sub { sprintf ("%02d%02d%04d.jpg", # Casio QV3000, QV4000
1540 # int(rand(12))+1, int(rand(31))+1,
1541 # int(rand(999))); },
1542 # sub { sprintf ("%02d%x%02d%04d.jpg", # Casio QV7000
1543 # int(rand(6)), # year
1544 # int(rand(12))+1, int(rand(31))+1,
1545 # int(rand(999))); },
1546 sub { sprintf ("IMGP%04d.jpg", int(rand(9999))); }, # Pentax Optio S
1547 sub { sprintf ("PANA%04d.jpg", int(rand(9999))); }, # Panasonic vid still
1548 sub { sprintf ("HPIM%04d.jpg", int(rand(9999))); }, # HP Photosmart
1549 sub { sprintf ("PCDV%04d.jpg", int(rand(9999))); }, # ?
1554 sub pick_from_google_image_photos($) {
1557 my $i = int(rand($#photomakers + 1));
1558 my $fn = $photomakers[$i];
1560 my $words .= $file . "%20filetype:jpg";
1562 pick_from_google_images ($timeout, $words);
1567 ############################################################################
1569 # Pick images by feeding random words into Alta Vista Text Search
1571 ############################################################################
1574 my $alta_vista_url = "http://www.altavista.com/web/results" .
1578 "&sc=on" . # "site collapse"
1583 sub pick_from_alta_vista_text($) {
1586 my $words = random_words('%20');
1587 my $page = (int(rand(9)) + 1);
1588 my $search_url = $alta_vista_url . $words;
1591 $search_url .= "&pgno=" . $page;
1592 $search_url .= "&stq=" . (($page-1) * 10);
1595 my ($search_hit_count, @subpages) =
1596 pick_from_search_engine ($timeout, $search_url, $words);
1598 my @candidates = ();
1599 foreach my $u (@subpages) {
1601 # Those altavista fuckers are playing really nasty redirection games
1602 # these days: the filter your clicks through their site, but use
1603 # onMouseOver to make it look like they're not! Well, it makes it
1604 # easier for us to identify search results...
1606 next unless ($u =~ s/^.*\*\*(http%3a.*$)/$1/gsi);
1607 $u = url_unquote($u);
1609 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1610 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1611 next if ($u =~ m@[/.]yahoo\.com\b@i); # yahoo and av in cahoots?
1613 LOG ($verbose_filter, " candidate: $u");
1614 push @candidates, $u;
1617 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1618 $timeout, @candidates);
1623 ############################################################################
1625 # Pick images by feeding random words into Hotbot
1627 ############################################################################
1629 my $hotbot_search_url =("http://hotbot.lycos.com/default.asp" .
1631 "&descriptiontype=0" .
1638 "&cobrand=undefined" .
1641 sub pick_from_hotbot_text($) {
1644 $last_search = $hotbot_search_url; # for warnings
1646 # lycos seems to always give us back dictionaries and word lists if
1647 # we search for more than one word...
1649 my $words = random_word();
1651 my $start = int(rand(8)) * 10 + 1;
1652 my $search_url = $hotbot_search_url . $words . "&first=$start&page=more";
1654 my ($search_hit_count, @subpages) =
1655 pick_from_search_engine ($timeout, $search_url, $words);
1657 my @candidates = ();
1658 foreach my $u (@subpages) {
1660 # Hotbot plays redirection games too
1662 # next unless ($u =~ m@/director.asp\?.*\btarget=([^&]+)@);
1663 # $u = url_decode($1);
1665 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1666 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip hotbot builtins
1667 next if ($u =~ m@[/.]lycos\.com\b@i); # skip hotbot builtins
1668 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip hotbot builtins
1670 LOG ($verbose_filter, " candidate: $u");
1671 push @candidates, $u;
1674 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1675 $timeout, @candidates);
1680 ############################################################################
1682 # Pick images by feeding random words into Lycos
1684 ############################################################################
1686 my $lycos_search_url = "http://search.lycos.com/default.asp" .
1692 sub pick_from_lycos_text($) {
1695 $last_search = $lycos_search_url; # for warnings
1697 # lycos seems to always give us back dictionaries and word lists if
1698 # we search for more than one word...
1700 my $words = random_word();
1702 my $start = int(rand(8)) * 10 + 1;
1703 my $search_url = $lycos_search_url . $words . "&first=$start&page=more";
1705 my ($search_hit_count, @subpages) =
1706 pick_from_search_engine ($timeout, $search_url, $words);
1708 my @candidates = ();
1709 foreach my $u (@subpages) {
1711 # Lycos plays redirection games.
1713 # next unless ($u =~ m@^http://click.lycos.com/director.asp
1718 # $u = url_decode($1);
1720 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1721 next if ($u =~ m@[/.]hotbot\.com\b@i); # skip lycos builtins
1722 next if ($u =~ m@[/.]lycos\.com\b@i); # skip lycos builtins
1723 next if ($u =~ m@[/.]terralycos\.com\b@i); # skip lycos builtins
1724 next if ($u =~ m@[/.]inktomi\.com\b@i); # skip lycos builtins
1727 LOG ($verbose_filter, " candidate: $u");
1728 push @candidates, $u;
1731 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1732 $timeout, @candidates);
1737 ############################################################################
1739 # Pick images by feeding random words into news.yahoo.com
1741 ############################################################################
1743 my $yahoo_news_url = "http://news.search.yahoo.com/search/news" .
1748 sub pick_from_yahoo_news_text($) {
1751 $last_search = $yahoo_news_url; # for warnings
1753 my $words = random_word();
1754 my $search_url = $yahoo_news_url . $words;
1756 my ($search_hit_count, @subpages) =
1757 pick_from_search_engine ($timeout, $search_url, $words);
1759 my @candidates = ();
1760 foreach my $u (@subpages) {
1762 # de-redirectize the URLs
1763 $u =~ s@^http://rds\.yahoo\.com/.*-http%3A@http:@s;
1765 # only accept URLs on Yahoo's news site
1766 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1767 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1768 next unless ($u =~ m@&u=/@);
1770 LOG ($verbose_filter, " candidate: $u");
1771 push @candidates, $u;
1774 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1775 $timeout, @candidates);
1780 ############################################################################
1782 # Pick images from LiveJournal's list of recently-posted images.
1784 ############################################################################
1786 my $livejournal_img_url = "http://www.livejournal.com/stats/latest-img.bml";
1788 # With most of our image sources, we get a random page and then select
1789 # from the images on it. However, in the case of LiveJournal, the page
1790 # of images tends to update slowly; so we'll remember the last N entries
1791 # on it and randomly select from those, to get a wider variety each time.
1793 my $lj_cache_size = 1000;
1794 my @lj_cache = (); # fifo, for ordering by age
1795 my %lj_cache = (); # hash, for detecting dups
1798 sub pick_from_livejournal_images($) {
1801 $last_search = $livejournal_img_url; # for warnings
1803 my ( $base, $body ) = get_document ($livejournal_img_url, undef, $timeout);
1804 return () unless $body;
1807 $body =~ s/(<recent-image)\b/\n$1/gsi;
1809 foreach (split (/\n/, $body)) {
1810 next unless (m/^<recent-image\b/);
1811 next unless (m/\bIMG=[\'\"]([^\'\"]+)[\'\"]/si);
1812 my $img = html_unquote ($1);
1814 next if ($lj_cache{$img}); # already have it
1816 next unless (m/\bURL=[\'\"]([^\'\"]+)[\'\"]/si);
1817 my $page = html_unquote ($1);
1818 my @pair = ($img, $page);
1819 LOG ($verbose_filter, " candidate: $img");
1820 push @lj_cache, \@pair;
1821 $lj_cache{$img} = \@pair;
1824 return () if ($#lj_cache == -1);
1826 my $n = $#lj_cache+1;
1827 my $i = int(rand($n));
1828 my ($img, $page) = @{$lj_cache[$i]};
1830 # delete this one from @lj_cache and from %lj_cache.
1832 @lj_cache = ( @lj_cache[0 .. $i-1],
1833 @lj_cache[$i+1 .. $#lj_cache] );
1834 delete $lj_cache{$img};
1836 # Keep the size of the cache under the limit by nuking older entries
1838 while ($#lj_cache >= $lj_cache_size) {
1839 my $pairP = shift @lj_cache;
1840 my $img = $pairP->[0];
1841 delete $lj_cache{$img};
1844 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
1846 return ($page, $img);
1850 ############################################################################
1852 # Pick images from ircimages.com (images that have been in the /topic of
1853 # various IRC channels.)
1855 ############################################################################
1857 my $ircimages_url = "http://ircimages.com/";
1860 sub pick_from_ircimages($) {
1863 $last_search = $ircimages_url; # for warnings
1865 my $n = int(rand(2900));
1866 my $search_url = $ircimages_url . "page-$n";
1868 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
1869 return () unless $body;
1871 my @candidates = ();
1874 $body =~ s/(<A)\b/\n$1/gsi;
1876 foreach (split (/\n/, $body)) {
1878 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
1881 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
1882 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
1884 next unless ($u =~ m/^http:/i);
1885 next if ($u =~ m@^http://(searchirc\.com\|ircimages\.com)@i);
1886 next unless ($u =~ m@[.](gif|jpg|jpeg|pjpg|pjpeg|png)$@i);
1888 LOG ($verbose_http, " HREF: $u");
1889 push @candidates, $u;
1892 LOG ($verbose_filter, "" . $#candidates+1 . " links on $search_url");
1894 return () if ($#candidates == -1);
1896 my $i = int(rand($#candidates+1));
1897 my $img = $candidates[$i];
1899 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#candidates+1) .
1902 $search_url = $img; # hmm...
1903 return ($search_url, $img);
1907 ############################################################################
1909 # Pick images from Twitpic's list of recently-posted images.
1911 ############################################################################
1913 my $twitpic_img_url = "http://twitpic.com/public_timeline/feed.rss";
1915 # With most of our image sources, we get a random page and then select
1916 # from the images on it. However, in the case of Twitpic, the page
1917 # of images tends to update slowly; so we'll remember the last N entries
1918 # on it and randomly select from those, to get a wider variety each time.
1920 my $twitpic_cache_size = 1000;
1921 my @twitpic_cache = (); # fifo, for ordering by age
1922 my %twitpic_cache = (); # hash, for detecting dups
1925 sub pick_from_twitpic_images($) {
1928 $last_search = $twitpic_img_url; # for warnings
1930 my ( $base, $body ) = get_document ($twitpic_img_url, undef, $timeout);
1936 $body =~ s/(<item)\b/\n$1/gsi;
1938 my @items = split (/\n/, $body);
1941 next unless (m@<link>([^<>]*)</link>@si);
1942 my $page = html_unquote ($1);
1947 next if ($twitpic_cache{$page}); # already have it
1949 LOG ($verbose_filter, " candidate: $page");
1950 push @twitpic_cache, $page;
1951 $twitpic_cache{$page} = $page;
1955 # Pull from the cache.
1957 return () if ($#twitpic_cache == -1);
1959 my $n = $#twitpic_cache+1;
1960 my $i = int(rand($n));
1961 my $page = $twitpic_cache[$i];
1963 # delete this one from @twitpic_cache and from %twitpic_cache.
1965 @twitpic_cache = ( @twitpic_cache[0 .. $i-1],
1966 @twitpic_cache[$i+1 .. $#twitpic_cache] );
1967 delete $twitpic_cache{$page};
1969 # Keep the size of the cache under the limit by nuking older entries
1971 while ($#twitpic_cache >= $twitpic_cache_size) {
1972 my $page = shift @twitpic_cache;
1973 delete $twitpic_cache{$page};
1976 ( $base, $body ) = get_document ($page, undef, $timeout);
1978 $body = '' unless defined($body);
1980 foreach (split (/<img\s+/, $body)) {
1981 my ($src) = m/\bsrc=[\"\'](.*?)[\"\']/si;
1984 next if m@/images/@s;
1988 $img = "http:$img" if ($img =~ m@^//@s); # Oh come on
1990 # Sometimes these images are hosted on twitpic, sometimes on Amazon.
1991 if ($img =~ m@^/@) {
1992 $base =~ s@^(https?://[^/]+)/.*@$1@s;
1993 $img = $base . $img;
1999 LOG ($verbose_load, "no matching images on $page\n");
2003 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2005 return ($page, $img);
2009 ############################################################################
2011 # Pick images from Twitter's list of recently-posted updates.
2013 ############################################################################
2015 # With most of our image sources, we get a random page and then select
2016 # from the images on it. However, in the case of Twitter, the page
2017 # of images only updates once a minute; so we'll remember the last N entries
2018 # on it and randomly select from those, to get a wider variety each time.
2020 my $twitter_img_url = "http://api.twitter.com/1/statuses/" .
2021 "public_timeline.json" .
2022 "?include_entities=true" .
2023 "&include_rts=true" .
2026 my $twitter_cache_size = 1000;
2028 my @twitter_cache = (); # fifo, for ordering by age
2029 my %twitter_cache = (); # hash, for detecting dups
2033 sub pick_from_twitter_images($) {
2036 $last_search = $twitter_img_url; # for warnings
2038 my ( $base, $body ) = get_document ($twitter_img_url, undef, $timeout);
2042 $body =~ s/[\r\n]+/ /gs;
2044 # Parsing JSON is a pain in the ass. So we halfass it as usual.
2045 $body =~ s/^\[|\]$//s;
2046 $body =~ s/(\[.*?\])/{ $_ = $1; s@\},@\} @gs; $_; }/gsexi;
2047 my @items = split (/},{/, $body);
2049 my ($name) = m@"screen_name":"([^\"]+)"@si;
2050 my ($img) = m@"media_url":"([^\"]+)"@si;
2051 my ($page) = m@"display_url":"([^\"]+)"@si;
2052 next unless ($name && $img && $page);
2053 foreach ($img, $page) {
2055 $_ = "http://$_" unless (m/^http/si);
2058 next if ($twitter_cache{$page}); # already have it
2060 LOG ($verbose_filter, " candidate: $page - $img");
2061 push @twitter_cache, $page;
2062 $twitter_cache{$page} = $img;
2066 # Pull from the cache.
2068 return () if ($#twitter_cache == -1);
2070 my $n = $#twitter_cache+1;
2071 my $i = int(rand($n));
2072 my $page = $twitter_cache[$i];
2073 my $url = $twitter_cache{$page};
2075 # delete this one from @twitter_cache and from %twitter_cache.
2077 @twitter_cache = ( @twitter_cache[0 .. $i-1],
2078 @twitter_cache[$i+1 .. $#twitter_cache] );
2079 delete $twitter_cache{$page};
2081 # Keep the size of the cache under the limit by nuking older entries
2083 while ($#twitter_cache >= $twitter_cache_size) {
2084 my $page = shift @twitter_cache;
2085 delete $twitter_cache{$page};
2088 LOG ($verbose_load, "picked page $url");
2090 $suppress_audit = 1;
2092 return ($page, $url);
2096 ############################################################################
2098 # Pick images from Flickr's page of recently-posted photos.
2100 ############################################################################
2102 my $flickr_img_url = "http://www.flickr.com/explore/";
2104 # Like LiveJournal, the Flickr page of images tends to update slowly,
2105 # so remember the last N entries on it and randomly select from those.
2107 # I know that Flickr has an API (http://www.flickr.com/services/api/)
2108 # but it was easy enough to scrape the HTML, so I didn't bother exploring.
2110 my $flickr_cache_size = 1000;
2111 my @flickr_cache = (); # fifo, for ordering by age
2112 my %flickr_cache = (); # hash, for detecting dups
2116 sub pick_from_flickr_recent($) {
2119 my $start = 16 * int(rand(100));
2121 $last_search = $flickr_img_url; # for warnings
2122 $last_search .= "?start=$start" if ($start > 0);
2124 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2125 return () unless $body;
2127 $body =~ s/[\r\n]/ /gs;
2128 $body =~ s/(<a)\b/\n$1/gsi;
2132 foreach (split (/\n/, $body)) {
2134 my ($page, $thumb) = m@<A \s [^<>]* \b HREF=\"([^<>\"]+)\" [^<>]* > \s*
2136 data-defer-src = \"([^<>\"]+)\" @xsi;
2137 next unless defined ($thumb);
2138 $page = html_unquote ($page);
2139 $thumb = html_unquote ($thumb);
2141 next unless ($thumb =~ m@^http://farm\d*\.static\.?flickr\.com/@);
2143 my $base = "http://www.flickr.com/";
2144 $page =~ s@^/@$base@;
2145 $thumb =~ s@^/@$base@;
2148 $img =~ s/_[a-z](\.[a-z\d]+)$/$1/si; # take off "thumb" suffix
2151 next if ($flickr_cache{$img}); # already have it
2153 my @pair = ($img, $page, $start);
2154 LOG ($verbose_filter, " candidate: $img");
2155 push @flickr_cache, \@pair;
2156 $flickr_cache{$img} = \@pair;
2160 return () if ($#flickr_cache == -1);
2162 my $n = $#flickr_cache+1;
2163 my $i = int(rand($n));
2164 my ($img, $page) = @{$flickr_cache[$i]};
2166 # delete this one from @flickr_cache and from %flickr_cache.
2168 @flickr_cache = ( @flickr_cache[0 .. $i-1],
2169 @flickr_cache[$i+1 .. $#flickr_cache] );
2170 delete $flickr_cache{$img};
2172 # Keep the size of the cache under the limit by nuking older entries
2174 while ($#flickr_cache >= $flickr_cache_size) {
2175 my $pairP = shift @flickr_cache;
2176 my $img = $pairP->[0];
2177 delete $flickr_cache{$img};
2180 LOG ($verbose_load, "picked image " .($i+1) . "/$n: $img");
2182 return ($page, $img);
2186 ############################################################################
2188 # Pick images from a random RSS feed on Flickr.
2190 ############################################################################
2192 my $flickr_rss_base = ("http://www.flickr.com/services/feeds/photos_public.gne".
2193 "?format=rss_200_enc&tagmode=any&tags=");
2195 # Picks a random RSS feed; picks a random image from that feed;
2196 # returns 2 URLs: the page containing the image, and the image.
2197 # Mostly by Joe Mcmahon <mcmahon@yahoo-inc.com>
2200 sub pick_from_flickr_random($) {
2201 my $timeout = shift;
2203 my $words = random_words(',');
2204 my $rss = $flickr_rss_base . $words;
2205 $last_search = $rss;
2210 print STDERR "\n\n" if ($verbose_load);
2211 LOG ($verbose_load, "words: $_");
2212 LOG ($verbose_load, "URL: $last_search");
2214 $suppress_audit = 1;
2216 my ( $base, $body ) = get_document ($last_search, undef, $timeout);
2217 if (!$base || !$body) {
2223 ($base, $img) = pick_image_from_rss ($base, $body);
2225 return () unless defined ($img);
2227 LOG ($verbose_load, "redirected to: $base");
2228 return ($base, $img);
2232 ############################################################################
2234 # Pick images by waiting for driftnet to populate a temp dir with files.
2235 # Requires driftnet version 0.1.5 or later.
2236 # (Driftnet is a program by Chris Lightfoot that sniffs your local ethernet
2237 # for images being downloaded by others.)
2238 # Driftnet/webcollage integration by jwz.
2240 ############################################################################
2243 sub pick_from_driftnet($) {
2246 my $id = $driftnet_magic;
2247 my $dir = $driftnet_dir;
2251 error ("\$driftnet_dir unset?") unless ($dir);
2254 error ("$dir unreadable") unless (-d "$dir/.");
2256 $timeout = $http_timeout unless ($timeout);
2259 while ($now = time, $now < $start + $timeout) {
2260 opendir (my $dir, $dir) || error ("$dir: $!");
2261 while (my $file = readdir($dir)) {
2262 next if ($file =~ m/^\./);
2263 $file = "$dir/$file";
2265 LOG ($verbose_load, "picked file $file ($id)");
2266 return ($id, $file);
2270 LOG (($verbose_net || $verbose_load), "timed out for $id");
2275 sub get_driftnet_file($) {
2278 error ("\$driftnet_dir unset?") unless ($driftnet_dir);
2280 my $id = $driftnet_magic;
2281 error ("$id: $file not in $driftnet_dir?")
2282 unless ($file =~ m@^\Q$driftnet_dir@o);
2284 open (my $in, '<', $file) || error ("$id: $file: $!");
2286 local $/ = undef; # read entire file
2288 close ($in) || error ("$id: $file: $!");
2289 unlink ($file) || error ("$id: $file: rm: $!");
2290 return ($id, $body);
2294 sub spawn_driftnet($) {
2297 # make a directory to use.
2299 my $tmp = $ENV{TEMPDIR} || "/tmp";
2300 $driftnet_dir = sprintf ("$tmp/driftcollage-%08x", rand(0xffffffff));
2301 LOG ($verbose_exec, "mkdir $driftnet_dir");
2302 last if mkdir ($driftnet_dir, 0700);
2305 if (! ($cmd =~ m/\s/)) {
2306 # if the command didn't have any arguments in it, then it must be just
2307 # a pointer to the executable. Append the default args to it.
2308 my $dargs = $default_driftnet_cmd;
2309 $dargs =~ s/^[^\s]+//;
2313 # point the driftnet command at our newly-minted private directory.
2315 $cmd .= " -d $driftnet_dir";
2316 $cmd .= ">/dev/null" unless ($verbose_exec);
2319 if ($pid < 0) { error ("fork: $!\n"); }
2322 push @pids_to_kill, $pid;
2323 LOG ($verbose_exec, "forked for \"$cmd\"");
2326 nontrapping_system ($cmd) || error ("exec: $!");
2329 # wait a bit, then make sure the process actually started up.
2332 error ("pid $pid failed to start \"$cmd\"")
2333 unless (1 == kill (0, $pid));
2337 sub pick_from_local_dir($) {
2340 my $id = $local_magic;
2343 my $dir = $local_dir;
2344 error ("\$local_dir unset?") unless ($dir);
2347 error ("$dir unreadable") unless (-d "$dir/.");
2349 my $v = ($verbose_exec ? "-v" : "");
2350 my $pick = `xscreensaver-getimage-file $v "$dir"`;
2352 $pick = "$dir/$pick" unless ($pick =~ m@^/@s); # relative path
2354 LOG ($verbose_load, "picked file $pick ($id)");
2355 return ($id, $pick);
2359 sub get_local_file($) {
2362 error ("\$local_dir unset?") unless ($local_dir);
2364 my $id = $local_magic;
2365 error ("$id: $file not in $local_dir?")
2366 unless ($file =~ m@^\Q$local_dir@o);
2368 open (my $in, '<', $file) || error ("$id: $file: $!");
2369 local $/ = undef; # read entire file
2371 close ($in) || error ("$id: $file: $!");
2372 return ($id, $body);
2377 ############################################################################
2379 # Pick a random image in a random way
2381 ############################################################################
2384 # Picks a random image on a random page, and returns two URLs:
2385 # the page containing the image, and the image.
2386 # Returns () if nothing found this time.
2389 sub pick_image(;$) {
2392 $current_state = "select";
2393 $load_method = "none";
2395 my $n = int(rand(100));
2398 my @rest = @search_methods;
2401 my $pct = shift @rest;
2402 my $name = shift @rest;
2403 my $tfn = shift @rest;
2405 if ($total > $n && !defined($fn)) {
2407 $current_state = $name;
2408 $load_method = $current_state;
2412 if ($total != 100) {
2413 error ("internal error: \@search_methods totals to $total%!");
2416 record_attempt ($current_state);
2417 return $fn->($timeout);
2422 ############################################################################
2424 # Statistics and logging
2426 ############################################################################
2429 return strftime ("%H:%M:%S: ", localtime);
2433 return "$progname: " . timestr() . "$current_state: ";
2438 print STDERR blurb() . "$err\n";
2444 print STDERR "$progname: stack trace:\n";
2446 my ($package, $filename, $line, $subroutine) = caller($i++);
2447 last unless defined($package);
2448 $filename =~ s@^.*/@@;
2449 print STDERR " $filename#$line, $subroutine\n";
2461 my $head = "$progname: DEBUG: ";
2462 foreach (split (/\n/, $lastlog)) {
2463 print STDERR "$head$_\n";
2469 my ($print, $msg) = @_;
2470 my $blurb = timestr() . "$current_state: ";
2471 $lastlog .= "$blurb$msg\n";
2472 print STDERR "$progname: $blurb$msg\n" if $print;
2477 my %stats_successes;
2480 my $last_state = undef;
2481 sub record_attempt($) {
2485 record_failure($last_state) unless ($image_succeeded > 0);
2487 $last_state = $name;
2490 report_performance();
2493 $image_succeeded = 0;
2494 $suppress_audit = 0;
2497 sub record_success($$$) {
2498 my ($name, $url, $base) = @_;
2499 if (defined($stats_successes{$name})) {
2500 $stats_successes{$name}++;
2502 $stats_successes{$name} = 1;
2505 stop_timer ($name, 1);
2506 my $o = $current_state;
2507 $current_state = $name;
2508 save_recent_url ($url, $base);
2509 $current_state = $o;
2510 $image_succeeded = 1;
2515 sub record_failure($) {
2518 return if $image_succeeded;
2520 stop_timer ($name, 0);
2521 if ($verbose_load && !$verbose_exec) {
2523 if ($suppress_audit) {
2524 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
2528 my $o = $current_state;
2529 $current_state = "DEBUG";
2531 my $line = "#" x 78;
2532 print STDERR "\n\n\n";
2533 print STDERR ("#" x 78) . "\n";
2534 print STDERR blurb() . "failed to get an image. Full audit log:\n";
2537 print STDERR ("-" x 78) . "\n";
2538 print STDERR "\n\n";
2540 $current_state = $o;
2542 $image_succeeded = 0;
2549 my $i = $stats_successes{$name};
2550 my $j = $stats_attempts{$name};
2553 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
2557 my $current_start_time = 0;
2559 sub start_timer($) {
2561 $current_start_time = time;
2563 if (defined($stats_attempts{$name})) {
2564 $stats_attempts{$name}++;
2566 $stats_attempts{$name} = 1;
2568 if (!defined($stats_elapsed{$name})) {
2569 $stats_elapsed{$name} = 0;
2573 sub stop_timer($$) {
2574 my ($name, $success) = @_;
2575 $stats_elapsed{$name} += time - $current_start_time;
2579 my $last_report_time = 0;
2580 sub report_performance() {
2582 return unless $verbose_warnings;
2585 return unless ($now >= $last_report_time + $report_performance_interval);
2586 my $ot = $last_report_time;
2587 $last_report_time = $now;
2589 return if ($ot == 0);
2591 my $blurb = "$progname: " . timestr();
2594 print STDERR "${blurb}Current standings:\n";
2596 foreach my $name (sort keys (%stats_attempts)) {
2597 my $try = $stats_attempts{$name};
2598 my $suc = $stats_successes{$name} || 0;
2599 my $pct = int($suc * 100 / $try);
2600 my $secs = $stats_elapsed{$name};
2601 my $secs_link = $secs / $try;
2602 print STDERR sprintf ("$blurb %-14s %4s (%d/%d);" .
2603 " \t %.1f secs/link\n",
2604 "$name:", "$pct%", $suc, $try, $secs_link);
2610 my $max_recent_images = 400;
2611 my $max_recent_sites = 20;
2612 my @recent_images = ();
2613 my @recent_sites = ();
2615 sub save_recent_url($$) {
2616 my ($url, $base) = @_;
2618 return unless ($verbose_warnings);
2621 my ($site) = m@^http://([^ \t\n\r/:]+)@;
2622 return unless defined ($site);
2624 if ($base eq $driftnet_magic || $base eq $local_magic) {
2626 @recent_images = ();
2630 foreach (@recent_images) {
2632 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
2633 " (on $base via $last_search)\n";
2639 # suppress "duplicate site" warning via %warningless_sites.
2641 if ($warningless_sites{$site}) {
2643 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
2644 $warningless_sites{$1}) {
2646 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
2647 $warningless_sites{$1}) {
2652 foreach (@recent_sites) {
2654 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
2655 " ($url on $base via $last_search)\n";
2661 push @recent_images, $url;
2662 push @recent_sites, $site;
2663 shift @recent_images if ($#recent_images >= $max_recent_images);
2664 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
2669 ##############################################################################
2673 ##############################################################################
2680 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
2685 # Given the raw body of a GIF document, returns the dimensions of the image.
2689 my $type = substr($body, 0, 6);
2691 return () unless ($type =~ /GIF8[7,9]a/);
2692 $s = substr ($body, 6, 10);
2693 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
2694 return () unless defined ($d);
2695 return (($b<<8|$a), ($d<<8|$c));
2698 # Given the raw body of a JPEG document, returns the dimensions of the image.
2703 my $L = length($body);
2705 my $c1 = substr($body, $i, 1); $i++;
2706 my $c2 = substr($body, $i, 1); $i++;
2707 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
2710 while (ord($ch) != 0xDA && $i < $L) {
2711 # Find next marker, beginning with 0xFF.
2712 while (ord($ch) != 0xFF) {
2713 return () if (length($body) <= $i);
2714 $ch = substr($body, $i, 1); $i++;
2716 # markers can be padded with any number of 0xFF.
2717 while (ord($ch) == 0xFF) {
2718 return () if (length($body) <= $i);
2719 $ch = substr($body, $i, 1); $i++;
2722 # $ch contains the value of the marker.
2723 my $marker = ord($ch);
2725 if (($marker >= 0xC0) &&
2726 ($marker <= 0xCF) &&
2727 ($marker != 0xC4) &&
2728 ($marker != 0xCC)) { # it's a SOFn marker
2730 return () if (length($body) <= $i);
2731 my $s = substr($body, $i, 4); $i += 4;
2732 my ($a,$b,$c,$d) = unpack("C"x4, $s);
2733 return (($c<<8|$d), ($a<<8|$b));
2736 # We must skip variables, since FFs in variable names aren't
2737 # valid JPEG markers.
2738 return () if (length($body) <= $i);
2739 my $s = substr($body, $i, 2); $i += 2;
2740 my ($c1, $c2) = unpack ("C"x2, $s);
2741 my $length = ($c1 << 8) | $c2;
2742 return () if ($length < 2);
2749 # Given the raw body of a PNG document, returns the dimensions of the image.
2753 return () unless ($body =~ m/^\211PNG\r/);
2754 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
2755 return () unless defined ($bits);
2756 return () unless ($bits =~ /^IHDR/);
2757 my ($ign, $w, $h) = unpack("a4N2", $bits);
2762 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
2767 my ($w, $h) = gif_size ($body);
2768 if ($w && $h) { return ($w, $h); }
2769 ($w, $h) = jpeg_size ($body);
2770 if ($w && $h) { return ($w, $h); }
2771 return png_size ($body);
2775 # returns the full path of the named program, or undef.
2779 foreach (split (/:/, $ENV{PATH})) {
2780 if (-x "$_/$prog") {
2788 # Like rand(), but chooses numbers with a bell curve distribution.
2791 $_ = 1.0 unless defined($_);
2793 return (rand($_) + rand($_) + rand($_));
2797 sub exit_cleanup() {
2799 print STDERR "$progname: exiting\n" if ($verbose_warnings);
2800 if (@pids_to_kill) {
2801 print STDERR blurb() . "killing: " . join(' ', @pids_to_kill) . "\n";
2802 kill ('TERM', @pids_to_kill);
2806 sub signal_cleanup($) {
2808 print STDERR blurb() . (defined($sig)
2809 ? "caught signal $sig."
2812 if ($verbose_exec || $verbose_warnings);
2818 ##############################################################################
2820 # Generating a list of urls only
2822 ##############################################################################
2824 sub url_only_output() {
2826 my ($base, $img) = pick_image;
2830 print "$img $base\n";
2835 ##############################################################################
2837 # Running as an xscreensaver module, or as a web page imagemap
2839 ##############################################################################
2841 my $image_ppm = sprintf ("%s/webcollage-%08x.ppm",
2842 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2844 my $image_tmp1 = sprintf ("%s/webcollage-1-%08x.ppm",
2845 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2847 my $image_tmp2 = sprintf ("%s/webcollage-2-%08x.ppm",
2848 ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp"),
2851 my $filter_cmd = undef;
2852 my $post_filter_cmd = undef;
2853 my $background = undef;
2855 my @imagemap_areas = ();
2856 my $imagemap_html_tmp = undef;
2857 my $imagemap_jpg_tmp = undef;
2860 my $img_width; # size of the image being generated.
2866 unlink $image_ppm, $image_tmp1, $image_tmp2;
2867 unlink $imagemap_html_tmp, $imagemap_jpg_tmp
2868 if (defined ($imagemap_html_tmp));
2872 # Like system, but prints status about exit codes, and kills this process
2873 # with whatever signal killed the sub-process, if any.
2875 sub nontrapping_system(@) {
2879 s/\"[^\"]+\"/\"...\"/g;
2881 LOG ($verbose_exec, "executing \"$_\"");
2886 LOG ($verbose_exec, "subproc exited normally.");
2887 } elsif (($rc & 0xff) == 0) {
2889 LOG ($verbose_exec, "subproc exited with status $rc.");
2892 LOG ($verbose_exec, "subproc dumped core.");
2895 LOG ($verbose_exec, "subproc died with signal $rc.");
2896 # die that way ourselves.
2904 # Given the URL of a GIF, JPEG, or PNG image, and the body of that image,
2905 # writes a PPM to the given output file. Returns the width/height of the
2906 # image if successful.
2908 sub image_to_pnm($$$) {
2909 my ($url, $body, $output) = @_;
2910 my ($cmd, $cmd2, $w, $h);
2912 if ((@_ = gif_size ($body))) {
2915 } elsif ((@_ = jpeg_size ($body))) {
2918 } elsif ((@_ = png_size ($body))) {
2922 LOG (($verbose_pbm || $verbose_load),
2923 "not a GIF, JPG, or PNG" .
2924 (($body =~ m@<(base|html|head|body|script|table|a href)\b@i)
2925 ? " (looks like HTML)" : "") .
2927 $suppress_audit = 1;
2931 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
2932 # do this, the process doesn't die properly.
2933 if (!$verbose_pbm) {
2935 # We get a "giftopnm: got a 'Application Extension' extension"
2936 # warning any time it's an animgif.
2938 # Note that "giftopnm: EOF / read error on image data" is not
2939 # always a fatal error -- sometimes the image looks fine anyway.
2941 $cmd2 .= " 2>/dev/null";
2944 # There exist corrupted GIF and JPEG files that can make giftopnm and
2945 # djpeg lose their minds and go into a loop. So this gives those programs
2946 # a small timeout -- if they don't complete in time, kill them.
2952 local $SIG{ALRM} = sub {
2954 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
2955 kill ('TERM', $pid) if ($pid);
2960 if (($pid = open (my $pipe, "| $cmd2 > $output"))) {
2967 LOG ($verbose_exec, "awaiting $pid");
2969 LOG ($verbose_exec, "$pid completed");
2971 my $size = (stat($output))[7];
2972 $size = -1 unless defined($size);
2974 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
2978 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
2981 print STDERR blurb() . "$cmd failed: $!\n";
2985 die if ($@ && $@ ne "alarm\n"); # propagate errors
2999 # Same as the "ppmmake" command: creates a solid-colored PPM.
3000 # Does not understand the rgb.txt color names except "black" and "white".
3003 my ($outfile, $bgcolor, $w, $h) = @_;
3006 if ($bgcolor =~ m/^\#?([\dA-F][\dA-F])([\dA-F][\dA-F])([\dA-F][\dA-F])$/i ||
3007 $bgcolor =~ m/^\#?([\dA-F])([\dA-F])([\dA-F])$/i) {
3008 ($r, $g, $b) = (hex($1), hex($2), hex($3));
3009 } elsif ($bgcolor =~ m/^black$/i) {
3010 ($r, $g, $b) = (0, 0, 0);
3011 } elsif ($bgcolor =~ m/^white$/i) {
3012 ($r, $g, $b) = (0xFF, 0xFF, 0xFF);
3014 error ("unparsable color name: $bgcolor");
3017 my $pixel = pack('CCC', $r, $g, $b);
3018 my $bits = "P6\n$w $h\n255\n" . ($pixel x ($w * $h));
3020 open (my $out, '>', $outfile) || error ("$outfile: $!");
3026 sub pick_root_displayer() {
3030 # see "xscreensaver/hacks/webcollage-cocoa.m"
3031 return "echo COCOA LOAD ";
3034 foreach my $cmd (@root_displayers) {
3036 my ($name) = m/^([^ ]+)/;
3037 push @names, "\"$name\"";
3038 LOG ($verbose_exec, "looking for $name...");
3039 foreach my $dir (split (/:/, $ENV{PATH})) {
3040 LOG ($verbose_exec, " checking $dir/$name");
3041 return $cmd if (-x "$dir/$name");
3045 $names[$#names] = "or " . $names[$#names];
3046 error "none of: " . join (", ", @names) . " were found on \$PATH.";
3050 my $ppm_to_root_window_cmd = undef;
3053 sub x_or_pbm_output($) {
3054 my ($window_id) = @_;
3056 # Check for our helper program, to see whether we need to use PPM pipelines.
3058 $_ = "webcollage-helper";
3059 if (defined ($webcollage_helper) || which ($_)) {
3060 $webcollage_helper = $_ unless (defined($webcollage_helper));
3061 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
3062 $webcollage_helper .= " -v";
3064 LOG (($verbose_pbm || $verbose_load), "no $_ program");
3067 if ($cocoa_p && !defined ($webcollage_helper)) {
3068 error ("webcollage-helper not found in Cocoa-mode!");
3072 # make sure the various programs we execute exist, right up front.
3076 if (!defined($webcollage_helper)) {
3077 # Only need these others if we don't have the helper.
3079 "giftopnm", "pngtopnm", "djpeg",
3080 "pnmpaste", "pnmscale", "pnmcut");
3084 which ($_) || error "$_ not found on \$PATH.";
3087 # find a root-window displayer program.
3089 if (!$no_output_p) {
3090 $ppm_to_root_window_cmd = pick_root_displayer();
3093 if (defined ($window_id)) {
3094 error ("-window-id only works if xscreensaver-getimage is installed")
3095 unless ($ppm_to_root_window_cmd =~ m/^xscreensaver-getimage\b/);
3097 error ("unparsable window id: $window_id")
3098 unless ($window_id =~ m/^\d+$|^0x[\da-f]+$/i);
3099 $ppm_to_root_window_cmd =~ s/--?root\b/$window_id/ ||
3100 error ("unable to munge displayer: $ppm_to_root_window_cmd");
3103 if (!$img_width || !$img_height) {
3105 if (!defined ($window_id) &&
3106 defined ($ENV{XSCREENSAVER_WINDOW})) {
3107 $window_id = $ENV{XSCREENSAVER_WINDOW};
3110 if (!defined ($window_id)) {
3112 which ($_) || error "$_ not found on \$PATH.";
3114 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
3115 if (!defined($img_height)) {
3116 error "xdpyinfo failed.";
3118 } else { # we have a window id
3120 which ($_) || error "$_ not found on \$PATH.";
3121 $_ .= " -id $window_id";
3123 ($img_width, $img_height) = m/^\s*Width:\s*(\d+)\n\s*Height:\s*(\d+)\n/m;
3125 if (!defined($img_height)) {
3126 error "xwininfo failed.";
3131 my $bgcolor = "#000000";
3132 my $bgimage = undef;
3135 if ($background =~ m/^\#[0-9a-f]+$/i) {
3136 $bgcolor = $background;
3138 } elsif (-r $background) {
3139 $bgimage = $background;
3141 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
3142 error "not a color or readable file: $background";
3145 # default to assuming it's a color
3146 $bgcolor = $background;
3150 # Create the sold-colored base image.
3152 LOG ($verbose_pbm, "creating base image: ${img_width}x${img_height}");
3153 $_ = ppmmake ($image_ppm, $bgcolor, $img_width, $img_height);
3155 # Paste the default background image in the middle of it.
3161 open (my $imgf, '<', $bgimage) || error "couldn't open $bgimage: $!";
3162 local $/ = undef; # read entire file
3167 if ((@_ = gif_size ($body))) {
3169 $cmd = "giftopnm |";
3171 } elsif ((@_ = jpeg_size ($body))) {
3175 } elsif ((@_ = png_size ($body))) {
3177 $cmd = "pngtopnm |";
3179 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
3185 error "$bgimage is not a GIF, JPEG, PNG, or PPM.";
3188 my $x = int (($img_width - $iw) / 2);
3189 my $y = int (($img_height - $ih) / 2);
3191 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
3193 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
3194 open ($imgf, "| $cmd") || error "running $cmd: $!";
3198 LOG ($verbose_exec, "subproc exited normally.");
3199 rename ($image_tmp1, $image_ppm) ||
3200 error "renaming $image_tmp1 to $image_ppm: $!";
3206 my ($base, $img) = pick_image();
3207 my $source = $current_state;
3208 $current_state = "loadimage";
3210 my ($headers, $body) = get_document ($img, $base);
3212 paste_image ($base, $img, $body, $source);
3216 $current_state = "idle";
3217 $load_method = "none";
3219 unlink $image_tmp1, $image_tmp2;
3224 sub paste_image($$$$) {
3225 my ($base, $img, $body, $source) = @_;
3227 $current_state = "paste";
3229 $suppress_audit = 0;
3231 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
3235 # If we are using the webcollage-helper, then we do not need to convert this
3236 # image to a PPM. But, if we're using a filter command, we still must, since
3237 # that's what the filters expect (webcollage-helper can read PPMs, so that's
3240 if (defined ($webcollage_helper) &&
3241 !defined ($filter_cmd)) {
3243 ($iw, $ih) = image_size ($body);
3245 LOG (($verbose_pbm || $verbose_load),
3246 "not a GIF, JPG, or PNG" .
3247 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
3248 ? " (looks like HTML)" : "") .
3250 $suppress_audit = 1;
3255 open (my $out, '>', $image_tmp1) || error ("writing $image_tmp1: $!");
3256 (print $out $body) || error ("writing $image_tmp1: $!");
3257 close ($out) || error ("writing $image_tmp1: $!");
3260 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
3263 LOG ($verbose_pbm, "unable to make PBM from $img");
3268 record_success ($load_method, $img, $base);
3271 my $ow = $iw; # used only for error messages
3274 # don't just tack this onto the front of the pipeline -- we want it to
3275 # be able to change the size of the input image.
3278 LOG ($verbose_pbm, "running $filter_cmd");
3280 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
3282 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
3283 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3286 rename ($image_tmp2, $image_tmp1);
3288 # re-get the width/height in case the filter resized it.
3289 open (my $imgf, '<', $image_tmp1) || return 0;
3292 ($iw, $ih) = m/^(\d+) (\d+)$/;
3294 return 0 unless ($iw && $ih);
3297 my $target_w = $img_width; # max rectangle into which the image must fit
3298 my $target_h = $img_height;
3304 # Usually scale the image to fit on the screen -- but sometimes scale it
3305 # to fit on half or a quarter of the screen. (We do this by reducing the
3306 # size of the target rectangle.) Note that the image is not merely scaled
3307 # to fit; we instead cut the image in half repeatedly until it fits in the
3308 # target rectangle -- that gives a wider distribution of sizes.
3310 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; } # reduce target rect
3311 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
3313 if ($iw > $target_w || $ih > $target_h) {
3314 while ($iw > $target_w ||
3320 if ($iw <= 10 || $ih <= 10) {
3321 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
3325 LOG ($verbose_pbm, "scaling to ${iw}x$ih ($scale)");
3327 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
3331 my $src = $image_tmp1;
3333 my $crop_x = 0; # the sub-rectangle of the image
3334 my $crop_y = 0; # that we will actually paste.
3338 # The chance that we will randomly crop out a section of an image starts
3339 # out fairly low, but goes up for images that are very large, or images
3340 # that have ratios that make them look like banners (we try to avoid
3341 # banner images entirely, but they slip through when the IMG tags didn't
3342 # have WIDTH and HEIGHT specified.)
3344 my $crop_chance = 0.2;
3345 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
3346 $crop_chance += 0.2;
3348 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
3349 $crop_chance += 0.2;
3351 if ($min_ratio && ($iw * $min_ratio) > $ih) {
3352 $crop_chance += 0.7;
3355 if ($crop_chance > 0.1) {
3356 LOG ($verbose_pbm, "crop chance: $crop_chance");
3359 if (rand() < $crop_chance) {
3364 if ($crop_w > $min_width) {
3365 # if it's a banner, select the width linearly.
3366 # otherwise, select a bell.
3367 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
3370 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
3371 $crop_x = int (rand() * ($ow - $crop_w));
3373 if ($crop_h > $min_height) {
3374 # height always selects as a bell.
3375 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
3376 $crop_y = int (rand() * ($oh - $crop_h));
3379 if ($crop_x != 0 || $crop_y != 0 ||
3380 $crop_w != $iw || $crop_h != $ih) {
3382 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3386 # Where the image should logically land -- this might be negative.
3388 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
3389 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
3391 # if we have chosen to paste the image outside of the rectangle of the
3392 # screen, then we need to crop it.
3396 $x + $crop_w > $img_width ||
3397 $y + $crop_h > $img_height) {
3400 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
3402 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
3403 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
3405 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
3406 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
3409 # If any cropping needs to happen, add pnmcut.
3411 if ($crop_x != 0 || $crop_y != 0 ||
3412 $crop_w != $iw || $crop_h != $ih) {
3415 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
3416 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
3419 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
3421 $cmd .= " | pnmpaste - $x $y $image_ppm";
3423 $cmd =~ s@^ *\| *@@;
3425 if (defined ($webcollage_helper)) {
3426 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
3427 "$scale $opacity " .
3428 "$crop_x $crop_y $x $y " .
3433 # use a PPM pipeline
3435 $_ .= " < $image_tmp1 > $image_tmp2";
3439 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
3441 $_ .= " 2> /dev/null";
3444 my $rc = nontrapping_system ($_);
3446 if (defined ($webcollage_helper) && -z $image_ppm) {
3447 LOG (1, "failed command: \"$cmd\"");
3448 print STDERR "\naudit log:\n\n\n";
3449 print STDERR ("#" x 78) . "\n";
3450 print STDERR blurb() . "$image_ppm has zero size\n";
3452 print STDERR "\n\n";
3457 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
3458 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
3462 if (!defined ($webcollage_helper)) {
3463 rename ($image_tmp2, $image_ppm) || return;
3466 my $target = "$image_ppm";
3468 # don't just tack this onto the end of the pipeline -- we don't want it
3469 # to end up in $image_ppm, because we don't want the results to be
3472 if ($post_filter_cmd) {
3476 $target = $image_tmp1;
3477 if (!defined ($webcollage_helper)) {
3478 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3480 # Blah, my scripts need the JPEG data, but some other folks need
3481 # the PPM data -- what to do? Ignore the problem, that's what!
3482 # $cmd = "djpeg < $image_ppm | ($post_filter_cmd) > $target";
3483 $cmd = "($post_filter_cmd) < $image_ppm > $target";
3486 $rc = nontrapping_system ($cmd);
3488 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
3493 if (!$no_output_p) {
3494 my $tsize = (stat($target))[7];
3496 $cmd = "$ppm_to_root_window_cmd $target";
3498 # xv seems to hate being killed. it tends to forget to clean
3499 # up after itself, and leaves windows around and colors allocated.
3500 # I had this same problem with vidwhacker, and I'm not entirely
3501 # sure what I did to fix it. But, let's try this: launch xv
3502 # in the background, so that killing this process doesn't kill it.
3503 # it will die of its own accord soon enough. So this means we
3504 # start pumping bits to the root window in parallel with starting
3505 # the next network retrieval, which is probably a better thing
3508 $cmd .= " &" unless ($cocoa_p);
3510 $rc = nontrapping_system ($cmd);
3513 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
3518 LOG ($verbose_pbm, "$target size is $tsize");
3522 $source .= "-" . stats_of($source);
3523 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
3524 if ($verbose_imgmap);
3525 if ($imagemap_base) {
3526 update_imagemap ($base, $x, $y, $iw, $ih,
3527 $image_ppm, $img_width, $img_height);
3536 sub update_imagemap($$$$$$$$) {
3537 my ($url, $x, $y, $w, $h, $image_ppm, $image_width, $image_height) = @_;
3539 $current_state = "imagemap";
3541 my $max_areas = 200;
3543 $url = html_quote ($url);
3546 my $area = "<AREA SHAPE=RECT COORDS=\"$x,$y,$x2,$y2\" HREF=\"$url\">";
3547 unshift @imagemap_areas, $area; # put one on the front
3548 if ($#imagemap_areas >= $max_areas) {
3549 pop @imagemap_areas; # take one off the back.
3552 LOG ($verbose_pbm, "area: $x,$y,$x2,$y2 (${w}x$h)");
3554 my $map_name = $imagemap_base;
3555 $map_name =~ s@^.*/@@;
3556 $map_name = 'collage' if ($map_name eq '');
3558 my $imagemap_html = $imagemap_base . ".html";
3559 my $imagemap_jpg = $imagemap_base . ".jpg";
3561 if (!defined ($imagemap_html_tmp)) {
3562 $imagemap_html_tmp = $imagemap_html . sprintf (".%08x", rand(0xffffffff));
3563 $imagemap_jpg_tmp = $imagemap_jpg . sprintf (".%08x", rand(0xffffffff));
3566 # Read the imagemap html file (if any) to get a template.
3568 my $template_html = '';
3570 if (open (my $in, '<', $imagemap_html)) {
3571 local $/ = undef; # read entire file
3572 $template_html = <$in>;
3574 LOG ($verbose_pbm, "read template $imagemap_html");
3577 if ($template_html =~ m/^\s*$/s) {
3578 $template_html = ("<MAP NAME=\"$map_name\"></MAP>\n" .
3579 "<IMG SRC=\"$imagemap_base.jpg\"" .
3580 " USEMAP=\"$map_name\">\n");
3581 LOG ($verbose_pbm, "created dummy template");
3585 # Write the jpg to a tmp file
3589 if (defined ($webcollage_helper)) {
3590 $cmd = "cp -p $image_ppm $imagemap_jpg_tmp";
3592 $cmd = "cjpeg < $image_ppm > $imagemap_jpg_tmp";
3594 my $rc = nontrapping_system ($cmd);
3596 error ("imagemap jpeg failed: \"$cmd\"\n");
3600 # Write the html to a tmp file
3603 my $body = $template_html;
3604 my $areas = join ("\n\t", @imagemap_areas);
3605 my $map = ("<MAP NAME=\"$map_name\">\n\t$areas\n</MAP>");
3606 my $img = ("<IMG SRC=\"$imagemap_base.jpg\" " .
3608 "WIDTH=$image_width HEIGHT=$image_height " .
3609 "USEMAP=\"#$map_name\">");
3610 $body =~ s@(<MAP\s+NAME=\"[^\"]*\"\s*>).*?(</MAP>)@$map@is;
3611 $body =~ s@<IMG\b[^<>]*\bUSEMAP\b[^<>]*>@$img@is;
3613 # if there are magic webcollage spans in the html, update those too.
3616 my @st = stat ($imagemap_jpg_tmp);
3617 my $date = strftime("%d-%b-%Y %l:%M:%S %p %Z", localtime($st[9]));
3618 my $size = int(($st[7] / 1024) + 0.5) . "K";
3619 $body =~ s@(<SPAN\s+CLASS=\"webcollage_date\">).*?(</SPAN>)@$1$date$2@si;
3620 $body =~ s@(<SPAN\s+CLASS=\"webcollage_size\">).*?(</SPAN>)@$1$size$2@si;
3623 open (my $out, '>', $imagemap_html_tmp) || error ("$imagemap_html_tmp: $!");
3624 (print $out $body) || error ("$imagemap_html_tmp: $!");
3625 close ($out) || error ("$imagemap_html_tmp: $!");
3626 LOG ($verbose_pbm, "wrote $imagemap_html_tmp");
3629 # Rename the two tmp files to the real files
3631 rename ($imagemap_html_tmp, $imagemap_html) ||
3632 error "renaming $imagemap_html_tmp to $imagemap_html";
3633 LOG ($verbose_pbm, "wrote $imagemap_html");
3634 rename ($imagemap_jpg_tmp, $imagemap_jpg) ||
3635 error "renaming $imagemap_jpg_tmp to $imagemap_jpg";
3636 LOG ($verbose_pbm, "wrote $imagemap_jpg");
3640 # Figure out what the proxy server should be, either from environment
3641 # variables or by parsing the output of the (MacOS) program "scutil",
3642 # which tells us what the system-wide proxy settings are.
3646 if (! $http_proxy) {
3647 # historical suckage: the environment variable name is lower case.
3648 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
3651 if (defined ($http_proxy)) {
3652 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
3653 # historical suckage: allow "http://host:port" as well as "host:port".
3658 my $proxy_data = `scutil --proxy 2>/dev/null`;
3659 my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
3660 my ($port) = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
3661 # Note: this ignores the "ExceptionsList".
3663 $http_proxy = $server;
3664 $http_proxy .= ":$port" if $port;
3669 LOG ($verbose_net, "proxy server: $http_proxy");
3674 sub init_signals() {
3676 $SIG{HUP} = \&signal_cleanup;
3677 $SIG{INT} = \&signal_cleanup;
3678 $SIG{QUIT} = \&signal_cleanup;
3679 $SIG{ABRT} = \&signal_cleanup;
3680 $SIG{KILL} = \&signal_cleanup;
3681 $SIG{TERM} = \&signal_cleanup;
3683 # Need this so that if giftopnm dies, we don't die.
3684 $SIG{PIPE} = 'IGNORE';
3687 END { exit_cleanup(); }
3696 my $driftnet_cmd = 0;
3698 $current_state = "init";
3699 $load_method = "none";
3702 my $window_id = undef;
3704 while ($_ = $ARGV[0]) {
3706 if ($_ eq "-display" ||
3712 $ENV{DISPLAY} = shift @ARGV;
3713 } elsif ($_ eq "-root") {
3715 } elsif ($_ eq "-window-id" || $_ eq "--window-id") {
3716 $window_id = shift @ARGV;
3718 } elsif ($_ eq "-no-output") {
3720 } elsif ($_ eq "-urls-only") {
3723 } elsif ($_ eq "-cocoa") {
3725 } elsif ($_ eq "-imagemap") {
3726 $imagemap_base = shift @ARGV;
3728 } elsif ($_ eq "-verbose") {
3730 } elsif (m/^-v+$/) {
3731 $verbose += length($_)-1;
3732 } elsif ($_ eq "-delay") {
3733 $delay = shift @ARGV;
3734 } elsif ($_ eq "-timeout") {
3735 $http_timeout = shift @ARGV;
3736 } elsif ($_ eq "-filter") {
3737 $filter_cmd = shift @ARGV;
3738 } elsif ($_ eq "-filter2") {
3739 $post_filter_cmd = shift @ARGV;
3740 } elsif ($_ eq "-background" || $_ eq "-bg") {
3741 $background = shift @ARGV;
3742 } elsif ($_ eq "-size") {
3744 if (m@^(\d+)x(\d+)$@) {
3748 error "argument to \"-size\" must be of the form \"640x400\"";
3750 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
3751 $http_proxy = shift @ARGV;
3752 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
3753 $dict = shift @ARGV;
3754 } elsif ($_ eq "-opacity") {
3755 $opacity = shift @ARGV;
3756 error ("opacity must be between 0.0 and 1.0")
3757 if ($opacity <= 0 || $opacity > 1);
3758 } elsif ($_ eq "-driftnet" || $_ eq "--driftnet") {
3759 @search_methods = ( 100, "driftnet", \&pick_from_driftnet );
3760 if (! ($ARGV[0] =~ m/^-/)) {
3761 $driftnet_cmd = shift @ARGV;
3763 $driftnet_cmd = $default_driftnet_cmd;
3765 } elsif ($_ eq "-directory" || $_ eq "--directory") {
3766 @search_methods = ( 100, "local", \&pick_from_local_dir );
3767 if (! ($ARGV[0] =~ m/^-/)) {
3768 $local_dir = shift @ARGV;
3770 error ("local directory path must be set")
3772 } elsif ($_ eq "-fps") {
3773 # -fps only works on MacOS, via "webcollage-cocoa.m".
3774 # Ignore it if passed to this script in an X11 context.
3775 } elsif ($_ eq "-debug" || $_ eq "--debug") {
3776 my $which = shift @ARGV;
3777 my @rest = @search_methods;
3780 my $pct = shift @rest;
3781 my $name = shift @rest;
3782 my $tfn = shift @rest;
3784 if ($name eq $which) {
3785 @search_methods = (100, $name, $tfn);
3790 error "no such search method as \"$which\"" unless ($ok);
3791 LOG (1, "DEBUG: using only \"$which\"");
3794 print STDERR "$copyright\nusage: $progname " .
3795 "[-root] [-display dpy] [-verbose] [-debug which]\n" .
3796 "\t\t [-timeout secs] [-delay secs] [-size WxH]\n" .
3797 "\t\t [-no-output] [-urls-only] [-imagemap filename]\n" .
3798 "\t\t [-background color] [-opacity f]\n" .
3799 "\t\t [-filter cmd] [-filter2 cmd]\n" .
3800 "\t\t [-dictionary dictionary-file] [-http-proxy host[:port]]\n" .
3801 "\t\t [-driftnet [driftnet-program-and-args]]\n" .
3802 "\t\t [-directory local-image-directory]\n" .
3808 if (!$root_p && !$no_output_p && !$cocoa_p) {
3809 print STDERR $copyright;
3810 error "the -root argument is mandatory (for now.)";
3813 if (!$no_output_p && !$cocoa_p && !$ENV{DISPLAY}) {
3814 error "\$DISPLAY is not set.";
3818 if ($verbose == 1) {
3819 $verbose_imgmap = 1;
3820 $verbose_warnings = 1;
3822 } elsif ($verbose == 2) {
3823 $verbose_imgmap = 1;
3824 $verbose_warnings = 1;
3827 } elsif ($verbose == 3) {
3828 $verbose_imgmap = 1;
3829 $verbose_warnings = 1;
3831 $verbose_filter = 1;
3833 } elsif ($verbose == 4) {
3834 $verbose_imgmap = 1;
3835 $verbose_warnings = 1;
3837 $verbose_filter = 1;
3840 } elsif ($verbose == 5) {
3841 $verbose_imgmap = 1;
3842 $verbose_warnings = 1;
3844 $verbose_filter = 1;
3848 } elsif ($verbose == 6) {
3849 $verbose_imgmap = 1;
3850 $verbose_warnings = 1;
3852 $verbose_filter = 1;
3857 } elsif ($verbose >= 7) {
3858 $verbose_imgmap = 1;
3859 $verbose_warnings = 1;
3861 $verbose_filter = 1;
3869 error ("$dict does not exist") unless (-f $dict);
3875 if ($imagemap_base && !($img_width && $img_height)) {
3876 error ("-size WxH is required with -imagemap");
3879 if (defined ($local_dir)) {
3880 $_ = "xscreensaver-getimage-file";
3881 which ($_) || error "$_ not found on \$PATH.";
3887 spawn_driftnet ($driftnet_cmd) if ($driftnet_cmd);
3892 x_or_pbm_output ($window_id);