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