Project

General

Profile

Feature #29595 ยป wiki_formatting.rb

M F, 2018-09-12 13:56

 
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

    
18
require 'digest/md5'
19

    
20
module Redmine
21
  module WikiFormatting
22
    class StaleSectionError < Exception; end
23

    
24
    @@formatters = {}
25

    
26
    class << self
27
      def map
28
        yield self
29
      end
30

    
31
      def register(name, *args)
32
        options = args.last.is_a?(Hash) ? args.pop : {}
33
        name = name.to_s
34
        raise ArgumentError, "format name '#{name}' is already taken" if @@formatters[name]
35

    
36
        formatter, helper, parser = args.any? ?
37
          args :
38
          %w(Formatter Helper HtmlParser).map {|m| "Redmine::WikiFormatting::#{name.classify}::#{m}".constantize rescue nil}
39

    
40
        raise "A formatter class is required" if formatter.nil?
41

    
42
        @@formatters[name] = {
43
          :formatter => formatter,
44
          :helper => helper,
45
          :html_parser => parser,
46
          :label => options[:label] || name.humanize
47
        }
48
      end
49

    
50
      def formatter
51
        formatter_for(Setting.text_formatting)
52
      end
53

    
54
      def html_parser
55
        html_parser_for(Setting.text_formatting)
56
      end
57

    
58
      def formatter_for(name)
59
        entry = @@formatters[name.to_s]
60
        (entry && entry[:formatter]) || Redmine::WikiFormatting::NullFormatter::Formatter
61
      end
62

    
63
      def helper_for(name)
64
        entry = @@formatters[name.to_s]
65
        (entry && entry[:helper]) || Redmine::WikiFormatting::NullFormatter::Helper
66
      end
67

    
68
      def html_parser_for(name)
69
        entry = @@formatters[name.to_s]
70
        (entry && entry[:html_parser]) || Redmine::WikiFormatting::HtmlParser
71
      end
72

    
73
      def format_names
74
        @@formatters.keys.map
75
      end
76

    
77
      def formats_for_select
78
        @@formatters.map {|name, options| [options[:label], name]}
79
      end
80

    
81
      def to_html(format, text, options = {})
82
        text = if Setting.cache_formatted_text? && text.size > 2.kilobyte && cache_store && cache_key = cache_key_for(format, text, options[:object], options[:attribute])
83
          # Text retrieved from the cache store may be frozen
84
          # We need to dup it so we can do in-place substitutions with gsub!
85
          cache_store.fetch cache_key do
86
            formatter_for(format).new(text).to_html
87
          end.dup
88
        else
89
          formatter_for(format).new(text).to_html
90
        end
91
        text
92
      end
93

    
94
      # Returns true if the text formatter supports single section edit
95
      def supports_section_edit?
96
        (formatter.instance_methods & ['update_section', :update_section]).any?
97
      end
98

    
99
      # Returns a cache key for the given text +format+, +text+, +object+ and +attribute+ or nil if no caching should be done
100
      def cache_key_for(format, text, object, attribute)
101
        if object && attribute && !object.new_record? && format.present?
102
          "formatted_text/#{format}/#{object.class.model_name.cache_key}/#{object.id}-#{attribute}-#{Digest::MD5.hexdigest text}"
103
        end
104
      end
105

    
106
      # Returns the cache store used to cache HTML output
107
      def cache_store
108
        ActionController::Base.cache_store
109
      end
110
    end
111

    
112
    module LinksHelper
113
      AUTO_LINK_RE = %r{
114
                      (                          # leading text
115
                        <\w+[^>]*?>|             # leading HTML tag, or
116
                        [\s\(\[,;]|              # leading punctuation, or
117
                        ^                        # beginning of line
118
                      )
119
                      (
120
                        (?:https?://)|           # protocol spec, or
121
                        (?:s?ftps?://)|
122
			(?:m-files?://)|
123
                        (?:www\.)                # www.*
124
                      )
125
                      (
126
                        ([^<]\S*?)               # url
127
                        (\/)?                    # slash
128
                      )
129
                      ((?:&gt;)?|[^[:alnum:]_\=\/;\(\)]*?)               # post
130
                      (?=<|\s|$)
131
                     }x unless const_defined?(:AUTO_LINK_RE)
132

    
133
      # Destructively replaces urls into clickable links
134
      def auto_link!(text)
135
        text.gsub!(AUTO_LINK_RE) do
136
          all, leading, proto, url, post = $&, $1, $2, $3, $6
137
          if leading =~ /<a\s/i || leading =~ /![<>=]?/
138
            # don't replace URLs that are already linked
139
            # and URLs prefixed with ! !> !< != (textile images)
140
            all
141
          else
142
            # Idea below : an URL with unbalanced parenthesis and
143
            # ending by ')' is put into external parenthesis
144
            if ( url[-1]==?) and ((url.count("(") - url.count(")")) < 0 ) )
145
              url=url[0..-2] # discard closing parenthesis from url
146
              post = ")"+post # add closing parenthesis to post
147
            end
148
            content = proto + url
149
            href = "#{proto=="www."?"http://www.":proto}#{url}"
150
            %(#{leading}<a class="external" href="#{ERB::Util.html_escape href}">#{ERB::Util.html_escape content}</a>#{post}).html_safe
151
          end
152
        end
153
      end
154

    
155
      # Destructively replaces email addresses into clickable links
156
      def auto_mailto!(text)
157
        text.gsub!(/((?<!@)\b[\w\.!#\$%\-+.\/]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do
158
          mail = $1
159
          if text.match(/<a\b[^>]*>(.*)(#{Regexp.escape(mail)})(.*)<\/a>/)
160
            mail
161
          else
162
            %(<a class="email" href="mailto:#{ERB::Util.html_escape mail}">#{ERB::Util.html_escape mail}</a>).html_safe
163
          end
164
        end
165
      end
166
    end
167

    
168
    # Default formatter module
169
    module NullFormatter
170
      class Formatter
171
        include ActionView::Helpers::TagHelper
172
        include ActionView::Helpers::TextHelper
173
        include ActionView::Helpers::UrlHelper
174
        include Redmine::WikiFormatting::LinksHelper
175

    
176
        def initialize(text)
177
          @text = text
178
        end
179

    
180
        def to_html(*args)
181
          t = CGI::escapeHTML(@text)
182
          auto_link!(t)
183
          auto_mailto!(t)
184
          simple_format(t, {}, :sanitize => false)
185
        end
186
      end
187

    
188
      module Helper
189
        def wikitoolbar_for(field_id)
190
        end
191

    
192
        def heads_for_wiki_formatter
193
        end
194

    
195
        def initial_page_content(page)
196
          page.pretty_title.to_s
197
        end
198
      end
199
    end
200
  end
201
end
    (1-1/1)