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