allow to specify an arbitrary format for comments of new images
[booh] / bin / booh-backend
1 #! /usr/bin/ruby
2 #
3 #                         *  BOOH  *
4 #
5 # A.k.a 'Best web-album Of the world, Or your money back, Humerus'.
6 #
7 # The acronyn sucks, however this is a tribute to Dragon Ball by
8 # Akira Toriyama, where the last enemy beaten by heroes of Dragon
9 # Ball is named "Boo". But there was already a free software project
10 # called Boo, so this one will be it "Booh". Or whatever.
11 #
12 #
13 # Copyright (c) 2005 Guillaume Cottenceau <gc3 at bluewin.ch>
14 #
15 # This software may be freely redistributed under the terms of the GNU
16 # public license version 2.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 require 'getoptlong'
23 require 'gettext'
24 include GetText
25 require 'rexml/document'
26 include REXML
27
28 require 'booh/booh-lib'
29 require 'booh/html-merges'
30
31 #- bind text domain as soon as possible because some _() functions are called early to build data structures
32 bindtextdomain("booh")
33
34 #- options
35 $options = [
36     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
37     [ '--version',       '-V', GetoptLong::NO_ARGUMENT,       _("Print version and exit") ],
38
39     [ '--source',        '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original images/videos as files or subdirs") ],
40     [ '--destination',   '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album") ],
41 #    [ '--clean',         '-c', GetoptLong::NO_ARGUMENT,       _("Clean destination directory") ],
42
43     [ '--theme',         '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
44     [ '--config',        '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing images and videos within directories with captions") ],
45     [ '--config-skel',   '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
46     [ '--merge-config',  '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new/removed images/videos from --source, and change theme info") ],
47     [ '--merge-config-onedir',  '-O', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the subdir specified with --dir") ],
48     [ '--merge-config-subdirs', '-U', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the new subdirs down the subdir specified with --dir") ],
49     [ '--dir',           '-D', GetoptLong::REQUIRED_ARGUMENT, _("Directory for merge with --merge-config-onedir or --merge-config-subdirs") ],
50     [ '--use-config',    '-u', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to change theme info") ],
51     [ '--force',         '-f', GetoptLong::NO_ARGUMENT,       _("Force generation of album even if the GUI marked some directories as already generated") ],
52
53     [ '--sizes',         '-S', GetoptLong::REQUIRED_ARGUMENT, _("Specify the list of images sizes to use instead of all specified in the theme (this is a comma-separated list)") ],
54     [ '--thumbnails-per-row', '-T', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per row in the thumbnails page (if applicable in theme)") ],
55     [ '--optimize-for-32', '-o', GetoptLong::NO_ARGUMENT,       _("Resize images with optimized sizes for 3/2 aspect ratio rather than 4/3 (typical aspect ratio of pictures from non digital cameras are 3/2 when pictures from digital cameras are 4/3)") ],
56     [ '--made-with',     '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages") ],
57     [ '--comments-format','-c', GetoptLong::REQUIRED_ARGUMENT, _("Specify comments format to use for images instead of only filename when creating new albums; use ImageMagick's format") ],
58
59     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
60
61     [ '--for-gui',       '-g', GetoptLong::NO_ARGUMENT,       _("Do the minimum work to be able to see the album under the GUI (don't generate all thumbnails)") ],
62
63     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
64     [ '--info-pipe',     '-i', GetoptLong::REQUIRED_ARGUMENT, _("Name a file where to write information about what's going on (used by the GUI)") ],
65 ]
66
67 #- default values for some globals 
68 $switches = []
69 $stdout.sync = true
70 $no_identify = false
71 $ignore_videos = false
72 $forgui = false
73 $hardlinks_ok = true
74
75 def usage
76     puts _("Usage: %s [OPTION]...") % File.basename($0)
77     $options.each { |ary|
78         printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
79     }
80 end
81
82 def handle_options
83     parser = GetoptLong.new
84     parser.set_options(*$options.collect { |ary| ary[0..2] })
85     begin
86         parser.each_option do |name, arg|
87             case name
88             when '--help'
89                 usage
90                 exit(0)
91
92             when '--version'
93                 puts _("Booh version %s
94
95 Copyright (c) 2005 Guillaume Cottenceau.
96 This is free software; see the source for copying conditions.  There is NO
97 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
98
99                 exit(0)
100
101             when '--source'
102                 $source = File.expand_path(arg.sub(%r|/$|, ''))
103                 if !File.directory?($source)
104                     die _("Argument to --source must be a directory")
105                 end
106             when '--destination'
107                 $dest = File.expand_path(arg.sub(%r|/$|, ''))
108                 if File.exists?($dest) && !File.directory?($dest)
109                     die _("If --destination exists, it must be a directory")
110                 end
111                 if $dest != make_dest_filename($dest)
112                     die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
113                 end
114 #            when '--clean'
115 #                system("rm -rf #{$dest}")
116
117             when '--theme'
118                 $theme = arg
119             when '--config'
120                 arg = File.expand_path(arg)
121                 if File.readable?(arg)
122                     $xmldoc = REXML::Document.new File.new(arg)
123                     $mode = 'use_config'
124                 else
125                     die _('Config file does not exist or is unreadable.')
126                 end
127             when '--config-skel'
128                 arg = File.expand_path(arg)
129                 if File.exists?(arg)
130                     if File.directory?(arg)
131                         die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
132                     else
133                         msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
134                         File.rename(arg, "#{arg}.backup")
135                     end
136                 end
137                 $config_writeto = arg
138                 $mode = 'gen_config'
139             when '--merge-config'
140                 arg = File.expand_path(arg)
141                 if File.readable?(arg)
142                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
143                     $xmldoc = REXML::Document.new File.new(arg)
144                     File.rename(arg, "#{arg}.backup")
145                     $config_writeto = arg
146                     $mode = 'merge_config'
147                 else
148                     die _('Config file does not exist or is unreadable.')
149                 end
150             when '--merge-config-onedir'
151                 arg = File.expand_path(arg)
152                 if File.readable?(arg)
153                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
154                     $xmldoc = REXML::Document.new File.new(arg)
155                     File.rename(arg, "#{arg}.backup")
156                     $config_writeto = arg
157                     $mode = 'merge_config_onedir'
158                 else
159                     die _('Config file does not exist or is unreadable.')
160                 end
161             when '--merge-config-subdirs'
162                 arg = File.expand_path(arg)
163                 if File.readable?(arg)
164                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
165                     $xmldoc = REXML::Document.new File.new(arg)
166                     File.rename(arg, "#{arg}.backup")
167                     $config_writeto = arg
168                     $mode = 'merge_config_subdirs'
169                 else
170                     die _('Config file does not exist or is unreadable.')
171                 end
172             when '--dir'
173                 arg = File.expand_path(arg)
174                 if !File.readable?(arg)
175                     die _('Specified directory to merge with --dir is not readable')
176                 else
177                     $onedir = arg
178                 end
179             when '--use-config'
180                 arg = File.expand_path(arg)
181                 if File.readable?(arg)
182                     msg 2, _("Use config notice: backuping current config file to %s.backup") % arg
183                     $xmldoc = REXML::Document.new File.new(arg)
184                     File.rename(arg, "#{arg}.backup")
185                     $config_writeto = arg
186                     $mode = 'use_config_changetheme'
187                 else
188                     die _('Config file does not exist or is unreadable.')
189                 end
190
191             when '--sizes'
192                 $limit_sizes = arg
193
194             when '--thumbnails-per-row'
195                 $N_per_row = arg
196
197             when '--optimize-for-32'
198                 $optimize_for_32 = true
199
200             when '--made-with'
201                 $madewith = arg
202
203             when '--comments-format'
204                 $commentsformat = arg
205
206             when '--force'
207                 $force = true
208
209             when '--mproc'
210                 $mproc = arg.to_i
211                 $pids = []
212
213             when '--for-gui'
214                 $forgui = true
215
216             when '--verbose-level'
217                 $verbose_level = arg.to_i
218
219             when '--info-pipe'
220                 $info_pipe = File.open(arg, File::WRONLY)
221                 $info_pipe.sync = true
222             end
223         end
224     rescue
225         puts $!
226         usage
227         exit(1)
228     end
229
230     if !$source && $xmldoc
231         $source = from_utf8($xmldoc.root.attributes['source'])
232         $dest = from_utf8($xmldoc.root.attributes['destination'])
233         $theme ||= $xmldoc.root.attributes['theme']
234         $limit_sizes ||= $xmldoc.root.attributes['limit-sizes']
235         if $mode == 'use_config' || $mode =~ /^merge_config/
236             $optimize_for_32 = !$xmldoc.root.attributes['optimize-for-32'].nil?
237             $N_per_row = $xmldoc.root.attributes['thumbnails-per-row']
238             $madewith = $xmldoc.root.attributes['made-with']
239         end
240     end
241
242     if $mode == 'merge_config_onedir' && !$onedir
243         die _("Missing --dir for --merge-config-onedir")
244     end
245     if $mode == 'merge_config_subdirs' && !$onedir
246         die _("Missing --dir for --merge-config-subdirs")
247     end
248
249     if !$source
250         usage
251         exit(0)
252     end
253     if !$dest
254         die _("Missing --destination parameter.")
255     end
256     if !$theme
257         $theme = 'simple'
258     end
259
260     select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
261
262     if !$xmldoc
263         additional_params = ''
264         if $limit_sizes
265             additional_params += "limit-sizes='#{$limit_sizes}'"
266         end
267         if $optimize_for_32
268             additional_params += " optimize-for-32='true'"
269         end
270         if $N_per_row
271             additional_params += " thumbnails-per-row='#{$N_per_row}'"
272         end
273         if $madewith
274             additional_params += " made-with='#{$madewith}'"
275         end
276         $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}' #{additional_params}/>"
277         $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
278         $mode = 'gen_config'
279     end
280
281     if $mode == 'merge_config' || $mode == 'use_config_changetheme'
282         $xmldoc.root.add_attribute('theme', $theme)
283         $xmldoc.root.add_attribute('version', $VERSION)
284         if $limit_sizes
285             $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
286         else
287             $xmldoc.root.delete_attribute('limit-sizes')
288         end
289         if $optimize_for_32
290             $xmldoc.root.add_attribute('optimize-for-32', 'true')
291         else
292             $xmldoc.root.delete_attribute('optimize-for-32')
293         end
294         if $N_per_row
295             $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
296         else
297             $xmldoc.root.delete_attribute('thumbnails-per-row')
298         end
299         if $madewith
300             $xmldoc.root.add_attribute('made-with', $madewith)
301         else
302             $xmldoc.root.delete_attribute('made-with')
303         end
304     end
305
306     if $madewith
307         $madewith = $madewith.gsub('%booh', '"http://zarb.org/~gc/html/booh.html"')
308     end
309 end
310
311 def read_config
312     $config = {}
313 end
314
315 def write_config
316 end
317
318 def info(value)
319     if $info_pipe
320         $info_pipe.puts(value)
321     end
322 end
323
324 def die(value)
325     if $info_pipe
326         $info_pipe.puts("die: " + value)
327     end
328     die_ value
329 end
330
331 def check_installation
332     if !system("which convert >/dev/null 2>/dev/null")
333         die _("The program 'convert' is needed. Please install it. 
334 It is generally available with the 'ImageMagick' software package.")
335     end
336     if !system("which identify >/dev/null 2>/dev/null")
337         msg 1, _("the program 'identify' is needed to get images sizes and EXIF data. Please install it.
338 It is generally available with the 'ImageMagick' software package.")
339         $no_identify = true
340     end
341     missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
342     if missing != []
343         msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
344         $ignore_videos = true
345     end
346 end
347
348 def replace_line(surround, keyword, line)
349     begin
350         contents = eval "$#{keyword}"
351         line.sub!(/#{surround}#{keyword}#{surround}/, contents)
352     rescue TypeError
353         die _("No '%s' found for substitution") % keyword
354     end
355 end
356
357 def build_html_skeletons
358     $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
359     $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
360     $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
361     for line in $html_images + $html_thumbnails + $html_index
362         while line =~ /~~~(\w+)~~~/
363             replace_line('~~~', $1, line)
364         end
365     end
366 end
367
368 def find_caption_value(xmldir, filename)
369     if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
370         return cap.gsub("\n", '<br/>')
371     else
372         return nil
373     end
374 end
375
376 def find_captions(xmldir, images)
377     return images.collect { |img| find_caption_value(xmldir, img) }
378 end
379
380 #- stolen from CVSspam
381 def urlencode(text)
382   text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
383     "%#{sprintf('%2X', $&[0])}"
384   end
385 end
386
387 def all_images_sizes
388     return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
389 end
390
391 def html_reload_to_thumbnails
392     html_reload_to_thumbnails = $preferred_size_reloader.clone
393     html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
394     html_reload_to_thumbnails.gsub!(/~~default_size~~/, $default_size['name'])
395     html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
396     return html_reload_to_thumbnails
397 end
398
399 def discover_iterations(iterations, line)
400     if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
401         for iter in iterations.values
402             if iter['open']
403                 iter['open'] = false
404                 iter['close_wait'] = $1.to_i
405             end
406         end
407         max = $3 == 'N' ? ($N_per_row || $default_N) : $3
408         iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
409         if $1.to_i == 1
410             line.sub!(/.*/, '~~thumbnails~~')
411         else
412             line.sub!(/.*/, '')
413         end
414     elsif line =~ /~~iterate(\d)_close~~/
415         iterations[$1.to_i]['open']  = false;
416         iterations[$1.to_i]['close'] = true;
417         line.sub!(/.*/, '')
418     else
419         for iter in iterations.values
420             if iter['open']
421                 iter['opening'] += line
422                 line.sub!(/.*/, '')
423             end
424             if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
425                 iter['closing'] += line
426                 line.sub!(/.*/, '')
427             end
428         end
429     end
430 end
431
432 def reset_iterations(iterations)
433     for iter in iterations.values
434         iter['value'] = 0
435     end
436 end
437
438 def run_iterations(iterations, amount)
439     html = ''
440     should_rerun = false
441     for level in iterations.keys.sort
442         if iterations[level]['value'] == 0
443             html += iterations[level]['opening']
444         elsif level == iterations.keys.max
445             if !iterations[level]['max'] || iterations[level]['max'] && iterations[level]['value'] + amount <= iterations[level]['max'].to_i
446                 html += iterations[level]['opening']
447             else
448                 should_rerun = true
449             end
450         end
451         iterations[level]['value'] += amount
452         if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
453             iterations[level]['value'] = 0
454             iterations[level-1]['value'] = 0
455             html += iterations[level-1]['closing']
456         end
457     end
458     if should_rerun
459         return html + run_iterations(iterations, amount)
460     else
461         return html
462     end
463 end
464
465 def close_iterations(iterations)
466     html = ''
467     for level in iterations.keys.sort.reverse
468         html += iterations[level]['closing']
469     end
470     return html
471 end
472
473 def img_element(fullpath)
474     if size = get_image_size(fullpath)
475         sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
476     else
477         sizespec = ''
478     end
479     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' class="image" alt="image"/>'
480 end
481
482 def size2js(name)
483     return name.gsub(/-/, '')
484 end
485
486 def substitute_html_sizes(html, sizeobj, type)
487     sizestrings = []
488     if $images_size.length > 1 || (type == 'image' && $limit_sizes =~ /original/)
489         for sizeobj2 in $images_size
490             if sizeobj != sizeobj2
491                 if type == 'thumbnails'
492                     sizestrings << '<a href="thumbnails-' + size2js(sizeobj2['name']) + '.html">' + sizename(sizeobj2['name']) + '</a>'
493                 else
494                     sizestrings << '<a id="link' + size2js(sizeobj2['name']) + '">' + sizename(sizeobj2['name']) + '</a>'
495                 end
496             else
497                 sizestrings << sizename(sizeobj2['name'])
498             end
499         end
500         if type == 'image' && $limit_sizes =~ /original/
501             sizestrings << '<a id="linkoriginal" target="newframe">' + sizename('original') + '</a>'
502         end
503     end
504     html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
505 end
506
507 def xmldir2destdir(xmldir)
508     return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
509 end
510
511 def find_previous_album(xmldir)
512     relative_pos = ''
513     begin
514         #- move to previous dir element if exists
515         if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
516             xmldir = prevelem
517             relative_pos += '../' + xmldir2destdir(xmldir) + '/'
518             child = nil
519             #- after having moved to previous dir, we need to go down last subdir until the last one
520             while child = xmldir.elements['dir']
521                 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
522                     child = nextchild
523                 end
524                 relative_pos += xmldir2destdir(child) + '/'
525                 xmldir = child
526             end
527         else
528             #- previous dir doesn't exist, move to previous dir element if exists
529             xmldir = xmldir.parent
530             if xmldir.name == 'dir' && !xmldir.attributes['deleted']
531                 relative_pos += '../'
532             else
533                 return nil
534             end
535         end
536     end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
537     return File.reduce_path(relative_pos)
538 end
539
540 def find_next_album(xmldir)
541     relative_pos = ''
542     begin
543         #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
544         if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
545             xmldir = firstchild
546             relative_pos += xmldir2destdir(xmldir) + '/'
547         #- next brother
548         elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
549             xmldir = nextbro
550             relative_pos += '../' + xmldir2destdir(xmldir) + '/'
551         else
552             #- go up until we have a next brother or we are finished
553             begin
554                 xmldir = xmldir.parent
555                 relative_pos += '../'
556             end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
557             if xmldir
558                 xmldir = xmldir.next_element_byname('dir')
559                 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
560             else
561                 return nil
562             end
563         end
564     end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
565     return File.reduce_path(relative_pos)
566 end
567
568 def sub_previous_next_album(previous_album, next_album, html)
569     if previous_album
570         html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails.html">' + utf8(_('previous album')) + '</a>')
571         html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
572     else
573         html.gsub!(/~~previous_album~~/, '')
574         html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
575     end
576     if next_album
577         html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails.html">' + utf8(_('next album')) + '</a>')
578         html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
579     else
580         html.gsub!(/~~next_album~~/, '')
581         html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
582     end
583     return html
584 end
585
586 def walk_source_dir
587
588     #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
589     optxpath = {}
590     $xmldoc.elements.each('//dir') { |elem|
591         optxpath[elem.attributes['path']] = elem
592     }
593
594     examined_dirs = nil
595     if $mode == 'merge_config_onedir'
596         examined_dirs = [ $onedir ]
597     elsif $mode == 'merge_config_subdirs'
598         examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
599     else
600         examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
601         if $mode == 'merge_config'
602             $xmldoc.elements.each('//dir') { |elem|
603                 if ! examined_dirs.include?(elem.attributes['path'])
604                     msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
605                     elem.remove
606                 end
607             }
608         end
609     end
610     info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
611
612     examined_dirs.each { |dir|
613         if dir =~ /'/
614             die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
615         end
616         if $mode !~ /^use_config/
617             Dir.entries(dir).each { |file|
618                 if file =~ /['"\[\]]/
619                     die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
620                 end
621             }
622         end
623     }
624
625     examined_dirs.each { |dir|
626         if File.basename(dir) =~ /^\./
627             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
628             next
629         end
630
631         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
632
633         #- place xml document on proper node if exists, else create
634         xmldir = optxpath[utf8(dir)]
635         if $mode == 'use_config' || $mode == 'use_config_changetheme'
636             if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
637                 info("walking: #{dir}|#{$source}, 0 elements")
638                 if xmldir && xmldir.attributes['deleted']
639                     system("rm -rf '#{dest_dir}'")
640                 end
641                 next
642             end
643         else
644             if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
645                 #- add the <dir..> element if necessary
646                 parent = File.dirname(dir)
647                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
648                 if !xmldir
649                     xmldir = $xmldoc.root
650                 end
651                 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
652                 xmldir.delete_attribute('already-generated')
653                 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
654             end
655         end
656         xmldir.delete_attribute('already-generated')
657
658         #- read images/videos entries from config or from directories depending on mode
659         entries = []
660         if $mode == 'use_config' || $mode == 'use_config_changetheme'
661             msg 2, _("Handling %s from config list...") % dir
662             xmldir.elements.each { |element|
663                 if %w(image video).include?(element.name) && !element.attributes['deleted']
664                     entries << from_utf8(element.attributes['filename'])
665                 end
666             }
667         else
668             msg 2, _("Examining %s...") % dir
669             entries = Dir.entries(dir).sort
670             #- populate config in case of gen_config, add new files in case of merge_config
671             for file in entries
672                 if file =~ /['"\[\]]/
673                     msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
674                 else
675                     type = entry2type(file)
676                     if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
677                         if $commentsformat && type == 'image'
678                             comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
679                         else
680                             comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
681                         end
682                         xmldir.add_element type, { "filename" => utf8(file), "caption" => comment }
683                     end
684                 end
685             end
686             if $mode != 'gen_config'
687                 #- cleanup removed files from config and reread entries from config to get proper ordering
688                 entries = []
689                 xmldir.elements.each { |element|
690                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
691                     if %w(image video).include?(element.name)
692                         if !File.readable?(fullpath)
693                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
694                             xmldir.delete(element)
695                         elsif !element.attributes['deleted']
696                             entries << from_utf8(element.attributes['filename'])
697                         end
698                     end
699                 }
700                 #- if there is no more elements here, there is no album here anymore
701                 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
702                     xmldir.delete_attribute('thumbnails-caption')
703                     xmldir.delete_attribute('thumbnails-captionfile')
704                 end
705             end
706         end
707         images = entries.find_all { |e| entry2type(e) == 'image' }
708         msg 3, _("\t%s images") % images.length
709         videos = entries.find_all { |e| entry2type(e) == 'video' }
710         msg 3, _("\t%s videos") % videos.length
711         info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
712
713         system("mkdir -p '#{dest_dir}'")
714
715         #- pass through if there are no images and videos
716         if images.size == 0 && videos.size == 0
717             if !$forgui
718                 #- cleanup old images/videos, especially if this directory contained images/videos previously.
719                 themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
720                                 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
721                 if $mode != 'gen_config'
722                     rightful_images = []
723                     if xmldir.attributes['thumbnails-caption']
724                         rightful_images << 'thumbnails-thumbnail.jpg'
725                     end
726                     xmldir.elements.each('dir') { |child|
727                         if child.attributes['deleted']
728                             next
729                         end
730                         subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
731                         rightful_images << "thumbnails-#{subdir}.jpg"
732                     }
733                     to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !rightful_images.include?(e) } - themestuff
734                     if to_del.size > 0
735                         system("rm -f " + to_del.collect { |e| "'#{dest_dir}/#{e}'" }.join(' '))
736                     end
737                 end
738                 
739                 #- copy any resource file that goes with the theme (css, images..)
740                 themestuff.each { |entry|
741                     if !File.exists?("#{dest_dir}/#{entry}")
742                         psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
743                     end
744                 }
745             end
746             next
747         end
748
749         msg 2, _("Outputting in %s...") % dest_dir
750
751         #- populate data structure with sizes from theme
752         for sizeobj in $images_size
753             fullscreen_images ||= {}
754             fullscreen_images[sizeobj['name']] = []
755             thumbnail_images ||= {}
756             thumbnail_images[sizeobj['name']] = []
757             thumbnail_videos ||= {}
758             thumbnail_videos[sizeobj['name']] = []
759         end
760         #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
761         thumbnail_images['dont-delete-file-for-gui'] = []
762         if $limit_sizes =~ /original/
763             fullscreen_images['original'] = []
764         end
765
766         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
767
768         #- create thumbnails for images
769         images.each { |img|
770             info("processing element")
771             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
772             if $forgui
773                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
774                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
775             else
776                 todo = []
777                 elem = xmldir.elements["image[@filename='#{utf8(img)}']"]
778                 for sizeobj in $images_size
779                     size_fullscreen = sizeobj['fullscreen']
780                     size_thumbnails = sizeobj['thumbnails']
781                     fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
782                     fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
783                     todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
784                     if pano = pano_amount(elem)
785                         thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
786                         size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
787                     end
788                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
789                     thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
790                     todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
791                 end
792                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
793                 if $limit_sizes =~ /original/
794                     fullscreen_images['original'] << img
795                 end
796                 destimg = "#{dest_dir}/#{img}"
797                 if $limit_sizes =~ /original/ && !File.exists?(destimg)
798                     if $hardlinks_ok
799                         if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
800                             $hardlinks_ok = false
801                         end
802                     end
803                     if ! $hardlinks_ok
804                         psys("cp '#{dir}/#{img}' '#{destimg}'")
805                     end
806                 end
807             end
808         }
809
810         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
811
812         #- create thumbnails for videos
813         videos.each { |video|
814             info("processing element")
815             if $forgui
816                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
817                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
818             else
819                 todo = []
820                 for sizeobj in $images_size
821                     size_thumbnails = sizeobj['thumbnails']
822                     thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
823                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
824                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
825                 end
826                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
827             end
828             destvideo = "#{dest_dir}/#{video}"
829             if !File.exists?(destvideo)
830                 if $hardlinks_ok
831                     if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
832                         $hardlinks_ok = false
833                     end
834                 end
835                 if ! $hardlinks_ok
836                     psys("cp '#{dir}/#{video}' '#{destvideo}'")
837                 end
838             end
839         }
840
841         if !$forgui
842             themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
843                              find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
844
845             #- cleanup old images/videos (for when removing elements or sizes)
846             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
847                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
848                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
849                      concat(videos)
850             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ } - themestuff
851             if to_del.size > 0
852                 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
853                 system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
854             end
855
856             #- copy any resource file that goes with the theme (css, images..)
857             themestuff.each { |entry|
858                 if !File.exists?("#{dest_dir}/#{entry}")
859                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
860                 end
861             }
862
863             #- generate .htaccess file if needed
864             if auth_user_file = xmldir.attributes['password-protect']
865                 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
866                 ios = File.open("#{dest_dir}/.htaccess", "w")
867                 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
868                 ios.close
869             end
870
871             msg 3, _("\tgenerating HTML pages...")
872
873             #- generate thumbnails.html (page with thumbnails)
874             for sizeobj in $images_size
875                 info("processing size")
876                 html = $html_thumbnails.collect { |l| l.clone }
877                 iterations = {}
878                 for i in html
879                     i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + '.html#run_slideshow=1">' + utf8(_('Run slideshow!'))+'</a>')
880                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
881                     substitute_html_sizes(i, sizeobj, 'thumbnails')
882                     discover_iterations(iterations, i)
883                 end
884                 html_thumbnails = ''
885                 reset_iterations(iterations)
886                 for file in entries
887                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
888                     if type
889                         if type == 'image' && elem = xmldir.elements["image[@filename='#{utf8(file)}']"]
890                             if  pano = pano_amount(elem)
891                                 html_thumbnails += run_iterations(iterations, pano)
892                                 html_thumbnails.gsub!(/~~colspan~~/) { 'colspan="' + pano.ceil.to_s + '"' }
893                             else
894                                 html_thumbnails += run_iterations(iterations, 1)
895                                 html_thumbnails.gsub!(/~~colspan~~/, '')
896                             end
897                         else 
898                             html_thumbnails += run_iterations(iterations, 1)
899                             html_thumbnails.gsub!(/~~colspan~~/, '')
900                         end
901                         if type == 'image'
902                             index = images.index(file)
903                             html_thumbnails.gsub!(/~~image_iteration~~/,
904                                                   '<a href="image-' + size2js(sizeobj['name']) + '.html#current=' + fullscreen_images[sizeobj['name']][index] +
905                                                       '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
906                                                       img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
907                             html_thumbnails.gsub!(/~~caption_iteration~~/,
908                                                   find_caption_value(xmldir, images[index]) || utf8(images[index]))
909                             html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
910                             html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
911                         elsif type == 'video'
912                             index = videos.index(file)
913                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
914                                 html_thumbnails.gsub!(/~~image_iteration~~/,
915                                                       '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
916                             else
917                                 html_thumbnails.gsub!(/~~image_iteration~~/,
918                                                       '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
919                             end
920                             html_thumbnails.gsub!(/~~caption_iteration~~/,
921                                                   find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
922                             html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
923                             html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
924                         end
925                     end
926                 end
927                 html_thumbnails += close_iterations(iterations)
928                 for i in html
929                     i.sub!(/~~thumbnails~~/, html_thumbnails)
930                     i.gsub!(/~~theme~~/, $theme)
931                     i.gsub!(/~~current_size~~/, sizeobj['name'])
932                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
933                     i.gsub!(/~~madewith~~/, $madewith || '')
934                 end
935                 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}.html", "w")
936                 ios.write(html)
937                 ios.close
938             end
939
940             info("finished processing sizes")
941
942             #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
943             ios = File.open("#{dest_dir}/thumbnails.html", "w")
944             ios.write(html_reload_to_thumbnails)
945             ios.close
946
947             #- generate image.html (page with fullscreen images)
948             if images.size > 0
949                 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
950
951                 for sizeobj in $images_size
952                     html = $html_images.collect { |l| l.clone }
953                     images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
954                     otherimages4js = ''
955                     othersizes = []
956                     for sizeobj2 in all_images_sizes
957                         if sizeobj != sizeobj2
958                             otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
959                             othersizes << "\"#{size2js(sizeobj2['name'])}\""
960                         end
961                     end
962                     for i in html
963                         i.gsub!(/~~images~~/, images4js)
964                         i.gsub!(/~~other_images~~/, otherimages4js)
965                         i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
966                         i.gsub!(/~~captions~~/, captions4js)
967                         i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
968                         i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + '.html" id="thumbnails">' + utf8(_('return to thumbnails')) + '</a>')
969                         i.gsub!(/~~theme~~/, $theme)
970                         i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
971                         i.gsub!(/~~madewith~~/, $madewith || '')
972                         substitute_html_sizes(i, sizeobj, 'image')
973                     end
974                     ios = File.open("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html", "w")
975                     ios.write(html)
976                     ios.close
977                 end
978             end
979         end
980     }
981
982     msg 3, ''
983
984     #- add attributes to <dir..> elements needing so
985     if $mode != 'use_config'
986         msg 3, _("\tfixating configuration file...")
987         $xmldoc.elements.each('//dir') { |element|
988             path = captionpath = element.attributes['path']
989             descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
990             if !descendant_element
991                 msg 3, _("\t\tremoving %s, no element in it") % path
992                 element.remove  #- means we have a directory with nothing interesting in it
993             else
994                 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
995                 basename = File.basename(path)
996                 if element.elements['dir']
997                     if !element.attributes['subdirs-caption']
998                         element.add_attribute('subdirs-caption', basename)
999                     end
1000                     if !element.attributes['subdirs-captionfile']
1001                         element.add_attribute('subdirs-captionfile', captionfile)
1002                     end
1003                 end
1004                 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1005                     if !element.attributes['thumbnails-caption']
1006                         element.add_attribute('thumbnails-caption', basename)
1007                     end
1008                     if !element.attributes['thumbnails-captionfile']
1009                         element.add_attribute('thumbnails-captionfile', captionfile)
1010                     end
1011                 end
1012             end
1013         }
1014     end
1015
1016     #- write down to disk config if necessary
1017     if $config_writeto
1018         ios = File.open($config_writeto, "w")
1019         $xmldoc.write(ios, 0)
1020         ios.close
1021     end
1022
1023     if $forgui
1024         msg 3, _(" completed necessary stuff for GUI, exiting.")
1025         return
1026     end
1027
1028     #- second pass to create index.html files and previous/next links
1029     info("creating index.html")
1030     msg 3, _("\trescanning directories to generate all 'index.html' files...")
1031
1032     #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1033     optxpath = {}
1034     $xmldoc.elements.each('//dir') { |elem|
1035         optxpath[elem.attributes['path']] = elem
1036     }
1037
1038     examined_dirs.each { |dir|
1039         info("index.html: #{dir}|#{$source}")
1040
1041         xmldir = optxpath[utf8(dir)]
1042         if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1043             next
1044         end
1045         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1046
1047         previous_album = find_previous_album(xmldir)
1048         next_album = find_next_album(xmldir)
1049
1050         if xmldir.elements['dir']
1051             html = $html_index.collect { |l| l.clone }
1052             iterations = {}
1053             for i in html
1054                 caption = xmldir.attributes['subdirs-caption']
1055                 i.gsub!(/~~title~~/, caption)
1056                 if xmldir.parent.name == 'dir'
1057                     nav = ''
1058                     path = '..'
1059                     parent = xmldir.parent
1060                     while parent.name == 'dir'
1061                         parentcaption = parent.attributes['subdirs-caption']
1062                         nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
1063                         path += '/..'
1064                         parent = parent.parent
1065                     end
1066                     i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
1067                     i.gsub!(/~~navigation~~/, nav + caption)
1068                 else
1069                     i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
1070                 end
1071                 discover_iterations(iterations, i)
1072             end
1073             
1074             html_index = ''
1075             reset_iterations(iterations)
1076             
1077             #- deal with "current" album (directs to "thumbnails" page)
1078             if xmldir.attributes['thumbnails-caption']
1079                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1080                 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1081                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1082                 html_index += run_iterations(iterations, 1)
1083                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails.html'>" + img_element(thumbnail) + '</a>')
1084                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
1085             end
1086
1087             #- deal with sub-albums (direct to subdirs/index.html pages)
1088             xmldir.elements.each('dir') { |child|
1089                 if child.attributes['deleted']
1090                     next
1091                 end
1092                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1093                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1094                 html_index += run_iterations(iterations, 1)
1095                 captionfile, caption = find_subalbum_caption_info(child)
1096                 gen_thumbnails_subdir(captionfile, child, false,
1097                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1098                 html_index.gsub!(/~~caption_iteration~~/, caption)
1099                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
1100             }
1101
1102             html_index += close_iterations(iterations)
1103
1104             for i in html
1105                 i.gsub!(/~~thumbnails~~/, html_index)
1106                 i.gsub!(/~~madewith~~/, $madewith || '')
1107             end
1108             
1109         else
1110             html = html_reload_to_thumbnails
1111         end
1112
1113         ios = File.open("#{dest_dir}/index.html", "w")
1114         ios.write(html)
1115         ios.close
1116
1117         #- substitute "return to albums" and previous/next correctly
1118         if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1119             for sizeobj in $images_size
1120                 substInFile("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}.html") { |line|
1121                     sub_previous_next_album(previous_album, next_album, line)
1122                     if xmldir.elements['dir']
1123                         line.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('return to albums')) + '</a>')
1124                     else
1125                         if xmldir.parent.name == 'dir'
1126                             line.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('return to albums')) + '</a>')
1127                         else
1128                             line.sub!(/~~return_to_albums~~/, '')
1129                         end
1130                     end
1131                     line
1132                 }
1133                 if xmldir.child_byname_notattr('image', 'deleted')
1134                     substInFile("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html") { |line|
1135                         sub_previous_next_album(previous_album, next_album, line)
1136                     }
1137                 end
1138             end
1139         end
1140     }
1141
1142     msg 3, _(" all done.")
1143 end
1144
1145 handle_options
1146 read_config
1147 check_installation
1148
1149 build_html_skeletons
1150
1151 walk_source_dir