You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wiki_formatting.rb 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'digest/md5'
  19. module Redmine
  20. module WikiFormatting
  21. class StaleSectionError < StandardError; end
  22. @@formatters = {}
  23. class << self
  24. def map
  25. yield self
  26. end
  27. def register(name, *args)
  28. options = args.last.is_a?(Hash) ? args.pop : {}
  29. name = name.to_s
  30. raise ArgumentError, "format name '#{name}' is already taken" if @@formatters[name]
  31. formatter, helper, parser =
  32. if args.any?
  33. args
  34. else
  35. %w(Formatter Helper HtmlParser).map {|m| "Redmine::WikiFormatting::#{name.classify}::#{m}".constantize rescue nil}
  36. end
  37. raise "A formatter class is required" if formatter.nil?
  38. @@formatters[name] = {
  39. :formatter => formatter,
  40. :helper => helper,
  41. :html_parser => parser,
  42. :label => options[:label] || name.humanize
  43. }
  44. end
  45. def formatter
  46. formatter_for(Setting.text_formatting)
  47. end
  48. def html_parser
  49. html_parser_for(Setting.text_formatting)
  50. end
  51. def formatter_for(name)
  52. entry = @@formatters[name.to_s]
  53. (entry && entry[:formatter]) || Redmine::WikiFormatting::NullFormatter::Formatter
  54. end
  55. def helper_for(name)
  56. entry = @@formatters[name.to_s]
  57. (entry && entry[:helper]) || Redmine::WikiFormatting::NullFormatter::Helper
  58. end
  59. def html_parser_for(name)
  60. entry = @@formatters[name.to_s]
  61. (entry && entry[:html_parser]) || Redmine::WikiFormatting::HtmlParser
  62. end
  63. def format_names
  64. @@formatters.keys.map
  65. end
  66. def formats_for_select
  67. @@formatters.map {|name, options| [options[:label], name]}
  68. end
  69. def to_html(format, text, options = {})
  70. text =
  71. if Setting.cache_formatted_text? && text.size > 2.kilobyte && cache_store &&
  72. cache_key = cache_key_for(format, text, options[:object], options[:attribute])
  73. # Text retrieved from the cache store may be frozen
  74. # We need to dup it so we can do in-place substitutions with gsub!
  75. cache_store.fetch cache_key do
  76. formatter_for(format).new(text).to_html
  77. end.dup
  78. else
  79. formatter_for(format).new(text).to_html
  80. end
  81. text
  82. end
  83. # Returns true if the text formatter supports single section edit
  84. def supports_section_edit?
  85. (formatter.instance_methods & ['update_section', :update_section]).any?
  86. end
  87. # Returns a cache key for the given text +format+, +text+, +object+ and +attribute+ or nil if no caching should be done
  88. def cache_key_for(format, text, object, attribute)
  89. if object && attribute && !object.new_record? && format.present?
  90. "formatted_text/#{format}/#{object.class.model_name.cache_key}/#{object.id}-#{attribute}-#{Digest::MD5.hexdigest text}"
  91. end
  92. end
  93. # Returns the cache store used to cache HTML output
  94. def cache_store
  95. ActionController::Base.cache_store
  96. end
  97. end
  98. module LinksHelper
  99. AUTO_LINK_RE = %r{
  100. ( # leading text
  101. <\w+[^>]*?>| # leading HTML tag, or
  102. [\s\(\[,;]| # leading punctuation, or
  103. ^ # beginning of line
  104. )
  105. (
  106. (?:https?://)| # protocol spec, or
  107. (?:s?ftps?://)|
  108. (?:www\.) # www.*
  109. )
  110. (
  111. ([^<]\S*?) # url
  112. (\/)? # slash
  113. )
  114. ((?:&gt;)?|[^[:alnum:]_\=\/;\(\)\-]*?) # post
  115. (?=<|\s|$)
  116. }x unless const_defined?(:AUTO_LINK_RE)
  117. # Destructively replaces urls into clickable links
  118. def auto_link!(text)
  119. text.gsub!(AUTO_LINK_RE) do
  120. all, leading, proto, url, post = $&, $1, $2, $3, $6
  121. if /<a\s/i.match?(leading) || /![<>=]?/.match?(leading)
  122. # don't replace URLs that are already linked
  123. # and URLs prefixed with ! !> !< != (textile images)
  124. all
  125. else
  126. # Idea below : an URL with unbalanced parenthesis and
  127. # ending by ')' is put into external parenthesis
  128. if url[-1] == ")" and ((url.count("(") - url.count(")")) < 0)
  129. url = url[0..-2] # discard closing parenthesis from url
  130. post = ")" + post # add closing parenthesis to post
  131. end
  132. content = proto + url
  133. href = "#{proto=="www."?"http://www.":proto}#{url}"
  134. %(#{leading}<a class="external" href="#{ERB::Util.html_escape href}">#{ERB::Util.html_escape content}</a>#{post}).html_safe
  135. end
  136. end
  137. end
  138. # Destructively replaces email addresses into clickable links
  139. def auto_mailto!(text)
  140. text.gsub!(/([\w\.!#\$%\-+.\/]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do
  141. mail = $1
  142. if /<a\b[^>]*>(.*)(#{Regexp.escape(mail)})(.*)<\/a>/.match?(text)
  143. mail
  144. else
  145. %(<a class="email" href="mailto:#{ERB::Util.html_escape mail}">#{ERB::Util.html_escape mail}</a>).html_safe
  146. end
  147. end
  148. end
  149. def restore_redmine_links(html)
  150. # restore wiki links eg. [[Foo]]
  151. html.gsub!(%r{\[<a href="(.*?)">(.*?)</a>\]}) do
  152. "[[#{$2}]]"
  153. end
  154. # restore Redmine links with double-quotes, eg. version:"1.0"
  155. html.gsub!(/(\w):&quot;(.+?)&quot;/) do
  156. "#{$1}:\"#{$2}\""
  157. end
  158. # restore user links with @ in login name eg. [@jsmith@somenet.foo]
  159. html.gsub!(%r{[@\A]<a(\sclass="email")? href="mailto:(.*?)">(.*?)</a>}) do
  160. "@#{$2}"
  161. end
  162. # restore user links with @ in login name eg. [user:jsmith@somenet.foo]
  163. html.gsub!(%r{\buser:<a(\sclass="email")? href="mailto:(.*?)">(.*?)<\/a>}) do
  164. "user:#{$2}"
  165. end
  166. # restore attachments links with @ in file name eg. [attachment:image@2x.png]
  167. html.gsub!(%r{\battachment:<a(\sclass="email")? href="mailto:(.*?)">(.*?)</a>}) do
  168. "attachment:#{$2}"
  169. end
  170. # restore hires images which are misrecognized as email address eg. [printscreen@2x.png]
  171. html.gsub!(%r{<a(\sclass="email")? href="mailto:[^"]+@\dx\.(bmp|gif|jpg|jpe|jpeg|png)">(.*?)</a>}) do
  172. "#{$3}"
  173. end
  174. html
  175. end
  176. end
  177. # Default formatter module
  178. module NullFormatter
  179. class Formatter
  180. include ActionView::Helpers::TagHelper
  181. include ActionView::Helpers::TextHelper
  182. include ActionView::Helpers::UrlHelper
  183. include Redmine::WikiFormatting::LinksHelper
  184. def initialize(text)
  185. @text = text
  186. end
  187. def to_html(*args)
  188. t = CGI::escapeHTML(@text)
  189. auto_link!(t)
  190. auto_mailto!(t)
  191. restore_redmine_links(t)
  192. simple_format(t, {}, :sanitize => false)
  193. end
  194. end
  195. module Helper
  196. def wikitoolbar_for(field_id, preview_url = preview_text_path)
  197. end
  198. def heads_for_wiki_formatter
  199. end
  200. def initial_page_content(page)
  201. page.pretty_title.to_s
  202. end
  203. end
  204. end
  205. end
  206. end