5 # Recursively create image gallery index and slideshow wrappings.
6 # Makes use of modified "slideshow" javascript by Samuel Birch
7 # http://www.phatfusion.net/slideshow/
9 # Copyright (c) 2006-2008 Eugene G. Crosser
11 # This software is provided 'as-is', without any express or implied
12 # warranty. In no event will the authors be held liable for any damages
13 # arising from the use of this software.
15 # Permission is granted to anyone to use this software for any purpose,
16 # including commercial applications, and to alter it and redistribute it
17 # freely, subject to the following restrictions:
19 # 1. The origin of this software must not be misrepresented; you must not
20 # claim that you wrote the original software. If you use this software
21 # in a product, an acknowledgment in the product documentation would be
22 # appreciated but is not required.
23 # 2. Altered source versions must be plainly marked as such, and must not be
24 # misrepresented as being the original software.
25 # 3. This notice may not be removed or altered from any source distribution.
31 use POSIX qw/getcwd strftime/;
33 use CGI qw/:html *table *Tr *td *center *div *Link/;
34 use Image::Info qw/image_info dim/;
38 #use encoding 'utf-8';
39 binmode(STDOUT, ":utf8");
41 my $haveimagick = eval { require Image::Magick; };
42 { package Image::Magick; } # to make perl compiler happy
44 my $haverss = eval { require XML::RSS; };
45 { package XML::RSS; } # to make perl compiler happy
47 my $haveatom = eval { require XML::Atom; };
48 { package XML::Atom; } # to make perl compiler happy
50 my $havegeoloc = eval { require Image::ExifTool::Location; };
51 { package Image::ExifTool::Location; } # to make perl compiler happy
53 my @sizes = (160, 640, 1600);
54 my $incdir = ".gallery2";
56 ######################################################################
70 'asktitle'=>\$asktitle,
71 'noasktitle'=>\$noasktitle,
77 if ($feed && ! ($haverss || $haveatom)) {
78 print STDERR "You need to get XML::RSS and/or XML::Atom to use --feed\n";
82 my $term = new Term::ReadLine "Edit Title";
84 FsObj->new(getcwd)->iterate;
85 if ($rssobj) { $rssobj->{-rss}->save($rssobj->{-savepath}); }
89 print STDERR <<__END__;
91 --help: print help message and exit
92 --incpath: do not try to find .gallery2 directory upstream, use
93 specified path (absolute or relavive). Use with causion.
94 --debug: print a lot of debugging info to stdout as you run
95 --asktitle: ask to edit album titles even if there are ".title" files
96 --noasktitle: don't ask to enter album titles even where ".title"
97 files are absent. Use partial directory names as titles.
98 --feed=...: build RSS feed for newly added "albums", give name of rss file
114 -root=>$parent->{-root},
115 -toppath=>$parent->{-toppath},
116 -depth=>$parent->{-depth}+1,
118 -fullpath=>$parent->{-fullpath}.'/'.$name,
119 -relpath=>$parent->{-relpath}.$name.'/',
120 -inc=>'../'.$parent->{-inc},
129 # fill in -inc, -rss, -relpath
130 initpaths($self); # we are not blessed yet, so cheat.
134 print "new $class:\n";
135 foreach my $k(keys %$self) {
136 print "\t$k\t=\t$self->{$k}\n";
143 my $self=shift; # this is not a method but we cheat
144 my $depth=20; # arbitrary max depth
145 my $fullpath=$self->{-fullpath};
151 $inc .= '/' unless ($inc =~ m%/$%);
154 while ( ! -d $fullpath."/".$inc."/".$incdir ) {
156 last unless ($depth-- > 0);
160 $self->{-inc} = $inc;
163 for ($pos=index($inc,'/');$pos>=0;
164 $pos=index($inc,'/',$pos+1)) {
167 $self->{-depth} = $dp;
168 for ($pos=length($fullpath);$dp>0 && $pos>0;
169 $pos=rindex($fullpath,'/',$pos-1)) {
172 my $relpath = substr($fullpath,$pos);
174 $relpath .= '/' if ($relpath);
175 $self->{-relpath} = $relpath;
176 $self->{-toppath} = substr($fullpath,0,$pos);
177 #print "rel=$relpath, top=$self->{-toppath}, inc=$inc\n";
180 $self->{-inc} = 'NO-.INCLUDE-IN-PATH/'; # won't work anyway
182 $self->{-relpath} = '';
188 my $self=shift; # this is not a method but we cheat
189 my $fullpath=$self->{-fullpath};
190 my $toppath=$self->{-toppath};
191 my $inc=$self->{-inc}.$incdir.'/';
192 my $conffile=$toppath.'/'.$incdir.'/feed.conf';
197 if (open($CONF,">".$conffile)) {
198 print $CONF $feed,"\n";
201 print STDERR "could not open $conffile: $!\n";
204 if (open($CONF,$conffile)) {
212 return unless ($feed);
214 my ($feedfile, $feedbase, $feedhub) = split(',', $feed);
215 $feedbase .= '/' unless ($feedbase =~ /\/$/);
216 print "($feedfile, $feedbase, $feedhub)\n";
218 $rssobj->{-savepath} = $self->{-toppath}.'/'.$feedfile;
219 $rssobj->{-file} = $feedfile;
220 $rssobj->{-base} = $feedbase;
221 $rssobj->{-hub} = $feedhub;
222 $rssobj->{-rss} = new XML::RSS (version=>'2.0');
223 if ( -f $rssobj->{-file} ) {
224 $rssobj->{-rss}->parsefile($rssobj->{-file});
225 my $itemstodel = @{$rssobj->{-rss}->{'items'}} - 15;
226 while ($itemstodel-- > 0) {
227 pop(@{$rssobj->{-rss}->{'items'}})
229 $rssobj->{-rss}->save($rssobj->{-savepath});
231 $rssobj->{-rss}->channel(
234 description=>'Gallery Feed',
235 #language=>$language,
237 #copyright=>$copyright,
239 #lastBuildDate=>$lastBuild,
241 #managingEditor=>$editor,
242 #webMaster=>$webMaster
244 $rssobj->{-rss}->save($rssobj->{-savepath});
246 $self->{-rss} = $rssobj->{-rss};
251 my $fullpath .= $self->{-fullpath};
252 print "iterate in dir $fullpath\n" if ($debug);
258 unless (opendir($D,$fullpath)) {
259 warn "cannot opendir $fullpath: $!";
262 while (my $de = readdir($D)) {
263 next if ($de =~ /^\./);
264 my $child = $self->new($de);
265 my @stat = stat($child->{-fullpath});
266 $youngest = $stat[9] if ($youngest < $stat[9]);
268 push(@rdirlist,$child);
269 } elsif ($child->isimg) {
270 push(@rimglist,$child);
274 my @dirlist = sort {$a->{-base} cmp $b->{-base}} @rdirlist;
275 undef @rdirlist; # inplace sorting would be handy here
276 my @imglist = sort {$a->{-base} cmp $b->{-base}} @rimglist;
277 undef @rimglist; # optimize away unsorted versions
278 $self->{-firstimg} = $imglist[0];
280 print "Dir: $self->{-fullpath}\n" if ($debug);
282 # 1. first of all, fill title for this directory and create hidden subdirs
286 # 2. recurse into subdirectories to get their titles filled
287 # before we start writing out subalbum list
289 foreach my $dir(@dirlist) {
293 # 3. iterate through images to build cross-links,
296 foreach my $img(@imglist) {
297 # list-linking must be done before generating
298 # aux html because aux pages rely on prev/next refs
300 $previmg->{-nextimg} = $img;
301 $img->{-previmg} = $previmg;
306 # 4. create scaled versions and aux html pages
308 foreach my $img(@imglist) {
309 # scaled versions must be generated before aux html
310 # and main image index because they both rely on
311 # refs to scaled images and they may be just original
312 # images, this is not known before we try scaling.
314 # finally, make aux html pages
318 # no need to go beyond this point if the directory timestamp did not
319 # change since we built index.html file last time.
321 my @istat = stat($self->{-fullpath}.'/index.html');
322 return unless ($youngest > $istat[9]);
324 # 5. start building index.html for the directory
328 # 6. iterate through subdirectories to build subalbums list
332 foreach my $dir(@dirlist) {
338 # 7. iterate through images to build thumb list
342 foreach my $img(@imglist) {
343 print "Img: $img->{-fullpath}\n" if ($debug);
349 # 8. comlplete building index.html for the directory
356 return ( -d $self->{-fullpath} );
361 my $fullpath = $self->{-fullpath};
362 return 0 unless ( -f $fullpath );
365 my $exif = new Image::ExifTool;
366 $exif->ExtractInfo($fullpath);
367 my ($la,$lo) = $exif->GetLocation();
369 $self->{-geoloc} = [$la,$lo];
373 my $info = image_info($fullpath);
374 if (my $error = $info->{error}) {
375 if (($error !~ "Unrecognized file format") &&
376 ($error !~ "Can't read head")) {
377 warn "File \"$fullpath\": $error\n";
382 tryapp12($info) unless ($info->{'ExifVersion'});
385 $self->{-info} = $info;
390 my $info = shift; # this is not a method
392 # dirty hack to take care of Image::Info parser strangeness
393 foreach my $k(keys %$info) {
394 $app12=substr($k,6).$info->{$k} if ($k =~ /^App12-/);
396 return unless ($app12); # bad luck
398 foreach my $ln(split /[\r\n]+/,$app12) {
399 $ln =~ s/[[:^print:]\000]/ /g;
400 unless ($seenfirstline) {
405 my ($k,$v)=split /=/,$ln,2;
406 if ($k eq 'TimeDate') {
407 $info->{'DateTime'} =
408 strftime("%Y:%m:%d %H:%M:%S", localtime($v))
410 } elsif ($k eq 'Shutter') {
411 $info->{'ExposureTime'} = '1/'.int(1000000/$v+.5);
412 } elsif ($k eq 'Flash') {
413 $info->{'Flash'} = $v?'Flash fired':'Flash did not fire';
414 } elsif ($k eq 'Type') {
415 $info->{'Model'} = $v;
416 } elsif ($k eq 'Version') {
417 $info->{'Software'} = $v;
418 } elsif ($k eq 'Fnumber') {
419 $info->{'FNumber'} = $v;
426 my $fullpath = $self->{-fullpath};
427 for my $subdir(@sizes, 'html') {
428 my $tdir=sprintf "%s/.%s",$self->{-fullpath},$subdir;
429 mkdir($tdir,0755) unless ( -d $tdir );
436 my $fullpath = $self->{-fullpath};
439 if (open($T,'<'.$fullpath.'/.title')) {
440 binmode($T, ":utf8");
442 $title =~ s/[\r\n]*$//;
445 if ($asktitle || (!$title && !$noasktitle)) {
446 my $prompt = $self->{-relpath};
447 $prompt = '/' unless ($prompt);
448 my $OUT = $term->OUT || \*STDOUT;
449 print $OUT "Enter title for $fullpath\n";
450 $title = $term->readline($prompt.' >',$title);
451 $term->addhistory($title) if ($title);
452 if (open($T,'>'.$fullpath.'/.title')) {
453 print $T $title,"\n";
458 $title=$self->{-relpath};
460 $self->{-title}=$title;
461 print "title in $fullpath is $title\n" if ($debug);
466 my $fn = $self->{-fullpath};
467 my $name = $self->{-base};
468 my $dn = $self->{-parent}->{-fullpath};
469 my ($w, $h) = dim($self->{-info});
470 my $max = ($w > $h)?$w:$h;
472 foreach my $size(@sizes) {
473 my $nref = '.'.$size.'/'.$name;
474 my $nfn = $dn.'/'.$nref;
475 my $factor=$size/$max;
477 $self->{$size}->{'url'} = $name; # unscaled version
478 $self->{$size}->{'dim'} = [$w, $h];
480 $self->{$size}->{'url'} = $nref;
481 $self->{$size}->{'dim'} = [int($w*$factor+.5),
483 if (isnewer($fn,$nfn)) {
484 doscaling($fn,$nfn,$factor,$w,$h);
491 my ($fn1,$fn2) = @_; # this is not a method
492 my @stat1=stat($fn1);
493 my @stat2=stat($fn2);
494 return (!@stat2 || ($stat1[9] > $stat2[9]));
495 # true if $fn2 is absent or is older than $fn1
499 my ($src,$dest,$factor,$w,$h) = @_; # this is not a method
503 my $im = new Image::Magick;
504 print "doscaling $src -> $dest by $factor\n" if ($debug);
505 if ($err = $im->Read($src)) {
506 warn "ImageMagick: read \"$src\": $err";
508 $im->Scale(width=>$w*$factor,height=>$h*$factor);
509 $err=$im->Write($dest);
510 warn "ImageMagick: write \"$dest\": $err" if ($err);
514 if ($err) { # fallback to command-line tools
515 system("djpeg \"$src\" | pnmscale \"$factor\" | cjpeg >\"$dest\"");
521 my $name = $self->{-base};
522 my $dn = $self->{-parent}->{-fullpath};
523 my $pref = $self->{-previmg}->{-base};
524 my $nref = $self->{-nextimg}->{-base};
525 my $inc = $self->{-inc}.$incdir.'/';
526 my $title = $self->{-info}->{'Comment'};
527 $title = $name unless ($title);
529 print "slide: \"$title\": \"$pref\"->\"$name\"->\"$nref\"\n" if ($debug);
532 for my $refresh('static', 'slide') {
533 my $fn = sprintf("%s/.html/%s-%s.html",$dn,$name,$refresh);
534 if (isnewer($self->{-fullpath},$fn)) {
535 my $imgsrc = '../'.$self->{$sizes[1]}->{'url'};
539 $fwdref = sprintf("%s-%s.html",$nref,$refresh);
541 $fwdref = '../index.html';
544 $bakref = sprintf("%s-%s.html",$pref,$refresh);
546 $bakref = '../index.html';
550 if ($refresh eq 'slide') {
551 $toggleref=sprintf("%s-static.html",$name);
552 $toggletext = 'Stop!';
554 $toggleref=sprintf("%s-slide.html",$name);
555 $toggletext = 'Play->';
558 unless (open($F,'>'.$fn)) {
559 warn "cannot open \"$fn\": $!";
562 binmode($F, ":utf8");
563 if ($refresh eq 'slide') {
568 -head=>meta({-http_equiv=>'Refresh',
569 -content=>"3; url=$fwdref"}),
570 -style=>{-src=>$inc."gallery.css"},
572 comment("Created by ".$version),"\n";
575 print $F start_html(-title=>$title,
578 -style=>{-src=>$inc."gallery.css"},
580 comment("Created by ".$version),"\n";
582 print $F start_table({-class=>'navi'}),start_Tr,"\n",
583 td(a({-href=>"../index.html"},"Index")),"\n",
584 td(a({-href=>$bakref},"<<Prev")),"\n",
585 td(a({-href=>$toggleref},$toggletext)),"\n",
586 td(a({-href=>$fwdref},"Next>>")),"\n",
587 td({-class=>'title'},$title),"\n",
590 center(table({-class=>'picframe'},
591 Tr(td(img({-src=>$imgsrc,
592 -class=>'standalone',
593 -alt=>$title}))))),"\n",
600 my $fn = sprintf("%s/.html/%s-info.html",$dn,$name);
601 if (isnewer($self->{-fullpath},$fn)) {
603 unless (open($F,'>'.$fn)) {
604 warn "cannot open \"$fn\": $!";
607 binmode($F, ":utf8");
608 my $imgsrc = sprintf("../.%s/%s",$sizes[0],$name);
609 print $F start_html(-title=>$title,
611 -style=>{-src=>$inc."gallery.css"},
613 {-src=>$inc."mootools.js"},
614 {-src=>$inc."urlparser.js"},
615 {-src=>$inc."infopage.js"},
617 comment("Created by ".$version),"\n",
620 table({-class=>'ipage'},
621 Tr(td(img({-src=>$imgsrc,
624 td($self->infotable))),
625 a({-href=>'../index.html',-class=>'conceal'},
635 my $fn = $self->{-fullpath}.'/index.html';
636 my $block = $self->{-fullpath}.'/.noindex';
637 $fn = '/dev/null' if ( -f $block );
639 unless (open($IND,'>'.$fn)) {
640 warn "cannot open $fn: $!";
643 binmode($IND, ":utf8");
644 $self->{-IND} = $IND;
646 my $inc = $self->{-inc}.$incdir.'/';
647 my $title = $self->{-title};
650 $rsslink=Link({-rel=>'alternate',
651 -type=>'application/rss+xml',
652 -title=>'Gallery Feed',
653 -href=>$rssobj->{-base}.$rssobj->{-file}});
655 print $IND start_html(-title => $title,
659 {-src=>$inc."gallery.css"},
660 {-src=>$inc."custom.css"},
663 {-src=>$inc."mootools.js"},
664 {-src=>$inc."overlay.js"},
665 {-src=>$inc."urlparser.js"},
666 {-src=>$inc."multibox.js"},
667 {-src=>$inc."showwin.js"},
668 {-src=>$inc."controls.js"},
669 {-src=>$inc."show.js"},
670 {-src=>$inc."gallery.js"},
672 comment("Created by ".$version),"\n",
673 start_div({-class => 'indexContainer',
674 -id => 'indexContainer'}),
677 if (open($EVL,$self->{-toppath}.'/'.$incdir.'/header.pl')) {
684 -version => $version,
685 -depth => $self->{-depth},
687 -path => $self->{-fullpath},
688 -breadcrumbs => "breadcrumbs unimplemented",
690 print $IND eval $prm,"\n";
692 print STDERR "could not open ",
693 $self->{-toppath}.'/'.$incdir.'/header.pl',
694 " ($!), reverting to default header";
695 print $IND a({-href=>"../index.html"},"UP"),"\n",
696 h1({-class=>'title'},$title),"\n",
702 my $IND = $self->{-IND};
706 if (open($EVL,$self->{-toppath}.'/'.$incdir.'/footer.pl')) {
713 -version => $version,
714 -depth => $self->{-depth},
715 -title => $self->{-title},
716 -breadcrumbs => "breadcrumbs unimplemented",
718 print $IND eval $prm,"\n";
720 print STDERR "could not open ",
721 $self->{-toppath}.'/'.$incdir.'/footer.pl',
722 " ($!), reverting to default empty footer";
724 print $IND end_html,"\n";
726 close($IND) if ($IND);
729 my $rsstitle=sprintf "%s [%d images, %d subalbums]",
733 my $rsslink=$rssobj->{-rss}->channel('link').
734 $self->{-relpath}."index.html";
735 $rssobj->{-rss}->add_item(
736 title => $self->{-title},
738 description => $rsstitle,
739 pubDate => time2str(time),
746 my $IND = $self->{-IND};
748 print $IND h2({-class=>"atitle"},"Albums"),"\n",start_table,"\n";
753 my $IND = $self->{-parent}->{-IND};
754 my $name = $self->{-base};
755 my $title = $self->{-title};
757 $self->{-parent}->{-numofsubs}++;
758 print $IND Tr(td(a({-href=>$name.'/index.html'},$name)),
759 td(a({-href=>$name.'/index.html'},$title))),"\n";
764 my $IND = $self->{-IND};
766 print $IND end_table,"\n",br({-clear=>'all'}),hr,"\n\n";
771 my $IND = $self->{-IND};
772 my $first = $self->{-firstimg}->{-base};
773 my $slideref = sprintf(".html/%s-slide.html",$first);
775 print $IND h2({-class=>"ititle"},"Images ",
776 a({-href=>$slideref,-class=>'showStart',-rel=>'i'.$first},
777 '> slideshow')),"\n";
782 my $IND = $self->{-parent}->{-IND};
783 my $name = $self->{-base};
784 my $title = $self->{-info}->{'Comment'};
785 $title = $name unless ($title);
786 my $thumb = $self->{$sizes[0]}->{'url'};
787 my $info = $self->{-info};
788 my ($w, $h) = dim($info);
790 my $i=0+$self->{-parent}->{-numofimgs};
791 $self->{-parent}->{-numofimgs}++;
793 print $IND a({-name=>$name}),"\n",
794 start_table({-class=>'slide'}),start_Tr,start_td,"\n";
795 print $IND div({-class=>'slidetitle'},
796 "\n ",a({-href=>".html/$name-info.html",
797 -title=>'Image Info: '.$name,
800 start_div({-class=>'slideimage'});
801 if ($self->{-geoloc}) {
802 my ($la,$lo) = @{$self->{-geoloc}};
803 print $IND a({-href=>"http://maps.google.com/".
804 "?q=$la,$lo&ll=$la,$lo",
807 div({-class=>'geoloc'},"")),"\n";
809 print $IND a({-href=>".html/$name-static.html",
815 -alt=>$title})),"\n",end_div,
816 start_div({-class=>'varimages',-id=>'i'.$name,-title=>$title}),"\n";
817 foreach my $sz(@sizes) {
818 my $src=$self->{$sz}->{'url'};
819 my $w=$self->{$sz}->{'dim'}->[0];
820 my $h=$self->{$sz}->{'dim'}->[1];
821 print $IND " ",a({-href=>$src,
824 -title=>"Reduced to ".$w."x".$h},
827 print $IND " ",a({-href=>$name,
829 -title=>'Original'},$w."x".$h),
831 end_td,end_Tr,end_table,"\n";
836 my $IND = $self->{-IND};
838 print $IND br({-clear=>'all'}),hr,"\n\n";
843 my $info = $self->{-info};
860 $msg.=start_table({-class=>'infotable'})."\n";
861 foreach my $k(@infokeys) {
862 $msg.=Tr(td($k.":"),td($info->{$k}))."\n" if ($info->{$k});
864 $msg.=end_table."\n";