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.0KB

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