also rescue Gtk::InitError for booh-backend
[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-2011 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 'booh/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     [ '--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)") ],
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-2011 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 '--flv-generator'
238                 if arg !~ /%f/ || arg !~ /%o/
239                     die _("--flv-generator: argument must contain %f for the input video and %o for the output video")
240                 end
241                 $flv_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 = 'simple'
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 $flv_generator
418         $xmldoc.root.add_attribute('flv-generator', $flv_generator)
419     else
420         $xmldoc.root.delete_attribute('flv-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             if auth_user_file = xmldir.attributes['password-protect']
947                 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
948                 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
949             end
950             if $multi_languages
951                 ios.write("Options +Multiviews\n")
952                 ios.write("LanguagePriority #{$multi_languages[1]}\n")
953                 ios.write("ForceLanguagePriority Prefer Fallback\n")
954                 ios.write("DirectoryIndex index\n")
955             end
956             ios.close
957         end
958
959         #- pass through if there are no images and videos
960         if images.size == 0 && videos.size == 0
961             if !$forgui
962                 #- cleanup old images/videos, especially if this directory contained images/videos previously.
963                 if $mode != 'gen_config'
964                     rightful_images = [ '.htaccess' ]
965                     if xmldir.attributes['thumbnails-caption']
966                         rightful_images << 'thumbnails-thumbnail.jpg'
967                     end
968                     xmldir.elements.each('dir') { |child|
969                         if child.attributes['deleted']
970                             next
971                         end
972                         subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
973                         rightful_images << "thumbnails-#{subdir}.jpg"
974                     }
975                     to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !rightful_images.include?(e) }
976                     if to_del.size > 0
977                         File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
978                     end
979                 end
980                 
981                 #- copy any resource file that goes with the theme (css, images..)
982                 themestuff = Dir.entries("#{$themedir}").
983                                  find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
984                 themestuff.each { |entry|
985                     if !File.exists?(File.join(dest_dir, entry))
986                         psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
987                     end
988                 }
989
990                 #- copy any root-only resource file that goes with the theme (css, images..)
991                 if xmldir.parent.name != 'dir'
992                     themestuff_root = Dir.entries("#{$themedir}/root").
993                                           find_all { |e| !%w(. ..).include?(e) }
994                     themestuff_root.each { |entry|
995                         if !File.exists?(File.join(dest_dir, entry))
996                             psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
997                         end
998                     }
999                     #- copy flowplayer stuff if needed
1000                     if $flv_generator
1001                         psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1002                     end
1003                 end
1004             end
1005             next
1006         end
1007
1008         msg 2, _("Outputting in %s...") % dest_dir
1009
1010         #- populate data structure with sizes from theme
1011         for sizeobj in $images_size
1012             fullscreen_images ||= {}
1013             fullscreen_images[sizeobj['name']] = []
1014             thumbnail_images ||= {}
1015             thumbnail_images[sizeobj['name']] = []
1016             fullscreen_videos ||= {}
1017             fullscreen_videos[sizeobj['name']] = []
1018             thumbnail_videos ||= {}
1019             thumbnail_videos[sizeobj['name']] = []
1020         end
1021         #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
1022         thumbnail_images['dont-delete-file-for-gui'] = []
1023         if $limit_sizes =~ /original/
1024             fullscreen_images['original'] = []
1025             fullscreen_videos['original'] = []
1026         end
1027
1028         images.size >= 1 and msg 3, _("\tcreating photos thumbnails...")
1029
1030         #- create thumbnails for images
1031         images.each { |img|
1032             info("processing element")
1033             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
1034             elem = optelements['image|' + utf8(img)]
1035             if $forgui
1036                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1037                 gen_thumbnails_element("#{dir}/#{img}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1038             else
1039                 todo = []
1040                 for sizeobj in $images_size
1041                     size_fullscreen = sizeobj['fullscreen']
1042                     size_thumbnails = sizeobj['thumbnails']
1043                     fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1044                     fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
1045                     todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1046                     if pano = pano_amount(elem)
1047                         thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
1048                         size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
1049                     end
1050                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1051                     thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
1052                     todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
1053                 end
1054                 gen_thumbnails_element("#{dir}/#{img}", elem, true, todo)
1055                 if $limit_sizes =~ /original/
1056                     fullscreen_images['original'] << img
1057                 end
1058                 destimg = "#{dest_dir}/#{img}"
1059                 if $limit_sizes =~ /original/ && !File.exists?(destimg)
1060                     if $hardlinks_ok
1061                         if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
1062                             $hardlinks_ok = false
1063                         end
1064                     end
1065                     if ! $hardlinks_ok
1066                         psys("cp '#{dir}/#{img}' '#{destimg}'")
1067                     end
1068                 end
1069             end
1070         }
1071
1072         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
1073         transcoded_videos = {}
1074         flv_videos = {}
1075
1076         #- create thumbnails for videos
1077         videos.each { |video|
1078             info("processing element")
1079             base_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, ''))
1080             elem = optelements['video|' + utf8(video)]
1081             if $forgui
1082                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1083                 gen_thumbnails_element("#{dir}/#{video}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1084             else
1085                 todo = []
1086                 for sizeobj in $images_size
1087                     size_fullscreen = sizeobj['fullscreen']
1088                     size_thumbnails = sizeobj['thumbnails']
1089                     fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1090                     fullscreen_videos[sizeobj['name']] << File.basename(fullscreen_dest_img)
1091                     todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1092                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1093                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
1094                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1095                 end
1096                 gen_thumbnails_element("#{dir}/#{video}", elem, true, todo)
1097
1098                 if $transcode_videos
1099                     parts = $transcode_videos.split(':', 2)
1100                     basedestvideo = video.sub(/\.\w+/, '') + '.' + parts[0]
1101                     transcoded_videos[video] = basedestvideo
1102                     destvideo = "#{dest_dir}/#{basedestvideo}"
1103                     if ! File.exists?(destvideo)
1104                         psys(parts[1].gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1105                     end
1106
1107                 elsif $flv_generator
1108                     basedestvideo = video.sub(/\.\w+/, '') + '.flv'
1109                     flv_videos[video] = basedestvideo
1110                     destvideo = "#{dest_dir}/#{basedestvideo}"
1111                     if File.exists?(destvideo) && File.size(destvideo) == 0
1112                         File.delete(destvideo)
1113                     end
1114                     if ! File.exists?(destvideo)
1115                         psys($flv_generator.gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1116                     end
1117
1118                 else
1119                     destvideo = "#{dest_dir}/#{video}"
1120                     if ! File.exists?(destvideo)
1121                         if $hardlinks_ok
1122                             if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
1123                                 $hardlinks_ok = false
1124                             end
1125                         end
1126                         if ! $hardlinks_ok
1127                             psys("cp '#{dir}/#{video}' '#{destvideo}'")
1128                         end
1129                     end
1130                 end
1131             end
1132         }
1133
1134         if !$forgui            
1135             #- cleanup old images/videos (for when removing elements or sizes)
1136             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
1137                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
1138                      concat(fullscreen_videos.collect { |e| e[1] }.flatten).
1139                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
1140                      concat($transcode_videos ? transcoded_videos.values : $flv_generator ? flv_videos.values : videos).
1141                      push('.htaccess')
1142             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ }
1143             if to_del.size > 0
1144                 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
1145                 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
1146             end
1147
1148             #- copy any resource file that goes with the theme (css, images..)
1149             themestuff = Dir.entries("#{$themedir}").
1150                              find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
1151             themestuff.each { |entry|
1152                 if !File.exists?(File.join(dest_dir, entry))
1153                     psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
1154                 end
1155             }
1156             
1157             #- copy any root-only resource file that goes with the theme (css, images..)
1158             if xmldir.parent.name != 'dir'
1159                 themestuff_root = Dir.entries("#{$themedir}/root").
1160                                       find_all { |e| !%w(. ..).include?(e) }
1161                 themestuff_root.each { |entry|
1162                     if !File.exists?(File.join(dest_dir, entry))
1163                         psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
1164                     end
1165                 }
1166                 #- copy flowplayer stuff if needed
1167                 if $flv_generator
1168                     psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1169                 end
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                     i.sub!(/~~flowplayer_head_code~~/, ($flv_generator && videos.size > 0) ? '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.2.6.min.js"></script>' : '')
1187                     discover_iterations(iterations, i)
1188                 end
1189                 all_pages = []
1190                 html_thumbnails = ''
1191                 html_thumbnails_nojs = ''
1192                 counter = 0
1193                 pagecount = 0
1194                 reset_iterations(iterations)
1195                 #- preprocess the @filename->elem, rexml is very slow with that; we dramatically improve this part of the processing
1196                 optfilename = {}
1197                 xmldir.elements.each('image') { |elem|
1198                     optfilename[elem.attributes['filename']] = elem
1199                 }
1200                 for file in entries
1201                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1202                     if type
1203                         homogeinize_width = 100 / ($N_per_row || $default_N).to_i
1204                         if type == 'image' && elem = optfilename[utf8(file)]
1205                             if pano = pano_amount(elem)
1206                                 html_elem = run_iterations(iterations, pano)
1207                                 counter += count = pano.ceil
1208                                 html_elem.gsub!(/~~colspan~~/) { "colspan=\"#{count}\"" }
1209                                 homogeinize_width *= count
1210                             else
1211                                 html_elem = run_iterations(iterations, 1)
1212                                 counter += 1
1213                                 html_elem.gsub!(/~~colspan~~/, '')
1214                             end
1215                         else 
1216                             html_elem = run_iterations(iterations, 1)
1217                             counter += 1
1218                             html_elem.gsub!(/~~colspan~~/, '')
1219                         end
1220                         html_elem.gsub!(/~~homogeinize_width~~/) { "width=\"#{homogeinize_width}%\"" }
1221                         if type == 'image'
1222                             index = images.index(file)
1223                             caption = find_caption_value(xmldir, images[index]) || utf8(images[index])
1224                             html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1225                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
1226                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
1227                         elsif type == 'video'
1228                             index = videos.index(file)
1229                             caption = find_caption_value(xmldir, videos[index]) || utf8(videos[index])
1230                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1231                                 video_preview = '<div class="thumbnail_video">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</div>'
1232                             else
1233                                 video_preview = defer_translation(N_("(no preview)"))
1234                             end
1235                             if $flv_generator
1236                                 size = get_image_size("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1237                                 if ! size
1238                                     sizeobj['thumbnails'] =~ /(\d+)x(\d+)/
1239                                     size = { :x => $1, :y => $2 }
1240                                 end
1241                                 sizespec = 'width:' + size[:x].to_s + 'px;height:' + (size[:y] + 24).to_s + 'px'
1242                                 image_iteration = '<a href="' + flv_videos[videos[index]] + '" style="display:block;' + sizespec + '"' +
1243                                                   '   id="player' + index.to_s + '">' + video_preview +
1244                                                   '<img src="~~pathtobase~~play_video.png" style="position:relative;top:-' + ((size[:y]+48)/2).to_s + 'px;border:0;background-color:transparent"/></a>' +
1245                                                   '<script>flowplayer("player' + index.to_s + '", "~~pathtobase~~flowplayer-3.2.7.swf")</script>'
1246                                 html_elem.gsub!(/~~image_iteration~~/, apply_hook(:image_iteration, image_iteration, 'video'))
1247                             else
1248                                 html_elem.gsub!(/~~image_iteration~~/,
1249                                                 '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
1250                                                     video_preview + '</a>')
1251                             end
1252                             html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1253                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
1254                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
1255                         end
1256                         html_thumbnails += html_elem
1257                         html_thumbnails_nojs += html_elem
1258                         if type == 'image'
1259                             img_preview = '<div class="thumbnail_image">' + img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</div>'
1260                             html_thumbnails.gsub!(/~~image_iteration~~/,
1261                                                   '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
1262                                                       '" name="' + fullscreen_images[sizeobj['name']][index] + '">' + img_preview + '</a>')
1263                             html_thumbnails_nojs.gsub!(/~~image_iteration~~/, 
1264                                                        '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1265                                                        img_preview + '</a>')
1266                         end
1267                         #- remember in which thumbnails page is this element, for element->thumbnail link
1268                         if sizeobj == $images_size[0]
1269                             element2thumbnailpage4js << pagecount
1270                         end
1271
1272                         if counter == $N_per_page
1273                             html_thumbnails      += close_iterations(iterations)
1274                             html_thumbnails_nojs += close_iterations(iterations)
1275                             all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1276                             html_thumbnails = ''
1277                             html_thumbnails_nojs = ''
1278                             counter = 0
1279                             reset_iterations(iterations)
1280                             pagecount += 1
1281                         end
1282                     end
1283                 end
1284                 if counter > 0
1285                     html_thumbnails      += close_iterations(iterations)
1286                     html_thumbnails_nojs += close_iterations(iterations)
1287                     all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1288                 end
1289                 for i in html
1290                     i.gsub!(/~~theme~~/, $theme)
1291                     i.gsub!(/~~current_size~~/, sizeobj['name'])
1292                     i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1293                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
1294                     i.gsub!(/~~madewith~~/, $madewith || '')
1295                     i.gsub!(/~~indexlink~~/, $indexlink || '')
1296                     if !$indexlink || $indexlink.empty?
1297                        i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1298                     else
1299                        i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1300                     end
1301                     substitute_addthis(i)
1302                     substitute_navigation(i, xmldir)
1303                 end
1304                 html_nojs = html.collect { |l| l.clone }
1305                 pagecount = 0
1306                 for page in all_pages
1307                     html_thumbnails, html_thumbnails_nojs = page
1308                     final_html = html.collect { |l| l.clone }
1309                     mstuff = defer_translation(N_("Pages: ")) +
1310                              (pagecount > 0 ? "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount - 1}#{$htmlsuffix}\">" + defer_translation(N_("<- Previous")) + "</a> " : '') +
1311                              all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
1312                              (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
1313                     for i in final_html
1314                         i.sub!(/~~run_slideshow_link~~/, entries.size <= 1 ? '' : 'image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1')
1315                         i.sub!(/~~run_slideshow_text~~/, defer_translation(N_("Run slideshow!")))
1316                         i.sub!(/~~run_slideshow~~/,
1317                                entries.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
1318                         i.sub!(/~~thumbnails~~/, html_thumbnails)
1319                         if all_pages.size == 1
1320                             i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1321                         else
1322                             i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1323                             i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', ''))
1324                         end
1325                         substitute_html_sizes(i, sizeobj, 'thumbnails', "-#{pagecount}")
1326                         substitute_pathtobase(i, xmldir)
1327                     end
1328                     save_html(final_html, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-#{pagecount}")
1329                     final_html_nojs = html_nojs.collect { |l| l.clone }
1330                     for i in final_html_nojs
1331                         i.sub!(/~~run_slideshow~~/, defer_translation(N_("<i>Click on an image to view it larger</i>")))
1332                         i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
1333                         if all_pages.size == 1
1334                             i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1335                         else
1336                             i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1337                             i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', '-nojs'))
1338                         end
1339                         substitute_html_sizes(i, sizeobj, 'thumbnails', "-nojs-#{pagecount}")
1340                         substitute_pathtobase(i, xmldir)
1341                     end
1342                     save_html(final_html_nojs, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs-#{pagecount}")
1343                     pagecount += 1
1344                 end
1345             end
1346
1347             info("finished processing sizes")
1348
1349             #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
1350             save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
1351
1352             #- generate image.html (page with fullscreen images)
1353             captions4js = []
1354             types4js = []
1355             videos4js = []
1356             for file in entries
1357                 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1358                 if type
1359                     caption = find_caption_value(xmldir, file)
1360                     if caption
1361                         captions4js << '"' + quote_caption(caption, true) + '"'
1362                     else
1363                         captions4js << '""'
1364                     end
1365                     types4js << '"' + type + '"'
1366                     if type == 'video'
1367                         index = videos.index(file)
1368                         if $flv_generator
1369                             videos4js << '"' + flv_videos[videos[index]] + '"'
1370                         else
1371                             videos4js << '"' + videos[index] + '"'
1372                         end
1373                     else
1374                         videos4js << '""'
1375                     end
1376                 end
1377             end
1378
1379             for sizeobj in $images_size
1380                 elements4js = []
1381                 elemswidths4js = []
1382                 elemsheights4js = []
1383                 for file in entries
1384                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1385                     if type
1386                         if type == 'image'
1387                             index = images.index(file)
1388                             elements4js << '"' + fullscreen_images[sizeobj['name']][index] + '"'
1389                             size = get_image_size("#{dest_dir}/#{fullscreen_images[sizeobj['name']][index]}")
1390                             if size
1391                                 elemswidths4js << size[:x].to_s
1392                                 elemsheights4js << size[:y].to_s
1393                             else
1394                                 elemswidths4js << "''"
1395                                 elemsheights4js << "''"
1396                             end
1397                         else
1398                             index = videos.index(file)
1399                             elements4js << '"' + fullscreen_videos[sizeobj['name']][index] + '"'
1400                             size = get_image_size("#{dest_dir}/#{fullscreen_videos[sizeobj['name']][index]}")
1401                             if size
1402                                 elemswidths4js << size[:x].to_s
1403                                 elemsheights4js << size[:y].to_s
1404                             else
1405                                 elemswidths4js << "''"
1406                                 elemsheights4js << "''"
1407                             end
1408                         end
1409                     end
1410                 end
1411
1412                 html = $html_images.collect { |l| l.clone }
1413                 hiddenimages4remotes = '<span style="display:none">' + thumbnail_images[sizeobj['name']][0..4].collect { |e| "<img src=\"#{e}\"/>" }.join('') + '</span>'
1414                 otherelements4js = ''
1415                 othersizes = []
1416                 for sizeobj2 in all_images_sizes
1417                     if sizeobj != sizeobj2
1418                         oe4js = []
1419                         for file in entries
1420                             type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1421                             if type
1422                                 if type == 'image'
1423                                     index = images.index(file)
1424                                     oe4js << '"' + fullscreen_images[sizeobj2['name']][index] + '"'
1425                                 elsif sizeobj2['name'] != 'original'
1426                                     index = videos.index(file)
1427                                     oe4js << '"' + fullscreen_videos[sizeobj2['name']][index] + '"'
1428                                 end
1429                             end
1430                         end
1431                         otherelements4js += "var elements_#{size2js(sizeobj2['name'])} = new Array(" + oe4js.join(', ') + ");\n"
1432                         othersizes << "\"#{size2js(sizeobj2['name'])}\""
1433                     end
1434                 end
1435                 for i in html
1436                     i.gsub!(/~~images~~/, elements4js.join(', '))
1437                     i.gsub!(/~~types~~/, types4js.join(', '))
1438                     i.gsub!(/~~videos~~/, videos4js.join(', '))
1439                     i.gsub!(/~~widths~~/, elemswidths4js.join(', '))
1440                     i.gsub!(/~~heights~~/, elemsheights4js.join(', '))
1441                     i.gsub!(/~~hidden_images_for_remotes~~/, hiddenimages4remotes)
1442                     i.gsub!(/~~other_images~~/, otherelements4js)
1443                     i.gsub!(/~~thumbnailspages~~/, element2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', '))
1444                     i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1445                     i.gsub!(/~~captions~~/, captions4js.join(', '))
1446                     i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1447                     if $flv_generator && videos.size > 0
1448                         i.sub!(/~~flowplayer_head_code~~/, '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.2.6.min.js"></script>')
1449                         i.sub!(/~~flowplayer_active~~/, 'true')
1450                     else
1451                         i.sub!(/~~flowplayer_head_code~~/, '')
1452                         i.sub!(/~~flowplayer_active~~/, 'false')
1453                     end
1454
1455                     i.gsub!(/~~thumbnails~~/, '<a id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
1456                     i.gsub!(/~~theme~~/, $theme)
1457                     i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1458                     i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1459                     i.gsub!(/~~madewith~~/, $madewith || '')
1460                     i.gsub!(/~~indexlink~~/, $indexlink || '')
1461                     if !$indexlink || $indexlink.empty?
1462                         i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1463                     else
1464                         i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1465                     end
1466                     substitute_addthis(i)
1467                     substitute_html_sizes(i, sizeobj, 'image', '')
1468                     substitute_navigation(i, xmldir)
1469                     substitute_pathtobase(i, xmldir)
1470                 end
1471                 save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
1472             end
1473         end
1474     }
1475
1476     msg 3, ''
1477
1478     #- add attributes to <dir..> elements needing so
1479     if $mode != 'use_config'
1480         msg 3, _("\tfixating configuration file...")
1481         $xmldoc.elements.each('//dir') { |element|
1482             path = captionpath = element.attributes['path']
1483             descendant_element = nil
1484             #- search if there is at least one image or video down that dir; use workarounds to rexml slowness
1485             #- first, look down only one level, very fast
1486             first_desc = nil
1487             element.elements.each { |elem|
1488                 if first_desc.nil?
1489                     first_desc = elem
1490                 end
1491                 if elem.name == 'image' || elem.name == 'video'
1492                     descendant_element = elem
1493                     break
1494                 end
1495             }
1496             if descendant_element.nil?
1497                 #- if there was nothing or only directory down one level, look down the first subdir
1498                 if ! first_desc.nil?
1499                     first_desc.elements.each { |elem|
1500                         if elem.name == 'image' || elem.name == 'video'
1501                             descendant_element = elem
1502                             break
1503                         end
1504                     }
1505                 end
1506                 if descendant_element.nil?
1507                     #- if there was still nothing found, use complete albeit slow method
1508                     descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1509                 end
1510             end
1511             if !descendant_element
1512                 msg 3, _("\t\tremoving %s, no element in it") % path
1513                 element.remove  #- means we have a directory with nothing interesting in it
1514             else
1515                 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1516                 basename = File.basename(path)
1517                 if element.elements['dir']
1518                     if !element.attributes['subdirs-caption']
1519                         element.add_attribute('subdirs-caption', basename)
1520                     end
1521                     if !element.attributes['subdirs-captionfile']
1522                         element.add_attribute('subdirs-captionfile', captionfile)
1523                     end
1524                 end
1525                 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1526                     if !element.attributes['thumbnails-caption']
1527                         element.add_attribute('thumbnails-caption', basename)
1528                     end
1529                     if !element.attributes['thumbnails-captionfile']
1530                         element.add_attribute('thumbnails-captionfile', captionfile)
1531                     end
1532                 end
1533             end
1534         }
1535     end
1536
1537     #- write down to disk config if necessary
1538     if $config_writeto
1539         ios = File.open($config_writeto, "w")
1540         $xmldoc.write(ios)
1541         ios.close
1542     end
1543
1544     if $forgui
1545         msg 3, _("completed necessary stuff for GUI, exiting.")
1546         return
1547     end
1548
1549     #- second pass to create index.html files and previous/next links
1550     info("creating index.html")
1551     msg 3, _("\trescanning directories to generate all 'index.html' files...")
1552
1553     #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1554     optxpath = {}
1555     $xmldoc.elements.each('//dir') { |elem|
1556         optxpath[elem.attributes['path']] = elem
1557     }
1558
1559     examined_dirs.each { |dir|
1560         info("index.html: #{dir}|#{$source}")
1561
1562         xmldir = optxpath[utf8(dir)]
1563         if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1564             next
1565         end
1566         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1567
1568         previous_album = find_previous_album(xmldir)
1569         next_album = find_next_album(xmldir)
1570
1571         if xmldir.elements['dir']
1572             html = $html_index.collect { |l| l.clone }
1573             iterations = {}
1574             for i in html
1575                 caption = xmldir.attributes['subdirs-caption']
1576                 i.gsub!(/~~title~~/, quote_caption(caption))
1577                 substitute_navigation(i, xmldir)
1578                 substitute_pathtobase(i, xmldir)
1579                 discover_iterations(iterations, i)
1580             end
1581             
1582             html_index = ''
1583             reset_iterations(iterations)
1584             
1585             #- deal with "current" album (directs to "thumbnails" page)
1586             if xmldir.attributes['thumbnails-caption']
1587                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1588                 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1589                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1590                 html_index += run_iterations(iterations, 1)
1591                 caption = xmldir.attributes['thumbnails-caption']
1592                 html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1593                 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1594             end
1595
1596             #- deal with sub-albums (direct to subdirs/index.html pages)
1597             xmldir.elements.each('dir') { |child|
1598                 if child.attributes['deleted']
1599                     next
1600                 end
1601                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1602                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1603                 html_index += run_iterations(iterations, 1)
1604                 captionfile, caption = find_subalbum_caption_info(child)
1605                 gen_thumbnails_subdir(captionfile, child, false,
1606                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1607                 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1608                 html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1609             }
1610
1611             html_index += close_iterations(iterations)
1612
1613             for i in html
1614                 i.gsub!(/~~thumbnails~~/, html_index)
1615                 i.gsub!(/~~madewith~~/, $madewith || '')
1616                 i.gsub!(/~~indexlink~~/, $indexlink || '')
1617                 if !$indexlink || $indexlink.empty?
1618                    i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1619                 else
1620                    i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1621                 end
1622                 substitute_addthis(i)
1623             end
1624             
1625         else
1626             html = html_reload_to_thumbnails
1627         end
1628
1629         save_html(html, "#{dest_dir}/index")
1630         if $multi_languages
1631             #- in case MultiViews will not work, generate some compat
1632             ios = File.open("#{dest_dir}/index.html", "w")
1633             ios.write("<html><head><meta http-equiv=\"refresh\" content=\"0.1;url=index.#{$multi_languages[1]}.html\"></head></html>")
1634             ios.close
1635         end
1636
1637         #- substitute multiple "return to albums", previous/next correctly
1638         #- the following two statements are dramatical optimizations to executing for each substInFile callback
1639         dirpresent = xmldir.elements['dir']
1640         parentname = xmldir.parent.name
1641         if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1642             for suffix in [ '', '-nojs' ]
1643                 for sizeobj in $images_size
1644                     Dir.glob("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}-*.html") do |file|
1645                         #- unroll translations, they are costly if rerun for each line of files
1646                         rta = find_translation_for_file(file, N_('return to albums'))
1647                         pa = find_translation_for_file(file, N_('previous album'))
1648                         na = find_translation_for_file(file, N_('next album'))
1649                         substInFile(file) { |line|
1650                             sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1651                             if dirpresent
1652                                 line.sub!(/~~return_to_albums~~/, '<a href="index' + $htmlsuffix + '">' + rta + '</a>')
1653                             else
1654                                 if parentname == 'dir'
1655                                     line.sub!(/~~return_to_albums~~/, '<a href="../index' + $htmlsuffix + '">' + rta + '</a>')
1656                                 else
1657                                     line.sub!(/~~return_to_albums~~/, '')
1658                                 end
1659                             end
1660                             line
1661                         }
1662                     end
1663                     if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1664                         Dir.glob("#{dest_dir}/image-#{size2js(sizeobj['name'])}*.html") do |file|
1665                             pa = find_translation_for_file(file, N_('previous album'))
1666                             na = find_translation_for_file(file, N_('next album'))
1667                             substInFile(file) { |line|
1668                                 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1669                             }
1670                         end
1671                     end
1672                 end
1673             end
1674         end
1675     }
1676
1677     msg 3, _(" all done.")
1678 end
1679
1680 handle_options
1681 read_config
1682 check_installation
1683
1684 build_html_skeletons
1685
1686 walk_source_dir
1687 exit(0)