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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 = args.any? ?
  32. args :
  33. %w(Formatter Helper HtmlParser).map {|m| "Redmine::WikiFormatting::#{name.classify}::#{m}".constantize rescue nil}
  34. raise "A formatter class is required" if formatter.nil?
  35. @@formatters[name] = {
  36. :formatter => formatter,
  37. :helper => helper,
  38. :html_parser => parser,
  39. :label => options[:label] || name.humanize
  40. }
  41. end
  42. def formatter
  43. formatter_for(Setting.text_formatting)
  44. end
  45. def html_parser
  46. html_parser_for(Setting.text_formatting)
  47. end
  48. def formatter_for(name)
  49. entry = @@formatters[name.to_s]
  50. (entry && entry[:formatter]) || Redmine::WikiFormatting::NullFormatter::Formatter
  51. end
  52. def helper_for(name)
  53. entry = @@formatters[name.to_s]
  54. (entry && entry[:helper]) || Redmine::WikiFormatting::NullFormatter::Helper
  55. end
  56. def html_parser_for(name)
  57. entry = @@formatters[name.to_s]
  58. (entry && entry[:html_parser]) || Redmine::WikiFormatting::HtmlParser
  59. end
  60. def format_names
  61. @@formatters.keys.map
  62. end
  63. def formats_for_select
  64. @@formatters.map {|name, options| [options[:label], name]}
  65. end
  66. def to_html(format, text, options = {})
  67. text = if Setting.cache_formatted_text? && text.size > 2.kilobyte && cache_store && cache_key = cache_key_for(format, text, options[:object], options[:attribute])
  68. # Text retrieved from the cache store may be frozen
  69. # We need to dup it so we can do in-place substitutions with gsub!
  70. cache_store.fetch cache_key do
  71. formatter_for(format).new(text).to_html
  72. end.dup
  73. else
  74. formatter_for(format).new(text).to_html
  75. end
  76. text
  77. end
  78. # Returns true if the text formatter supports single section edit
  79. def supports_section_edit?
  80. (formatter.instance_methods & ['update_section', :update_section]).any?
  81. end
  82. # Returns a cache key for the given text +format+, +text+, +object+ and +attribute+ or nil if no caching should be done
  83. def cache_key_for(format, text, object, attribute)
  84. if object && attribute && !object.new_record? && format.present?
  85. "formatted_text/#{format}/#{object.class.model_name.cache_key}/#{object.id}-#{attribute}-#{Digest::MD5.hexdigest text}"
  86. end
  87. end
  88. # Returns the cache store used to cache HTML output
  89. def cache_store
  90. ActionController::Base.cache_store
  91. end
  92. end
  93. module LinksHelper
  94. AUTO_LINK_RE = %r{
  95. ( # leading text
  96. <\w+[^>]*?>| # leading HTML tag, or
  97. [\s\(\[,;]| # leading punctuation, or
  98. ^ # beginning of line
  99. )
  100. (
  101. (?:https?://)| # protocol spec, or
  102. (?:s?ftps?://)|
  103. (?:www\.) # www.*
  104. )
  105. (
  106. ([^<]\S*?) # url
  107. (\/)? # slash
  108. )
  109. ((?:&gt;)?|[^[:alnum:]_\=\/;\(\)\-]*?) # post
  110. (?=<|\s|$)
  111. }x unless const_defined?(:AUTO_LINK_RE)
  112. # Destructively replaces urls into clickable links
  113. def auto_link!(text)
  114. text.gsub!(AUTO_LINK_RE) do
  115. all, leading, proto, url, post = $&, $1, $2, $3, $6
  116. if /<a\s/i.match?(leading) || /![<>=]?/.match?(leading)
  117. # don't replace URLs that are already linked
  118. # and URLs prefixed with ! !> !< != (textile images)
  119. all
  120. else
  121. # Idea below : an URL with unbalanced parenthesis and
  122. # ending by ')' is put into external parenthesis
  123. if ( url[-1]==?) and ((url.count("(") - url.count(")")) < 0 ) )
  124. url=url[0..-2] # discard closing parenthesis from url
  125. post = ")"+post # add closing parenthesis to post
  126. end
  127. content = proto + url
  128. href = "#{proto=="www."?"http://www.":proto}#{url}"
  129. %(#{leading}<a class="external" href="#{ERB::Util.html_escape href}">#{ERB::Util.html_escape content}</a>#{post}).html_safe
  130. end
  131. end
  132. end
  133. # Destructively replaces email addresses into clickable links
  134. def auto_mailto!(text)
  135. text.gsub!(/([\w\.!#\$%\-+.\/]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do
  136. mail = $1
  137. if /<a\b[^>]*>(.*)(#{Regexp.escape(mail)})(.*)<\/a>/.match?(text)
  138. mail
  139. else
  140. %(<a class="email" href="mailto:#{ERB::Util.html_escape mail}">#{ERB::Util.html_escape mail}</a>).html_safe
  141. end
  142. end
  143. end
  144. def restore_redmine_links(html)
  145. # restore wiki links eg. [[Foo]]
  146. html.gsub!(%r{\[<a href="(.*?)">(.*?)</a>\]}) do
  147. "[[#{$2}]]"
  148. end
  149. # restore Redmine links with double-quotes, eg. version:"1.0"
  150. html.gsub!(/(\w):&quot;(.+?)&quot;/) do
  151. "#{$1}:\"#{$2}\""
  152. end
  153. # restore user links with @ in login name eg. [@jsmith@somenet.foo]
  154. html.gsub!(%r{[@\A]<a(\sclass="email")? href="mailto:(.*?)">(.*?)</a>}) do
  155. "@#{$2}"
  156. end
  157. # restore user links with @ in login name eg. [user:jsmith@somenet.foo]
  158. html.gsub!(%r{\buser:<a(\sclass="email")? href="mailto:(.*?)">(.*?)<\/a>}) do
  159. "user:#{$2}"
  160. end
  161. # restore attachments links with @ in file name eg. [attachment:image@2x.png]
  162. html.gsub!(%r{\battachment:<a(\sclass="email")? href="mailto:(.*?)">(.*?)</a>}) do
  163. "attachment:#{$2}"
  164. end
  165. # restore hires images which are misrecognized as email address eg. [printscreen@2x.png]
  166. html.gsub!(%r{<a(\sclass="email")? href="mailto:[^"]+@\dx\.(bmp|gif|jpg|jpe|jpeg|png)">(.*?)</a>}) do
  167. "#{$3}"
  168. end
  169. html
  170. end
  171. end
  172. # Default formatter module
  173. module NullFormatter
  174. class Formatter
  175. include ActionView::Helpers::TagHelper
  176. include ActionView::Helpers::TextHelper
  177. include ActionView::Helpers::UrlHelper
  178. include Redmine::WikiFormatting::LinksHelper
  179. def initialize(text)
  180. @text = text
  181. end
  182. def to_html(*args)
  183. t = CGI::escapeHTML(@text)
  184. auto_link!(t)
  185. auto_mailto!(t)
  186. restore_redmine_links(t)
  187. simple_format(t, {}, :sanitize => false)
  188. end
  189. end
  190. module Helper
  191. def wikitoolbar_for(field_id, preview_url = preview_text_path)
  192. end
  193. def heads_for_wiki_formatter
  194. end
  195. def initial_page_content(page)
  196. page.pretty_title.to_s
  197. end
  198. end
  199. end
  200. end
  201. end