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->{'file'}); }
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 $rssobj->{'file'} = $self->{-toppath}.'/'.$feed;
215 $rssobj->{'rss'} = new XML::RSS (version=>'2.0');
216 if ( -f $rssobj->{'file'} ) {
217 $rssobj->{'rss'}->parsefile($rssobj->{'file'});
218 my $itemstodel = @{$rssobj->{'rss'}->{'items'}} - 15;
219 while ($itemstodel-- > 0) {
220 pop(@{$rssobj->{'rss'}->{'items'}})
222 $rssobj->{'rss'}->save($rssobj->{'file'});
227 for ($p1=0,$p2=length($toppath);
228 substr($feed,$p1,3) eq '../' && $p2>0;
229 $p1+=3,$p2=rindex($toppath,'/',$p2-1)) {;}
230 $link=substr($toppath,$p2);
232 $link .= '/' if ($link);
233 while (($p1=index($feed,'/',$p1+1)) >= 0) {
237 $rssobj->{'rss'}->channel(
240 description=>'Gallery Feed',
241 #language=>$language,
243 #copyright=>$copyright,
245 #lastBuildDate=>$lastBuild,
247 #managingEditor=>$editor,
248 #webMaster=>$webMaster
250 $rssobj->{'rss'}->save($rssobj->{'file'});
252 $self->{-rss} = $rssobj->{'rss'};
257 my $fullpath .= $self->{-fullpath};
258 print "iterate in dir $fullpath\n" if ($debug);
264 unless (opendir($D,$fullpath)) {
265 warn "cannot opendir $fullpath: $!";
268 while (my $de = readdir($D)) {
269 next if ($de =~ /^\./);
270 my $child = $self->new($de);
271 my @stat = stat($child->{-fullpath});
272 $youngest = $stat[9] if ($youngest < $stat[9]);
274 push(@rdirlist,$child);
275 } elsif ($child->isimg) {
276 push(@rimglist,$child);
280 my @dirlist = sort {$a->{-base} cmp $b->{-base}} @rdirlist;
281 undef @rdirlist; # inplace sorting would be handy here
282 my @imglist = sort {$a->{-base} cmp $b->{-base}} @rimglist;
283 undef @rimglist; # optimize away unsorted versions
284 $self->{-firstimg} = $imglist[0];
286 print "Dir: $self->{-fullpath}\n" if ($debug);
288 # 1. first of all, fill title for this directory and create hidden subdirs
292 # 2. recurse into subdirectories to get their titles filled
293 # before we start writing out subalbum list
295 foreach my $dir(@dirlist) {
299 # 3. iterate through images to build cross-links,
302 foreach my $img(@imglist) {
303 # list-linking must be done before generating
304 # aux html because aux pages rely on prev/next refs
306 $previmg->{-nextimg} = $img;
307 $img->{-previmg} = $previmg;
312 # 4. create scaled versions and aux html pages
314 foreach my $img(@imglist) {
315 # scaled versions must be generated before aux html
316 # and main image index because they both rely on
317 # refs to scaled images and they may be just original
318 # images, this is not known before we try scaling.
320 # finally, make aux html pages
324 # no need to go beyond this point if the directory timestamp did not
325 # change since we built index.html file last time.
327 my @istat = stat($self->{-fullpath}.'/index.html');
328 return unless ($youngest > $istat[9]);
330 # 5. start building index.html for the directory
334 # 6. iterate through subdirectories to build subalbums list
338 foreach my $dir(@dirlist) {
344 # 7. iterate through images to build thumb list
348 foreach my $img(@imglist) {
349 print "Img: $img->{-fullpath}\n" if ($debug);
355 # 8. comlplete building index.html for the directory
362 return ( -d $self->{-fullpath} );
367 my $fullpath = $self->{-fullpath};
368 return 0 unless ( -f $fullpath );
371 my $exif = new Image::ExifTool;
372 $exif->ExtractInfo($fullpath);
373 my ($la,$lo) = $exif->GetLocation();
375 $self->{-geoloc} = [$la,$lo];
379 my $info = image_info($fullpath);
380 if (my $error = $info->{error}) {
381 if (($error !~ "Unrecognized file format") &&
382 ($error !~ "Can't read head")) {
383 warn "File \"$fullpath\": $error\n";
388 tryapp12($info) unless ($info->{'ExifVersion'});
391 $self->{-info} = $info;
396 my $info = shift; # this is not a method
398 # dirty hack to take care of Image::Info parser strangeness
399 foreach my $k(keys %$info) {
400 $app12=substr($k,6).$info->{$k} if ($k =~ /^App12-/);
402 return unless ($app12); # bad luck
404 foreach my $ln(split /[\r\n]+/,$app12) {
405 $ln =~ s/[[:^print:]\000]/ /g;
406 unless ($seenfirstline) {
411 my ($k,$v)=split /=/,$ln,2;
412 if ($k eq 'TimeDate') {
413 $info->{'DateTime'} =
414 strftime("%Y:%m:%d %H:%M:%S", localtime($v))
416 } elsif ($k eq 'Shutter') {
417 $info->{'ExposureTime'} = '1/'.int(1000000/$v+.5);
418 } elsif ($k eq 'Flash') {
419 $info->{'Flash'} = $v?'Flash fired':'Flash did not fire';
420 } elsif ($k eq 'Type') {
421 $info->{'Model'} = $v;
422 } elsif ($k eq 'Version') {
423 $info->{'Software'} = $v;
424 } elsif ($k eq 'Fnumber') {
425 $info->{'FNumber'} = $v;
432 my $fullpath = $self->{-fullpath};
433 for my $subdir(@sizes, 'html') {
434 my $tdir=sprintf "%s/.%s",$self->{-fullpath},$subdir;
435 mkdir($tdir,0755) unless ( -d $tdir );
442 my $fullpath = $self->{-fullpath};
445 if (open($T,'<'.$fullpath.'/.title')) {
446 binmode($T, ":utf8");
448 $title =~ s/[\r\n]*$//;
451 if ($asktitle || (!$title && !$noasktitle)) {
452 my $prompt = $self->{-relpath};
453 $prompt = '/' unless ($prompt);
454 my $OUT = $term->OUT || \*STDOUT;
455 print $OUT "Enter title for $fullpath\n";
456 $title = $term->readline($prompt.' >',$title);
457 $term->addhistory($title) if ($title);
458 if (open($T,'>'.$fullpath.'/.title')) {
459 print $T $title,"\n";
464 $title=$self->{-relpath};
466 $self->{-title}=$title;
467 print "title in $fullpath is $title\n" if ($debug);
472 my $fn = $self->{-fullpath};
473 my $name = $self->{-base};
474 my $dn = $self->{-parent}->{-fullpath};
475 my ($w, $h) = dim($self->{-info});
476 my $max = ($w > $h)?$w:$h;
478 foreach my $size(@sizes) {
479 my $nref = '.'.$size.'/'.$name;
480 my $nfn = $dn.'/'.$nref;
481 my $factor=$size/$max;
483 $self->{$size}->{'url'} = $name; # unscaled version
484 $self->{$size}->{'dim'} = [$w, $h];
486 $self->{$size}->{'url'} = $nref;
487 $self->{$size}->{'dim'} = [int($w*$factor+.5),
489 if (isnewer($fn,$nfn)) {
490 doscaling($fn,$nfn,$factor,$w,$h);
497 my ($fn1,$fn2) = @_; # this is not a method
498 my @stat1=stat($fn1);
499 my @stat2=stat($fn2);
500 return (!@stat2 || ($stat1[9] > $stat2[9]));
501 # true if $fn2 is absent or is older than $fn1
505 my ($src,$dest,$factor,$w,$h) = @_; # this is not a method
509 my $im = new Image::Magick;
510 print "doscaling $src -> $dest by $factor\n" if ($debug);
511 if ($err = $im->Read($src)) {
512 warn "ImageMagick: read \"$src\": $err";
514 $im->Scale(width=>$w*$factor,height=>$h*$factor);
515 $err=$im->Write($dest);
516 warn "ImageMagick: write \"$dest\": $err" if ($err);
520 if ($err) { # fallback to command-line tools
521 system("djpeg \"$src\" | pnmscale \"$factor\" | cjpeg >\"$dest\"");
527 my $name = $self->{-base};
528 my $dn = $self->{-parent}->{-fullpath};
529 my $pref = $self->{-previmg}->{-base};
530 my $nref = $self->{-nextimg}->{-base};
531 my $inc = $self->{-inc}.$incdir.'/';
532 my $title = $self->{-info}->{'Comment'};
533 $title = $name unless ($title);
535 print "slide: \"$title\": \"$pref\"->\"$name\"->\"$nref\"\n" if ($debug);
538 for my $refresh('static', 'slide') {
539 my $fn = sprintf("%s/.html/%s-%s.html",$dn,$name,$refresh);
540 if (isnewer($self->{-fullpath},$fn)) {
541 my $imgsrc = '../'.$self->{$sizes[1]}->{'url'};
545 $fwdref = sprintf("%s-%s.html",$nref,$refresh);
547 $fwdref = '../index.html';
550 $bakref = sprintf("%s-%s.html",$pref,$refresh);
552 $bakref = '../index.html';
556 if ($refresh eq 'slide') {
557 $toggleref=sprintf("%s-static.html",$name);
558 $toggletext = 'Stop!';
560 $toggleref=sprintf("%s-slide.html",$name);
561 $toggletext = 'Play->';
564 unless (open($F,'>'.$fn)) {
565 warn "cannot open \"$fn\": $!";
568 binmode($F, ":utf8");
569 if ($refresh eq 'slide') {
574 -head=>meta({-http_equiv=>'Refresh',
575 -content=>"3; url=$fwdref"}),
576 -style=>{-src=>$inc."gallery.css"},
578 comment("Created by ".$version),"\n";
581 print $F start_html(-title=>$title,
584 -style=>{-src=>$inc."gallery.css"},
586 comment("Created by ".$version),"\n";
588 print $F start_table({-class=>'navi'}),start_Tr,"\n",
589 td(a({-href=>"../index.html"},"Index")),"\n",
590 td(a({-href=>$bakref},"<<Prev")),"\n",
591 td(a({-href=>$toggleref},$toggletext)),"\n",
592 td(a({-href=>$fwdref},"Next>>")),"\n",
593 td({-class=>'title'},$title),"\n",
596 center(table({-class=>'picframe'},
597 Tr(td(img({-src=>$imgsrc,
598 -class=>'standalone',
599 -alt=>$title}))))),"\n",
606 my $fn = sprintf("%s/.html/%s-info.html",$dn,$name);
607 if (isnewer($self->{-fullpath},$fn)) {
609 unless (open($F,'>'.$fn)) {
610 warn "cannot open \"$fn\": $!";
613 binmode($F, ":utf8");
614 my $imgsrc = sprintf("../.%s/%s",$sizes[0],$name);
615 print $F start_html(-title=>$title,
617 -style=>{-src=>$inc."gallery.css"},
619 {-src=>$inc."mootools.js"},
620 {-src=>$inc."urlparser.js"},
621 {-src=>$inc."infopage.js"},
623 comment("Created by ".$version),"\n",
626 table({-class=>'ipage'},
627 Tr(td(img({-src=>$imgsrc,
630 td($self->infotable))),
631 a({-href=>'../index.html',-class=>'conceal'},
641 my $fn = $self->{-fullpath}.'/index.html';
642 my $block = $self->{-fullpath}.'/.noindex';
643 $fn = '/dev/null' if ( -f $block );
645 unless (open($IND,'>'.$fn)) {
646 warn "cannot open $fn: $!";
649 binmode($IND, ":utf8");
650 $self->{-IND} = $IND;
652 my $inc = $self->{-inc}.$incdir.'/';
653 my $title = $self->{-title};
656 $rsslink=Link({-rel=>'alternate',
657 -type=>'application/rss+xml',
659 -href=>$self->{-inc}.$feed});
661 print $IND start_html(-title => $title,
665 {-src=>$inc."gallery.css"},
666 {-src=>$inc."custom.css"},
669 {-src=>$inc."mootools.js"},
670 {-src=>$inc."overlay.js"},
671 {-src=>$inc."urlparser.js"},
672 {-src=>$inc."multibox.js"},
673 {-src=>$inc."showwin.js"},
674 {-src=>$inc."controls.js"},
675 {-src=>$inc."show.js"},
676 {-src=>$inc."gallery.js"},
678 comment("Created by ".$version),"\n",
679 start_div({-class => 'indexContainer',
680 -id => 'indexContainer'}),
683 if (open($EVL,$self->{-toppath}.'/'.$incdir.'/header.pl')) {
690 -version => $version,
691 -depth => $self->{-depth},
693 -breadcrumbs => "breadcrumbs unimplemented",
695 print $IND eval $prm,"\n";
697 print STDERR "could not open ",
698 $self->{-toppath}.'/'.$incdir.'/header.pl',
699 " ($!), reverting to default header";
700 print $IND a({-href=>"../index.html"},"UP"),"\n",
701 h1({-class=>'title'},$title),"\n",
707 my $IND = $self->{-IND};
711 if (open($EVL,$self->{-toppath}.'/'.$incdir.'/footer.pl')) {
718 -version => $version,
719 -depth => $self->{-depth},
720 -title => $self->{-title},
721 -breadcrumbs => "breadcrumbs unimplemented",
723 print $IND eval $prm,"\n";
725 print STDERR "could not open ",
726 $self->{-toppath}.'/'.$incdir.'/footer.pl',
727 " ($!), reverting to default empty footer";
729 print $IND end_html,"\n";
731 close($IND) if ($IND);
734 my $rsstitle=sprintf "%s [%d images, %d subalbums]",
738 my $rsslink=$rssobj->{'rss'}->channel('link').
739 $self->{-relpath}."index.html";
740 $rssobj->{'rss'}->add_item(
741 title => $self->{-title},
743 description => $rsstitle,
744 pubDate => time2str(time),
751 my $IND = $self->{-IND};
753 print $IND h2({-class=>"atitle"},"Albums"),"\n",start_table,"\n";
758 my $IND = $self->{-parent}->{-IND};
759 my $name = $self->{-base};
760 my $title = $self->{-title};
762 $self->{-parent}->{-numofsubs}++;
763 print $IND Tr(td(a({-href=>$name.'/index.html'},$name)),
764 td(a({-href=>$name.'/index.html'},$title))),"\n";
769 my $IND = $self->{-IND};
771 print $IND end_table,"\n",br({-clear=>'all'}),hr,"\n\n";
776 my $IND = $self->{-IND};
777 my $first = $self->{-firstimg}->{-base};
778 my $slideref = sprintf(".html/%s-slide.html",$first);
780 print $IND h2({-class=>"ititle"},"Images ",
781 a({-href=>$slideref,-class=>'showStart',-rel=>'i'.$first},
782 '> slideshow')),"\n";
787 my $IND = $self->{-parent}->{-IND};
788 my $name = $self->{-base};
789 my $title = $self->{-info}->{'Comment'};
790 $title = $name unless ($title);
791 my $thumb = $self->{$sizes[0]}->{'url'};
792 my $info = $self->{-info};
793 my ($w, $h) = dim($info);
795 my $i=0+$self->{-parent}->{-numofimgs};
796 $self->{-parent}->{-numofimgs}++;
798 print $IND a({-name=>$name}),"\n",
799 start_table({-class=>'slide'}),start_Tr,start_td,"\n";
800 print $IND div({-class=>'slidetitle'},
801 "\n ",a({-href=>".html/$name-info.html",
802 -title=>'Image Info: '.$name,
805 start_div({-class=>'slideimage'});
806 if ($self->{-geoloc}) {
807 my ($la,$lo) = @{$self->{-geoloc}};
808 print $IND a({-href=>"http://maps.google.com/".
809 "?q=$la,$lo&ll=$la,$lo",
812 div({-class=>'geoloc'},"")),"\n";
814 print $IND a({-href=>".html/$name-static.html",
820 -alt=>$title})),"\n",end_div,
821 start_div({-class=>'varimages',-id=>'i'.$name,-title=>$title}),"\n";
822 foreach my $sz(@sizes) {
823 my $src=$self->{$sz}->{'url'};
824 my $w=$self->{$sz}->{'dim'}->[0];
825 my $h=$self->{$sz}->{'dim'}->[1];
826 print $IND " ",a({-href=>$src,
829 -title=>"Reduced to ".$w."x".$h},
832 print $IND " ",a({-href=>$name,
834 -title=>'Original'},$w."x".$h),
836 end_td,end_Tr,end_table,"\n";
841 my $IND = $self->{-IND};
843 print $IND br({-clear=>'all'}),hr,"\n\n";
848 my $info = $self->{-info};
865 $msg.=start_table({-class=>'infotable'})."\n";
866 foreach my $k(@infokeys) {
867 $msg.=Tr(td($k.":"),td($info->{$k}))."\n" if ($info->{$k});
869 $msg.=end_table."\n";