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