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