Class: Post
Constant Summary
collapse
- BAKED_VERSION =
increase this number to force a system wide post rebake Recreate ‘index_for_rebake_old` when the number is increased Version 1, was the initial version Version 2 15-12-2017, introduces CommonMark and a huge number of onebox fixes
2
- PERMANENT_DELETE_TIMER =
Time between the delete and permanent delete of a post
5.minutes
- MISSING_UPLOADS =
"missing uploads"
- MISSING_UPLOADS_IGNORED =
"missing uploads ignored"
- NOTICE =
"notice"
- SHORT_POST_CHARS =
1200
- MAX_REPLY_LEVEL =
1000
HasCustomFields::CUSTOM_FIELDS_MAX_ITEMS, HasCustomFields::DEFAULT_FIELD_DESCRIPTOR
Constants included
from Searchable
Searchable::PRIORITIES
Instance Attribute Summary collapse
#preloaded_custom_fields
Class Method Summary
collapse
-
.allowed_image_classes ⇒ Object
-
.cook_methods ⇒ Object
-
.estimate_posts_per_day ⇒ Object
-
.excerpt(cooked, maxlength = nil, options = {}) ⇒ Object
-
.find_by_detail(key, value) ⇒ Object
-
.find_by_number(topic_id, post_number) ⇒ Object
-
.find_missing_uploads(include_local_upload: true) ⇒ Object
-
.hidden_reasons ⇒ Object
-
.notices ⇒ Object
-
.private_messages_count_per_day(start_date, end_date, topic_subtype) ⇒ Object
-
.public_posts_count_per_day(start_date, end_date, category_id = nil, include_subcategories = false, group_ids = nil) ⇒ Object
-
.rebake_all_quoted_posts(user_id) ⇒ Object
-
.rebake_old(limit, priority: :normal, rate_limiter: true) ⇒ Object
-
.regular_order ⇒ Object
-
.reverse_order ⇒ Object
-
.summary(topic_id) ⇒ Object
-
.types ⇒ Object
-
.url(slug, topic_id, post_number, opts = nil) ⇒ Object
-
.urls(post_ids) ⇒ Object
Instance Method Summary
collapse
-
#acting_user ⇒ Object
Sometimes the post is being edited by someone else, for example, a mod.
-
#acting_user=(pu) ⇒ Object
-
#add_detail(key, value, extra = nil) ⇒ Object
-
#add_nofollow? ⇒ Boolean
-
#advance_draft_sequence ⇒ Object
-
#allowed_spam_hosts ⇒ Object
-
#archetype ⇒ Object
-
#cannot_permanently_delete_reason(user) ⇒ Object
-
#canonical_url ⇒ Object
-
#cook(raw, opts = {}) ⇒ Object
-
#delete_post_notices ⇒ Object
-
#each_upload_url(fragments: nil, include_local_upload: true) ⇒ Object
-
#excerpt(maxlength = nil, options = {}) ⇒ Object
Strip out most of the markup.
-
#excerpt_for_topic ⇒ Object
-
#external_id ⇒ Object
-
#extract_quoted_post_numbers ⇒ Object
TODO: move to post-analyzer? Determine what posts are quoted by this post.
-
#filter_quotes(parent_post = nil) ⇒ Object
-
#flags ⇒ Object
-
#full_url(opts = {}) ⇒ Object
-
#has_host_spam? ⇒ Boolean
Prevent new users from posting the same hosts too many times.
-
#hide!(post_action_type_id, reason = nil, custom_message: nil) ⇒ Object
-
#image_url ⇒ Object
-
#index_search ⇒ Object
-
#is_category_description? ⇒ Boolean
-
#is_first_post? ⇒ Boolean
-
#is_flagged? ⇒ Boolean
-
#is_reply_by_email? ⇒ Boolean
-
#last_editor ⇒ Object
-
#limit_posts_per_day ⇒ Object
-
#link_post_uploads(fragments: nil) ⇒ Object
-
#locked? ⇒ Boolean
-
#matches_recent_post? ⇒ Boolean
-
#mentions ⇒ Object
-
#omit_nofollow? ⇒ Boolean
-
#owned_uploads_via_access_control ⇒ Object
-
#post_action_type_view ⇒ Object
-
#post_analyzer ⇒ Object
-
#publish_change_to_clients!(type, opts = {}) ⇒ Object
-
#publish_message!(channel, message, opts = {}) ⇒ Object
-
#raw_hash ⇒ Object
-
#readers_count ⇒ Object
-
#rebake!(invalidate_broken_images: false, invalidate_oneboxes: false, priority: nil) ⇒ Object
-
#recover! ⇒ Object
-
#recover_public_post_actions ⇒ Object
-
#relative_url(opts = {}) ⇒ Object
-
#reply_ids(guardian = nil, only_replies_to_single_post: true) ⇒ Object
-
#reply_notification_target ⇒ Object
-
#reply_to_post ⇒ Object
-
#revert_to(number) ⇒ Object
-
#reviewable_flag ⇒ Object
-
#revise(updated_by, changes = {}, opts = {}) ⇒ Object
-
#save_reply_relationships ⇒ Object
-
#seen?(user) ⇒ Boolean
-
#set_owner(new_user, actor, skip_revision = false) ⇒ Object
-
#should_secure_uploads? ⇒ Boolean
NOTE (martin): This is turning into hack city; when changing this also consider how it interacts with UploadSecurity and the uploads.rake tasks.
-
#store_unique_post_key ⇒ Object
-
#total_hosts_usage ⇒ Object
-
#trash!(trashed_by = nil) ⇒ Object
-
#trigger_post_process(bypass_bump: false, priority: :normal, new_post: false, skip_pull_hotlinked_images: false) ⇒ Object
Enqueue post processing for this post.
-
#unhide! ⇒ Object
-
#unique_post_key ⇒ Object
The key we use in redis to ensure unique posts.
-
#unsubscribe_url(user) ⇒ Object
-
#update_uploads_secure_status(source:) ⇒ Object
-
#url(opts = nil) ⇒ Object
-
#whisper? ⇒ Boolean
#edit_time_limit_expired?
#clear_custom_fields, #create_singular, #custom_field_preloaded?, #custom_fields, #custom_fields=, #custom_fields_clean?, #custom_fields_fk, #custom_fields_preloaded?, #on_custom_fields_change, #reload, #save_custom_fields, #set_preloaded_custom_fields, #upsert_custom_fields
Methods included from Trashable
#trashed?
#default_rate_limiter, #disable_rate_limits!, included
Instance Attribute Details
#cooking_options ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def cooking_options
@cooking_options
end
|
#image_sizes ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def image_sizes
@image_sizes
end
|
#invalidate_oneboxes ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def invalidate_oneboxes
@invalidate_oneboxes
end
|
#no_bump ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def no_bump
@no_bump
end
|
#quoted_post_numbers ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def quoted_post_numbers
@quoted_post_numbers
end
|
#skip_unique_check ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def skip_unique_check
@skip_unique_check
end
|
#skip_validation ⇒ Object
We can pass several creating options to a post via attributes
81
82
83
|
# File 'app/models/post.rb', line 81
def skip_validation
@skip_validation
end
|
Class Method Details
.allowed_image_classes ⇒ Object
293
294
295
|
# File 'app/models/post.rb', line 293
def self.allowed_image_classes
@allowed_image_classes ||= %w[avatar favicon thumbnail emoji ytp-thumbnail-image]
end
|
.cook_methods ⇒ Object
185
186
187
|
# File 'app/models/post.rb', line 185
def self.cook_methods
@cook_methods ||= Enum.new(regular: 1, raw_html: 2, email: 3)
end
|
.estimate_posts_per_day ⇒ Object
867
868
869
870
871
872
873
874
875
|
# File 'app/models/post.rb', line 867
def self.estimate_posts_per_day
val = Discourse.redis.get("estimated_posts_per_day")
return val.to_i if val
posts_per_day =
Topic.listable_topics.secured.joins(:posts).merge(Post.created_since(30.days.ago)).count / 30
Discourse.redis.setex("estimated_posts_per_day", 1.day.to_i, posts_per_day.to_s)
posts_per_day
end
|
.excerpt(cooked, maxlength = nil, options = {}) ⇒ Object
531
532
533
534
|
# File 'app/models/post.rb', line 531
def self.excerpt(cooked, maxlength = nil, options = {})
maxlength ||= SiteSetting.post_excerpt_maxlength
PrettyText.excerpt(cooked, maxlength, options)
end
|
.find_by_detail(key, value) ⇒ Object
193
194
195
|
# File 'app/models/post.rb', line 193
def self.find_by_detail(key, value)
includes(:post_details).find_by(post_details: { key: key, value: value })
end
|
.find_by_number(topic_id, post_number) ⇒ Object
197
198
199
|
# File 'app/models/post.rb', line 197
def self.find_by_number(topic_id, post_number)
find_by(topic_id: topic_id, post_number: post_number)
end
|
.find_missing_uploads(include_local_upload: true) ⇒ Object
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
|
# File 'app/models/post.rb', line 1229
def self.find_missing_uploads(include_local_upload: true)
missing_uploads = []
missing_post_uploads = {}
count = 0
DistributedMutex.synchronize("find_missing_uploads", validity: 30.minutes) do
PostCustomField.where(name: Post::MISSING_UPLOADS).delete_all
query =
Post
.have_uploads
.joins(:topic)
.joins(
"LEFT JOIN post_custom_fields ON posts.id = post_custom_fields.post_id AND post_custom_fields.name = '#{Post::MISSING_UPLOADS_IGNORED}'",
)
.where("post_custom_fields.id IS NULL")
.select(:id, :cooked)
query.find_in_batches do |posts|
ids = posts.pluck(:id)
sha1s =
Upload
.joins(:upload_references)
.where(upload_references: { target_type: "Post" })
.where("upload_references.target_id BETWEEN ? AND ?", ids.min, ids.max)
.pluck(:sha1)
posts.each do |post|
post.each_upload_url do |src, path, sha1|
next if sha1.present? && sha1s.include?(sha1)
missing_post_uploads[post.id] ||= []
if missing_uploads.include?(src)
missing_post_uploads[post.id] << src
next
end
upload_id = nil
upload_id = Upload.where(sha1: sha1).pick(:id) if sha1.present?
upload_id ||= yield(post, src, path, sha1)
if upload_id.blank?
missing_uploads << src
missing_post_uploads[post.id] << src
end
end
end
end
missing_post_uploads =
missing_post_uploads.reject do |post_id, uploads|
if uploads.present?
PostCustomField.create!(
post_id: post_id,
name: Post::MISSING_UPLOADS,
value: uploads.to_json,
)
count += uploads.count
end
uploads.empty?
end
end
{ uploads: missing_uploads, post_uploads: missing_post_uploads, count: count }
end
|
.hidden_reasons ⇒ Object
167
168
169
170
171
172
173
174
175
176
177
178
179
|
# File 'app/models/post.rb', line 167
def self.hidden_reasons
@hidden_reasons ||=
Enum.new(
flag_threshold_reached: 1,
flag_threshold_reached_again: 2,
new_user_spam_threshold_reached: 3,
flagged_by_tl3_user: 4,
email_spam_header_found: 5,
flagged_by_tl4_user: 6,
email_authentication_result_header: 7,
imported_as_unlisted: 8,
)
end
|
.notices ⇒ Object
189
190
191
|
# File 'app/models/post.rb', line 189
def self.notices
@notices ||= Enum.new(custom: "custom", new_user: "new_user", returning_user: "returning_user")
end
|
.private_messages_count_per_day(start_date, end_date, topic_subtype) ⇒ Object
979
980
981
982
983
984
985
986
|
# File 'app/models/post.rb', line 979
def self.private_messages_count_per_day(start_date, end_date, topic_subtype)
private_posts
.with_topic_subtype(topic_subtype)
.where("posts.created_at >= ? AND posts.created_at <= ?", start_date, end_date)
.group("date(posts.created_at)")
.order("date(posts.created_at)")
.count
end
|
.public_posts_count_per_day(start_date, end_date, category_id = nil, include_subcategories = false, group_ids = nil) ⇒ Object
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
|
# File 'app/models/post.rb', line 947
def self.public_posts_count_per_day(
start_date,
end_date,
category_id = nil,
include_subcategories = false,
group_ids = nil
)
result =
public_posts.where(
"posts.created_at >= ? AND posts.created_at <= ?",
start_date,
end_date,
).where(post_type: Post.types[:regular])
if category_id
if include_subcategories
result = result.where("topics.category_id IN (?)", Category.subcategory_ids(category_id))
else
result = result.where("topics.category_id IN (?)", category_id)
end
end
if group_ids
result =
result
.joins("INNER JOIN users ON users.id = posts.user_id")
.joins("INNER JOIN group_users ON group_users.user_id = users.id")
.where("group_users.group_id IN (?)", group_ids)
end
result.group("date(posts.created_at)").order("date(posts.created_at)").count
end
|
.rebake_all_quoted_posts(user_id) ⇒ Object
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
|
# File 'app/models/post.rb', line 1042
def self.rebake_all_quoted_posts(user_id)
return if user_id.blank?
DB.exec(<<~SQL, user_id)
WITH user_quoted_posts AS (
SELECT post_id
FROM quoted_posts
WHERE quoted_post_id IN (SELECT id FROM posts WHERE user_id = ?)
)
UPDATE posts
SET baked_version = NULL
WHERE baked_version IS NOT NULL
AND id IN (SELECT post_id FROM user_quoted_posts)
SQL
end
|
.rebake_old(limit, priority: :normal, rate_limiter: true) ⇒ Object
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
|
# File 'app/models/post.rb', line 776
def self.rebake_old(limit, priority: :normal, rate_limiter: true)
limiter =
RateLimiter.new(
nil,
"global_periodical_rebake_limit",
GlobalSetting.max_old_rebakes_per_15_minutes,
900,
global: true,
)
problems = []
Post
.where("baked_version IS NULL OR baked_version < ?", BAKED_VERSION)
.order("id desc")
.limit(limit)
.pluck(:id)
.each do |id|
begin
break if !limiter.can_perform?
post = Post.find(id)
post.rebake!(priority: priority)
begin
limiter.performed! if rate_limiter
rescue RateLimiter::LimitExceeded
break
end
rescue => e
problems << { post: post, ex: e }
attempts = post.custom_fields["rebake_attempts"].to_i
if attempts > 3
post.update_columns(baked_version: BAKED_VERSION)
Discourse.warn_exception(
e,
message: "Can not rebake post# #{post.id} after 3 attempts, giving up",
)
else
post.custom_fields["rebake_attempts"] = attempts + 1
post.save_custom_fields
end
end
end
problems
end
|
.regular_order ⇒ Object
437
438
439
|
# File 'app/models/post.rb', line 437
def self.regular_order
order(:sort_order, :post_number)
end
|
.reverse_order ⇒ Object
441
442
443
|
# File 'app/models/post.rb', line 441
def self.reverse_order
order("sort_order desc, post_number desc")
end
|
.summary(topic_id) ⇒ Object
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
|
# File 'app/models/post.rb', line 445
def self.summary(topic_id)
topic_id = topic_id.to_i
where(topic_id: topic_id).where(
[
"posts.id = ANY(
(
SELECT posts.id
FROM posts
WHERE posts.topic_id = #{topic_id.to_i}
AND posts.post_number = 1
) UNION
(
SELECT p1.id
FROM posts p1
WHERE p1.percent_rank <= ?
AND p1.topic_id = #{topic_id.to_i}
ORDER BY p1.percent_rank
LIMIT ?
)
)",
SiteSetting.summary_percent_filter.to_f / 100.0,
SiteSetting.summary_max_results,
],
)
end
|
.types ⇒ Object
181
182
183
|
# File 'app/models/post.rb', line 181
def self.types
@types ||= Enum.new(regular: 1, moderator_action: 2, small_action: 3, whisper: 4)
end
|
.url(slug, topic_id, post_number, opts = nil) ⇒ Object
744
745
746
747
748
749
750
751
752
753
754
755
|
# File 'app/models/post.rb', line 744
def self.url(slug, topic_id, post_number, opts = nil)
opts ||= {}
result = +"/t/"
result << "#{slug}/" if !opts[:without_slug]
if post_number == 1 && opts[:share_url]
"#{result}#{topic_id}"
else
"#{result}#{topic_id}/#{post_number}"
end
end
|
.urls(post_ids) ⇒ Object
757
758
759
760
761
762
763
764
765
766
767
768
769
770
|
# File 'app/models/post.rb', line 757
def self.urls(post_ids)
ids = post_ids.map { |u| u }
if ids.length > 0
urls = {}
Topic
.joins(:posts)
.where("posts.id" => ids)
.select(["posts.id as post_id", "post_number", "topics.slug", "topics.title", "topics.id"])
.each { |t| urls[t.post_id.to_i] = url(t.slug, t.id, t.post_number) }
urls
else
{}
end
end
|
Instance Method Details
#acting_user ⇒ Object
Sometimes the post is being edited by someone else, for example, a mod. If that’s the case, they should not be bound by the original poster’s restrictions, for example on not posting images.
375
376
377
|
# File 'app/models/post.rb', line 375
def acting_user
@acting_user || user
end
|
#acting_user=(pu) ⇒ Object
379
380
381
|
# File 'app/models/post.rb', line 379
def acting_user=(pu)
@acting_user = pu
end
|
#add_detail(key, value, extra = nil) ⇒ Object
205
206
207
|
# File 'app/models/post.rb', line 205
def add_detail(key, value, = nil)
post_details.build(key: key, value: value, extra: )
end
|
#add_nofollow? ⇒ Boolean
312
313
314
315
|
# File 'app/models/post.rb', line 312
def add_nofollow?
return false if user&.staff?
user.blank? || SiteSetting.tl3_links_no_follow? || !user.has_trust_level?(TrustLevel[3])
end
|
#advance_draft_sequence ⇒ Object
887
888
889
890
|
# File 'app/models/post.rb', line 887
def advance_draft_sequence
return if topic.blank? DraftSequence.next!(last_editor_id, topic.draft_key) if last_editor_id
end
|
#allowed_spam_hosts ⇒ Object
387
388
389
390
391
392
393
394
395
396
397
|
# File 'app/models/post.rb', line 387
def allowed_spam_hosts
hosts =
SiteSetting
.allowed_spam_host_domains
.split("|")
.map { |h| h.strip }
.reject { |h| !h.include?(".") }
hosts << GlobalSetting.hostname
hosts << RailsMultisite::ConnectionManagement.current_hostname
end
|
#archetype ⇒ Object
433
434
435
|
# File 'app/models/post.rb', line 433
def archetype
topic&.archetype
end
|
#cannot_permanently_delete_reason(user) ⇒ Object
1306
1307
1308
1309
1310
1311
1312
1313
1314
|
# File 'app/models/post.rb', line 1306
def cannot_permanently_delete_reason(user)
if self.deleted_by_id == user&.id && self.deleted_at >= Post::PERMANENT_DELETE_TIMER.ago
time_left =
RateLimiter.time_left(
Post::PERMANENT_DELETE_TIMER.to_i - Time.zone.now.to_i + self.deleted_at.to_i,
)
I18n.t("post.cannot_permanently_delete.wait_or_different_admin", time_left: time_left)
end
end
|
#canonical_url ⇒ Object
728
729
730
731
732
733
734
735
736
|
# File 'app/models/post.rb', line 728
def canonical_url
topic_view = TopicView.new(topic, nil, post_number: post_number)
page = ""
page = "?page=#{topic_view.page}" if topic_view.page > 1
"#{topic.url}#{page}#post_#{post_number}"
end
|
#cook(raw, opts = {}) ⇒ Object
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
|
# File 'app/models/post.rb', line 321
def cook(raw, opts = {})
return raw if cook_method == Post.cook_methods[:raw_html]
options = opts.dup
options[:cook_method] = cook_method
options[:user_id] = self.last_editor_id
options[:omit_nofollow] = true if omit_nofollow?
options[:post_id] = self.id
if self.should_secure_uploads?
each_upload_url do |url|
uri = URI.parse(url)
if FileHelper.is_supported_media?(File.basename(uri.path))
raw =
raw.sub(
url,
Rails.application.routes.url_for(
controller: "uploads",
action: "show_secure",
path: uri.path[1..-1],
host: Discourse.current_hostname,
),
)
end
end
end
cooked = post_analyzer.cook(raw, options)
new_cooked = Plugin::Filter.apply(:after_post_cook, self, cooked)
if post_type == Post.types[:regular]
if new_cooked != cooked && new_cooked.blank?
Rails.logger.debug("Plugin is blanking out post: #{self.url}\nraw: #{raw}")
elsif new_cooked.blank?
Rails.logger.debug("Blank post detected post: #{self.url}\nraw: #{raw}")
end
end
new_cooked
end
|
#delete_post_notices ⇒ Object
473
474
475
476
|
# File 'app/models/post.rb', line 473
def delete_post_notices
self.custom_fields.delete(Post::NOTICE)
self.save_custom_fields
end
|
#each_upload_url(fragments: nil, include_local_upload: true) ⇒ Object
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
|
# File 'app/models/post.rb', line 1137
def each_upload_url(fragments: nil, include_local_upload: true)
current_db = RailsMultisite::ConnectionManagement.current_db
upload_patterns = [
%r{/uploads/#{current_db}/},
%r{/original/},
%r{/optimized/},
%r{/uploads/short-url/[a-zA-Z0-9]+(\.[a-z0-9]+)?},
]
fragments ||= Nokogiri::HTML5.fragment(self.cooked)
selectors =
fragments.css(
"a/@href",
"img/@src",
"source/@src",
"track/@src",
"video/@poster",
"div/@data-video-src",
)
links =
selectors
.map do |media|
src = media.value
next if src.blank?
if src.end_with?("/images/transparent.png") &&
(parent = media.parent)["data-orig-src"].present?
parent["data-orig-src"]
else
src
end
end
.compact
.uniq
links.each do |src|
src = src.split("?")[0]
if src.start_with?("upload://")
sha1 = Upload.sha1_from_short_url(src)
yield(src, nil, sha1)
next
end
if src.include?("/uploads/short-url/")
host =
begin
URI(src).host
rescue URI::Error
end
next if host.present? && host != Discourse.current_hostname
sha1 = Upload.sha1_from_short_path(src)
yield(src, nil, sha1)
next
end
next if upload_patterns.none? { |pattern| src =~ pattern }
next if Rails.configuration.multisite && src.exclude?(current_db)
src = "#{SiteSetting.force_https ? "https" : "http"}:#{src}" if src.start_with?("//")
if !Discourse.store.has_been_uploaded?(src) && !Upload.secure_uploads_url?(src) &&
!(include_local_upload && src =~ %r{\A/[^/]}i)
next
end
path =
begin
URI(
UrlHelper.unencode(GlobalSetting.cdn_url ? src.sub(GlobalSetting.cdn_url, "") : src),
)&.path
rescue URI::Error
end
next if path.blank?
sha1 =
if path.include? "optimized"
OptimizedImage.(path)
else
Upload.(path) || Upload.sha1_from_short_path(path)
end
yield(src, path, sha1)
end
end
|
#excerpt(maxlength = nil, options = {}) ⇒ Object
Strip out most of the markup
537
538
539
|
# File 'app/models/post.rb', line 537
def excerpt(maxlength = nil, options = {})
Post.excerpt(cooked, maxlength, options.merge(post: self))
end
|
#excerpt_for_topic ⇒ Object
541
542
543
544
545
546
547
548
549
|
# File 'app/models/post.rb', line 541
def excerpt_for_topic
Post.excerpt(
cooked,
SiteSetting.topic_excerpt_maxlength,
strip_links: true,
strip_images: true,
post: self,
)
end
|
#external_id ⇒ Object
507
508
509
|
# File 'app/models/post.rb', line 507
def external_id
"#{topic_id}/#{post_number}"
end
|
TODO: move to post-analyzer? Determine what posts are quoted by this post
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
|
# File 'app/models/post.rb', line 894
def
temp_collector = []
raw
.scan(/\[quote=\"([^"]+)"\]/)
.each do |quote|
args = parse_quote_into_arguments(quote)
if !(args[:topic].present? && topic_id != args[:topic]) && args[:post] != post_number
temp_collector << args[:post]
end
end
temp_collector.uniq!
self.quoted_post_numbers = temp_collector
self.quote_count = temp_collector.size
end
|
#filter_quotes(parent_post = nil) ⇒ Object
492
493
494
495
496
497
498
499
500
501
502
503
504
505
|
# File 'app/models/post.rb', line 492
def filter_quotes(parent_post = nil)
return cooked if parent_post.blank?
return cooked unless (quote_count == 1)
parent_raw = parent_post.raw.sub(%r{\[quote.+/quote\]}m, "")
if raw[parent_raw] || (parent_raw.size < SHORT_POST_CHARS)
return cooked.sub(%r{\<aside.+\</aside\>}m, "")
end
cooked
end
|
#flags ⇒ Object
571
572
573
574
575
576
|
# File 'app/models/post.rb', line 571
def flags
post_actions.where(
post_action_type_id: post_action_type_view.flag_types_without_additional_message.values,
deleted_at: nil,
)
end
|
#full_url(opts = {}) ⇒ Object
710
711
712
|
# File 'app/models/post.rb', line 710
def full_url(opts = {})
"#{Discourse.base_url}#{url(opts)}"
end
|
#has_host_spam? ⇒ Boolean
Prevent new users from posting the same hosts too many times.
420
421
422
423
424
425
426
427
428
429
430
431
|
# File 'app/models/post.rb', line 420
def has_host_spam?
if acting_user.present? &&
(
acting_user.staged? || acting_user.mature_staged? ||
acting_user.has_trust_level?(TrustLevel[1])
)
return false
end
return false if topic&.private_message?
total_hosts_usage.values.any? { |count| count >= SiteSetting.newuser_spam_host_threshold }
end
|
#hide!(post_action_type_id, reason = nil, custom_message: nil) ⇒ Object
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
|
# File 'app/models/post.rb', line 613
def hide!(post_action_type_id, reason = nil, custom_message: nil)
return if hidden?
reason ||=
(
if hidden_at
Post.hidden_reasons[:flag_threshold_reached_again]
else
Post.hidden_reasons[:flag_threshold_reached]
end
)
hiding_again = hidden_at.present?
Post.transaction do
self.skip_validation = true
should_update_user_stat = true
update!(hidden: true, hidden_at: Time.zone.now, hidden_reason_id: reason)
any_visible_posts_in_topic =
Post.exists?(topic_id: topic_id, hidden: false, post_type: Post.types[:regular])
if !any_visible_posts_in_topic
self.topic.update_status(
"visible",
false,
Discourse.system_user,
{ visibility_reason_id: Topic.visibility_reasons[:op_flag_threshold_reached] },
)
should_update_user_stat = false
end
UserStatCountUpdater.decrement!(self) if should_update_user_stat
end
if user.present?
options = {
url: url,
edit_delay: SiteSetting.cooldown_minutes_after_hiding_posts,
flag_reason:
I18n.t(
"flag_reasons.#{post_action_type_view.types[post_action_type_id]}",
locale: SiteSetting.default_locale,
base_path: Discourse.base_path,
default: PostActionType.names[post_action_type_id],
),
}
message = custom_message
message = hiding_again ? :post_hidden_again : :post_hidden if message.nil?
Jobs.enqueue_in(
5.seconds,
:send_system_message,
user_id: user.id,
message_type: message.to_s,
message_options: options,
)
end
end
|
#image_url ⇒ Object
1301
1302
1303
1304
|
# File 'app/models/post.rb', line 1301
def image_url
raw_url = image_upload&.url
UrlHelper.cook_url(raw_url, secure: image_upload&.secure?, local: true) if raw_url
end
|
#is_category_description? ⇒ Boolean
555
556
557
|
# File 'app/models/post.rb', line 555
def is_category_description?
topic.present? && topic.is_category_topic? && is_first_post?
end
|
#is_first_post? ⇒ Boolean
551
552
553
|
# File 'app/models/post.rb', line 551
def is_first_post?
post_number.blank? ? topic.try(:highest_post_number) == 0 : post_number == 1
end
|
#is_flagged? ⇒ Boolean
563
564
565
|
# File 'app/models/post.rb', line 563
def is_flagged?
flags.count != 0
end
|
#is_reply_by_email? ⇒ Boolean
559
560
561
|
# File 'app/models/post.rb', line 559
def is_reply_by_email?
via_email && post_number.present? && post_number > 1
end
|
#last_editor ⇒ Object
383
384
385
|
# File 'app/models/post.rb', line 383
def last_editor
self.last_editor_id ? (User.find_by_id(self.last_editor_id) || user) : user
end
|
#limit_posts_per_day ⇒ Object
209
210
211
212
213
214
215
216
217
218
|
# File 'app/models/post.rb', line 209
def limit_posts_per_day
if user && user.new_user_posting_on_first_day? && post_number && post_number > 1
RateLimiter.new(
user,
"first-day-replies-per-day",
SiteSetting.max_replies_in_first_day,
1.day.to_i,
)
end
end
|
#link_post_uploads(fragments: nil) ⇒ Object
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
|
# File 'app/models/post.rb', line 1072
def link_post_uploads(fragments: nil)
upload_ids = []
each_upload_url(fragments: fragments) do |src, _, sha1|
upload = nil
upload = Upload.find_by(sha1: sha1) if sha1.present?
upload ||= Upload.get_from_url(src)
if SiteSetting.video_thumbnails_enabled && upload.present? &&
FileHelper.supported_video.include?(upload.extension&.downcase)
thumbnail =
Upload
.where("original_filename like ?", "#{upload.sha1}.%")
.order(id: :desc)
.first if upload.sha1.present?
if thumbnail.present?
upload_ids << thumbnail.id
if self.is_first_post? && !self.topic.image_upload_id
self.topic.update_column(:image_upload_id, thumbnail.id)
=
ThemeModifierHelper.new(
theme_ids: Theme.user_selectable.pluck(:id),
).topic_thumbnail_sizes
self.topic.generate_thumbnails!(extra_sizes: )
end
end
end
upload_ids << upload.id if upload.present?
end
upload_references =
upload_ids.map do |upload_id|
{
target_id: self.id,
target_type: self.class.name,
upload_id: upload_id,
created_at: Time.zone.now,
updated_at: Time.zone.now,
}
end
UploadReference.transaction do
UploadReference.where(target: self).delete_all
UploadReference.insert_all(upload_references) if upload_references.size > 0
if SiteSetting.secure_uploads?
Upload
.where(id: upload_ids, access_control_post_id: nil)
.where("id NOT IN (SELECT upload_id FROM custom_emojis)")
.update_all(access_control_post_id: self.id)
end
end
end
|
#locked? ⇒ Boolean
1068
1069
1070
|
# File 'app/models/post.rb', line 1068
def locked?
locked_by_id.present?
end
|
#matches_recent_post? ⇒ Boolean
283
284
285
286
|
# File 'app/models/post.rb', line 283
def matches_recent_post?
post_id = Discourse.redis.get(unique_post_key)
post_id != (nil) && post_id.to_i != (id)
end
|
#mentions ⇒ Object
1316
1317
1318
|
# File 'app/models/post.rb', line 1316
def mentions
PrettyText.(Nokogiri::HTML5.fragment(cooked))
end
|
#omit_nofollow? ⇒ Boolean
317
318
319
|
# File 'app/models/post.rb', line 317
def omit_nofollow?
!add_nofollow?
end
|
#owned_uploads_via_access_control ⇒ Object
1297
1298
1299
|
# File 'app/models/post.rb', line 1297
def owned_uploads_via_access_control
Upload.where(access_control_post_id: self.id)
end
|
#post_action_type_view ⇒ Object
567
568
569
|
# File 'app/models/post.rb', line 567
def post_action_type_view
@post_action_type_view ||= PostActionTypeView.new
end
|
#post_analyzer ⇒ Object
297
298
299
300
|
# File 'app/models/post.rb', line 297
def post_analyzer
@post_analyzers ||= {}
@post_analyzers[raw_hash] ||= PostAnalyzer.new(raw, topic_id)
end
|
#publish_change_to_clients!(type, opts = {}) ⇒ Object
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
# File 'app/models/post.rb', line 225
def publish_change_to_clients!(type, opts = {})
return unless topic
skip_topic_stats = opts.delete(:skip_topic_stats)
message = {
id: id,
post_number: post_number,
updated_at: Time.now,
user_id: user_id,
last_editor_id: last_editor_id,
type: type,
version: version,
}.merge(opts)
publish_message!("/topic/#{topic_id}", message)
Topic.publish_stats_to_clients!(topic.id, type) unless skip_topic_stats
end
|
#publish_message!(channel, message, opts = {}) ⇒ Object
246
247
248
249
250
251
252
253
254
255
256
|
# File 'app/models/post.rb', line 246
def publish_message!(channel, message, opts = {})
return unless topic
if Topic.visible_post_types.include?(post_type)
opts.merge!(topic.secure_audience_publish_messages)
else
opts[:user_ids] = User.human_users.where("admin OR moderator OR id = ?", user_id).pluck(:id)
end
MessageBus.publish(channel, message, opts) if opts[:user_ids] != [] && opts[:group_ids] != []
end
|
#raw_hash ⇒ Object
288
289
290
291
|
# File 'app/models/post.rb', line 288
def raw_hash
return if raw.blank?
Digest::SHA1.hexdigest(raw)
end
|
#readers_count ⇒ Object
220
221
222
223
|
# File 'app/models/post.rb', line 220
def readers_count
read_count = reads - 1 read_count < 0 ? 0 : read_count
end
|
#rebake!(invalidate_broken_images: false, invalidate_oneboxes: false, priority: nil) ⇒ Object
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
|
# File 'app/models/post.rb', line 824
def rebake!(invalidate_broken_images: false, invalidate_oneboxes: false, priority: nil)
new_cooked = cook(raw, topic_id: topic_id, invalidate_oneboxes: invalidate_oneboxes)
old_cooked = cooked
update_columns(cooked: new_cooked, baked_at: Time.zone.now, baked_version: BAKED_VERSION)
topic&.update_excerpt(excerpt_for_topic) if is_first_post?
if invalidate_broken_images
post_hotlinked_media.download_failed.destroy_all
post_hotlinked_media.upload_create_failed.destroy_all
end
TopicLink.(self)
QuotedPost.(self)
trigger_post_process(bypass_bump: true, priority: priority)
publish_change_to_clients!(:rebaked)
new_cooked != old_cooked
end
|
#recover! ⇒ Object
264
265
266
267
268
269
270
|
# File 'app/models/post.rb', line 264
def recover!
super
recover_public_post_actions
TopicLink.(self)
QuotedPost.(self)
topic.category.update_latest if topic && topic.category_id && topic.category
end
|
#recover_public_post_actions ⇒ Object
478
479
480
481
482
483
484
485
486
487
488
489
490
|
# File 'app/models/post.rb', line 478
def recover_public_post_actions
PostAction
.publics
.with_deleted
.where(post_id: self.id, id: self.custom_fields["deleted_public_actions"])
.find_each do |post_action|
post_action.recover!
post_action.save!
end
self.custom_fields.delete("deleted_public_actions")
self.save_custom_fields
end
|
#relative_url(opts = {}) ⇒ Object
714
715
716
|
# File 'app/models/post.rb', line 714
def relative_url(opts = {})
"#{Discourse.base_path}#{url(opts)}"
end
|
#reply_ids(guardian = nil, only_replies_to_single_post: true) ⇒ Object
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
|
# File 'app/models/post.rb', line 990
def reply_ids(guardian = nil, only_replies_to_single_post: true)
builder = DB.build(<<~SQL)
WITH RECURSIVE breadcrumb(id, level) AS (
SELECT :post_id, 0
UNION
SELECT reply_post_id, level + 1
FROM post_replies AS r
JOIN posts AS p ON p.id = reply_post_id
JOIN breadcrumb AS b ON (r.post_id = b.id)
WHERE r.post_id <> r.reply_post_id
AND b.level < :max_reply_level
AND p.topic_id = :topic_id
), breadcrumb_with_count AS (
SELECT
id,
level,
COUNT(*) AS count
FROM post_replies AS r
JOIN breadcrumb AS b ON (r.reply_post_id = b.id)
WHERE r.reply_post_id <> r.post_id
GROUP BY id, level
)
SELECT id, MIN(level) AS level
FROM breadcrumb_with_count
/*where*/
GROUP BY id
ORDER BY id
SQL
builder.where("level > 0")
builder.where("count = 1") if only_replies_to_single_post
replies = builder.query_hash(post_id: id, max_reply_level: MAX_REPLY_LEVEL, topic_id: topic_id)
replies.each { |r| r.symbolize_keys! }
secured_ids = Post.secured(guardian).where(id: replies.map { |r| r[:id] }).pluck(:id).to_set
replies.reject { |r| !secured_ids.include?(r[:id]) }
end
|
#reply_notification_target ⇒ Object
521
522
523
524
525
526
527
528
529
|
# File 'app/models/post.rb', line 521
def reply_notification_target
return if reply_to_post_number.blank?
Post.find_by(
"topic_id = :topic_id AND post_number = :post_number AND user_id <> :user_id",
topic_id: topic_id,
post_number: reply_to_post_number,
user_id: user_id,
).try(:user)
end
|
#reply_to_post ⇒ Object
511
512
513
514
515
516
517
518
519
|
# File 'app/models/post.rb', line 511
def reply_to_post
return if reply_to_post_number.blank?
@reply_to_post ||=
Post.find_by(
"topic_id = :topic_id AND post_number = :post_number",
topic_id: topic_id,
post_number: reply_to_post_number,
)
end
|
#revert_to(number) ⇒ Object
1033
1034
1035
1036
1037
1038
1039
1040
|
# File 'app/models/post.rb', line 1033
def revert_to(number)
return if number >= version
post_revision = PostRevision.find_by(post_id: id, number: (number + 1))
post_revision.modifications.each do |attribute, change|
attribute = "version" if attribute == "cached_version"
write_attribute(attribute, change[0])
end
end
|
#reviewable_flag ⇒ Object
578
579
580
|
# File 'app/models/post.rb', line 578
def reviewable_flag
ReviewableFlaggedPost.pending.find_by(target: self)
end
|
#revise(updated_by, changes = {}, opts = {}) ⇒ Object
772
773
774
|
# File 'app/models/post.rb', line 772
def revise(updated_by, changes = {}, opts = {})
PostRevisor.new(self).revise!(updated_by, changes, opts)
end
|
#save_reply_relationships ⇒ Object
913
914
915
916
917
918
919
920
921
922
|
# File 'app/models/post.rb', line 913
def save_reply_relationships
add_to_quoted_post_numbers(reply_to_post_number)
return if self.quoted_post_numbers.blank?
self.quoted_post_numbers.each do |p|
post = Post.find_by(topic_id: topic_id, post_number: p)
create_reply_relationship_with(post)
end
end
|
#seen?(user) ⇒ Boolean
1058
1059
1060
|
# File 'app/models/post.rb', line 1058
def seen?(user)
PostTiming.where(topic_id: topic_id, post_number: post_number, user_id: user.id).exists?
end
|
#set_owner(new_user, actor, skip_revision = false) ⇒ Object
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
|
# File 'app/models/post.rb', line 849
def set_owner(new_user, actor, skip_revision = false)
return if user_id == new_user.id
edit_reason = I18n.t("change_owner.post_revision_text", locale: SiteSetting.default_locale)
revise(
actor,
{ raw: self.raw, user_id: new_user.id, edit_reason: edit_reason },
bypass_bump: true,
skip_revision: skip_revision,
skip_validations: true,
)
topic.update_columns(last_post_user_id: new_user.id) if post_number == topic.highest_post_number
end
|
#should_secure_uploads? ⇒ Boolean
NOTE (martin): This is turning into hack city; when changing this also consider how it interacts with UploadSecurity and the uploads.rake tasks.
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
|
# File 'app/models/post.rb', line 584
def should_secure_uploads?
return false if !SiteSetting.secure_uploads?
topic_including_deleted = Topic.with_deleted.find_by(id: self.topic_id)
return false if topic_including_deleted.blank?
modifier_result =
DiscoursePluginRegistry.apply_modifier(
:post_should_secure_uploads?,
nil,
self,
topic_including_deleted,
)
return modifier_result if !modifier_result.nil?
return topic_including_deleted.private_message? if SiteSetting.secure_uploads_pm_only?
SiteSetting.login_required? || topic_including_deleted.private_message? ||
topic_including_deleted.read_restricted_category?
end
|
#store_unique_post_key ⇒ Object
277
278
279
280
281
|
# File 'app/models/post.rb', line 277
def store_unique_post_key
if SiteSetting.unique_posts_mins > 0
Discourse.redis.setex(unique_post_key, SiteSetting.unique_posts_mins.minutes.to_i, id)
end
end
|
#total_hosts_usage ⇒ Object
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
|
# File 'app/models/post.rb', line 399
def total_hosts_usage
hosts = linked_hosts.clone
allowlisted = allowed_spam_hosts
hosts.reject! { |h| allowlisted.any? { |w| h.end_with?(w) } }
return hosts if hosts.length == 0
TopicLink
.where(domain: hosts.keys, user_id: acting_user.id)
.group(:domain, :post_id)
.count
.each_key do |tuple|
domain = tuple[0]
hosts[domain] = (hosts[domain] || 0) + 1
end
hosts
end
|
#trash!(trashed_by = nil) ⇒ Object
258
259
260
261
262
|
# File 'app/models/post.rb', line 258
def trash!(trashed_by = nil)
self.topic_links.each(&:destroy)
self.save_custom_fields if self.custom_fields.delete(Post::NOTICE)
super(trashed_by)
end
|
#trigger_post_process(bypass_bump: false, priority: :normal, new_post: false, skip_pull_hotlinked_images: false) ⇒ Object
Enqueue post processing for this post
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
|
# File 'app/models/post.rb', line 925
def trigger_post_process(
bypass_bump: false,
priority: :normal,
new_post: false,
skip_pull_hotlinked_images: false
)
args = {
bypass_bump: bypass_bump,
cooking_options: self.cooking_options,
new_post: new_post,
post_id: self.id,
skip_pull_hotlinked_images: skip_pull_hotlinked_images,
}
args[:image_sizes] = image_sizes if self.image_sizes.present?
args[:invalidate_oneboxes] = true if self.invalidate_oneboxes.present?
args[:queue] = priority.to_s if priority && priority != :normal
Jobs.enqueue(:process_post, args)
DiscourseEvent.trigger(:after_trigger_post_process, self)
end
|
#unhide! ⇒ Object
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
|
# File 'app/models/post.rb', line 678
def unhide!
Post.transaction do
self.update!(hidden: false)
should_update_user_stat = true
hidden_because_of_op_flagging =
self.topic.visibility_reason_id == Topic.visibility_reasons[:op_flag_threshold_reached] ||
self.topic.visibility_reason_id.nil?
if is_first_post? && hidden_because_of_op_flagging
self.topic.update_status(
"visible",
true,
Discourse.system_user,
{ visibility_reason_id: Topic.visibility_reasons[:op_unhidden] },
)
should_update_user_stat = false
end
UserStatCountUpdater.increment!(self) if should_update_user_stat
save(validate: false)
end
publish_change_to_clients!(:acted)
end
|
#unique_post_key ⇒ Object
The key we use in redis to ensure unique posts
273
274
275
|
# File 'app/models/post.rb', line 273
def unique_post_key
"unique#{topic&.private_message? ? "-pm" : ""}-post-#{user_id}:#{raw_hash}"
end
|
#unsubscribe_url(user) ⇒ Object
#update_uploads_secure_status(source:) ⇒ Object
1131
1132
1133
1134
1135
|
# File 'app/models/post.rb', line 1131
def update_uploads_secure_status(source:)
if Discourse.store.external?
self.uploads.each { |upload| upload.update_secure_status(source: source) }
end
end
|
#url(opts = nil) ⇒ Object
718
719
720
721
722
723
724
725
726
|
# File 'app/models/post.rb', line 718
def url(opts = nil)
opts ||= {}
if topic
Post.url(topic.slug, topic.id, post_number, opts)
else
"/404"
end
end
|
#whisper? ⇒ Boolean
201
202
203
|
# File 'app/models/post.rb', line 201
def whisper?
post_type == Post.types[:whisper]
end
|