forked from discourse/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpretty_text.rb
317 lines (258 loc) · 8.71 KB
/
pretty_text.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
require 'v8'
require 'nokogiri'
require_dependency 'excerpt_parser'
require_dependency 'post'
module PrettyText
class Helpers
def t(key, opts)
str = I18n.t("js." + key)
if opts
# TODO: server localisation has no parity with client should be fixed
str = str.dup
opts.each do |k,v|
str.gsub!("{{#{k}}}", v)
end
end
str
end
# function here are available to v8
def avatar_template(username)
return "" unless username
user = User.find_by(username_lower: username.downcase)
user.avatar_template if user.present?
end
def is_username_valid(username)
return false unless username
username = username.downcase
return User.exec_sql('SELECT 1 FROM users WHERE username_lower = ?', username).values.length == 1
end
end
@mutex = Mutex.new
@ctx_init = Mutex.new
def self.mention_matcher
Regexp.new("(\@[a-zA-Z0-9_]{#{User.username_length.begin},#{User.username_length.end}})")
end
def self.app_root
Rails.root
end
def self.create_new_context
# timeout any eval that takes longer that 5 seconds
ctx = V8::Context.new(timeout: 5000)
ctx["helpers"] = Helpers.new
ctx_load(ctx,
"vendor/assets/javascripts/md5.js",
"vendor/assets/javascripts/lodash.js",
"vendor/assets/javascripts/Markdown.Converter.js",
"lib/headless-ember.js",
"vendor/assets/javascripts/rsvp.js",
Rails.configuration.ember.handlebars_location
)
ctx.eval("var Discourse = {}; Discourse.SiteSettings = {};")
ctx.eval("var window = {}; window.devicePixelRatio = 2;") # hack to make code think stuff is retina
ctx.eval("var I18n = {}; I18n.t = function(a,b){ return helpers.t(a,b); }");
decorate_context(ctx)
ctx_load(ctx,
"public/javascripts/highlight.pack.js",
"vendor/assets/javascripts/better_markdown.js",
"app/assets/javascripts/defer/html-sanitizer-bundle.js",
"app/assets/javascripts/discourse/dialects/dialect.js",
"app/assets/javascripts/discourse/lib/utilities.js",
"app/assets/javascripts/discourse/lib/html.js",
"app/assets/javascripts/discourse/lib/markdown.js"
)
Dir["#{Rails.root}/app/assets/javascripts/discourse/dialects/**.js"].sort.each do |dialect|
unless dialect =~ /\/dialect\.js$/
ctx.load(dialect)
end
end
# Load server side javascripts
if DiscoursePluginRegistry.server_side_javascripts.present?
DiscoursePluginRegistry.server_side_javascripts.each do |ssjs|
if(ssjs =~ /\.erb/)
erb = ERB.new(File.read(ssjs))
erb.filename = ssjs
ctx.eval(erb.result)
else
ctx.load(ssjs)
end
end
end
ctx['quoteTemplate'] = File.open(app_root + 'app/assets/javascripts/discourse/templates/quote.js.handlebars') {|f| f.read}
ctx['quoteEmailTemplate'] = File.open(app_root + 'lib/assets/quote_email.js.handlebars') {|f| f.read}
ctx.eval("HANDLEBARS_TEMPLATES = {
'quote': Handlebars.compile(quoteTemplate),
'quote_email': Handlebars.compile(quoteEmailTemplate),
};")
ctx
end
def self.v8
return @ctx if @ctx
# ensure we only init one of these
@ctx_init.synchronize do
return @ctx if @ctx
@ctx = create_new_context
end
@ctx
end
def self.decorate_context(context)
context.eval("Discourse.SiteSettings = #{SiteSetting.client_settings_json};")
context.eval("Discourse.CDN = '#{Rails.configuration.action_controller.asset_host}';")
context.eval("Discourse.BaseUrl = 'http://#{RailsMultisite::ConnectionManagement.current_hostname}';")
context.eval("Discourse.getURL = function(url) {return '#{Discourse::base_uri}' + url};")
end
def self.markdown(text, opts=nil)
# we use the exact same markdown converter as the client
# TODO: use the same extensions on both client and server (in particular the template for mentions)
baked = nil
protect do
context = v8
# we need to do this to work in a multi site environment, many sites, many settings
decorate_context(context)
context_opts = opts || {}
context_opts[:sanitize] ||= true
context['opts'] = context_opts
context['raw'] = text
if Post.white_listed_image_classes.present?
Post.white_listed_image_classes.each do |klass|
context.eval("Discourse.Markdown.whiteListClass('#{klass}')")
end
end
context.eval('opts["mentionLookup"] = function(u){return helpers.is_username_valid(u);}')
context.eval('opts["lookupAvatar"] = function(p){return Discourse.Utilities.avatarImg({size: "tiny", avatarTemplate: helpers.avatar_template(p)});}')
baked = context.eval('Discourse.Markdown.markdownConverter(opts).makeHtml(raw)')
end
baked
end
# leaving this here, cause it invokes v8, don't want to implement twice
def self.avatar_img(avatar_template, size)
protect do
v8['avatarTemplate'] = avatar_template
v8['size'] = size
decorate_context(v8)
v8.eval("Discourse.Utilities.avatarImg({ avatarTemplate: avatarTemplate, size: size });")
end
end
def self.cook(text, opts={})
cloned = opts.dup
# we have a minor inconsistency
cloned[:topicId] = opts[:topic_id]
sanitized = markdown(text.dup, cloned)
sanitized = add_rel_nofollow_to_user_content(sanitized) if !cloned[:omit_nofollow] && SiteSetting.add_rel_nofollow_to_user_content
sanitized
end
def self.add_rel_nofollow_to_user_content(html)
whitelist = []
domains = SiteSetting.exclude_rel_nofollow_domains
whitelist = domains.split('|') if domains.present?
site_uri = nil
doc = Nokogiri::HTML.fragment(html)
doc.css("a").each do |l|
href = l["href"].to_s
begin
uri = URI(href)
site_uri ||= URI(Discourse.base_url)
if !uri.host.present? ||
uri.host.ends_with?(site_uri.host) ||
whitelist.any?{|u| uri.host.ends_with?(u)}
# we are good no need for nofollow
else
l["rel"] = "nofollow"
end
rescue URI::InvalidURIError, URI::InvalidComponentError
# add a nofollow anyway
l["rel"] = "nofollow"
end
end
doc.to_html
end
class DetectedLink
attr_accessor :is_quote, :url
def initialize(url, is_quote=false)
@url = url
@is_quote = is_quote
end
end
def self.extract_links(html)
links = []
doc = Nokogiri::HTML.fragment(html)
# remove href inside quotes
doc.css("aside.quote a").each { |l| l["href"] = "" }
# extract all links from the post
doc.css("a").each { |l|
unless l["href"].blank?
links << DetectedLink.new(l["href"])
end
}
# extract links to quotes
doc.css("aside.quote[data-topic]").each do |a|
topic_id = a['data-topic']
url = "/t/topic/#{topic_id}"
if post_number = a['data-post']
url << "/#{post_number}"
end
links << DetectedLink.new(url, true)
end
links
end
def self.excerpt(html, max_length, options={})
ExcerptParser.get_excerpt(html, max_length, options)
end
def self.strip_links(string)
return string if string.blank?
# If the user is not basic, strip links from their bio
fragment = Nokogiri::HTML.fragment(string)
fragment.css('a').each {|a| a.replace(a.text) }
fragment.to_html
end
# Given a Nokogiri doc, convert all links to absolute
def self.make_all_links_absolute(doc)
site_uri = nil
doc.css("a").each do |link|
href = link["href"].to_s
begin
uri = URI(href)
site_uri ||= URI(Discourse.base_url)
link["href"] = "#{site_uri}#{link['href']}" unless uri.host.present?
rescue URI::InvalidURIError, URI::InvalidComponentError
# leave it
end
end
end
def self.strip_image_wrapping(doc)
doc.css(".lightbox-wrapper .meta").remove
end
def self.format_for_email(html)
doc = Nokogiri::HTML.fragment(html)
make_all_links_absolute(doc)
strip_image_wrapping(doc)
doc.to_html
end
protected
class JavaScriptError < StandardError
attr_accessor :message, :backtrace
def initialize(message, backtrace)
@message = message
@backtrace = backtrace
end
end
def self.protect
rval = nil
@mutex.synchronize do
begin
rval = yield
# This may seem a bit odd, but we don't want to leak out
# objects that require locks on the v8 vm, to get a backtrace
# you need a lock, if this happens in the wrong spot you can
# deadlock a process
rescue V8::Error => e
raise JavaScriptError.new(e.message, e.backtrace)
end
end
rval
end
def self.ctx_load(ctx, *files)
files.each do |file|
ctx.load(app_root + file)
end
end
end