From http://www.jwz.org/xscreensaver/xscreensaver-5.40.tar.gz
[xscreensaver] / driver / xscreensaver-getimage-file
1 #!/usr/bin/perl -w
2 # Copyright © 2001-2018 Jamie Zawinski <jwz@jwz.org>.
3 #
4 # Permission to use, copy, modify, distribute, and sell this software and its
5 # documentation for any purpose is hereby granted without fee, provided that
6 # the above copyright notice appear in all copies and that both that
7 # copyright notice and this permission notice appear in supporting
8 # documentation.  No representations are made about the suitability of this
9 # software for any purpose.  It is provided "as is" without express or 
10 # implied warranty.
11 #
12 # This program chooses a random file from under the given directory, and
13 # prints its name.  The file will be an image file whose dimensions are
14 # larger than a certain minimum size.
15 #
16 # If the directory is a URL, it is assumed to be an RSS or Atom feed.
17 # The images from that feed will be downloaded, cached, and selected from
18 # at random.  The feed will be re-polled periodically, as needed.
19 #
20 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
21 # the image to manipulate by running the "xscreensaver-getimage" program.
22 #
23 # Under X11, the "xscreensaver-getimage" program invokes this script,
24 # depending on the value of the "chooseRandomImages" and "imageDirectory"
25 # settings in the ~/.xscreensaver file (or .../app-defaults/XScreenSaver).
26 # The screen savers invoke "xscreensaver-getimage" via utils/grabclient.c,
27 # which then invokes this script.
28 #
29 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
30 # directly from utils/grabclient.c.
31 #
32 # Created: 12-Apr-01.
33
34 require 5;
35 #use diagnostics;       # Fails on some MacOS 10.5 systems
36 use strict;
37
38 use POSIX;
39 use Fcntl;
40
41 use Fcntl ':flock'; # import LOCK_* constants
42
43 use POSIX ':fcntl_h';                           # S_ISDIR was here in Perl 5.6
44 import Fcntl ':mode' unless defined &S_ISUID;   # but it is here in Perl 5.8
45         # but in Perl 5.10, both of these load, and cause errors!
46         # So we have to check for S_ISUID instead of S_ISDIR?  WTF?
47
48 use Digest::MD5 qw(md5_base64);
49
50 # Some Linux systems don't install LWP by default!
51 # Only error out if we're actually loading a URL instead of local data.
52 BEGIN { eval 'use LWP::Simple;' }
53
54
55 my $progname = $0; $progname =~ s@.*/@@g;
56 my ($version) = ('$Revision: 1.52 $' =~ m/\s(\d[.\d]+)\s/s);
57
58 my $verbose = 0;
59
60 # Whether to use MacOS X's Spotlight to generate the list of files.
61 # When set to -1, uses Spotlight if "mdfind" exists.
62 #
63 # (In my experience, this isn't actually any faster, and might not find
64 # everything if your Spotlight index is out of date, which happens often.)
65 #
66 my $use_spotlight_p = 0;
67
68 # Whether to cache the results of the last run.
69 #
70 my $cache_p = 1;
71
72 # Regenerate the cache if it is older than this many seconds.
73 #
74 my $cache_max_age = 60 * 60 * 3;   # 3 hours
75
76 # Re-poll RSS/Atom feeds when local copy is older than this many seconds.
77 #
78 my $feed_max_age = $cache_max_age;
79
80
81 # This matches files that we are allowed to use as images (case-insensitive.)
82 # Anything not matching this is ignored.  This is so you can point your
83 # imageDirectory at directory trees that have things other than images in
84 # them, but it assumes that you gave your images sensible file extensions.
85 #
86 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
87                        'tif', 'tiff', 'xbm', 'xpm');
88 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
89
90 # This matches file extensions that might occur in an image directory,
91 # and that are never used in the name of a subdirectory.  This is an
92 # optimization that prevents us from having to stat() those files to
93 # tell whether they are directories or not.  (It speeds things up a
94 # lot.  Don't give your directories stupid names.)
95 #
96 my @nondir_extensions = ('ai', 'bmp', 'bz2', 'cr2', 'crw', 'db',
97    'dmg', 'eps', 'gz', 'hqx', 'htm', 'html', 'icns', 'ilbm', 'mov',
98    'nef', 'pbm', 'pdf', 'php', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh',
99    'shtml', 'tar', 'tgz', 'thb', 'txt', 'xcf', 'xmp', 'Z', 'zip' );
100 my $nondir_re = '\.(' . join("|", @nondir_extensions) . ')$';
101
102
103 # JPEG, GIF, and PNG files that are are smaller than this are rejected:
104 # this is so that you can use an image directory that contains both big
105 # images and thumbnails, and have it only select the big versions.
106 # But, if all of your images are smaller than this, all will be rejected.
107 #
108 my $min_image_width  = 500;
109 my $min_image_height = 500;
110
111 my @all_files = ();         # list of "good" files we've collected
112 my %seen_inodes;            # for breaking recursive symlink loops
113
114 # For diagnostic messages:
115 #
116 my $dir_count = 1;          # number of directories seen
117 my $stat_count = 0;         # number of files/dirs stat'ed
118 my $skip_count_unstat = 0;  # number of files skipped without stat'ing
119 my $skip_count_stat = 0;    # number of files skipped after stat
120
121 my $config_file = $ENV{HOME} . "/.xscreensaver";
122 my $image_directory = undef;
123
124
125 sub find_all_files($);
126 sub find_all_files($) {
127   my ($dir) = @_;
128
129   print STDERR "$progname:  + reading dir $dir/...\n" if ($verbose > 1);
130
131   my $dd;
132   if (! opendir ($dd, $dir)) {
133     print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
134     return;
135   }
136   my @files = readdir ($dd);
137   closedir ($dd);
138
139   my @dirs = ();
140
141   foreach my $file (@files) {
142     next if ($file =~ m/^\./);      # silently ignore dot files/dirs
143
144     if ($file =~ m/[~%\#]$/) {      # ignore backup files (and dirs...)
145       $skip_count_unstat++;
146       print STDERR "$progname:  - skip file  $file\n" if ($verbose > 1);
147     }
148
149     $file = "$dir/$file";
150
151     if ($file =~ m/$good_file_re/io) {
152       #
153       # Assume that files ending in .jpg exist and are not directories.
154       #
155       push @all_files, $file;
156       print STDERR "$progname:  - found file $file\n" if ($verbose > 1);
157
158     } elsif ($file =~ m/$nondir_re/io) {
159       #
160       # Assume that files ending in .html are not directories.
161       #
162       $skip_count_unstat++;
163       print STDERR "$progname: -- skip file  $file\n" if ($verbose > 1);
164
165     } else {
166       #
167       # Now we need to stat the file to see if it's a subdirectory.
168       #
169       # Note: we could use the trick of checking "nlinks" on the parent
170       # directory to see if this directory contains any subdirectories,
171       # but that would exclude any symlinks to directories.
172       #
173       my @st = stat($file);
174       my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
175           $atime,$mtime,$ctime,$blksize,$blocks) = @st;
176
177       $stat_count++;
178
179       if ($#st == -1) {
180         if ($verbose) {
181           my $ll = readlink $file;
182           if (defined ($ll)) {
183             print STDERR "$progname: + dangling symlink: $file -> $ll\n";
184           } else {
185             print STDERR "$progname: + unreadable: $file\n";
186           }
187         }
188         next;
189       }
190
191       next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
192       $seen_inodes{"$dev:$ino"} = 1;
193
194       if (S_ISDIR($mode)) {
195         push @dirs, $file;
196         $dir_count++;
197         print STDERR "$progname:  + found dir  $file\n" if ($verbose > 1);
198
199       } else {
200         $skip_count_stat++;
201         print STDERR "$progname:  + skip file  $file\n" if ($verbose > 1);
202       }
203     }
204   }
205
206   foreach (@dirs) {
207     find_all_files ($_);
208   }
209 }
210
211
212 sub spotlight_all_files($) {
213   my ($dir) = @_;
214
215   my @terms = ();
216   # "public.image" matches all (indexed) images, including Photoshop, etc.
217 #  push @terms, "kMDItemContentTypeTree == 'public.image'";
218   foreach (@good_extensions) {
219
220     # kMDItemFSName hits the file system every time: much worse than "find".
221 #    push @terms, "kMDItemFSName == '*.$_'";
222
223     # kMDItemDisplayName matches against the name in the Spotlight index,
224     # but won't find files that (for whatever reason) didn't get indexed.
225     push @terms, "kMDItemDisplayName == '*.$_'";
226   }
227
228   $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi;  # quote for sh
229   my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
230
231   print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
232   @all_files = split (/[\r\n]+/, `$cmd`);
233 }
234
235
236 # If we're using cacheing, read the cache file and return its contents,
237 # if any.  This also holds an exclusive lock on the cache file, which 
238 # has the additional benefit that if two copies of this program are
239 # running at once, one will wait for the other, instead of both of
240 # them spanking the same file system at the same time.
241 #
242 my $cache_fd = undef;
243 my $cache_file_name = undef;
244 my $read_cache_p = 0;
245
246 sub read_cache($) {
247   my ($dir) = @_;
248
249   return () unless ($cache_p);
250
251   my $dd = "$ENV{HOME}/Library/Caches";    # MacOS location
252   if (-d $dd) {
253     $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
254   } elsif (-d "$ENV{HOME}/.cache") {       # Gnome "FreeDesktop XDG" location
255     $dd = "$ENV{HOME}/.cache/xscreensaver";
256     if (! -d $dd) { mkdir ($dd) || error ("mkdir $dd: $!"); }
257     $cache_file_name = "$dd/xscreensaver-getimage.cache"
258   } elsif (-d "$ENV{HOME}/tmp") {          # If ~/tmp/ exists, use it.
259     $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
260   } else {
261     $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
262   }
263
264   print STDERR "$progname: awaiting lock: $cache_file_name\n"
265     if ($verbose > 1);
266
267   my $file = $cache_file_name;
268   open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
269   flock ($cache_fd, LOCK_EX)     || error ("unable to lock $file: $!");
270   seek ($cache_fd, 0, 0)         || error ("unable to rewind $file: $!");
271
272   my $mtime = (stat($cache_fd))[9];
273
274   if ($mtime + $cache_max_age < time) {
275     print STDERR "$progname: cache is too old\n" if ($verbose);
276     return ();
277   }
278
279   my $odir = <$cache_fd>;
280   $odir =~ s/[\r\n]+$//s if defined ($odir);
281   if (!defined ($odir) || ($dir ne $odir)) {
282     print STDERR "$progname: cache is for $odir, not $dir\n"
283       if ($verbose && $odir);
284     return ();
285   }
286
287   my @files = ();
288   while (<$cache_fd>) { 
289     s/[\r\n]+$//s;
290     push @files, "$odir/$_";
291   }
292
293   print STDERR "$progname: " . ($#files+1) . " files in cache\n"
294     if ($verbose);
295
296   $read_cache_p = 1;
297   return @files;
298 }
299
300
301 sub write_cache($) {
302   my ($dir) = @_;
303
304   return unless ($cache_p);
305
306   # If we read the cache, just close it without rewriting it.
307   # If we didn't read it, then write it now.
308
309   if (! $read_cache_p) {
310
311     truncate ($cache_fd, 0) ||
312       error ("unable to truncate $cache_file_name: $!");
313     seek ($cache_fd, 0, 0) ||
314       error ("unable to rewind $cache_file_name: $!");
315
316     if ($#all_files >= 0) {
317       print $cache_fd "$dir\n";
318       foreach (@all_files) {
319         my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
320         $f =~ s@^\Q$dir/@@so || die;  # remove $dir from front
321         print $cache_fd "$f\n";
322       }
323     }
324
325     print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
326       if ($verbose);
327   }
328
329   flock ($cache_fd, LOCK_UN) ||
330     error ("unable to unlock $cache_file_name: $!");
331   close ($cache_fd);
332   $cache_fd = undef;
333 }
334
335
336 sub html_unquote($) {
337   my ($h) = @_;
338
339   # This only needs to handle entities that occur in RSS, not full HTML.
340   my %ent = ( 'amp' => '&', 'lt' => '<', 'gt' => '>', 
341               'quot' => '"', 'apos' => "'" );
342   $h =~ s/(&(\#)?([[:alpha:]\d]+);?)/
343     {
344      my ($o, $c) = ($1, $3);
345      if (! defined($2)) {
346        $c = $ent{$c};                   # for &lt;
347      } else {
348        if ($c =~ m@^x([\dA-F]+)$@si) {  # for &#x41;
349          $c = chr(hex($1));
350        } elsif ($c =~ m@^\d+$@si) {     # for &#65;
351          $c = chr($c);
352        } else {
353          $c = undef;
354        }
355      }
356      ($c || $o);
357     }
358    /gexi;
359   return $h;
360 }
361
362
363
364 # Figure out what the proxy server should be, either from environment
365 # variables or by parsing the output of the (MacOS) program "scutil",
366 # which tells us what the system-wide proxy settings are.
367 #
368 sub set_proxy($) {
369   my ($ua) = @_;
370
371   my $proxy_data = `scutil --proxy 2>/dev/null`;
372   foreach my $proto ('http', 'https') {
373     my ($server) = ($proxy_data =~ m/\b${proto}Proxy\s*:\s*([^\s]+)/si);
374     my ($port)   = ($proxy_data =~ m/\b${proto}Port\s*:\s*([^\s]+)/si);
375     my ($enable) = ($proxy_data =~ m/\b${proto}Enable\s*:\s*([^\s]+)/si);
376
377     if ($server && $enable) {
378       # Note: this ignores the "ExceptionsList".
379       my $proto2 = 'http';
380       $ENV{"${proto}_proxy"} = ("${proto2}://" . $server .
381                                 ($port ? ":$port" : "") . "/");
382       print STDERR "$progname: MacOS $proto proxy: " .
383                    $ENV{"${proto}_proxy"} . "\n"
384         if ($verbose > 2);
385     }
386   }
387
388   $ua->env_proxy();
389 }
390
391
392 sub init_lwp() {
393   if (! defined ($LWP::Simple::ua)) {
394     error ("\n\n\tPerl is broken. Do this to repair it:\n" .
395            "\n\tsudo cpan LWP::Simple LWP::Protocol::https Mozilla::CA\n");
396   }
397   set_proxy ($LWP::Simple::ua);
398 }
399
400
401 sub sanity_check_lwp() {
402   my $url1 = 'https://www.mozilla.org/';
403   my $url2 =  'http://www.mozilla.org/';
404   my $body = (LWP::Simple::get($url1) || '');
405   if (length($body) < 10240) {
406     my $err = "";
407     $body = (LWP::Simple::get($url2) || '');
408     if (length($body) < 10240) {
409       $err = "Perl is broken: neither HTTP nor HTTPS URLs work.";
410     } else {
411       $err = "Perl is broken: HTTP URLs work but HTTPS URLs don't.";
412     }
413     $err .= "\nMaybe try: sudo cpan -f Mozilla::CA LWP::Protocol::https";
414     $err =~ s/^/\t/gm;
415     error ("\n\n$err\n");
416   }
417 }
418
419
420 # If the URL does not already end with an extension appropriate for the
421 # content-type, add it after a "#" search.
422 #
423 # This is for when we know the content type of the URL, but the URL is
424 # some crazy thing without an extension. The files on disk need to have
425 # proper extensions.
426 #
427 sub force_extension($$) {
428   my ($url, $ct) = @_;
429   return $url unless (defined($url) && defined($ct));
430   my ($ext) = ($ct =~ m@^image/([-a-z\d]+)@si);
431   return $url unless $ext;
432   $ext = lc($ext);
433   $ext = 'jpg' if ($ext eq 'jpeg');
434   return $url if ($url =~ m/\.$ext$/si);
435   return "$url#.$ext";
436 }
437
438
439 # Returns a list of the image enclosures in the RSS or Atom feed.
440 # Elements of the list are references, [ "url", "guid" ].
441 #
442 sub parse_feed($);
443 sub parse_feed($) {
444   my ($url) = @_;
445
446   init_lwp();
447   $LWP::Simple::ua->agent ("$progname/$version");
448   $LWP::Simple::ua->timeout (10);  # bail sooner than the default of 3 minutes
449
450
451   # Half the time, random Linux systems don't have Mozilla::CA installed,
452   # which results in "Can't verify SSL peers without knowning which
453   # Certificate Authorities to trust".
454   #
455   # In xscreensaver-text we just disabled certificate checks. However,
456   # malicious images really do exist, so for xscreensaver-getimage-file,
457   # let's actually require that SSL be installed properly.
458
459   print STDERR "$progname: loading $url\n" if ($verbose);
460   my $body = (LWP::Simple::get($url) || '');
461
462   if ($body !~ m@^\s*<(\?xml|rss)\b@si) {
463     # Not an RSS/Atom feed.  Try RSS autodiscovery.
464
465     # (Great news, everybody: Flickr no longer provides RSS for "Sets",
466     # only for "Photostreams", and only the first 20 images of those.
467     # Thanks, assholes.)
468
469     if ($body =~ m/^\s*$/s) {
470       sanity_check_lwp();
471       error ("null response: $url");
472     }
473
474     error ("not an RSS or Atom feed, or HTML: $url")
475       unless ($body =~ m@<(HEAD|BODY|A|IMG)\b@si);
476
477     # Find the first <link> with RSS or Atom in it, and use that instead.
478
479     $body =~ s@<LINK\s+([^<>]*)>@{
480       my $p = $1;
481       if ($p =~ m! \b REL  \s* = \s* ['"]? alternate \b!six &&
482           $p =~ m! \b TYPE \s* = \s* ['"]? application/(atom|rss) !six &&
483           $p =~ m! \b HREF \s* = \s* ['"]  ( [^<>'"]+ ) !six
484          ) {
485         my $u2 = html_unquote ($1);
486         if ($u2 =~ m!^/!s) {
487           my ($h) = ($url =~ m!^([a-z]+://[^/]+)!si);
488           $u2 = "$h$u2";
489         }
490         print STDERR "$progname: found feed: $u2\n"
491           if ($verbose);
492         return parse_feed ($u2);
493       }
494       '';
495     }@gsexi;
496
497     error ("no RSS or Atom feed for HTML page: $url");
498   }
499
500
501   $body =~ s@(<ENTRY|<ITEM)@\001$1@gsi;
502   my @items = split(/\001/, $body);
503   shift @items;
504
505   my @imgs = ();
506   my %ids;
507
508   foreach my $item (@items) {
509     my $iurl = undef;
510     my $id = undef;
511
512     # First look for <link rel="enclosure" href="...">
513     #
514     if (! $iurl) {
515       foreach my $link ($item =~ m@<LINK[^<>]*>@gsi) {
516         last if $iurl;
517         my ($href) = ($link =~ m/\bHREF\s*=\s*[\"\']([^<>\'\"]+)/si);
518         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
519         my ($rel)  = ($link =~ m/\bREL\s*=\s*[\"\']?([^<>\'\"]+)/si);
520         $href = undef unless (lc($rel || '') eq 'enclosure');
521         $href = undef if ($type && $type !~ m@^image/@si);  # omit videos
522         $iurl = html_unquote($href) if $href;
523         $iurl = force_extension ($iurl, $type);
524       }
525     }
526
527     # Then look for <media:content url="...">
528     #
529     if (! $iurl) {
530       foreach my $link ($item =~ m@<MEDIA:CONTENT[^<>]*>@gsi) {
531         last if $iurl;
532         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
533         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
534         my ($med)  = ($link =~ m/\bMEDIUM\s*=\s*[\"\']?([^<>\'\"]+)/si);
535         $type = 'image/jpeg' if (!$type && lc($med || '') eq 'image');
536         $href = undef if ($type && $type !~ m@^image/@si);  # omit videos
537         $iurl = html_unquote($href) if $href;
538         $iurl = force_extension ($iurl, $type);
539       }
540     }
541
542     # Then look for <enclosure url="..."/> 
543     #
544     if (! $iurl) {
545       foreach my $link ($item =~ m@<ENCLOSURE[^<>]*>@gsi) {
546         last if $iurl;
547         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
548         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
549         $href = undef if ($type && $type !~ m@^image/@si);  # omit videos
550         $iurl = html_unquote($href) if ($href);
551         $iurl = force_extension ($iurl, $type);
552       }
553     }
554
555     # Ok, maybe there's an image in the <url> field?
556     #
557     if (! $iurl) {
558       foreach my $link ($item =~ m@<URL\b[^<>]*>([^<>]*)@gsi) {
559         last if $iurl;
560         my $u2 = $1;
561         $iurl = html_unquote($u2) if ($u2 =~ m/$good_file_re/io);
562         if (! $iurl) {
563           my $u3 = $u2;
564           $u3 =~ s/#.*$//gs;
565           $u3 =~ s/[?&].*$//gs;
566           $iurl = html_unquote($u2) if ($u3 =~ m/$good_file_re/io);
567         }
568       }
569     }
570
571     # Then look for <content:encoded> or <description>... with an
572     # <img src="..."> inside. If more than one image, take the first.
573     #
574     foreach my $t ('content:encoded', 'description') {
575       last if $iurl;
576       foreach my $link ($item =~ m@<$t[^<>]*>(.*?)</$t>@gsi) {
577         last if $iurl;
578         my $desc = $1;
579         if ($desc =~ m@<!\[CDATA\[\s*(.*?)\s*\]\]>@gs) {
580           $desc = $1;
581         } else {
582           $desc = html_unquote($desc);
583         }
584         my ($href) = ($desc =~ m@<IMG[^<>]*\bSRC=[\"\']?([^\"\'<>]+)@si);
585         $iurl = html_unquote($href) if ($href);
586         # If IMG SRC has a bogus extension, pretend it's a JPEG.
587         $iurl = force_extension ($iurl, 'image/jpeg')
588           if ($iurl && $iurl !~ m/$good_file_re/io);
589       }
590     }
591
592     # Find a unique ID for this image, to defeat image farms.
593     # First look for <id>...</id>
594     ($id) = ($item =~ m!<ID\b[^<>]*>\s*([^<>]+?)\s*</ID>!si) unless $id;
595
596     # Then look for <guid isPermaLink=...> ... </guid>
597     ($id) = ($item =~ m!<GUID\b[^<>]*>\s*([^<>]+?)\s*</GUID>!si) unless $id;
598
599     # Then look for <link> ... </link>
600     ($id) = ($item =~ m!<LINK\b[^<>]*>\s*([^<>]+?)\s*</LINK>!si) unless $id;
601
602     # If we only have a GUID or LINK, but it's an image, use that.
603     $iurl = $id if (!$iurl && $id && $id =~ m/$good_file_re/io);
604
605     if ($iurl) {
606       $id = $iurl unless $id;
607       my $o = $ids{$id};
608       if (! $o) {
609         $ids{$id} = $iurl;
610         my @P = ($iurl, $id);
611         push @imgs, \@P;
612       } elsif ($iurl ne $o) {
613         print STDERR "$progname: WARNING: dup ID \"$id\"" .
614                      " for \"$o\" and \"$iurl\"\n";
615       }
616     }
617   }
618
619   return @imgs;
620 }
621
622
623 # Like md5_base64 but uses filename-safe characters.
624 #
625 sub md5_file($) {
626   my ($s) = @_;
627   $s = md5_base64($s);
628   $s =~ s@[/]@_@gs;
629   $s =~ s@[+]@-@gs;
630   return $s;
631 }
632
633
634 # expands the first URL relative to the second.
635 #
636 sub expand_url($$) {
637   my ($url, $base) = @_;
638
639   $url =~ s/^\s+//gs;  # lose whitespace at front and back
640   $url =~ s/\s+$//gs;
641
642   if (! ($url =~ m/^[a-z]+:/)) {
643
644     $base =~ s@(\#.*)$@@;       # strip anchors
645     $base =~ s@(\?.*)$@@;       # strip arguments
646     $base =~ s@/[^/]*$@/@;      # take off trailing file component
647
648     my $tail = '';
649     if ($url =~ s@(\#.*)$@@) { $tail = $1; }         # save anchors
650     if ($url =~ s@(\?.*)$@@) { $tail = "$1$tail"; }  # save arguments
651
652     my $base2 = $base;
653
654     $base2 =~ s@^([a-z]+:/+[^/]+)/.*@$1@        # if url is an absolute path
655       if ($url =~ m@^/@);
656
657     my $ourl = $url;
658
659     $url = $base2 . $url;
660     $url =~ s@/\./@/@g;                         # expand "."
661     1 while ($url =~ s@/[^/]+/\.\./@/@s);       # expand ".."
662
663     $url .= $tail;                              # put anchors/args back
664
665     print STDERR "$progname: relative URL: $ourl --> $url\n"
666       if ($verbose > 1);
667
668   } else {
669     print STDERR "$progname: absolute URL: $url\n"
670       if ($verbose > 2);
671   }
672
673   return $url;
674 }
675
676
677 # Given the URL of an image, download it into the given directory
678 # and return the file name.
679 #
680 sub download_image($$$) {
681   my ($url, $uid, $dir) = @_;
682
683   my $url2 = $url;
684   $url2 =~ s/\#.*$//s;          # Omit search terms after file extension
685   $url2 =~ s/\?.*$//s;
686   my ($ext) = ($url  =~ m@\.([a-z\d]+)$@si);
687      ($ext) = ($url2 =~ m@\.([a-z\d]+)$@si) unless $ext;
688
689   # If the feed hasn't put a sane extension on their URLs, nothing's going
690   # to work. This code assumes that file names have extensions, even the
691   # ones in the cache directory.
692   #
693   if (! $ext) {
694     print STDERR "$progname: skipping extensionless URL: $url\n"
695       if ($verbose > 1);
696     return undef;
697   }
698
699   # Don't bother downloading files that we will reject anyway.
700   #
701   if (! ($url  =~ m/$good_file_re/io ||
702          $url2 =~ m/$good_file_re/io)) {
703     print STDERR "$progname: skipping non-image URL: $url\n"
704       if ($verbose > 1);
705     return undef;
706   }
707
708   my $file = md5_file ($uid);
709   $file .= '.' . lc($ext) if $ext;
710
711   # Don't bother doing If-Modified-Since to see if the URL has changed.
712   # If we have already downloaded it, assume it's good.
713   if (-f "$dir/$file") {
714     print STDERR "$progname: exists: $dir/$file for $uid / $url\n" 
715       if ($verbose > 1);
716     return $file;
717   }
718
719   # Special-case kludge for Flickr:
720   # Their RSS feeds sometimes include only the small versions of the images.
721   # So if the URL ends in one of the "small-size" letters, change it to "b".
722   #
723   #     _o  orig,  1600 +
724   #     _k  large, 2048 max
725   #     _h  large, 1600 max
726   #     _b  large, 1024 max
727   #     _c  medium, 800 max
728   #     _z  medium, 640 max
729   #     ""  medium, 500 max
730   #     _n  small,  320 max
731   #     _m  small,  240 max
732   #     _t  thumb,  100 max
733   #     _q  square, 150x150
734   #     _s  square,  75x75
735   #
736   # Note: if we wanted to get the _k or _o version instead of the _b or _h
737   # version, we'd need to crack the DRM -- which is easy: see crack_secret
738   # in "https://www.jwz.org/hacks/galdown".
739   #
740   $url =~ s@_[sqtmnzc](\.[a-z]+)$@_b$1@si
741     if ($url =~ m@^https?://[^/?#&]*?flickr\.com/@si);
742
743   print STDERR "$progname: downloading: $dir/$file for $uid / $url\n" 
744     if ($verbose > 1);
745   init_lwp();
746   $LWP::Simple::ua->agent ("$progname/$version");
747
748   $url =~ s/\#.*$//s;           # Omit search terms
749   my $status = LWP::Simple::mirror ($url, "$dir/$file");
750   if (!LWP::Simple::is_success ($status)) {
751     print STDERR "$progname: error $status: $url\n";   # keep going
752   }
753
754   return $file;
755 }
756
757
758 sub mirror_feed($) {
759   my ($url) = @_;
760
761   if ($url !~ m/^https?:/si) {   # not a URL: local directory.
762     return (undef, $url);
763   }
764
765   my $dir = "$ENV{HOME}/Library/Caches";    # MacOS location
766   if (-d $dir) {
767     $dir = "$dir/org.jwz.xscreensaver.feeds";
768   } elsif (-d "$ENV{HOME}/.cache") {       # Gnome "FreeDesktop XDG" location
769     $dir = "$ENV{HOME}/.cache/xscreensaver";
770     if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
771     $dir .= "/feeds";
772     if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
773   } elsif (-d "$ENV{HOME}/tmp") {          # If ~/tmp/ exists, use it.
774     $dir = "$ENV{HOME}/tmp/.xscreensaver-feeds";
775   } else {
776     $dir = "$ENV{HOME}/.xscreensaver-feeds";
777   }
778
779   if (! -d $dir) {
780     mkdir ($dir) || error ("mkdir $dir: $!");
781     print STDERR "$progname: mkdir $dir/\n" if ($verbose);
782   }
783
784   # MD5 for directory name to use for cache of a feed URL.
785   $dir .= '/' . md5_file ($url);
786
787   if (! -d $dir) {
788     mkdir ($dir) || error ("mkdir $dir: $!");
789     print STDERR "$progname: mkdir $dir/ for $url\n" if ($verbose);
790   }
791
792   # At this point, we have the directory corresponding to this URL.
793   # Now check to see if the files in it are up to date, and download
794   # them if not.
795
796   my $stamp = '.timestamp';
797   my $lock = "$dir/$stamp";
798
799   print STDERR "$progname: awaiting lock: $lock\n"
800     if ($verbose > 1);
801
802   my $mtime = ((stat($lock))[9]) || 0;
803
804   my $lock_fd;
805   open ($lock_fd, '+>>', $lock) || error ("unable to write $lock: $!");
806   flock ($lock_fd, LOCK_EX)     || error ("unable to lock $lock: $!");
807   seek ($lock_fd, 0, 0)         || error ("unable to rewind $lock: $!");
808
809   my $poll_p = ($mtime + $feed_max_age < time);
810
811   # --no-cache cmd line arg means poll again right now.
812   $poll_p = 1 unless ($cache_p);
813
814   # Even if the cache is young, make sure there is at least one file,
815   # and re-check if not.
816   #
817   if (! $poll_p) {
818     my $count = 0;
819     opendir (my $dirh, $dir) || error ("$dir: $!");
820     foreach my $f (readdir ($dirh)) {
821       next if ($f =~ m/^\./s);
822       $count++;
823       last;
824     }
825     closedir $dirh;
826
827     if ($count <= 0) {
828       print STDERR "$progname: no image files in cache of $url\n"
829         if ($verbose);
830       $poll_p = 1;
831     }
832   }
833
834   if ($poll_p) {
835
836     print STDERR "$progname: loading $url\n" if ($verbose);
837
838     my %files;
839     opendir (my $dirh, $dir) || error ("$dir: $!");
840     foreach my $f (readdir ($dirh)) {
841       next if ($f eq '.' || $f eq '..');
842       $files{$f} = 0;  # 0 means "file exists, should be deleted"
843     }
844     closedir $dirh;
845
846     $files{$stamp} = 1;
847
848     # Download each image currently in the feed.
849     #
850     my $count = 0;
851     my @urls = parse_feed ($url);
852     print STDERR "$progname: " . ($#urls + 1) . " images\n"
853       if ($verbose > 1);
854     my %seen_src_urls;
855     foreach my $p (@urls) {
856       my ($furl, $id) = @$p;
857       $furl = expand_url ($furl, $url);
858
859       # No need to download the same image twice, even if it was in the feed
860       # multiple times under different GUIDs.
861       next if ($seen_src_urls{$furl});
862       $seen_src_urls{$furl} = 1;
863
864       my $f = download_image ($furl, $id, $dir);
865       next unless $f;
866       $files{$f} = 1;    # Got it, don't delete
867       $count++;
868     }
869
870     my $empty_p = ($count <= 0);
871
872     # Now delete any files that are no longer in the feed.
873     # But if there was nothing in the feed (network failure?)
874     # then don't blow away the old files.
875     #
876     my $kept = 0;
877     foreach my $f (keys(%files)) {
878       if ($count <= 0) {
879         $kept++;
880       } elsif ($files{$f}) {
881         $kept++;
882       } else {
883         if (unlink ("$dir/$f")) {
884           print STDERR "$progname: rm $dir/$f\n" if ($verbose > 1);
885         } else {
886           print STDERR "$progname: rm $dir/$f: $!\n";   # don't bail
887         }
888       }
889     }
890
891     # Both feed and cache are empty. No files at all. Bail.
892     error ("empty feed: $url") if ($kept <= 1);
893
894     # Feed is empty, but we have some files from last time. Warn.
895     print STDERR "$progname: empty feed: using cache: $url\n"
896       if ($empty_p);
897
898     $mtime = time();    # update the timestamp
899
900   } else {
901
902     # Not yet time to re-check the URL.
903     print STDERR "$progname: using cache: $url\n" if ($verbose);
904
905   }
906
907   # Unlock and update the write date on the .timestamp file.
908   #
909   truncate ($lock_fd, 0) || error ("unable to truncate $lock: $!");
910   seek ($lock_fd, 0, 0)  || error ("unable to rewind $lock: $!");
911   utime ($mtime, $mtime, $lock_fd) || error ("unable to touch $lock: $!");
912   flock ($lock_fd, LOCK_UN) || error ("unable to unlock $lock: $!");
913   close ($lock_fd);
914   $lock_fd = undef;
915   print STDERR "$progname: unlocked $lock\n" if ($verbose > 1);
916
917   # Don't bother using the imageDirectory cache.  We know that this directory
918   # is flat, and we can assume that an RSS feed doesn't contain 100,000 images
919   # like ~/Pictures/ might.
920   #
921   $cache_p = 0;
922
923   # Return the URL and directory name of the files of that URL's local cache.
924   #
925   return ($url, $dir);
926 }
927
928
929 sub find_random_file($) {
930   my ($dir) = @_;
931
932   if ($use_spotlight_p == -1) {
933     $use_spotlight_p = 0;
934     if (-x '/usr/bin/mdfind') {
935       $use_spotlight_p = 1;
936     }
937   }
938
939   my $url;
940   ($url, $dir) = mirror_feed ($dir);
941
942   if ($url) {
943     $use_spotlight_p = 0;
944     print STDERR "$progname: $dir is cache for $url\n" if ($verbose > 1);
945   }
946
947   @all_files = read_cache ($dir);
948
949   if ($#all_files >= 0) {
950     # got it from the cache...
951
952   } elsif ($use_spotlight_p) {
953     print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
954     spotlight_all_files ($dir);
955     print STDERR "$progname: found " . ($#all_files+1) .
956                  " file" . ($#all_files == 0 ? "" : "s") .
957                  " via Spotlight\n"
958       if ($verbose);
959   } else {
960     print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
961     find_all_files ($dir);
962     print STDERR "$progname: " .
963                  "f=" . ($#all_files+1) . "; " .
964                  "d=$dir_count; " .
965                  "s=$stat_count; " .
966                  "skip=${skip_count_unstat}+$skip_count_stat=" .
967                   ($skip_count_unstat + $skip_count_stat) .
968                  ".\n"
969       if ($verbose);
970   }
971
972   write_cache ($dir);
973
974   if ($#all_files < 0) {
975     print STDERR "$progname: no image files in $dir\n";
976     exit 1;
977   }
978
979   my $max_tries = 50;
980   my $total_files = @all_files;
981   my $sparse_p = ($total_files < 20);
982
983   # If the directory has a lot of files in it:
984   #   Make a pass through looking for hirez files (assume some are thumbs);
985   #   If we found none, then, select any other file at random.
986   # Otherwise if there are a small number of files:
987   #   Just select one at random (in case there's like, just one hirez).
988
989   for (my $check_size_p = $sparse_p ? 0 : 1;
990        $check_size_p >= 0; $check_size_p--) {
991
992     for (my $i = 0; $i < $max_tries; $i++) {
993       my $n = int (rand ($total_files));
994       my $file = $all_files[$n];
995       if (!$check_size_p || large_enough_p ($file)) {
996         if (! $url) {
997           $file =~ s@^\Q$dir/@@so || die;  # remove $dir from front
998         }
999         return $file;
1000       }
1001     }
1002   }
1003
1004   print STDERR "$progname: no suitable images in " . ($url || $dir) . " -- " .
1005                ($total_files <= $max_tries
1006                 ? "all $total_files images"
1007                 : "$max_tries of $total_files images") .
1008                " are smaller than ${min_image_width}x${min_image_height}.\n";
1009
1010   # If we got here, blow away the cache.  Maybe it's stale.
1011   unlink $cache_file_name if $cache_file_name;
1012
1013   exit 1;
1014 }
1015
1016
1017 sub large_enough_p($) {
1018   my ($file) = @_;
1019
1020   my ($w, $h) = image_file_size ($file);
1021
1022   if (!defined ($h)) {
1023
1024     # Nonexistent files are obviously too small!
1025     # Already printed $verbose message about the file not existing.
1026     return 0 unless -f $file;
1027
1028     print STDERR "$progname: $file: unable to determine image size\n"
1029       if ($verbose);
1030     # Assume that unknown files are of good sizes: this will happen if
1031     # they matched $good_file_re, but we don't have code to parse them.
1032     # (This will also happen if the file is junk...)
1033     return 1;
1034   }
1035
1036   if ($w < $min_image_width || $h < $min_image_height) {
1037     print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
1038     return 0;
1039   }
1040
1041   print STDERR "$progname: $file: $w x $h\n" if ($verbose);
1042   return 1;
1043 }
1044
1045
1046
1047 # Given the raw body of a GIF document, returns the dimensions of the image.
1048 #
1049 sub gif_size($) {
1050   my ($body) = @_;
1051   my $type = substr($body, 0, 6);
1052   my $s;
1053   return () unless ($type =~ /GIF8[7,9]a/);
1054   $s = substr ($body, 6, 10);
1055   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1056   return (($b<<8|$a), ($d<<8|$c));
1057 }
1058
1059 # Given the raw body of a JPEG document, returns the dimensions of the image.
1060 #
1061 sub jpeg_size($) {
1062   my ($body) = @_;
1063   my $i = 0;
1064   my $L = length($body);
1065
1066   my $c1 = substr($body, $i, 1); $i++;
1067   my $c2 = substr($body, $i, 1); $i++;
1068   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1069
1070   my $ch = "0";
1071   while (ord($ch) != 0xDA && $i < $L) {
1072     # Find next marker, beginning with 0xFF.
1073     while (ord($ch) != 0xFF) {
1074       return () if (length($body) <= $i);
1075       $ch = substr($body, $i, 1); $i++;
1076     }
1077     # markers can be padded with any number of 0xFF.
1078     while (ord($ch) == 0xFF) {
1079       return () if (length($body) <= $i);
1080       $ch = substr($body, $i, 1); $i++;
1081     }
1082
1083     # $ch contains the value of the marker.
1084     my $marker = ord($ch);
1085
1086     if (($marker >= 0xC0) &&
1087         ($marker <= 0xCF) &&
1088         ($marker != 0xC4) &&
1089         ($marker != 0xCC)) {  # it's a SOFn marker
1090       $i += 3;
1091       return () if (length($body) <= $i);
1092       my $s = substr($body, $i, 4); $i += 4;
1093       my ($a,$b,$c,$d) = unpack("C"x4, $s);
1094       return (($c<<8|$d), ($a<<8|$b));
1095
1096     } else {
1097       # We must skip variables, since FFs in variable names aren't
1098       # valid JPEG markers.
1099       return () if (length($body) <= $i);
1100       my $s = substr($body, $i, 2); $i += 2;
1101       my ($c1, $c2) = unpack ("C"x2, $s);
1102       my $length = ($c1 << 8) | $c2;
1103       return () if ($length < 2);
1104       $i += $length-2;
1105     }
1106   }
1107   return ();
1108 }
1109
1110 # Given the raw body of a PNG document, returns the dimensions of the image.
1111 #
1112 sub png_size($) {
1113   my ($body) = @_;
1114   return () unless ($body =~ m/^\211PNG\r/s);
1115   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
1116   return () unless defined ($bits);
1117   return () unless ($bits =~ /^IHDR/);
1118   my ($ign, $w, $h) = unpack("a4N2", $bits);
1119   return ($w, $h);
1120 }
1121
1122
1123 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
1124 # of the image.
1125 #
1126 sub image_size($) {
1127   my ($body) = @_;
1128   return () if (length($body) < 10);
1129   my ($w, $h) = gif_size ($body);
1130   if ($w && $h) { return ($w, $h); }
1131   ($w, $h) = jpeg_size ($body);
1132   if ($w && $h) { return ($w, $h); }
1133   # #### TODO: need image parsers for TIFF, XPM, XBM.
1134   return png_size ($body);
1135 }
1136
1137 # Returns the dimensions of the image file.
1138 #
1139 sub image_file_size($) {
1140   my ($file) = @_;
1141   my $in;
1142   if (! open ($in, '<:raw', $file)) {
1143     print STDERR "$progname: $file: $!\n" if ($verbose);
1144     return ();
1145   }
1146   my $body = '';
1147   sysread ($in, $body, 1024 * 50);  # The first 50k should be enough.
1148   close $in;                        # (It's not for certain huge jpegs...
1149   return image_size ($body);        # but we know they're huge!)
1150 }
1151
1152
1153 # Reads the prefs we use from ~/.xscreensaver
1154 #
1155 sub get_x11_prefs() {
1156   my $got_any_p = 0;
1157
1158   if (open (my $in, '<', $config_file)) {
1159     print STDERR "$progname: reading $config_file\n" if ($verbose > 1);
1160     local $/ = undef;  # read entire file
1161     my $body = <$in>;
1162     close $in;
1163     $got_any_p = get_x11_prefs_1 ($body);
1164
1165   } elsif ($verbose > 1) {
1166     print STDERR "$progname: $config_file: $!\n";
1167   }
1168
1169   if (! $got_any_p && defined ($ENV{DISPLAY})) {
1170     # We weren't able to read settings from the .xscreensaver file.
1171     # Fall back to any settings in the X resource database
1172     # (/usr/X11R6/lib/X11/app-defaults/XScreenSaver)
1173     #
1174     print STDERR "$progname: reading X resources\n" if ($verbose > 1);
1175     my $body = `appres XScreenSaver xscreensaver -1`;
1176     $got_any_p = get_x11_prefs_1 ($body);
1177   }
1178 }
1179
1180
1181 sub get_x11_prefs_1($) {
1182   my ($body) = @_;
1183
1184   my $got_any_p = 0;
1185   $body =~ s@\\\n@@gs;
1186   $body =~ s@^[ \t]*#[^\n]*$@@gm;
1187
1188   if ($body =~ m/^[.*]*imageDirectory:[ \t]*([^\s]+)\s*$/im) {
1189     $image_directory = $1;
1190     $got_any_p = 1;
1191   }
1192   return $got_any_p;
1193 }
1194
1195
1196 sub get_cocoa_prefs($) {
1197   my ($id) = @_;
1198   print STDERR "$progname: reading Cocoa prefs: \"$id\"\n" if ($verbose > 1);
1199   my $v = get_cocoa_pref_1 ($id, "imageDirectory");
1200   $v = '~/Pictures' unless defined ($v);  # Match default in XScreenSaverView
1201   $image_directory = $v if defined ($v);
1202 }
1203
1204
1205 sub get_cocoa_pref_1($$) {
1206   my ($id, $key) = @_;
1207   # make sure there's nothing stupid/malicious in either string.
1208   $id  =~ s/[^-a-z\d. ]/_/gsi;
1209   $key =~ s/[^-a-z\d. ]/_/gsi;
1210   my $cmd = "defaults -currentHost read \"$id\" \"$key\"";
1211
1212   print STDERR "$progname: executing $cmd\n"
1213     if ($verbose > 3);
1214
1215   my $val = `$cmd 2>/dev/null`;
1216   $val =~ s/^\s+//s;
1217   $val =~ s/\s+$//s;
1218
1219   print STDERR "$progname: Cocoa: $id $key = \"$val\"\n"
1220     if ($verbose > 2);
1221
1222   $val = undef if ($val =~ m/^$/s);
1223
1224   return $val;
1225 }
1226
1227
1228 sub error($) {
1229   my ($err) = @_;
1230   print STDERR "$progname: $err\n";
1231   exit 1;
1232 }
1233
1234 sub usage() {
1235   print STDERR "usage: $progname [--verbose] [ directory-or-feed-url ]\n\n" .
1236   "       Prints the name of a randomly-selected image file.  The directory\n" .
1237   "       is searched recursively.  Images smaller than " .
1238          "${min_image_width}x${min_image_height} are excluded.\n" .
1239   "\n" .
1240   "       The directory may also be the URL of an RSS/Atom feed.  Enclosed\n" .
1241   "       images will be downloaded and cached locally.\n" .
1242   "\n";
1243   exit 1;
1244 }
1245
1246 sub main() {
1247   my $cocoa_id = undef;
1248   my $abs_p = 0;
1249
1250   while ($_ = $ARGV[0]) {
1251     shift @ARGV;
1252     if    (m/^--?verbose$/s)      { $verbose++; }
1253     elsif (m/^-v+$/s)             { $verbose += length($_)-1; }
1254     elsif (m/^--?name$/s)         { }   # ignored, for compatibility
1255     elsif (m/^--?spotlight$/s)    { $use_spotlight_p = 1; }
1256     elsif (m/^--?no-spotlight$/s) { $use_spotlight_p = 0; }
1257     elsif (m/^--?cache$/s)        { $cache_p = 1; }
1258     elsif (m/^--?no-?cache$/s)    { $cache_p = 0; }
1259     elsif (m/^--?cocoa$/)         { $cocoa_id = shift @ARGV; }
1260     elsif (m/^--?abs(olute)?$/)   { $abs_p = 1; }
1261     elsif (m/^-./)                { usage; }
1262     elsif (!defined($image_directory)) { $image_directory = $_; }
1263     else                          { usage; }
1264   }
1265
1266   # Most hacks (X11 and Cocoa) pass a --directory value on the command line,
1267   # but if they don't, look it up from the resources.  Currently this only
1268   # happens with "glitchpeg" which invokes xscreensaver-getimage-file
1269   # directly instead of going through the traditional path.
1270   #
1271   if (! $image_directory) {
1272     if (!defined ($cocoa_id)) {
1273       # see OSX/XScreenSaverView.m
1274       $cocoa_id = $ENV{XSCREENSAVER_CLASSPATH};
1275     }
1276
1277     if (defined ($cocoa_id)) {
1278       get_cocoa_prefs($cocoa_id);
1279       error ("no imageDirectory in $cocoa_id") unless $image_directory;
1280     } else {
1281       get_x11_prefs();
1282       error ("no imageDirectory in X11 resources") unless $image_directory;
1283     }
1284   }
1285
1286   usage unless (defined($image_directory));
1287
1288   $image_directory =~ s@^feed:@http:@si;
1289
1290   if ($image_directory =~ m/^https?:/si) {
1291     # ok
1292   } else {
1293     $image_directory =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
1294     $image_directory =~ s@/+$@@s;                # omit trailing /
1295
1296     if (! -d $image_directory) {
1297       print STDERR "$progname: $image_directory not a directory or URL\n";
1298       usage;
1299     }
1300   }
1301
1302   my $file = find_random_file ($image_directory);
1303
1304   # With --absolute return fully qualified paths instead of relative to --dir.
1305   if ($abs_p &&
1306       $file !~ m@^/@ &&
1307       $image_directory =~ m@^/@s) {
1308     $file = "$image_directory/$file";
1309     $file =~ s@//+@/@gs;
1310   }
1311
1312   print STDOUT "$file\n";
1313 }
1314
1315 main;
1316 exit 0;