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 $haverssxml = eval { require XML::RSS; };
45 { package XML::RSS; } # to make perl compiler happy
47 my $havegeoloc = eval { require Image::ExifTool::Location; };
48 { package Image::ExifTool::Location; } # to make perl compiler happy
50 my @sizes = (160, 640, 1600);
51 my $incdir = ".gallery2";
53 ######################################################################
67 'asktitle'=>\$asktitle,
68 'noasktitle'=>\$noasktitle,
69 'rssfile=s'=>\$rssfile,
74 if ($rssfile && ! $haverssxml) {
75 print STDERR "You need to get XML::RSS from CPAN to use --rssfile\n";
79 my $term = new Term::ReadLine "Edit Title";
81 FsObj->new(getcwd)->iterate;
82 if ($rssobj) { $rssobj->{'rss'}->save($rssobj->{'file'}); }
86 print STDERR <<__END__;
88 --help: print help message and exit
89 --incpath: do not try to find .gallery2 diretory upstream, use
90 specified path (absolute or relavive). Use with causion.
91 --debug: print a lot of debugging info to stdout as you run
92 --asktitle: ask to edit album titles even if there are ".title" files
93 --noasktitle: don't ask to enter album titles even where ".title"
94 files are absent. Use partial directory names as titles.
95 --rssfile=...: build RSS feed for newly added "albums", give name of rss file
111 -root=>$parent->{-root},
112 -toppath=>$parent->{-toppath},
113 -depth=>$parent->{-depth}+1,
115 -fullpath=>$parent->{-fullpath}.'/'.$name,
116 -relpath=>$parent->{-relpath}.$name.'/',
117 -inc=>'../'.$parent->{-inc},
126 # fill in -inc, -rss, -relpath
127 initpaths($self); # we are not blessed yet, so cheat.
131 print "new $class:\n";
132 foreach my $k(keys %$self) {
133 print "\t$k\t=\t$self->{$k}\n";
140 my $self=shift; # this is not a method but we cheat
141 my $depth=20; # arbitrary max depth
142 my $fullpath=$self->{-fullpath};
148 $inc .= '/' unless ($inc =~ m%/$%);
151 while ( ! -d $fullpath."/".$inc."/".$incdir ) {
153 last unless ($depth-- > 0);
157 $self->{-inc} = $inc;
160 for ($pos=index($inc,'/');$pos>=0;
161 $pos=index($inc,'/',$pos+1)) {
164 $self->{-depth} = $dp;
165 for ($pos=length($fullpath);$dp>0 && $pos>0;
166 $pos=rindex($fullpath,'/',$pos-1)) {
169 my $relpath = substr($fullpath,$pos);
171 $relpath .= '/' if ($relpath);
172 $self->{-relpath} = $relpath;
173 $self->{-toppath} = substr($fullpath,0,$pos);
174 #print "rel=$relpath, top=$self->{-toppath}, inc=$inc\n";
177 $self->{-inc} = 'NO-.INCLUDE-IN-PATH/'; # won't work anyway
179 $self->{-relpath} = '';
185 my $self=shift; # this is not a method but we cheat
186 my $fullpath=$self->{-fullpath};
187 my $toppath=$self->{-toppath};
188 my $inc=$self->{-inc}.$incdir.'/';
189 my $conffile=$toppath.'/'.$incdir.'/rss.conf';
193 if (open($CONF,">".$conffile)) {
194 print $CONF "file: ",$rssfile,"\n";
197 print STDERR "could not open $conffile: $!\n";
200 if (open($CONF,$conffile)) {
204 my ($k,$v)=split(':', $ln);
215 return unless ($rssfile);
217 $rssobj->{'file'} = $self->{-toppath}.'/'.$rssfile;
218 $rssobj->{'rss'} = new XML::RSS (version=>'2.0');
219 if ( -f $rssobj->{'file'} ) {
220 $rssobj->{'rss'}->parsefile($rssobj->{'file'});
221 my $itemstodel = @{$rssobj->{'rss'}->{'items'}} - 15;
222 while ($itemstodel-- > 0) {
223 pop(@{$rssobj->{'rss'}->{'items'}})
225 $rssobj->{'rss'}->save($rssobj->{'file'});
230 for ($p1=0,$p2=length($toppath);
231 substr($rssfile,$p1,3) eq '../' && $p2>0;
232 $p1+=3,$p2=rindex($toppath,'/',$p2-1)) {;}
233 $link=substr($toppath,$p2);
235 $link .= '/' if ($link);
236 while (($p1=index($rssfile,'/',$p1+1)) >= 0) {
240 $rssobj->{'rss'}->channel(
243 description=>'Gallery Feed',
244 #language=>$language,
246 #copyright=>$copyright,
248 #lastBuildDate=>$lastBuild,
250 #managingEditor=>$editor,
251 #webMaster=>$webMaster
253 $rssobj->{'rss'}->save($rssobj->{'file'});
255 $self->{-rss} = $rssobj->{'rss'};
260 my $fullpath .= $self->{-fullpath};
261 print "iterate in dir $fullpath\n" if ($debug);
267 unless (opendir($D,$fullpath)) {
268 warn "cannot opendir $fullpath: $!";
271 while (my $de = readdir($D)) {
272 next if ($de =~ /^\./);
273 my $child = $self->new($de);
274 my @stat = stat($child->{-fullpath});
275 $youngest = $stat[9] if ($youngest < $stat[9]);
277 push(@rdirlist,$child);
278 } elsif ($child->isimg) {
279 push(@rimglist,$child);
283 my @dirlist = sort {$a->{-base} cmp $b->{-base}} @rdirlist;
284 undef @rdirlist; # inplace sorting would be handy here
285 my @imglist = sort {$a->{-base} cmp $b->{-base}} @rimglist;
286 undef @rimglist; # optimize away unsorted versions
287 $self->{-firstimg} = $imglist[0];
289 print "Dir: $self->{-fullpath}\n" if ($debug);
291 # 1. first of all, fill title for this directory and create hidden subdirs
295 # 2. recurse into subdirectories to get their titles filled
296 # before we start writing out subalbum list
298 foreach my $dir(@dirlist) {
302 # 3. iterate through images to build cross-links,
305 foreach my $img(@imglist) {
306 # list-linking must be done before generating
307 # aux html because aux pages rely on prev/next refs
309 $previmg->{-nextimg} = $img;
310 $img->{-previmg} = $previmg;
315 # 4. create scaled versions and aux html pages
317 foreach my $img(@imglist) {
318 # scaled versions must be generated before aux html
319 # and main image index because they both rely on
320 # refs to scaled images and they may be just original
321 # images, this is not known before we try scaling.
323 # finally, make aux html pages
327 # no need to go beyond this point if the directory timestamp did not
328 # change since we built index.html file last time.
330 my @istat = stat($self->{-fullpath}.'/index.html');
331 return unless ($youngest > $istat[9]);
333 # 5. start building index.html for the directory
337 # 6. iterate through subdirectories to build subalbums list
341 foreach my $dir(@dirlist) {
347 # 7. iterate through images to build thumb list
351 foreach my $img(@imglist) {
352 print "Img: $img->{-fullpath}\n" if ($debug);
358 # 8. comlplete building index.html for the directory
365 return ( -d $self->{-fullpath} );
370 my $fullpath = $self->{-fullpath};
371 return 0 unless ( -f $fullpath );
374 my $exif = new Image::ExifTool;
375 $exif->ExtractInfo($fullpath);
376 my ($la,$lo) = $exif->GetLocation();
378 $self->{-geoloc} = [$la,$lo];
382 my $info = image_info($fullpath);
383 if (my $error = $info->{error}) {
384 if (($error !~ "Unrecognized file format") &&
385 ($error !~ "Can't read head")) {
386 warn "File \"$fullpath\": $error\n";
391 tryapp12($info) unless ($info->{'ExifVersion'});
394 $self->{-info} = $info;
399 my $info = shift; # this is not a method
401 # dirty hack to take care of Image::Info parser strangeness
402 foreach my $k(keys %$info) {
403 $app12=substr($k,6).$info->{$k} if ($k =~ /^App12-/);
405 return unless ($app12); # bad luck
407 foreach my $ln(split /[\r\n]+/,$app12) {
408 $ln =~ s/[[:^print:]\000]/ /g;
409 unless ($seenfirstline) {
414 my ($k,$v)=split /=/,$ln,2;
415 if ($k eq 'TimeDate') {
416 $info->{'DateTime'} =
417 strftime("%Y:%m:%d %H:%M:%S", localtime($v))
419 } elsif ($k eq 'Shutter') {
420 $info->{'ExposureTime'} = '1/'.int(1000000/$v+.5);
421 } elsif ($k eq 'Flash') {
422 $info->{'Flash'} = $v?'Flash fired':'Flash did not fire';
423 } elsif ($k eq 'Type') {
424 $info->{'Model'} = $v;
425 } elsif ($k eq 'Version') {
426 $info->{'Software'} = $v;
427 } elsif ($k eq 'Fnumber') {
428 $info->{'FNumber'} = $v;
435 my $fullpath = $self->{-fullpath};
436 for my $subdir(@sizes, 'html') {
437 my $tdir=sprintf "%s/.%s",$self->{-fullpath},$subdir;
438 mkdir($tdir,0755) unless ( -d $tdir );
445 my $fullpath = $self->{-fullpath};
448 if (open($T,'<'.$fullpath.'/.title')) {
450 $title =~ s/[\r\n]*$//;
453 if ($asktitle || (!$title && !$noasktitle)) {
454 my $prompt = $self->{-relpath};
455 $prompt = '/' unless ($prompt);
456 my $OUT = $term->OUT || \*STDOUT;
457 print $OUT "Enter title for $fullpath\n";
458 $title = $term->readline($prompt.' >',$title);
459 $term->addhistory($title) if ($title);
460 if (open($T,'>'.$fullpath.'/.title')) {
461 print $T $title,"\n";
466 $title=$self->{-relpath};
468 $self->{-title}=$title;
469 print "title in $fullpath is $title\n" if ($debug);
474 my $fn = $self->{-fullpath};
475 my $name = $self->{-base};
476 my $dn = $self->{-parent}->{-fullpath};
477 my ($w, $h) = dim($self->{-info});
478 my $max = ($w > $h)?$w:$h;
480 foreach my $size(@sizes) {
481 my $nref = '.'.$size.'/'.$name;
482 my $nfn = $dn.'/'.$nref;
483 my $factor=$size/$max;
485 $self->{$size}->{'url'} = $name; # unscaled version
486 $self->{$size}->{'dim'} = [$w, $h];
488 $self->{$size}->{'url'} = $nref;
489 $self->{$size}->{'dim'} = [int($w*$factor+.5),
491 if (isnewer($fn,$nfn)) {
492 doscaling($fn,$nfn,$factor,$w,$h);
499 my ($fn1,$fn2) = @_; # this is not a method
500 my @stat1=stat($fn1);
501 my @stat2=stat($fn2);
502 return (!@stat2 || ($stat1[9] > $stat2[9]));
503 # true if $fn2 is absent or is older than $fn1
507 my ($src,$dest,$factor,$w,$h) = @_; # this is not a method
511 my $im = new Image::Magick;
512 print "doscaling $src -> $dest by $factor\n" if ($debug);
513 if ($err = $im->Read($src)) {
514 warn "ImageMagick: read \"$src\": $err";
516 $im->Scale(width=>$w*$factor,height=>$h*$factor);
517 $err=$im->Write($dest);
518 warn "ImageMagick: write \"$dest\": $err" if ($err);
522 if ($err) { # fallback to command-line tools
523 system("djpeg \"$src\" | pnmscale \"$factor\" | cjpeg >\"$dest\"");
529 my $name = $self->{-base};
530 my $dn = $self->{-parent}->{-fullpath};
531 my $pref = $self->{-previmg}->{-base};
532 my $nref = $self->{-nextimg}->{-base};
533 my $inc = $self->{-inc}.$incdir.'/';
534 my $title = $self->{-info}->{'Comment'};
535 $title = $name unless ($title);
537 print "slide: \"$title\": \"$pref\"->\"$name\"->\"$nref\"\n" if ($debug);
540 for my $refresh('static', 'slide') {
541 my $fn = sprintf("%s/.html/%s-%s.html",$dn,$name,$refresh);
542 if (isnewer($self->{-fullpath},$fn)) {
543 my $imgsrc = '../'.$self->{$sizes[1]}->{'url'};
547 $fwdref = sprintf("%s-%s.html",$nref,$refresh);
549 $fwdref = '../index.html';
552 $bakref = sprintf("%s-%s.html",$pref,$refresh);
554 $bakref = '../index.html';
558 if ($refresh eq 'slide') {
559 $toggleref=sprintf("%s-static.html",$name);
560 $toggletext = 'Stop!';
562 $toggleref=sprintf("%s-slide.html",$name);
563 $toggletext = 'Play->';
566 unless (open($F,'>'.$fn)) {
567 warn "cannot open \"$fn\": $!";
570 binmode($F, ":utf8");
571 if ($refresh eq 'slide') {
576 -head=>meta({-http_equiv=>'Refresh',
577 -content=>"3; url=$fwdref"}),
578 -style=>{-src=>$inc."gallery.css"},
580 comment("Created by ".$version),"\n";
583 print $F start_html(-title=>$title,
586 -style=>{-src=>$inc."gallery.css"},
588 comment("Created by ".$version),"\n";
590 print $F start_table({-class=>'navi'}),start_Tr,"\n",
591 td(a({-href=>"../index.html"},"Index")),"\n",
592 td(a({-href=>$bakref},"<<Prev")),"\n",
593 td(a({-href=>$toggleref},$toggletext)),"\n",
594 td(a({-href=>$fwdref},"Next>>")),"\n",
595 td({-class=>'title'},$title),"\n",
598 center(table({-class=>'picframe'},
599 Tr(td(img({-src=>$imgsrc,
600 -class=>'standalone',
601 -alt=>$title}))))),"\n",
608 my $fn = sprintf("%s/.html/%s-info.html",$dn,$name);
609 if (isnewer($self->{-fullpath},$fn)) {
611 unless (open($F,'>'.$fn)) {
612 warn "cannot open \"$fn\": $!";
615 binmode($F, ":utf8");
616 my $imgsrc = sprintf("../.%s/%s",$sizes[0],$name);
617 print $F start_html(-title=>$title,
619 -style=>{-src=>$inc."gallery.css"},
621 {-src=>$inc."mootools.js"},
622 {-src=>$inc."urlparser.js"},
623 {-src=>$inc."infopage.js"},
625 comment("Created by ".$version),"\n",
628 table({-class=>'ipage'},
629 Tr(td(img({-src=>$imgsrc,
632 td($self->infotable))),
633 a({-href=>'../index.html',-class=>'conceal'},
643 my $fn = $self->{-fullpath}.'/index.html';
644 my $block = $self->{-fullpath}.'/.noindex';
645 $fn = '/dev/null' if ( -f $block );
647 unless (open($IND,'>'.$fn)) {
648 warn "cannot open $fn: $!";
651 binmode($IND, ":utf8");
652 $self->{-IND} = $IND;
654 my $inc = $self->{-inc}.$incdir.'/';
655 my $title = $self->{-title};
658 $rsslink=Link({-rel=>'alternate',
659 -type=>'application/rss+xml',
661 -href=>$self->{-inc}.$rssfile});
663 print $IND start_html(-title => $title,
667 {-src=>$inc."gallery.css"},
668 {-src=>$inc."custom.css"},
671 {-src=>$inc."mootools.js"},
672 {-src=>$inc."overlay.js"},
673 {-src=>$inc."urlparser.js"},
674 {-src=>$inc."multibox.js"},
675 {-src=>$inc."showwin.js"},
676 {-src=>$inc."controls.js"},
677 {-src=>$inc."show.js"},
678 {-src=>$inc."gallery.js"},
680 comment("Created by ".$version),"\n",
681 start_div({-class => 'indexContainer',
682 -id => 'indexContainer'}),
685 if (open($EVL,$self->{-toppath}.'/'.$incdir.'/header.pl')) {
692 -version => $version,
693 -depth => $self->{-depth},
695 -breadcrumbs => "breadcrumbs unimplemented",
697 print $IND eval $prm,"\n";
699 print STDERR "could not open ",
700 $self->{-toppath}.'/'.$incdir.'/header.pl',
701 " ($!), reverting to default header";
702 print $IND a({-href=>"../index.html"},"UP"),"\n",
703 h1({-class=>'title'},$title),"\n",
709 my $IND = $self->{-IND};
713 if (open($EVL,$self->{-toppath}.'/'.$incdir.'/footer.pl')) {
720 -version => $version,
721 -depth => $self->{-depth},
722 -title => $self->{-title},
723 -breadcrumbs => "breadcrumbs unimplemented",
725 print $IND eval $prm,"\n";
727 print STDERR "could not open ",
728 $self->{-toppath}.'/'.$incdir.'/footer.pl',
729 " ($!), reverting to default empty footer";
731 print $IND end_html,"\n";
733 close($IND) if ($IND);
736 my $rsstitle=sprintf "%s [%d images, %d subalbums]",
740 my $rsslink=$rssobj->{'rss'}->channel('link').
741 $self->{-relpath}."index.html";
742 $rssobj->{'rss'}->add_item(
743 title => $self->{-title},
745 description => $rsstitle,
746 pubDate => time2str(time),
753 my $IND = $self->{-IND};
755 print $IND h2({-class=>"atitle"},"Albums"),"\n",start_table,"\n";
760 my $IND = $self->{-parent}->{-IND};
761 my $name = $self->{-base};
762 my $title = $self->{-title};
764 $self->{-parent}->{-numofsubs}++;
765 print $IND Tr(td(a({-href=>$name.'/index.html'},$name)),
766 td(a({-href=>$name.'/index.html'},$title))),"\n";
771 my $IND = $self->{-IND};
773 print $IND end_table,"\n",br({-clear=>'all'}),hr,"\n\n";
778 my $IND = $self->{-IND};
779 my $first = $self->{-firstimg}->{-base};
780 my $slideref = sprintf(".html/%s-slide.html",$first);
782 print $IND h2({-class=>"ititle"},"Images ",
783 a({-href=>$slideref,-class=>'showStart',-rel=>'i'.$first},
784 '> slideshow')),"\n";
789 my $IND = $self->{-parent}->{-IND};
790 my $name = $self->{-base};
791 my $title = $self->{-info}->{'Comment'};
792 $title = $name unless ($title);
793 my $thumb = $self->{$sizes[0]}->{'url'};
794 my $info = $self->{-info};
795 my ($w, $h) = dim($info);
797 my $i=0+$self->{-parent}->{-numofimgs};
798 $self->{-parent}->{-numofimgs}++;
800 print $IND a({-name=>$name}),"\n",
801 start_table({-class=>'slide'}),start_Tr,start_td,"\n";
802 print $IND div({-class=>'slidetitle'},
803 "\n ",a({-href=>".html/$name-info.html",
804 -title=>'Image Info: '.$name,
807 start_div({-class=>'slideimage'});
808 if ($self->{-geoloc}) {
809 my ($la,$lo) = @{$self->{-geoloc}};
810 print $IND a({-href=>"http://maps.google.com/".
811 "?q=$la,$lo&ll=$la,$lo",
814 div({-class=>'geoloc'},"")),"\n";
816 print $IND a({-href=>".html/$name-static.html",
822 -alt=>$title})),"\n",end_div,
823 start_div({-class=>'varimages',-id=>'i'.$name,-title=>$title}),"\n";
824 foreach my $sz(@sizes) {
825 my $src=$self->{$sz}->{'url'};
826 my $w=$self->{$sz}->{'dim'}->[0];
827 my $h=$self->{$sz}->{'dim'}->[1];
828 print $IND " ",a({-href=>$src,
831 -title=>"Reduced to ".$w."x".$h},
834 print $IND " ",a({-href=>$name,
836 -title=>'Original'},$w."x".$h),
838 end_td,end_Tr,end_table,"\n";
843 my $IND = $self->{-IND};
845 print $IND br({-clear=>'all'}),hr,"\n\n";
850 my $info = $self->{-info};
867 $msg.=start_table({-class=>'infotable'})."\n";
868 foreach my $k(@infokeys) {
869 $msg.=Tr(td($k.":"),td($info->{$k}))."\n" if ($info->{$k});
871 $msg.=end_table."\n";