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