+# Return the first paragraph of the given item as a string.
+def item_longdesc(item)
+ xml = Nokogiri::XML("<body xmlns='" + Xmlns["xhtml"] + "'>" +
+ item.compiled_content(snapshot: :rawbody) +
+ "</body>")
+
+ p = xml.xpath('//xhtml:p', Xmlns)
+ if p.empty? then nil else p[0].xpath('string(.)') end
+end
+
+def counter(name = :default, item = @item)
+ $counters[item] ||= {}
+ $counters[item][name] ||= 0
+
+ name.to_s.capitalize + " " + ($counters[item][name] += 1).to_s
+end
+
+def img_rep_fallback(item, rep)
+ return rep unless item.reps[rep].raw_path.nil?
+ return :large
+end
+
+def item_to_img(item, rep: :large, alt: nil, caption: nil)
+ unless item
+ return "[image not found]"
+ end
+
+ alt ||= item[:title]
+ caption ||= alt
+ caption = caption.strip
+ caption.gsub!(/\s+/, " ")
+
+ rep = img_rep_fallback(item, rep)
+ attrs = { :src => item_uri(item, rep: rep), :alt => item[:title] }
+ attrs[:width], attrs[:height] = FastImage.size(item.reps[rep].raw_path)
+
+ b = Nokogiri::XML::Builder.new do |xml|
+ xml.a(:href => item_uri(item, rep: :info)) {
+ xml.img(attrs)
+ unless caption.empty?
+ xml << " ⁠"
+ xml.small {
+ xml << caption
+ }
+ end
+ }
+ end
+ b.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::NO_DECLARATION)
+end
+
+def expand_copyright(copyright)
+ result = { :years => {} }
+
+ /^([-–[:digit:][:space:],]*)(.*)$/.match(copyright) do |m|
+ m[1].split(/\s*,\s*/).each do |range|
+ lo, hi = range.split(/[^[:digit:]]+/)
+ for y in (lo..hi||lo)
+ result[:years][y] = 1
+ end
+ end
+
+ result[:years] = result[:years].keys.sort
+ result[:name] = m[2]
+ return result