no longer use internalized rexml
[booh] / bin / booh-backend
old mode 100755 (executable)
new mode 100644 (file)
index 42e6300..12de9d8
@@ -10,7 +10,7 @@
 # called Boo, so this one will be it "Booh". Or whatever.
 #
 #
-# Copyright (c) 2004-2009 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
+# Copyright (c) 2004-2013 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
 #
 # This software may be freely redistributed under the terms of the GNU
 # public license version 2.
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
+begin
+    require 'rubygems'
+rescue LoadError
+end
+
 require 'getoptlong'
 begin
     #- new style (ruby-locale separated package)
@@ -29,7 +34,7 @@ rescue LoadError
 end
 require 'gettext'
 include GetText
-require 'booh/rexml/document'
+require 'rexml/document'
 include REXML
 
 require 'booh/booh-lib'
@@ -64,8 +69,11 @@ $options = [
     [ '--thumbnails-per-page', '-p', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per page in the thumbnails page, after which split occurs") ],
     [ '--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)") ],
     [ '--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") ],
+    [ '--mp4-generator', '-F', GetoptLong::REQUIRED_ARGUMENT, _("Use this .mp4 generator (%f is the placeholder for the input video, %o for the output video)") ],
     [ '--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)") ],
+    [ '--addthis', '-a', GetoptLong::NO_ARGUMENT, _("Include the 'addthis' bookmarking and sharing button") ],
     [ '--made-with',     '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
+    [ '--quote-html',    '-q', GetoptLong::NO_ARGUMENT, _("Quote HTML markup in captions") ],
     [ '--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") ],
 
     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
@@ -104,7 +112,7 @@ def handle_options
             when '--version'
                 puts _("Booh version %s
 
-Copyright (c) 2005-2009 Guillaume Cottenceau.
+Copyright (c) 2005-2013 Guillaume Cottenceau.
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
 
@@ -226,12 +234,24 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
                 end
                 $transcode_videos = arg
 
+            when '--mp4-generator'
+                if arg !~ /%f/ || arg !~ /%o/
+                    die _("--mp4-generator: argument must contain %f for the input video and %o for the output video")
+                end
+                $mp4_generator = arg
+
             when '--made-with'
                 $madewith = arg
 
             when '--index-link'
                 $indexlink = arg
 
+            when '--addthis'
+                $addthis = true
+
+            when '--quote-html'
+                $quote_html = true
+
             when '--comments-format'
                 $commentsformat = arg
 
@@ -275,6 +295,8 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
             $N_per_page = $xmldoc.root.attributes['thumbnails-per-page']
             $madewith = $xmldoc.root.attributes['made-with']
             $indexlink = $xmldoc.root.attributes['index-link']
+            $addthis = !$xmldoc.root.attributes['addthis'].nil?
+            $quote_html = !$xmldoc.root.attributes['quote-html'].nil?
         end
     end
 
@@ -293,7 +315,7 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         die _("Missing --destination parameter.")
     end
     if !$theme
-        $theme = 'simple'
+        $theme = 'gradient'
     end
 
     select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
@@ -326,6 +348,12 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         if $indexlink
             $xmldoc.root.add_attribute('index-link', $indexlink)
         end
+        if $addthis
+            $xmldoc.root.add_attribute('addthis', 'true')
+        end
+        if $quote_html
+            $xmldoc.root.add_attribute('quote-html', 'true')
+        end
         $mode = 'gen_config'
     end
 
@@ -368,6 +396,16 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         else
             $xmldoc.root.delete_attribute('index-link')
         end
+        if $addthis
+            $xmldoc.root.add_attribute('addthis', 'true')
+        else
+            $xmldoc.root.delete_attribute('addthis')
+        end
+        if $quote_html
+            $xmldoc.root.add_attribute('quote-html', 'true')
+        else
+            $xmldoc.root.delete_attribute('quote-html')
+        end
     end
 
     if $transcode_videos
@@ -376,6 +414,12 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         $xmldoc.root.delete_attribute('transcode-videos')
     end
 
+    if $mp4_generator
+        $xmldoc.root.add_attribute('mp4-generator', $mp4_generator)
+    else
+        $xmldoc.root.delete_attribute('mp4-generator')
+    end
+
     if $madewith
         $madewith = $madewith.gsub('%booh', '"http://booh.org/"')
     end
@@ -451,12 +495,14 @@ def find_caption_value(xmldir, filename)
     end
 end
 
-def quote_caption(input)
-    return input.gsub('<', '&lt;').gsub('>', '&gt;').gsub('"', '&quot;').gsub("'", '&#39;').gsub("\n", '<br/>')
-end
-
-def find_captions(xmldir, images)
-    return images.collect { |img| find_caption_value(xmldir, img) }
+def quote_caption(input, *for_attribute)
+    if $quote_html
+        return input.gsub('<', '&lt;').gsub('>', '&gt;').gsub('"', '&quot;').gsub("'", '&#39;').gsub("\n", '<br/>')
+    elsif for_attribute[0]
+        return input.gsub('"', '&quot;').gsub("\n", '<br/>')
+    else
+        return input.gsub("\n", '<br/>')
+    end
 end
 
 #- stolen from CVSspam
@@ -564,7 +610,7 @@ def img_element(fullpath, caption)
     else
         sizespec = ''
     end
-    return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="' + quote_caption(caption) + '"/>'
+    return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="' + quote_caption(caption, true) + '"/>'
 end
 
 def size2js(name)
@@ -597,21 +643,29 @@ end
 def substitute_navigation(html, xmldir)
     if xmldir.parent.name == 'dir'
         nav = ''
+        navtable = ''
         path = '..'
         parent = xmldir.parent
         while parent.name == 'dir'
             parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
             nav = "<a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a> #{defer_translation(N_(" > "))} #{nav}"
+            navtable = "<td><a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a></td>#{navtable}"
             path += '/..'
             parent = parent.parent
         end
         html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
         html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
+        html.gsub!(/~~navigationtable~~/, '<table id="navigation"><tr>' + navtable + "<td>" +
+                                          (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])) + "</td></tr></table>")
     else
         html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
     end
 end
 
+def substitute_addthis(html)
+    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>' : '')
+end
+
 def substitute_pathtobase(html, xmldir)
     path = ''
     location = xmldir
@@ -735,6 +789,18 @@ def save_html(html, base_filename)
     end
 end
 
+def apply_hook(name, content, *params)
+    if $hooks.nil?
+        return content
+    end
+    hook = $hooks[name]
+    if hook.nil?
+        return content
+    else
+        return hook.call(content, *params)
+    end
+end
+
 def walk_source_dir
 
     #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
@@ -747,9 +813,9 @@ def walk_source_dir
     if $mode == 'merge_config_onedir'
         examined_dirs = [ $onedir ]
     elsif $mode == 'merge_config_subdirs'
-        examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
+        examined_dirs = `find '#{$onedir}' -type d -follow`.split("\n").sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
     else
-        examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
+        examined_dirs = `find '#{$source}' -type d -follow`.split("\n").sort.collect { |v| v.chomp }
         if $mode == 'merge_config'
             $xmldoc.elements.each('//dir') { |elem|
                 if ! examined_dirs.include?(elem.attributes['path'])
@@ -877,6 +943,12 @@ def walk_source_dir
         if !$forgui
             ios = File.open("#{dest_dir}/.htaccess", "w")
             ios.write("AddCharset UTF-8 .html\n")
+            ios.write("\n")
+            ios.write("<IfModule mod_expires.c>\n")
+            ios.write(" ExpiresActive On\n")
+            ios.write(" ExpiresDefault A1800\n")
+            ios.write("</IfModule>")
+            ios.write("\n")
             if auth_user_file = xmldir.attributes['password-protect']
                 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
                 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
@@ -943,6 +1015,8 @@ def walk_source_dir
             fullscreen_images[sizeobj['name']] = []
             thumbnail_images ||= {}
             thumbnail_images[sizeobj['name']] = []
+            fullscreen_videos ||= {}
+            fullscreen_videos[sizeobj['name']] = []
             thumbnail_videos ||= {}
             thumbnail_videos[sizeobj['name']] = []
         end
@@ -950,6 +1024,7 @@ def walk_source_dir
         thumbnail_images['dont-delete-file-for-gui'] = []
         if $limit_sizes =~ /original/
             fullscreen_images['original'] = []
+            fullscreen_videos['original'] = []
         end
 
         images.size >= 1 and msg 3, _("\tcreating photos thumbnails...")
@@ -976,7 +1051,7 @@ def walk_source_dir
                     end
                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
                     thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
-                    todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
+                    todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
                 end
                 gen_thumbnails_element("#{dir}/#{img}", elem, true, todo)
                 if $limit_sizes =~ /original/
@@ -998,19 +1073,25 @@ def walk_source_dir
 
         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
         transcoded_videos = {}
+        mp4_videos = {}
 
         #- create thumbnails for videos
         videos.each { |video|
             info("processing element")
+            base_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, ''))
             elem = optelements['video|' + utf8(video)]
             if $forgui
-                thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
+                thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
                 gen_thumbnails_element("#{dir}/#{video}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
             else
                 todo = []
                 for sizeobj in $images_size
+                    size_fullscreen = sizeobj['fullscreen']
                     size_thumbnails = sizeobj['thumbnails']
-                    thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
+                    fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
+                    fullscreen_videos[sizeobj['name']] << File.basename(fullscreen_dest_img)
+                    todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
+                    thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
                 end
@@ -1024,6 +1105,20 @@ def walk_source_dir
                     if ! File.exists?(destvideo)
                         psys(parts[1].gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
                     end
+
+                elsif $mp4_generator
+                    msg 3, "video1"
+                    basedestvideo = video.sub(/\.\w+/, '') + '.mp4'
+                    mp4_videos[video] = basedestvideo
+                    destvideo = "#{dest_dir}/#{basedestvideo}"
+                    if File.exists?(destvideo) && File.size(destvideo) == 0
+                        File.delete(destvideo)
+                    end
+                    if ! File.exists?(destvideo)
+                        psys($mp4_generator.gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
+                    end
+                    msg 3, "video2"
+
                 else
                     destvideo = "#{dest_dir}/#{video}"
                     if ! File.exists?(destvideo)
@@ -1044,12 +1139,13 @@ def walk_source_dir
             #- cleanup old images/videos (for when removing elements or sizes)
             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
+                     concat(fullscreen_videos.collect { |e| e[1] }.flatten).
                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
-                     concat($transcode_videos ? transcoded_videos.values : videos).
+                     concat($transcode_videos ? transcoded_videos.values : $mp4_generator ? mp4_videos.values : videos).
                      push('.htaccess')
             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ }
             if to_del.size > 0
-                msg 3, _("\tcleaning up: #{to_del.join(', ')}")
+                msg 3, _("\tcleaning up: ") + to_del.join(', ')
                 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
             end
 
@@ -1080,7 +1176,7 @@ def walk_source_dir
             end
 
             #- generate thumbnails*.html (page with thumbnails)
-            image2thumbnailpage4js = []
+            element2thumbnailpage4js = []
             for sizeobj in $images_size
                 info("processing size")
                 html = $html_thumbnails.collect { |l| l.clone }
@@ -1131,13 +1227,25 @@ def walk_source_dir
                             index = videos.index(file)
                             caption = find_caption_value(xmldir, videos[index]) || utf8(videos[index])
                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
-                                html_elem.gsub!(/~~image_iteration~~/,
-                                                '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
-                                                    img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</a>')
+                                video_preview = '<div class="thumbnail_video">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</div>'
+                            else
+                                video_preview = defer_translation(N_("(no preview)"))
+                            end
+                            if $mp4_generator
+                                size = get_image_size("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
+                                if ! size
+                                    sizeobj['thumbnails'] =~ /(\d+)x(\d+)/
+                                    size = { :x => $1, :y => $2 }
+                                end
+                                sizespec = 'width:' + size[:x].to_s + 'px;height:' + (size[:y] + 24).to_s + 'px'
+                                image_iteration = '<a href="' + mp4_videos[videos[index]] + '" style="display:block;' + sizespec + '"' +
+                                                  '   id="player' + index.to_s + '">' + video_preview +
+                                                  '<img src="~~pathtobase~~play_video.png" style="position:relative;top:-' + ((size[:y]+48)/2).to_s + 'px;border:0;background-color:transparent"/></a>'
+                                html_elem.gsub!(/~~image_iteration~~/, apply_hook(:image_iteration, image_iteration, 'video'))
                             else
                                 html_elem.gsub!(/~~image_iteration~~/,
                                                 '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
-                                                    defer_translation(N_("(no preview)")) + '</a>')
+                                                    video_preview + '</a>')
                             end
                             html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
@@ -1146,17 +1254,17 @@ def walk_source_dir
                         html_thumbnails += html_elem
                         html_thumbnails_nojs += html_elem
                         if type == 'image'
+                            img_preview = '<div class="thumbnail_image">' + img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</div>'
                             html_thumbnails.gsub!(/~~image_iteration~~/,
                                                   '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
-                                                      '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
-                                                      img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</a>')
+                                                      '" name="' + fullscreen_images[sizeobj['name']][index] + '">' + img_preview + '</a>')
                             html_thumbnails_nojs.gsub!(/~~image_iteration~~/, 
                                                        '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
-                                                       img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</a>')
-                            #- remember in which thumbnails page is this element, for image->thumbnail link
-                            if sizeobj == $images_size[0]
-                                image2thumbnailpage4js << pagecount
-                            end
+                                                       img_preview + '</a>')
+                        end
+                        #- remember in which thumbnails page is this element, for element->thumbnail link
+                        if sizeobj == $images_size[0]
+                            element2thumbnailpage4js << pagecount
                         end
 
                         if counter == $N_per_page
@@ -1183,6 +1291,12 @@ def walk_source_dir
                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
                     i.gsub!(/~~madewith~~/, $madewith || '')
                     i.gsub!(/~~indexlink~~/, $indexlink || '')
+                    if !$indexlink || $indexlink.empty?
+                       i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
+                    else
+                       i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
+                    end
+                    substitute_addthis(i)
                     substitute_navigation(i, xmldir)
                 end
                 html_nojs = html.collect { |l| l.clone }
@@ -1195,8 +1309,10 @@ def walk_source_dir
                              all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
                              (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
                     for i in final_html
+                        i.sub!(/~~run_slideshow_link~~/, entries.size <= 1 ? '' : 'image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1')
+                        i.sub!(/~~run_slideshow_text~~/, defer_translation(N_("Run slideshow!")))
                         i.sub!(/~~run_slideshow~~/,
-                               images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
+                               entries.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
                         i.sub!(/~~thumbnails~~/, html_thumbnails)
                         if all_pages.size == 1
                             i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
@@ -1232,39 +1348,118 @@ def walk_source_dir
             save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
 
             #- generate image.html (page with fullscreen images)
-            if images.size > 0
-                captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
-                thumbnailspage4js = image2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', ')
-                for sizeobj in $images_size
-                    html = $html_images.collect { |l| l.clone }
-                    images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
-                    otherimages4js = ''
-                    othersizes = []
-                    for sizeobj2 in all_images_sizes
-                        if sizeobj != sizeobj2
-                            otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
-                            othersizes << "\"#{size2js(sizeobj2['name'])}\""
+            captions4js = []
+            types4js = []
+            videos4js = []
+            for file in entries
+                type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
+                if type
+                    caption = find_caption_value(xmldir, file)
+                    if caption
+                        captions4js << '"' + quote_caption(caption, true) + '"'
+                    else
+                        captions4js << '""'
+                    end
+                    types4js << '"' + type + '"'
+                    if type == 'video'
+                        index = videos.index(file)
+                        if $mp4_generator
+                            videos4js << '"' + mp4_videos[videos[index]] + '"'
+                        else
+                            videos4js << '"' + videos[index] + '"'
                         end
+                    else
+                        videos4js << '""'
                     end
-                    for i in html
-                        i.gsub!(/~~images~~/, images4js)
-                        i.gsub!(/~~other_images~~/, otherimages4js)
-                        i.gsub!(/~~thumbnailspages~~/, thumbnailspage4js)
-                        i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
-                        i.gsub!(/~~captions~~/, captions4js)
-                        i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
-                        i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + $htmlsuffix + '" id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
-                        i.gsub!(/~~theme~~/, $theme)
-                        i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
-                        i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
-                        i.gsub!(/~~madewith~~/, $madewith || '')
-                        i.gsub!(/~~indexlink~~/, $indexlink || '')
-                        substitute_html_sizes(i, sizeobj, 'image', '')
-                        substitute_navigation(i, xmldir)
-                        substitute_pathtobase(i, xmldir)
+                end
+            end
+
+            for sizeobj in $images_size
+                elements4js = []
+                elemswidths4js = []
+                elemsheights4js = []
+                for file in entries
+                    type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
+                    if type
+                        if type == 'image'
+                            index = images.index(file)
+                            elements4js << '"' + fullscreen_images[sizeobj['name']][index] + '"'
+                            size = get_image_size("#{dest_dir}/#{fullscreen_images[sizeobj['name']][index]}")
+                            if size
+                                elemswidths4js << size[:x].to_s
+                                elemsheights4js << size[:y].to_s
+                            else
+                                elemswidths4js << "''"
+                                elemsheights4js << "''"
+                            end
+                        else
+                            index = videos.index(file)
+                            elements4js << '"' + fullscreen_videos[sizeobj['name']][index] + '"'
+                            size = get_image_size("#{dest_dir}/#{fullscreen_videos[sizeobj['name']][index]}")
+                            if size
+                                elemswidths4js << size[:x].to_s
+                                elemsheights4js << size[:y].to_s
+                            else
+                                elemswidths4js << "''"
+                                elemsheights4js << "''"
+                            end
+                        end
+                    end
+                end
+
+                html = $html_images.collect { |l| l.clone }
+                hiddenimages4remotes = '<span style="display:none">' + thumbnail_images[sizeobj['name']][0..4].collect { |e| "<img src=\"#{e}\"/>" }.join('') + '</span>'
+                otherelements4js = ''
+                othersizes = []
+                for sizeobj2 in all_images_sizes
+                    if sizeobj != sizeobj2
+                        oe4js = []
+                        for file in entries
+                            type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
+                            if type
+                                if type == 'image'
+                                    index = images.index(file)
+                                    oe4js << '"' + fullscreen_images[sizeobj2['name']][index] + '"'
+                                elsif sizeobj2['name'] != 'original'
+                                    index = videos.index(file)
+                                    oe4js << '"' + fullscreen_videos[sizeobj2['name']][index] + '"'
+                                end
+                            end
+                        end
+                        otherelements4js += "var elements_#{size2js(sizeobj2['name'])} = new Array(" + oe4js.join(', ') + ");\n"
+                        othersizes << "\"#{size2js(sizeobj2['name'])}\""
                     end
-                    save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
                 end
+                for i in html
+                    i.gsub!(/~~images~~/, elements4js.join(', '))
+                    i.gsub!(/~~types~~/, types4js.join(', '))
+                    i.gsub!(/~~videos~~/, videos4js.join(', '))
+                    i.gsub!(/~~widths~~/, elemswidths4js.join(', '))
+                    i.gsub!(/~~heights~~/, elemsheights4js.join(', '))
+                    i.gsub!(/~~hidden_images_for_remotes~~/, hiddenimages4remotes)
+                    i.gsub!(/~~other_images~~/, otherelements4js)
+                    i.gsub!(/~~thumbnailspages~~/, element2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', '))
+                    i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
+                    i.gsub!(/~~captions~~/, captions4js.join(', '))
+                    i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
+
+                    i.gsub!(/~~thumbnails~~/, '<a id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
+                    i.gsub!(/~~theme~~/, $theme)
+                    i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
+                    i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
+                    i.gsub!(/~~madewith~~/, $madewith || '')
+                    i.gsub!(/~~indexlink~~/, $indexlink || '')
+                    if !$indexlink || $indexlink.empty?
+                        i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
+                    else
+                        i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
+                    end
+                    substitute_addthis(i)
+                    substitute_html_sizes(i, sizeobj, 'image', '')
+                    substitute_navigation(i, xmldir)
+                    substitute_pathtobase(i, xmldir)
+                end
+                save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
             end
         end
     }
@@ -1333,7 +1528,7 @@ def walk_source_dir
     #- write down to disk config if necessary
     if $config_writeto
         ios = File.open($config_writeto, "w")
-        $xmldoc.write(ios, 0)
+        $xmldoc.write(ios)
         ios.close
     end
 
@@ -1410,6 +1605,12 @@ def walk_source_dir
                 i.gsub!(/~~thumbnails~~/, html_index)
                 i.gsub!(/~~madewith~~/, $madewith || '')
                 i.gsub!(/~~indexlink~~/, $indexlink || '')
+                if !$indexlink || $indexlink.empty?
+                   i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
+                else
+                   i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
+                end
+                substitute_addthis(i)
             end
             
         else
@@ -1474,3 +1675,4 @@ check_installation
 build_html_skeletons
 
 walk_source_dir
+exit(0)