3effa7f5da3b9b4d036f3eefd7dbac49c1c749da
[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) 2004-2008 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 SUPPORTED_LANGUAGES = %w(en de fr ja eo)
35
36 #- options
37 $options = [
38     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
39     [ '--version',       '-V', GetoptLong::NO_ARGUMENT,       _("Print version and exit") ],
40
41     [ '--source',        '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original images/videos as files or subdirs") ],
42     [ '--destination',   '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album") ],
43 #    [ '--clean',         '-c', GetoptLong::NO_ARGUMENT,       _("Clean destination directory") ],
44
45     [ '--theme',         '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
46     [ '--config',        '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing images and videos within directories with captions") ],
47     [ '--config-skel',   '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
48     [ '--merge-config',  '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new/removed images/videos from --source, and change theme info") ],
49     [ '--merge-config-onedir',  '-O', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the subdir specified with --dir") ],
50     [ '--merge-config-subdirs', '-U', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the new subdirs down the subdir specified with --dir") ],
51     [ '--dir',           '-D', GetoptLong::REQUIRED_ARGUMENT, _("Directory for merge with --merge-config-onedir or --merge-config-subdirs") ],
52     [ '--use-config',    '-u', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to change theme info") ],
53     [ '--force',         '-f', GetoptLong::NO_ARGUMENT,       _("Force generation of album even if the GUI marked some directories as already generated") ],
54
55     [ '--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)") ],
56     [ '--multi-languages', '-L', GetoptLong::REQUIRED_ARGUMENT, _("Specify the list of languages to support (uses Apache MultiViews); this is a comma-separated list of supported languages, with last element used as the default language; for example: 'fr,eo,en,en'; supported languages: %s") % SUPPORTED_LANGUAGES.join(', ') ],
57     [ '--thumbnails-per-row', '-T', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per row in the thumbnails page (if applicable in theme)") ],
58     [ '--thumbnails-per-page', '-p', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per page in the thumbnails page, after which split occurs") ],
59     [ '--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)") ],
60     [ '--index-link',    '-l', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small link returning to wherever you see fit in your website (or somewhere else)") ],
61     [ '--made-with',     '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
62     [ '--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") ],
63
64     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
65
66     [ '--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)") ],
67
68     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
69     [ '--info-pipe',     '-i', GetoptLong::REQUIRED_ARGUMENT, _("Name a file where to write information about what's going on (used by the GUI)") ],
70 ]
71
72 #- default values for some globals 
73 $switches = []
74 $stdout.sync = true
75 $no_identify = false
76 $ignore_videos = false
77 $forgui = false
78 $hardlinks_ok = true
79
80 def usage
81     puts _("Usage: %s [OPTION]...") % File.basename($0)
82     $options.each { |ary|
83         printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
84     }
85 end
86
87 def handle_options
88     parser = GetoptLong.new
89     parser.set_options(*$options.collect { |ary| ary[0..2] })
90     begin
91         parser.each_option do |name, arg|
92             case name
93             when '--help'
94                 usage
95                 exit(0)
96
97             when '--version'
98                 puts _("Booh version %s
99
100 Copyright (c) 2005 Guillaume Cottenceau.
101 This is free software; see the source for copying conditions.  There is NO
102 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
103
104                 exit(0)
105
106             when '--source'
107                 $source = File.expand_path(arg.sub(%r|/$|, ''))
108                 if !File.directory?($source)
109                     die _("Argument to --source must be a directory")
110                 end
111             when '--destination'
112                 $dest = File.expand_path(arg.sub(%r|/$|, ''))
113                 if File.exists?($dest) && !File.directory?($dest)
114                     die _("If --destination exists, it must be a directory")
115                 end
116                 if $dest != make_dest_filename($dest)
117                     die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
118                 end
119 #            when '--clean'
120 #                system("rm -rf #{$dest}")
121
122             when '--theme'
123                 $theme = arg
124             when '--config'
125                 arg = File.expand_path(arg)
126                 if File.readable?(arg)
127                     $xmldoc = REXML::Document.new File.new(arg)
128                     $mode = 'use_config'
129                 else
130                     die _('Config file does not exist or is unreadable.')
131                 end
132             when '--config-skel'
133                 arg = File.expand_path(arg)
134                 if File.exists?(arg)
135                     if File.directory?(arg)
136                         die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
137                     else
138                         msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
139                         File.rename(arg, "#{arg}.backup")
140                     end
141                 end
142                 $config_writeto = arg
143                 $mode = 'gen_config'
144             when '--merge-config'
145                 arg = File.expand_path(arg)
146                 if File.readable?(arg)
147                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
148                     $xmldoc = REXML::Document.new File.new(arg)
149                     File.rename(arg, "#{arg}.backup")
150                     $config_writeto = arg
151                     $mode = 'merge_config'
152                 else
153                     die _('Config file does not exist or is unreadable.')
154                 end
155             when '--merge-config-onedir'
156                 arg = File.expand_path(arg)
157                 if File.readable?(arg)
158                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
159                     $xmldoc = REXML::Document.new File.new(arg)
160                     File.rename(arg, "#{arg}.backup")
161                     $config_writeto = arg
162                     $mode = 'merge_config_onedir'
163                 else
164                     die _('Config file does not exist or is unreadable.')
165                 end
166             when '--merge-config-subdirs'
167                 arg = File.expand_path(arg)
168                 if File.readable?(arg)
169                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
170                     $xmldoc = REXML::Document.new File.new(arg)
171                     File.rename(arg, "#{arg}.backup")
172                     $config_writeto = arg
173                     $mode = 'merge_config_subdirs'
174                 else
175                     die _('Config file does not exist or is unreadable.')
176                 end
177             when '--dir'
178                 arg = File.expand_path(arg)
179                 if !File.readable?(arg)
180                     die _('Specified directory to merge with --dir is not readable')
181                 else
182                     $onedir = arg
183                 end
184             when '--use-config'
185                 arg = File.expand_path(arg)
186                 if File.readable?(arg)
187                     msg 2, _("Use config notice: backuping current config file to %s.backup") % arg
188                     $xmldoc = REXML::Document.new File.new(arg)
189                     File.rename(arg, "#{arg}.backup")
190                     $config_writeto = arg
191                     $mode = 'use_config_changetheme'
192                 else
193                     die _('Config file does not exist or is unreadable.')
194                 end
195
196             when '--sizes'
197                 $limit_sizes = arg
198
199             when '--multi-languages'
200                 parts = arg.split(',')
201                 if parts.size == 0 || parts.find_all { |e| ! SUPPORTED_LANGUAGES.include?(e.strip) }.size > 0
202                     die _("--multi-languages: argument must be a comma-separated list of supported languages, with last element used as the default language; for example: 'fr,eo,en,en'; supported languages: %s") % SUPPORTED_LANGUAGES.join(', ')
203                 end
204                 $multi_languages = [ parts[0..-2], parts[-1] ]
205
206             when '--thumbnails-per-row'
207                 $N_per_row = arg
208
209             when '--thumbnails-per-page'
210                 $N_per_page = arg
211
212             when '--optimize-for-32'
213                 $optimize_for_32 = true
214
215             when '--made-with'
216                 $madewith = arg
217
218             when '--index-link'
219                 $indexlink = arg
220
221             when '--comments-format'
222                 $commentsformat = arg
223
224             when '--force'
225                 $force = true
226
227             when '--mproc'
228                 $mproc = arg.to_i
229                 $pids = []
230
231             when '--for-gui'
232                 $forgui = true
233
234             when '--verbose-level'
235                 $verbose_level = arg.to_i
236
237             when '--info-pipe'
238                 $info_pipe = File.open(arg, File::WRONLY)
239                 $info_pipe.sync = true
240             end
241         end
242     rescue
243         puts $!
244         usage
245         exit(1)
246     end
247
248     if !$source && $xmldoc
249         $source = from_utf8($xmldoc.root.attributes['source']).sub(%r|/$|, '')
250         $dest = from_utf8($xmldoc.root.attributes['destination']).sub(%r|/$|, '')
251         $theme ||= $xmldoc.root.attributes['theme']
252         $limit_sizes ||= $xmldoc.root.attributes['limit-sizes']
253         if $mode == 'use_config' || $mode =~ /^merge_config/
254             $optimize_for_32 = !$xmldoc.root.attributes['optimize-for-32'].nil?
255             $N_per_row = $xmldoc.root.attributes['thumbnails-per-row']
256             languages = $xmldoc.root.attributes['multi-languages']
257             if languages
258                 languages = languages.split(',')
259                 $multi_languages = [ languages[0..-2], languages[-1] ]
260             end
261             $N_per_page = $xmldoc.root.attributes['thumbnails-per-page']
262             $madewith = $xmldoc.root.attributes['made-with']
263             $indexlink = $xmldoc.root.attributes['index-link']
264         end
265     end
266
267     if $mode == 'merge_config_onedir' && !$onedir
268         die _("Missing --dir for --merge-config-onedir")
269     end
270     if $mode == 'merge_config_subdirs' && !$onedir
271         die _("Missing --dir for --merge-config-subdirs")
272     end
273
274     if !$source
275         usage
276         exit(0)
277     end
278     if !$dest
279         die _("Missing --destination parameter.")
280     end
281     if !$theme
282         $theme = 'simple'
283     end
284
285     select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
286
287     if !$xmldoc
288         additional_params = ''
289         if $limit_sizes
290             additional_params += "limit-sizes='#{$limit_sizes}'"
291         end
292         if $multi_languages
293             additional_params += " multi-languages='#{$multi_languages[0].join(',')},#{$multi_languages[1]}'"
294         end
295         if $optimize_for_32
296             additional_params += " optimize-for-32='true'"
297         end
298         if $N_per_row
299             additional_params += " thumbnails-per-row='#{$N_per_row}'"
300         end
301         if $N_per_page
302             additional_params += " thumbnails-per-page='#{$N_per_page}'"
303         end
304         if $madewith
305             additional_params += " made-with='#{$madewith}'"
306         end
307         if $indexlink
308             additional_params += " index-link='#{$indexlink}'"
309         end
310         $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}' #{additional_params}/>"
311         $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
312         $mode = 'gen_config'
313     end
314
315     if $mode == 'merge_config' || $mode == 'use_config_changetheme'
316         $xmldoc.root.add_attribute('theme', $theme)
317         $xmldoc.root.add_attribute('version', $VERSION)
318         if $limit_sizes
319             $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
320         else
321             $xmldoc.root.delete_attribute('limit-sizes')
322         end
323         if $multi_languages
324             $xmldoc.root.add_attribute('multi-languages', $multi_languages[0].join(',') + ',' + $multi_languages[1])
325         else
326             $xmldoc.root.delete_attribute('multi-languages')
327         end
328
329         if $optimize_for_32
330             $xmldoc.root.add_attribute('optimize-for-32', 'true')
331         else
332             $xmldoc.root.delete_attribute('optimize-for-32')
333         end
334         if $N_per_row
335             $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
336         else
337             $xmldoc.root.delete_attribute('thumbnails-per-row')
338         end
339         if $N_per_page
340             $xmldoc.root.add_attribute('thumbnails-per-page', $N_per_page)
341         else
342             $xmldoc.root.delete_attribute('thumbnails-per-page')
343         end
344         if $madewith
345             $xmldoc.root.add_attribute('made-with', $madewith)
346         else
347             $xmldoc.root.delete_attribute('made-with')
348         end
349         if $indexlink
350             $xmldoc.root.add_attribute('index-link', $indexlink)
351         else
352             $xmldoc.root.delete_attribute('index-link')
353         end
354     end
355
356     if $madewith
357         $madewith = $madewith.gsub('%booh', '"http://booh.org/"')
358     end
359     if $multi_languages
360         $htmlsuffix = ''
361     else
362         $htmlsuffix = '.html'
363     end
364 end
365
366 def read_config
367     $config = {}
368 end
369
370 def write_config
371 end
372
373 def info(value)
374     if $info_pipe
375         $info_pipe.puts(value)
376     end
377 end
378
379 def die(value)
380     if $info_pipe
381         $info_pipe.puts("die: " + value)
382     end
383     die_ value
384 end
385
386 def check_installation
387     if !system("which convert >/dev/null 2>/dev/null")
388         die _("The program 'convert' is needed. Please install it. 
389 It is generally available with the 'ImageMagick' software package.")
390     end
391     if !system("which identify >/dev/null 2>/dev/null")
392         msg 1, _("the program 'identify' is needed to get images sizes and EXIF data. Please install it.
393 It is generally available with the 'ImageMagick' software package.")
394         $no_identify = true
395     end
396     missing = %w(mplayer).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
397     if missing != []
398         msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
399         $ignore_videos = true
400     end
401 end
402
403 def replace_line(surround, keyword, line)
404     begin
405         contents = eval "$#{keyword}"
406         line.sub!(/#{surround}#{keyword}#{surround}/, contents)
407     rescue TypeError
408         die _("No '%s' found for substitution") % keyword
409     end
410 end
411
412 def build_html_skeletons
413     $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
414     $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
415     $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
416     for line in $html_images + $html_thumbnails + $html_index
417         while line =~ /~~~(\w+)~~~/
418             replace_line('~~~', $1, line)
419         end
420     end
421 end
422
423 def find_caption_value(xmldir, filename)
424     if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
425         return cap.gsub("\n", '<br/>')
426     else
427         return nil
428     end
429 end
430
431 def find_captions(xmldir, images)
432     return images.collect { |img| find_caption_value(xmldir, img) }
433 end
434
435 #- stolen from CVSspam
436 def urlencode(text)
437   text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
438     "%#{sprintf('%2X', $&[0])}"
439   end
440 end
441
442 def all_images_sizes
443     return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
444 end
445
446 def html_reload_to_thumbnails
447     html_reload_to_thumbnails = $preferred_size_reloader.clone
448     html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
449     html_reload_to_thumbnails.gsub!(/~~default_size~~/, $default_size['name'])
450     html_reload_to_thumbnails.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
451     html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
452     size_auto_chooser = '';
453     all_images_sizes.find_all { |s| s.has_key?('optimizedforwidth') }.
454                      sort { |a,b| b['optimizedforwidth'].to_i <=> a['optimizedforwidth'].to_i }.
455                      each { |s| size_auto_chooser += "if (w + 50 > #{s['optimizedforwidth']}) { return 'thumbnails-#{size2js(s['name'])}-0#{$htmlsuffix}'; }\n" }
456     html_reload_to_thumbnails.gsub!(/~~size_auto_chooser~~/, size_auto_chooser)
457     return html_reload_to_thumbnails
458 end
459
460 def discover_iterations(iterations, line)
461     if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
462         for iter in iterations.values
463             if iter['open']
464                 iter['open'] = false
465                 iter['close_wait'] = $1.to_i
466             end
467         end
468         max = $3 == 'N' ? ($N_per_row || $default_N) : $3
469         iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
470         if $1.to_i == 1
471             line.sub!(/.*/, '~~thumbnails~~')
472         else
473             line.sub!(/.*/, '')
474         end
475     elsif line =~ /~~iterate(\d)_close~~/
476         iterations[$1.to_i]['open']  = false;
477         iterations[$1.to_i]['close'] = true;
478         line.sub!(/.*/, '')
479     else
480         for iter in iterations.values
481             if iter['open']
482                 iter['opening'] += line
483                 line.sub!(/.*/, '')
484             end
485             if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
486                 iter['closing'] += line
487                 line.sub!(/.*/, '')
488             end
489         end
490     end
491 end
492
493 def reset_iterations(iterations)
494     for iter in iterations.values
495         iter['value'] = 0
496     end
497 end
498
499 def run_iterations(iterations, amount)
500     html = ''
501     should_rerun = false
502     for level in iterations.keys.sort
503         if iterations[level]['value'] == 0
504             html += iterations[level]['opening']
505         elsif level == iterations.keys.max
506             if !iterations[level]['max'] || iterations[level]['max'] && iterations[level]['value'] + amount <= iterations[level]['max'].to_i
507                 html += iterations[level]['opening']
508             else
509                 should_rerun = true
510             end
511         end
512         iterations[level]['value'] += amount
513         if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
514             iterations[level]['value'] = 0
515             iterations[level-1]['value'] = 0
516             html += iterations[level-1]['closing']
517         end
518     end
519     if should_rerun
520         return html + run_iterations(iterations, amount)
521     else
522         return html
523     end
524 end
525
526 def close_iterations(iterations)
527     html = ''
528     for level in iterations.keys.sort.reverse
529         html += iterations[level]['closing']
530     end
531     return html
532 end
533
534 def img_element(fullpath)
535     if size = get_image_size(fullpath)
536         sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
537     else
538         sizespec = ''
539     end
540     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="image"/>'
541 end
542
543 def size2js(name)
544     return name.gsub(/-/, '')
545 end
546
547 def substitute_html_sizes(html, sizeobj, type, suffix)
548     sizestrings = []
549     if $images_size.length > 1 || (type == 'image' && $limit_sizes =~ /original/)
550         for sizeobj2 in $images_size
551             sizejs = size2js(sizeobj2['name'])
552             sizen = defer_translation(sizename(sizeobj2['name'], false))
553             if sizeobj != sizeobj2
554                 if type == 'thumbnails'
555                     sizestrings << '<a href="thumbnails-' + sizejs + suffix + $htmlsuffix + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
556                 else
557                     sizestrings << '<a id="link' + sizejs + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
558                 end
559             else
560                 sizestrings << sizen
561             end
562         end
563         if type == 'image' && $limit_sizes =~ /original/
564             sizestrings << '<a id="linkoriginal" target="newframe">' + defer_translation(sizename('original'), false) + '</a>'
565         end
566     end
567     html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
568 end
569
570 def substitute_navigation(html, xmldir)
571     if xmldir.parent.name == 'dir'
572         nav = ''
573         path = '..'
574         parent = xmldir.parent
575         while parent.name == 'dir'
576             parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
577             nav = "<a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a> #{defer_translation(N_(" > "))} #{nav}"
578             path += '/..'
579             parent = parent.parent
580         end
581         html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
582         html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
583     else
584         html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
585     end
586 end
587
588 def substitute_pathtobase(html, xmldir)
589     path = ''
590     location = xmldir
591     while location.parent.name == 'dir'
592         path = '../' + path
593         location = location.parent
594     end
595     html.gsub!(/~~pathtobase~~/, path)
596 end
597
598 def xmldir2destdir(xmldir)
599     return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
600 end
601
602 def find_previous_album(xmldir)
603     relative_pos = ''
604     begin
605         #- move to previous dir element if exists
606         if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
607             xmldir = prevelem
608             relative_pos += '../' + xmldir2destdir(xmldir) + '/'
609             child = nil
610             #- after having moved to previous dir, we need to go down last subdir until the last one
611             while child = xmldir.elements['dir']
612                 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
613                     child = nextchild
614                 end
615                 relative_pos += xmldir2destdir(child) + '/'
616                 xmldir = child
617             end
618         else
619             #- previous dir doesn't exist, move to previous dir element if exists
620             xmldir = xmldir.parent
621             if xmldir.name == 'dir' && !xmldir.attributes['deleted']
622                 relative_pos += '../'
623             else
624                 return nil
625             end
626         end
627     end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
628     return File.reduce_path(relative_pos)
629 end
630
631 def find_next_album(xmldir)
632     relative_pos = ''
633     begin
634         #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
635         if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
636             xmldir = firstchild
637             relative_pos += xmldir2destdir(xmldir) + '/'
638         #- next brother
639         elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
640             xmldir = nextbro
641             relative_pos += '../' + xmldir2destdir(xmldir) + '/'
642         else
643             #- go up until we have a next brother or we are finished
644             begin
645                 xmldir = xmldir.parent
646                 relative_pos += '../'
647             end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
648             if xmldir
649                 xmldir = xmldir.next_element_byname('dir')
650                 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
651             else
652                 return nil
653             end
654         end
655     end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
656     return File.reduce_path(relative_pos)
657 end
658
659 def find_translation_for_file(file, msg)
660     if $multi_languages
661         if file =~ /\.(\w\w)\.html$/
662             bindtextdomain("booh", { :locale => "#{$1}.UTF-8" })
663             return _(msg)
664         else
665             die "Internal error: cannot find multi language suffix of file '#{file}'"
666         end
667     else
668         return utf8(_(msg))
669     end
670 end
671
672 def sub_previous_next_album(file, previous_album, next_album, html)
673     if previous_album
674         html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails' + $htmlsuffix + '">' + find_translation_for_file(file, N_('previous album')) + '</a>')
675         html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
676     else
677         html.gsub!(/~~previous_album~~/, '')
678         html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
679     end
680     if next_album
681         html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails' + $htmlsuffix + '">' + find_translation_for_file(file, N_('next album')) + '</a>')
682         html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
683     else
684         html.gsub!(/~~next_album~~/, '')
685         html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
686     end
687     return html
688 end
689
690 def save_html(html, base_filename)
691     if html.class == Array
692         html = html.join("\n")
693     end
694     if $multi_languages
695         for language in $multi_languages[0]
696             bindtextdomain("booh", { :locale => "#{language}.UTF-8" })
697             ios = File.open("#{base_filename}.#{language}.html", "w")
698             ios.write(html.gsub(/@@(.*?)@@/) { _($1) })
699             ios.close
700         end
701     else
702         ios = File.open("#{base_filename}.html", "w")
703         ios.write(html.gsub(/@@(.*?)@@/) { utf8(_($1)) })
704         ios.close
705     end
706 end
707
708 def walk_source_dir
709
710     #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
711     optxpath = {}
712     $xmldoc.elements.each('//dir') { |elem|
713         optxpath[elem.attributes['path']] = elem
714     }
715
716     examined_dirs = nil
717     if $mode == 'merge_config_onedir'
718         examined_dirs = [ $onedir ]
719     elsif $mode == 'merge_config_subdirs'
720         examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
721     else
722         examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
723         if $mode == 'merge_config'
724             $xmldoc.elements.each('//dir') { |elem|
725                 if ! examined_dirs.include?(elem.attributes['path'])
726                     msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
727                     elem.remove
728                 end
729             }
730         end
731     end
732     info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
733
734     examined_dirs.each { |dir|
735         if dir =~ /'/
736             die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
737         end
738         if $mode !~ /^use_config/
739             Dir.entries(dir).each { |file|
740                 if file =~ /['"\[\]]/
741                     die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
742                 end
743             }
744         end
745     }
746
747     examined_dirs.each { |dir|
748         if File.basename(dir) =~ /^\./
749             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
750             next
751         end
752
753         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
754
755         #- place xml document on proper node if exists, else create
756         xmldir = optxpath[utf8(dir)]
757         if $mode == 'use_config' || $mode == 'use_config_changetheme'
758             if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
759                 info("walking: #{dir}|#{$source}, 0 elements")
760                 if xmldir && xmldir.attributes['deleted']
761                     system("rm -rf '#{dest_dir}'")
762                 end
763                 next
764             end
765         else
766             if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
767                 #- add the <dir..> element if necessary
768                 parent = File.dirname(dir)
769                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
770                 if !xmldir
771                     xmldir = $xmldoc.root
772                 end
773                 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
774                 xmldir.delete_attribute('already-generated')
775                 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
776             end
777         end
778         xmldir.delete_attribute('already-generated')
779
780         #- read images/videos entries from config or from directories depending on mode
781         entries = []
782         if $mode == 'use_config' || $mode == 'use_config_changetheme'
783             msg 2, _("Handling %s from config list...") % dir
784             xmldir.elements.each { |element|
785                 if %w(image video).include?(element.name) && !element.attributes['deleted']
786                     entries << from_utf8(element.attributes['filename'])
787                 end
788             }
789         else
790             msg 2, _("Examining %s...") % dir
791             entries = Dir.entries(dir).sort
792             #- populate config in case of gen_config, add new files in case of merge_config
793             for file in entries
794                 if file =~ /['"\[\]]/
795                     msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
796                 else
797                     type = entry2type(file)
798                     if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
799                         #- hack: don't run identify (which is slow) if format only contains default %t
800                         if $commentsformat && type == 'image' && $commentsformat != '%t'
801                             comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
802                         else
803                             comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
804                         end
805                         xmldir.add_element type, { "filename" => utf8(file), "caption" => comment }
806                     end
807                 end
808             end
809             if $mode != 'gen_config'
810                 #- cleanup removed files from config and reread entries from config to get proper ordering
811                 entries = []
812                 xmldir.elements.each { |element|
813                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
814                     if %w(image video).include?(element.name)
815                         if !File.readable?(fullpath)
816                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
817                             xmldir.delete(element)
818                         elsif !element.attributes['deleted']
819                             entries << from_utf8(element.attributes['filename'])
820                         end
821                     end
822                 }
823                 #- if there is no more elements here, there is no album here anymore
824                 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
825                     xmldir.delete_attribute('thumbnails-caption')
826                     xmldir.delete_attribute('thumbnails-captionfile')
827                 end
828             end
829         end
830         images = entries.find_all { |e| entry2type(e) == 'image' }
831         msg 3, _("\t%s images") % images.length
832         videos = entries.find_all { |e| entry2type(e) == 'video' }
833         msg 3, _("\t%s videos") % videos.length
834         info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
835
836         system("mkdir -p '#{dest_dir}'")
837
838         #- generate .htaccess file
839         if !$forgui
840             ios = File.open("#{dest_dir}/.htaccess", "w")
841             ios.write("AddCharset UTF-8 .html\n")
842             if auth_user_file = xmldir.attributes['password-protect']
843                 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
844                 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
845             end
846             if $multi_languages
847                 ios.write("LanguagePriority #{$multi_languages[1]}\n")
848                 ios.write("ForceLanguagePriority Prefer Fallback\n")
849                 ios.write("DirectoryIndex index\n")
850             end
851             ios.close
852         end
853
854         #- pass through if there are no images and videos
855         if images.size == 0 && videos.size == 0
856             if !$forgui
857                 #- cleanup old images/videos, especially if this directory contained images/videos previously.
858                 themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
859                                 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root CVS).include?(e) }
860                 themestuff_root = Dir.entries("#{$FPATH}/themes/#{$theme}/root").
861                                      find_all { |e| !%w(. .. CVS).include?(e) }
862                 if $mode != 'gen_config'
863                     rightful_images = [ '.htaccess' ]
864                     if xmldir.attributes['thumbnails-caption']
865                         rightful_images << 'thumbnails-thumbnail.jpg'
866                     end
867                     xmldir.elements.each('dir') { |child|
868                         if child.attributes['deleted']
869                             next
870                         end
871                         subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
872                         rightful_images << "thumbnails-#{subdir}.jpg"
873                     }
874                     to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !rightful_images.include?(e) } - themestuff - themestuff_root
875                     if to_del.size > 0
876                         File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
877                     end
878                 end
879                 
880                 #- copy any resource file that goes with the theme (css, images..)
881                 themestuff.each { |entry|
882                     if !File.exists?(File.join(dest_dir, entry))
883                         psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
884                     end
885                 }
886
887                 #- copy any root-only resource file that goes with the theme (css, images..)
888                 if xmldir.parent.name != 'dir'
889                     themestuff_root.each { |entry|
890                         if !File.exists?(File.join(dest_dir, entry))
891                             psys("cp '#{$FPATH}/themes/#{$theme}/root/#{entry}' '#{dest_dir}'")
892                         end
893                     }
894                 end
895             end
896             next
897         end
898
899         msg 2, _("Outputting in %s...") % dest_dir
900
901         #- populate data structure with sizes from theme
902         for sizeobj in $images_size
903             fullscreen_images ||= {}
904             fullscreen_images[sizeobj['name']] = []
905             thumbnail_images ||= {}
906             thumbnail_images[sizeobj['name']] = []
907             thumbnail_videos ||= {}
908             thumbnail_videos[sizeobj['name']] = []
909         end
910         #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
911         thumbnail_images['dont-delete-file-for-gui'] = []
912         if $limit_sizes =~ /original/
913             fullscreen_images['original'] = []
914         end
915
916         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
917
918         #- create thumbnails for images
919         images.each { |img|
920             info("processing element")
921             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
922             if $forgui
923                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
924                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
925             else
926                 todo = []
927                 elem = xmldir.elements["image[@filename='#{utf8(img)}']"]
928                 for sizeobj in $images_size
929                     size_fullscreen = sizeobj['fullscreen']
930                     size_thumbnails = sizeobj['thumbnails']
931                     fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
932                     fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
933                     todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
934                     if pano = pano_amount(elem)
935                         thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
936                         size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
937                     end
938                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
939                     thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
940                     todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
941                 end
942                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
943                 if $limit_sizes =~ /original/
944                     fullscreen_images['original'] << img
945                 end
946                 destimg = "#{dest_dir}/#{img}"
947                 if $limit_sizes =~ /original/ && !File.exists?(destimg)
948                     if $hardlinks_ok
949                         if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
950                             $hardlinks_ok = false
951                         end
952                     end
953                     if ! $hardlinks_ok
954                         psys("cp '#{dir}/#{img}' '#{destimg}'")
955                     end
956                 end
957             end
958         }
959
960         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
961
962         #- create thumbnails for videos
963         videos.each { |video|
964             info("processing element")
965             if $forgui
966                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
967                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
968             else
969                 todo = []
970                 for sizeobj in $images_size
971                     size_thumbnails = sizeobj['thumbnails']
972                     thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
973                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
974                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
975                 end
976                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
977             end
978             destvideo = "#{dest_dir}/#{video}"
979             if !File.exists?(destvideo)
980                 if $hardlinks_ok
981                     if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
982                         $hardlinks_ok = false
983                     end
984                 end
985                 if ! $hardlinks_ok
986                     psys("cp '#{dir}/#{video}' '#{destvideo}'")
987                 end
988             end
989         }
990
991         if !$forgui
992             themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
993                             find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root CVS).include?(e) }
994             themestuff_root = Dir.entries("#{$FPATH}/themes/#{$theme}/root").
995                                  find_all { |e| !%w(. .. CVS).include?(e) }
996             
997             #- cleanup old images/videos (for when removing elements or sizes)
998             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
999                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
1000                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
1001                      concat(videos).
1002                      push('.htaccess')
1003             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ } - themestuff - themestuff_root
1004             if to_del.size > 0
1005                 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
1006                 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
1007             end
1008
1009             #- copy any resource file that goes with the theme (css, images..)
1010             themestuff.each { |entry|
1011                 if !File.exists?(File.join(dest_dir, entry))
1012                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
1013                 end
1014             }
1015             
1016             #- copy any root-only resource file that goes with the theme (css, images..)
1017             if xmldir.parent.name != 'dir'
1018                 themestuff_root.each { |entry|
1019                     if !File.exists?(File.join(dest_dir, entry))
1020                         psys("cp '#{$FPATH}/themes/#{$theme}/root/#{entry}' '#{dest_dir}'")
1021                     end
1022                 }
1023             end
1024             
1025             msg 3, _("\tgenerating HTML pages...")
1026             #- fixup max per page
1027             if $N_per_page && $N_per_row
1028                 $N_per_page = $N_per_page.to_i / $N_per_row.to_i * $N_per_row.to_i
1029             end
1030
1031             #- generate thumbnails*.html (page with thumbnails)
1032             image2thumbnailpage4js = []
1033             for sizeobj in $images_size
1034                 info("processing size")
1035                 html = $html_thumbnails.collect { |l| l.clone }
1036                 iterations = {}
1037                 for i in html
1038                     i.sub!(/~~title~~/,
1039                            xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
1040                     discover_iterations(iterations, i)
1041                 end
1042                 all_pages = []
1043                 html_thumbnails = ''
1044                 html_thumbnails_nojs = ''
1045                 counter = 0
1046                 pagecount = 0
1047                 reset_iterations(iterations)
1048                 #- preprocess the @filename->elem, rexml is very slow with that; we dramatically improve this part of the processing
1049                 optfilename = {}
1050                 xmldir.elements.each('image') { |elem|
1051                     optfilename[elem.attributes['filename']] = elem
1052                 }
1053                 for file in entries
1054                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1055                     if type
1056                         if type == 'image' && elem = optfilename[utf8(file)]
1057                             if pano = pano_amount(elem)
1058                                 html_elem = run_iterations(iterations, pano)
1059                                 counter += count = pano.ceil
1060                                 html_elem.gsub!(/~~colspan~~/) { "colspan=\"#{count}\"" }
1061                             else
1062                                 html_elem = run_iterations(iterations, 1)
1063                                 counter += 1
1064                                 html_elem.gsub!(/~~colspan~~/, '')
1065                             end
1066                         else 
1067                             html_elem = run_iterations(iterations, 1)
1068                             counter += 1
1069                             html_elem.gsub!(/~~colspan~~/, '')
1070                         end
1071                         if type == 'image'
1072                             index = images.index(file)
1073                             html_elem.gsub!(/~~caption_iteration~~/,
1074                                             find_caption_value(xmldir, images[index]) || utf8(images[index]))
1075                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
1076                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
1077                         elsif type == 'video'
1078                             index = videos.index(file)
1079                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1080                                 html_elem.gsub!(/~~image_iteration~~/,
1081                                                 '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
1082                             else
1083                                 html_elem.gsub!(/~~image_iteration~~/,
1084                                                 '<a href="' + videos[index] + '">' + defer_translation(N_("(no preview)")) + '</a>')
1085                             end
1086                             html_elem.gsub!(/~~caption_iteration~~/, find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
1087                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
1088                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
1089                         end
1090                         html_thumbnails += html_elem
1091                         html_thumbnails_nojs += html_elem
1092                         if type == 'image'
1093                             html_thumbnails.gsub!(/~~image_iteration~~/,
1094                                                   '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
1095                                                       '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1096                                                       img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
1097                             html_thumbnails_nojs.gsub!(/~~image_iteration~~/, 
1098                                                        '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1099                                                        img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
1100                             #- remember in which thumbnails page is this element, for image->thumbnail link
1101                             if sizeobj == $images_size[0]
1102                                 image2thumbnailpage4js << pagecount
1103                             end
1104                         end
1105
1106                         if counter == $N_per_page
1107                             html_thumbnails      += close_iterations(iterations)
1108                             html_thumbnails_nojs += close_iterations(iterations)
1109                             all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1110                             html_thumbnails = ''
1111                             html_thumbnails_nojs = ''
1112                             counter = 0
1113                             reset_iterations(iterations)
1114                             pagecount += 1
1115                         end
1116                     end
1117                 end
1118                 if counter > 0
1119                     html_thumbnails      += close_iterations(iterations)
1120                     html_thumbnails_nojs += close_iterations(iterations)
1121                     all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1122                 end
1123                 for i in html
1124                     i.gsub!(/~~theme~~/, $theme)
1125                     i.gsub!(/~~current_size~~/, sizeobj['name'])
1126                     i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1127                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
1128                     i.gsub!(/~~madewith~~/, $madewith || '')
1129                     i.gsub!(/~~indexlink~~/, $indexlink || '')
1130                     substitute_navigation(i, xmldir)
1131                 end
1132                 html_nojs = html.collect { |l| l.clone }
1133                 pagecount = 0
1134                 for page in all_pages
1135                     html_thumbnails, html_thumbnails_nojs = page
1136                     final_html = html.collect { |l| l.clone }
1137                     mstuff = defer_translation(N_("Pages: ")) +
1138                              (pagecount > 0 ? "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount - 1}#{$htmlsuffix}\">" + defer_translation(N_("<- Previous")) + "</a> " : '') +
1139                              all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
1140                              (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
1141                     for i in final_html
1142                         i.sub!(/~~run_slideshow~~/,
1143                                images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
1144                         i.sub!(/~~thumbnails~~/, html_thumbnails)
1145                         if all_pages.size == 1
1146                             i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1147                         else
1148                             i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1149                             i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', ''))
1150                         end
1151                         substitute_html_sizes(i, sizeobj, 'thumbnails', "-#{pagecount}")
1152                         substitute_pathtobase(i, xmldir)
1153                     end
1154                     save_html(final_html, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-#{pagecount}")
1155                     final_html_nojs = html_nojs.collect { |l| l.clone }
1156                     for i in final_html_nojs
1157                         i.sub!(/~~run_slideshow~~/, defer_translation(N_("<i>Click on an image to view it larger</i>")))
1158                         i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
1159                         if all_pages.size == 1
1160                             i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1161                         else
1162                             i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1163                             i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', '-nojs'))
1164                         end
1165                         substitute_html_sizes(i, sizeobj, 'thumbnails', "-nojs-#{pagecount}")
1166                     end
1167                     save_html(final_html_nojs, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs-#{pagecount}")
1168                     pagecount += 1
1169                 end
1170             end
1171
1172             info("finished processing sizes")
1173
1174             #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
1175             save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
1176
1177             #- generate image.html (page with fullscreen images)
1178             if images.size > 0
1179                 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
1180                 thumbnailspage4js = image2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', ')
1181                 for sizeobj in $images_size
1182                     html = $html_images.collect { |l| l.clone }
1183                     images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
1184                     otherimages4js = ''
1185                     othersizes = []
1186                     for sizeobj2 in all_images_sizes
1187                         if sizeobj != sizeobj2
1188                             otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
1189                             othersizes << "\"#{size2js(sizeobj2['name'])}\""
1190                         end
1191                     end
1192                     for i in html
1193                         i.gsub!(/~~images~~/, images4js)
1194                         i.gsub!(/~~other_images~~/, otherimages4js)
1195                         i.gsub!(/~~thumbnailspages~~/, thumbnailspage4js)
1196                         i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1197                         i.gsub!(/~~captions~~/, captions4js)
1198                         i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
1199                         i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + $htmlsuffix + '" id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
1200                         i.gsub!(/~~theme~~/, $theme)
1201                         i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1202                         i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1203                         i.gsub!(/~~madewith~~/, $madewith || '')
1204                         i.gsub!(/~~indexlink~~/, $indexlink || '')
1205                         substitute_html_sizes(i, sizeobj, 'image', '')
1206                         substitute_navigation(i, xmldir)
1207                         substitute_pathtobase(i, xmldir)
1208                     end
1209                     save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
1210                 end
1211             end
1212         end
1213     }
1214
1215     msg 3, ''
1216
1217     #- add attributes to <dir..> elements needing so
1218     if $mode != 'use_config'
1219         msg 3, _("\tfixating configuration file...")
1220         $xmldoc.elements.each('//dir') { |element|
1221             path = captionpath = element.attributes['path']
1222             descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1223             if !descendant_element
1224                 msg 3, _("\t\tremoving %s, no element in it") % path
1225                 element.remove  #- means we have a directory with nothing interesting in it
1226             else
1227                 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1228                 basename = File.basename(path)
1229                 if element.elements['dir']
1230                     if !element.attributes['subdirs-caption']
1231                         element.add_attribute('subdirs-caption', basename)
1232                     end
1233                     if !element.attributes['subdirs-captionfile']
1234                         element.add_attribute('subdirs-captionfile', captionfile)
1235                     end
1236                 end
1237                 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1238                     if !element.attributes['thumbnails-caption']
1239                         element.add_attribute('thumbnails-caption', basename)
1240                     end
1241                     if !element.attributes['thumbnails-captionfile']
1242                         element.add_attribute('thumbnails-captionfile', captionfile)
1243                     end
1244                 end
1245             end
1246         }
1247     end
1248
1249     #- write down to disk config if necessary
1250     if $config_writeto
1251         ios = File.open($config_writeto, "w")
1252         $xmldoc.write(ios, 0)
1253         ios.close
1254     end
1255
1256     if $forgui
1257         msg 3, _(" completed necessary stuff for GUI, exiting.")
1258         return
1259     end
1260
1261     #- second pass to create index.html files and previous/next links
1262     info("creating index.html")
1263     msg 3, _("\trescanning directories to generate all 'index.html' files...")
1264
1265     #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1266     optxpath = {}
1267     $xmldoc.elements.each('//dir') { |elem|
1268         optxpath[elem.attributes['path']] = elem
1269     }
1270
1271     examined_dirs.each { |dir|
1272         info("index.html: #{dir}|#{$source}")
1273
1274         xmldir = optxpath[utf8(dir)]
1275         if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1276             next
1277         end
1278         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1279
1280         previous_album = find_previous_album(xmldir)
1281         next_album = find_next_album(xmldir)
1282
1283         if xmldir.elements['dir']
1284             html = $html_index.collect { |l| l.clone }
1285             iterations = {}
1286             for i in html
1287                 caption = xmldir.attributes['subdirs-caption']
1288                 i.gsub!(/~~title~~/, caption)
1289                 substitute_navigation(i, xmldir)
1290                 substitute_pathtobase(i, xmldir)
1291                 discover_iterations(iterations, i)
1292             end
1293             
1294             html_index = ''
1295             reset_iterations(iterations)
1296             
1297             #- deal with "current" album (directs to "thumbnails" page)
1298             if xmldir.attributes['thumbnails-caption']
1299                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1300                 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1301                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1302                 html_index += run_iterations(iterations, 1)
1303                 html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail) + '</a>')
1304                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
1305             end
1306
1307             #- deal with sub-albums (direct to subdirs/index.html pages)
1308             xmldir.elements.each('dir') { |child|
1309                 if child.attributes['deleted']
1310                     next
1311                 end
1312                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1313                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1314                 html_index += run_iterations(iterations, 1)
1315                 captionfile, caption = find_subalbum_caption_info(child)
1316                 gen_thumbnails_subdir(captionfile, child, false,
1317                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1318                 html_index.gsub!(/~~caption_iteration~~/, caption)
1319                 html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail) + '</a>')
1320             }
1321
1322             html_index += close_iterations(iterations)
1323
1324             for i in html
1325                 i.gsub!(/~~thumbnails~~/, html_index)
1326                 i.gsub!(/~~madewith~~/, $madewith || '')
1327                 i.gsub!(/~~indexlink~~/, $indexlink || '')
1328             end
1329             
1330         else
1331             html = html_reload_to_thumbnails
1332         end
1333
1334         save_html(html, "#{dest_dir}/index")
1335         if $multi_languages
1336             #- in case MultiViews will not work, generate some compat
1337             ios = File.open("#{dest_dir}/index.html", "w")
1338             ios.write("<html><head><meta http-equiv=\"refresh\" content=\"0.1;url=index.#{$multi_languages[1]}.html\"></head></html>")
1339             ios.close
1340         end
1341
1342         #- substitute multiple "return to albums", previous/next correctly
1343         #- the following two statements are dramatical optimizations to executing for each substInFile callback
1344         dirpresent = xmldir.elements['dir']
1345         parentname = xmldir.parent.name
1346         if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1347             for suffix in [ '', '-nojs' ]
1348                 for sizeobj in $images_size
1349                     Dir.glob("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}-*.html") do |file|
1350                         substInFile(file) { |line|
1351                             sub_previous_next_album(file, previous_album, next_album, line)
1352                             if dirpresent
1353                                 line.sub!(/~~return_to_albums~~/, '<a href="index' + $htmlsuffix + '">' + find_translation_for_file(file, N_('return to albums')) + '</a>')
1354                             else
1355                                 if parentname == 'dir'
1356                                     line.sub!(/~~return_to_albums~~/, '<a href="../index' + $htmlsuffix + '">' + find_translation_for_file(file, N_('return to albums')) + '</a>')
1357                                 else
1358                                     line.sub!(/~~return_to_albums~~/, '')
1359                                 end
1360                             end
1361                             line
1362                         }
1363                     end
1364                     if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1365                         Dir.glob("#{dest_dir}/image-#{size2js(sizeobj['name'])}*.html") do |file|
1366                             substInFile(file) { |line|
1367                                 sub_previous_next_album(file, previous_album, next_album, line)
1368                             }
1369                         end
1370                     end
1371                 end
1372             end
1373         end
1374     }
1375
1376     msg 3, _(" all done.")
1377 end
1378
1379 handle_options
1380 read_config
1381 check_installation
1382
1383 build_html_skeletons
1384
1385 walk_source_dir