/
topic.rb
1808 lines (1508 loc) · 59.1 KB
/
topic.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
318
319
320
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
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
612
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
677
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
class Topic < ActiveRecord::Base
class UserExists < StandardError; end
class NotAllowed < StandardError; end
include ActionView::Helpers::SanitizeHelper
include RateLimiter::OnCreateRecord
include HasCustomFields
include Trashable
include Searchable
include LimitedEdit
extend Forwardable
self.ignored_columns = [
"avg_time", # TODO(2021-01-04): remove
"image_url" # TODO(2021-06-01): remove
]
def_delegator :featured_users, :user_ids, :featured_user_ids
def_delegator :featured_users, :choose, :feature_topic_users
def_delegator :notifier, :watch!, :notify_watch!
def_delegator :notifier, :track!, :notify_tracking!
def_delegator :notifier, :regular!, :notify_regular!
def_delegator :notifier, :mute!, :notify_muted!
def_delegator :notifier, :toggle_mute, :toggle_mute
attr_accessor :allowed_user_ids, :tags_changed, :includes_destination_category
def self.max_fancy_title_length
400
end
def self.share_thumbnail_size
[1024, 1024]
end
def self.thumbnail_sizes
[ self.share_thumbnail_size ] + DiscoursePluginRegistry.topic_thumbnail_sizes
end
def thumbnail_job_redis_key(sizes)
"generate_topic_thumbnail_enqueue_#{id}_#{sizes.inspect}"
end
def filtered_topic_thumbnails(extra_sizes: [])
return nil unless original = image_upload
return nil unless original.read_attribute(:width) && original.read_attribute(:height)
thumbnail_sizes = Topic.thumbnail_sizes + extra_sizes
topic_thumbnails.filter { |record| thumbnail_sizes.include?([record.max_width, record.max_height]) }
end
def thumbnail_info(enqueue_if_missing: false, extra_sizes: [])
return nil unless original = image_upload
return nil unless original.filesize < SiteSetting.max_image_size_kb.kilobytes
return nil unless original.read_attribute(:width) && original.read_attribute(:height)
infos = []
infos << { # Always add original
max_width: nil,
max_height: nil,
width: original.width,
height: original.height,
url: original.url
}
records = filtered_topic_thumbnails(extra_sizes: extra_sizes)
records.each do |record|
next unless record.optimized_image # Only serialize successful thumbnails
infos << {
max_width: record.max_width,
max_height: record.max_height,
width: record.optimized_image&.width,
height: record.optimized_image&.height,
url: record.optimized_image&.url
}
end
thumbnail_sizes = Topic.thumbnail_sizes + extra_sizes
if SiteSetting.create_thumbnails &&
enqueue_if_missing &&
records.length < thumbnail_sizes.length &&
Discourse.redis.set(thumbnail_job_redis_key(thumbnail_sizes), 1, nx: true, ex: 1.minute)
Jobs.enqueue(:generate_topic_thumbnails, { topic_id: id, extra_sizes: extra_sizes })
end
infos.each { |i| i[:url] = UrlHelper.cook_url(i[:url], secure: original.secure?) }
infos.sort_by! { |i| -i[:width] * i[:height] }
end
def generate_thumbnails!(extra_sizes: [])
return nil unless SiteSetting.create_thumbnails
return nil unless original = image_upload
return nil unless original.filesize < SiteSetting.max_image_size_kb.kilobytes
return nil unless original.width && original.height
extra_sizes = [] unless extra_sizes.kind_of?(Array)
(Topic.thumbnail_sizes + extra_sizes).each do |dim|
TopicThumbnail.find_or_create_for!(original, max_width: dim[0], max_height: dim[1])
end
end
def image_url(enqueue_if_missing: false)
thumbnail = topic_thumbnails.detect do |record|
record.max_width == Topic.share_thumbnail_size[0] &&
record.max_height == Topic.share_thumbnail_size[1]
end
if thumbnail.nil? &&
image_upload &&
SiteSetting.create_thumbnails &&
image_upload.filesize < SiteSetting.max_image_size_kb.kilobytes &&
image_upload.read_attribute(:width) &&
image_upload.read_attribute(:height) &&
enqueue_if_missing &&
Discourse.redis.set(thumbnail_job_redis_key([]), 1, nx: true, ex: 1.minute)
Jobs.enqueue(:generate_topic_thumbnails, { topic_id: id })
end
raw_url = thumbnail&.optimized_image&.url || image_upload&.url
UrlHelper.cook_url(raw_url, secure: image_upload&.secure?)
end
def featured_users
@featured_users ||= TopicFeaturedUsers.new(self)
end
def trash!(trashed_by = nil)
if deleted_at.nil?
update_category_topic_count_by(-1)
CategoryTagStat.topic_deleted(self) if self.tags.present?
DiscourseEvent.trigger(:topic_trashed, self)
end
super(trashed_by)
self.topic_embed.trash! if has_topic_embed?
end
def recover!(recovered_by = nil)
unless deleted_at.nil?
update_category_topic_count_by(1)
CategoryTagStat.topic_recovered(self) if self.tags.present?
DiscourseEvent.trigger(:topic_recovered, self)
end
# Note parens are required because superclass doesn't take `recovered_by`
super()
unless (topic_embed = TopicEmbed.with_deleted.find_by_topic_id(id)).nil?
topic_embed.recover!
end
end
rate_limit :default_rate_limiter
rate_limit :limit_topics_per_day
rate_limit :limit_private_messages_per_day
validates :title, if: Proc.new { |t| t.new_record? || t.title_changed? },
presence: true,
topic_title_length: true,
censored_words: true,
watched_words: true,
quality_title: { unless: :private_message? },
max_emojis: true,
unique_among: { unless: Proc.new { |t| (SiteSetting.allow_duplicate_topic_titles? || t.private_message?) },
message: :has_already_been_used,
allow_blank: true,
case_sensitive: false,
collection: Proc.new { |t|
SiteSetting.allow_duplicate_topic_titles_category? ?
Topic.listable_topics.where("category_id = ?", t.category_id) :
Topic.listable_topics
}
}
validates :category_id,
presence: true,
exclusion: {
in: Proc.new { [SiteSetting.uncategorized_category_id] }
},
if: Proc.new { |t|
(t.new_record? || t.category_id_changed?) &&
!SiteSetting.allow_uncategorized_topics &&
(t.archetype.nil? || t.regular?)
}
validates :featured_link, allow_nil: true, url: true
validate if: :featured_link do
errors.add(:featured_link, :invalid_category) unless !featured_link_changed? ||
Guardian.new.can_edit_featured_link?(category_id)
end
before_validation do
self.title = TextCleaner.clean_title(TextSentinel.title_sentinel(title).text) if errors[:title].empty?
self.featured_link = self.featured_link.strip.presence if self.featured_link
end
belongs_to :category
has_many :category_users, through: :category
has_many :posts
has_many :bookmarks
has_many :ordered_posts, -> { order(post_number: :asc) }, class_name: "Post"
has_many :topic_allowed_users
has_many :topic_allowed_groups
has_many :incoming_email
has_many :group_archived_messages, dependent: :destroy
has_many :user_archived_messages, dependent: :destroy
has_many :allowed_groups, through: :topic_allowed_groups, source: :group
has_many :allowed_group_users, through: :allowed_groups, source: :users
has_many :allowed_users, through: :topic_allowed_users, source: :user
has_many :topic_tags
has_many :tags, through: :topic_tags, dependent: :destroy # dependent destroy applies to the topic_tags records
has_many :tag_users, through: :tags
has_one :top_topic
has_one :shared_draft, dependent: :destroy
has_one :published_page
belongs_to :user
belongs_to :last_poster, class_name: 'User', foreign_key: :last_post_user_id
belongs_to :featured_user1, class_name: 'User', foreign_key: :featured_user1_id
belongs_to :featured_user2, class_name: 'User', foreign_key: :featured_user2_id
belongs_to :featured_user3, class_name: 'User', foreign_key: :featured_user3_id
belongs_to :featured_user4, class_name: 'User', foreign_key: :featured_user4_id
has_many :topic_users
has_many :topic_links
has_many :topic_invites
has_many :invites, through: :topic_invites, source: :invite
has_many :topic_timers, dependent: :destroy
has_many :reviewables
has_many :user_profiles
has_one :user_warning
has_one :first_post, -> { where post_number: 1 }, class_name: 'Post'
has_one :topic_search_data
has_one :topic_embed, dependent: :destroy
has_one :linked_topic, dependent: :destroy
belongs_to :image_upload, class_name: 'Upload'
has_many :topic_thumbnails, through: :image_upload
# When we want to temporarily attach some data to a forum topic (usually before serialization)
attr_accessor :user_data
attr_accessor :category_user_data
attr_accessor :posters # TODO: can replace with posters_summary once we remove old list code
attr_accessor :participants
attr_accessor :topic_list
attr_accessor :meta_data
attr_accessor :include_last_poster
attr_accessor :import_mode # set to true to optimize creation and save for imports
# The regular order
scope :topic_list_order, -> { order('topics.bumped_at desc') }
# Return private message topics
scope :private_messages, -> { where(archetype: Archetype.private_message) }
PRIVATE_MESSAGES_SQL = <<~SQL
SELECT topic_id
FROM topic_allowed_users
WHERE user_id = :user_id
UNION ALL
SELECT tg.topic_id
FROM topic_allowed_groups tg
JOIN group_users gu ON gu.user_id = :user_id AND gu.group_id = tg.group_id
SQL
scope :private_messages_for_user, ->(user) {
private_messages.where("topics.id IN (#{PRIVATE_MESSAGES_SQL})", user_id: user.id)
}
scope :listable_topics, -> { where('topics.archetype <> ?', Archetype.private_message) }
scope :by_newest, -> { order('topics.created_at desc, topics.id desc') }
scope :visible, -> { where(visible: true) }
scope :created_since, lambda { |time_ago| where('topics.created_at > ?', time_ago) }
scope :exclude_scheduled_bump_topics, -> { where.not(id: TopicTimer.scheduled_bump_topics) }
scope :secured, lambda { |guardian = nil|
ids = guardian.secure_category_ids if guardian
# Query conditions
condition = if ids.present?
["NOT read_restricted OR id IN (:cats)", cats: ids]
else
["NOT read_restricted"]
end
where("topics.category_id IS NULL OR topics.category_id IN (SELECT id FROM categories WHERE #{condition[0]})", condition[1])
}
scope :in_category_and_subcategories, lambda { |category_id|
where("topics.category_id IN (?)", Category.subcategory_ids(category_id.to_i)) if category_id
}
scope :with_subtype, ->(subtype) { where('topics.subtype = ?', subtype) }
attr_accessor :ignore_category_auto_close
attr_accessor :skip_callbacks
before_create do
initialize_default_values
end
after_create do
unless skip_callbacks
changed_to_category(category)
advance_draft_sequence
end
end
before_save do
unless skip_callbacks
ensure_topic_has_a_category
end
if title_changed?
write_attribute(:fancy_title, Topic.fancy_title(title))
end
if category_id_changed? || new_record?
inherit_auto_close_from_category
end
end
after_save do
banner = "banner"
if archetype_before_last_save == banner || archetype == banner
ApplicationController.banner_json_cache.clear
end
if tags_changed || saved_change_to_attribute?(:category_id) || saved_change_to_attribute?(:title)
SearchIndexer.queue_post_reindex(self.id)
if tags_changed
TagUser.auto_watch(topic_id: id)
TagUser.auto_track(topic_id: id)
self.tags_changed = false
end
end
SearchIndexer.index(self)
end
after_update do
if saved_changes[:category_id] && self.tags.present?
CategoryTagStat.topic_moved(self, *saved_changes[:category_id])
elsif saved_changes[:category_id] && self.category&.read_restricted?
UserProfile.remove_featured_topic_from_all_profiles(self)
end
end
def initialize_default_values
self.bumped_at ||= Time.now
self.last_post_user_id ||= user_id
end
def inherit_auto_close_from_category
if !self.closed &&
!@ignore_category_auto_close &&
self.category &&
self.category.auto_close_hours &&
!public_topic_timer&.execute_at
based_on_last_post = self.category.auto_close_based_on_last_post
duration = based_on_last_post ? self.category.auto_close_hours : nil
self.set_or_create_timer(
TopicTimer.types[:close],
self.category.auto_close_hours,
by_user: Discourse.system_user,
based_on_last_post: based_on_last_post,
duration: duration
)
end
end
def advance_draft_sequence
if self.private_message?
DraftSequence.next!(user, Draft::NEW_PRIVATE_MESSAGE)
else
DraftSequence.next!(user, Draft::NEW_TOPIC)
end
end
def ensure_topic_has_a_category
if category_id.nil? && (archetype.nil? || self.regular?)
self.category_id = category&.id || SiteSetting.uncategorized_category_id
end
end
def self.visible_post_types(viewed_by = nil)
types = Post.types
result = [types[:regular], types[:moderator_action], types[:small_action]]
result << types[:whisper] if viewed_by&.staff?
result
end
def self.top_viewed(max = 10)
Topic.listable_topics.visible.secured.order('views desc').limit(max)
end
def self.recent(max = 10)
Topic.listable_topics.visible.secured.order('created_at desc').limit(max)
end
def self.count_exceeds_minimum?
count > SiteSetting.minimum_topics_similar
end
def best_post
posts.where(post_type: Post.types[:regular], user_deleted: false).order('score desc nulls last').limit(1).first
end
def has_flags?
ReviewableFlaggedPost.pending.default_visible.where(topic_id: id).exists?
end
def is_official_warning?
subtype == TopicSubtype.moderator_warning
end
# all users (in groups or directly targetted) that are going to get the pm
def all_allowed_users
moderators_sql = " UNION #{User.moderators.to_sql}" if private_message? && (has_flags? || is_official_warning?)
User.from("(#{allowed_users.to_sql} UNION #{allowed_group_users.to_sql}#{moderators_sql}) as users")
end
# Additional rate limits on topics: per day and private messages per day
def limit_topics_per_day
if user && user.new_user_posting_on_first_day?
limit_first_day_topics_per_day
else
apply_per_day_rate_limit_for("topics", :max_topics_per_day)
end
end
def limit_private_messages_per_day
return unless private_message?
apply_per_day_rate_limit_for("pms", :max_personal_messages_per_day)
end
def self.fancy_title(title)
return unless escaped = ERB::Util.html_escape(title)
fancy_title = Emoji.unicode_unescape(HtmlPrettify.render(escaped))
fancy_title.length > Topic.max_fancy_title_length ? escaped : fancy_title
end
def fancy_title
return ERB::Util.html_escape(title) unless SiteSetting.title_fancy_entities?
unless fancy_title = read_attribute(:fancy_title)
fancy_title = Topic.fancy_title(title)
write_attribute(:fancy_title, fancy_title)
if !new_record? && !Discourse.readonly_mode?
# make sure data is set in table, this also allows us to change algorithm
# by simply nulling this column
DB.exec("UPDATE topics SET fancy_title = :fancy_title where id = :id", id: self.id, fancy_title: fancy_title)
end
end
fancy_title
end
# Returns hot topics since a date for display in email digest.
def self.for_digest(user, since, opts = nil)
opts = opts || {}
score = "#{ListController.best_period_for(since)}_score"
topics = Topic
.visible
.secured(Guardian.new(user))
.joins("LEFT OUTER JOIN topic_users ON topic_users.topic_id = topics.id AND topic_users.user_id = #{user.id.to_i}")
.joins("LEFT OUTER JOIN category_users ON category_users.category_id = topics.category_id AND category_users.user_id = #{user.id.to_i}")
.joins("LEFT OUTER JOIN users ON users.id = topics.user_id")
.where(closed: false, archived: false)
.where("COALESCE(topic_users.notification_level, 1) <> ?", TopicUser.notification_levels[:muted])
.created_since(since)
.where('topics.created_at < ?', (SiteSetting.editing_grace_period || 0).seconds.ago)
.listable_topics
.includes(:category)
unless opts[:include_tl0] || user.user_option.try(:include_tl0_in_digests)
topics = topics.where("COALESCE(users.trust_level, 0) > 0")
end
if !!opts[:top_order]
topics = topics.joins("LEFT OUTER JOIN top_topics ON top_topics.topic_id = topics.id")
.order(TopicQuerySQL.order_top_with_notification_levels(score))
end
if opts[:limit]
topics = topics.limit(opts[:limit])
end
# Remove category topics
category_topic_ids = Category.pluck(:topic_id).compact!
if category_topic_ids.present?
topics = topics.where("topics.id NOT IN (?)", category_topic_ids)
end
# Remove muted and shared draft categories
remove_category_ids = CategoryUser.where(user_id: user.id, notification_level: CategoryUser.notification_levels[:muted]).pluck(:category_id)
if SiteSetting.digest_suppress_categories.present?
remove_category_ids += SiteSetting.digest_suppress_categories.split("|").map(&:to_i)
end
if SiteSetting.shared_drafts_enabled?
remove_category_ids << SiteSetting.shared_drafts_category
end
if remove_category_ids.present?
remove_category_ids.uniq!
topics = topics.where("topics.category_id NOT IN (?)", remove_category_ids)
end
# Remove muted tags
muted_tag_ids = TagUser.lookup(user, :muted).pluck(:tag_id)
unless muted_tag_ids.empty?
# If multiple tags per topic, include topics with tags that aren't muted,
# and don't forget untagged topics.
topics = topics.where(
"EXISTS ( SELECT 1 FROM topic_tags WHERE topic_tags.topic_id = topics.id AND tag_id NOT IN (?) )
OR NOT EXISTS (SELECT 1 FROM topic_tags WHERE topic_tags.topic_id = topics.id)", muted_tag_ids)
end
topics
end
def meta_data=(data)
custom_fields.replace(data)
end
def meta_data
custom_fields
end
def update_meta_data(data)
custom_fields.update(data)
save
end
def reload(options = nil)
@post_numbers = nil
@public_topic_timer = nil
@is_category_topic = nil
super(options)
end
def post_numbers
@post_numbers ||= posts.order(:post_number).pluck(:post_number)
end
def age_in_minutes
((Time.zone.now - created_at) / 1.minute).round
end
def self.listable_count_per_day(start_date, end_date, category_id = nil, include_subcategories = false)
result = listable_topics.where("topics.created_at >= ? AND topics.created_at <= ?", start_date, end_date)
result = result.group('date(topics.created_at)').order('date(topics.created_at)')
result = result.where(category_id: include_subcategories ? Category.subcategory_ids(category_id) : category_id) if category_id
result.count
end
def private_message?
archetype == Archetype.private_message
end
def regular?
self.archetype == Archetype.default
end
MAX_SIMILAR_BODY_LENGTH ||= 200
def self.similar_to(title, raw, user = nil)
return [] if title.blank?
raw = raw.presence || ""
tsquery = Search.set_tsquery_weight_filter(
Search.prepare_data(title.strip),
'A'
)
if raw.present?
cooked = SearchIndexer::HtmlScrubber.scrub(
PrettyText.cook(raw[0...MAX_SIMILAR_BODY_LENGTH].strip)
)
prepared_data = cooked.present? && Search.prepare_data(cooked)
if prepared_data.present?
raw_tsquery = Search.set_tsquery_weight_filter(
prepared_data,
'B'
)
tsquery = "#{tsquery} & #{raw_tsquery}"
end
end
tsquery = Search.to_tsquery(term: tsquery, joiner: "|")
candidates = Topic
.visible
.listable_topics
.secured(Guardian.new(user))
.joins("JOIN topic_search_data s ON topics.id = s.topic_id")
.joins("LEFT JOIN categories c ON topics.id = c.topic_id")
.where("search_data @@ #{tsquery}")
.where("c.topic_id IS NULL")
.order("ts_rank(search_data, #{tsquery}) DESC")
.limit(SiteSetting.max_similar_results * 3)
candidate_ids = candidates.pluck(:id)
return [] if candidate_ids.blank?
similars = Topic
.joins("JOIN posts AS p ON p.topic_id = topics.id AND p.post_number = 1")
.where("topics.id IN (?)", candidate_ids)
.order("similarity DESC")
.limit(SiteSetting.max_similar_results)
if raw.present?
similars
.select(sanitize_sql_array(["topics.*, similarity(topics.title, :title) + similarity(p.raw, :raw) AS similarity, p.cooked AS blurb", title: title, raw: raw]))
.where("similarity(topics.title, :title) + similarity(p.raw, :raw) > 0.2", title: title, raw: raw)
else
similars
.select(sanitize_sql_array(["topics.*, similarity(topics.title, :title) AS similarity, p.cooked AS blurb", title: title]))
.where("similarity(topics.title, :title) > 0.2", title: title)
end
end
def update_status(status, enabled, user, opts = {})
TopicStatusUpdater.new(self, user).update!(status, enabled, opts)
DiscourseEvent.trigger(:topic_status_updated, self, status, enabled)
if status == 'closed'
StaffActionLogger.new(user).log_topic_closed(self, closed: enabled)
elsif status == 'archived'
StaffActionLogger.new(user).log_topic_archived(self, archived: enabled)
end
if enabled && private_message? && status.to_s["closed"]
group_ids = user.groups.pluck(:id)
if group_ids.present?
allowed_group_ids = self.allowed_groups
.where('topic_allowed_groups.group_id IN (?)', group_ids).pluck(:id)
allowed_group_ids.each do |id|
GroupArchivedMessage.archive!(id, self)
end
end
end
end
# Atomically creates the next post number
def self.next_post_number(topic_id, opts = {})
highest = DB.query_single("SELECT coalesce(max(post_number),0) AS max FROM posts WHERE topic_id = ?", topic_id).first.to_i
if opts[:whisper]
result = DB.query_single(<<~SQL, highest, topic_id)
UPDATE topics
SET highest_staff_post_number = ? + 1
WHERE id = ?
RETURNING highest_staff_post_number
SQL
result.first.to_i
else
reply_sql = opts[:reply] ? ", reply_count = reply_count + 1" : ""
posts_sql = opts[:post] ? ", posts_count = posts_count + 1" : ""
result = DB.query_single(<<~SQL, highest: highest, topic_id: topic_id)
UPDATE topics
SET highest_staff_post_number = :highest + 1,
highest_post_number = :highest + 1
#{reply_sql}
#{posts_sql}
WHERE id = :topic_id
RETURNING highest_post_number
SQL
result.first.to_i
end
end
def self.reset_all_highest!
DB.exec <<~SQL
WITH
X as (
SELECT topic_id,
COALESCE(MAX(post_number), 0) highest_post_number
FROM posts
WHERE deleted_at IS NULL
GROUP BY topic_id
),
Y as (
SELECT topic_id,
coalesce(MAX(post_number), 0) highest_post_number,
count(*) posts_count,
max(created_at) last_posted_at
FROM posts
WHERE deleted_at IS NULL AND post_type <> 4
GROUP BY topic_id
)
UPDATE topics
SET
highest_staff_post_number = X.highest_post_number,
highest_post_number = Y.highest_post_number,
last_posted_at = Y.last_posted_at,
posts_count = Y.posts_count
FROM X, Y
WHERE
topics.archetype <> 'private_message' AND
X.topic_id = topics.id AND
Y.topic_id = topics.id AND (
topics.highest_staff_post_number <> X.highest_post_number OR
topics.highest_post_number <> Y.highest_post_number OR
topics.last_posted_at <> Y.last_posted_at OR
topics.posts_count <> Y.posts_count
)
SQL
DB.exec <<~SQL
WITH
X as (
SELECT topic_id,
COALESCE(MAX(post_number), 0) highest_post_number
FROM posts
WHERE deleted_at IS NULL
GROUP BY topic_id
),
Y as (
SELECT topic_id,
coalesce(MAX(post_number), 0) highest_post_number,
count(*) posts_count,
max(created_at) last_posted_at
FROM posts
WHERE deleted_at IS NULL AND post_type <> 3 AND post_type <> 4
GROUP BY topic_id
)
UPDATE topics
SET
highest_staff_post_number = X.highest_post_number,
highest_post_number = Y.highest_post_number,
last_posted_at = Y.last_posted_at,
posts_count = Y.posts_count
FROM X, Y
WHERE
topics.archetype = 'private_message' AND
X.topic_id = topics.id AND
Y.topic_id = topics.id AND (
topics.highest_staff_post_number <> X.highest_post_number OR
topics.highest_post_number <> Y.highest_post_number OR
topics.last_posted_at <> Y.last_posted_at OR
topics.posts_count <> Y.posts_count
)
SQL
end
# If a post is deleted we have to update our highest post counters
def self.reset_highest(topic_id)
archetype = Topic.where(id: topic_id).pluck_first(:archetype)
# ignore small_action replies for private messages
post_type = archetype == Archetype.private_message ? " AND post_type <> #{Post.types[:small_action]}" : ''
result = DB.query_single(<<~SQL, topic_id: topic_id)
UPDATE topics
SET
highest_staff_post_number = (
SELECT COALESCE(MAX(post_number), 0) FROM posts
WHERE topic_id = :topic_id AND
deleted_at IS NULL
),
highest_post_number = (
SELECT COALESCE(MAX(post_number), 0) FROM posts
WHERE topic_id = :topic_id AND
deleted_at IS NULL AND
post_type <> 4
#{post_type}
),
posts_count = (
SELECT count(*) FROM posts
WHERE deleted_at IS NULL AND
topic_id = :topic_id AND
post_type <> 4
#{post_type}
),
last_posted_at = (
SELECT MAX(created_at) FROM posts
WHERE topic_id = :topic_id AND
deleted_at IS NULL AND
post_type <> 4
#{post_type}
)
WHERE id = :topic_id
RETURNING highest_post_number
SQL
highest_post_number = result.first.to_i
# Update the forum topic user records
DB.exec(<<~SQL, highest: highest_post_number, topic_id: topic_id)
UPDATE topic_users
SET last_read_post_number = CASE
WHEN last_read_post_number > :highest THEN :highest
ELSE last_read_post_number
END,
highest_seen_post_number = CASE
WHEN highest_seen_post_number > :highest THEN :highest
ELSE highest_seen_post_number
END
WHERE topic_id = :topic_id
SQL
end
cattr_accessor :update_featured_topics
def changed_to_category(new_category)
return true if new_category.blank? || Category.exists?(topic_id: id)
return false if new_category.id == SiteSetting.uncategorized_category_id && !SiteSetting.allow_uncategorized_topics
Topic.transaction do
old_category = category
if self.category_id != new_category.id
self.update_attribute(:category_id, new_category.id)
if old_category
Category
.where(id: old_category.id)
.update_all("topic_count = topic_count - 1")
end
# when a topic changes category we may have to start watching it
# if we happen to have read state for it
CategoryUser.auto_watch(category_id: new_category.id, topic_id: self.id)
CategoryUser.auto_track(category_id: new_category.id, topic_id: self.id)
if post = self.ordered_posts.first
notified_user_ids = [post.user_id, post.last_editor_id].uniq
DB.after_commit do
Jobs.enqueue(:notify_category_change, post_id: post.id, notified_user_ids: notified_user_ids)
end
end
end
Category.where(id: new_category.id).update_all("topic_count = topic_count + 1")
if Topic.update_featured_topics != false
CategoryFeaturedTopic.feature_topics_for(old_category) unless @import_mode
CategoryFeaturedTopic.feature_topics_for(new_category) unless @import_mode || old_category.try(:id) == new_category.id
end
# when a topic changes category we may need to make uploads
# linked to posts secure/not secure depending on whether the
# category is private
DB.after_commit do
Jobs.enqueue(:update_topic_upload_security, topic_id: self.id)
end
end
true
end
def add_small_action(user, action_code, who = nil, opts = {})
custom_fields = {}
custom_fields["action_code_who"] = who if who.present?
opts = opts.merge(
post_type: Post.types[:small_action],
action_code: action_code,
custom_fields: custom_fields
)
add_moderator_post(user, nil, opts)
end
def add_moderator_post(user, text, opts = nil)
opts ||= {}
new_post = nil
creator = PostCreator.new(user,
raw: text,
post_type: opts[:post_type] || Post.types[:moderator_action],
action_code: opts[:action_code],
no_bump: opts[:bump].blank?,
topic_id: self.id,
skip_validations: true,
custom_fields: opts[:custom_fields],
import_mode: opts[:import_mode])
if (new_post = creator.create) && new_post.present?
increment!(:moderator_posts_count) if new_post.persisted?
# If we are moving posts, we want to insert the moderator post where the previous posts were
# in the stream, not at the end.
new_post.update!(post_number: opts[:post_number], sort_order: opts[:post_number]) if opts[:post_number].present?
# Grab any links that are present
TopicLink.extract_from(new_post)
QuotedPost.extract_from(new_post)
end
new_post
end
def change_category_to_id(category_id)
return false if private_message?
new_category_id = category_id.to_i
# if the category name is blank, reset the attribute
new_category_id = SiteSetting.uncategorized_category_id if new_category_id == 0
return true if self.category_id == new_category_id
cat = Category.find_by(id: new_category_id)
return false unless cat
reviewables.update_all(category_id: new_category_id)
changed_to_category(cat)
end
def remove_allowed_group(removed_by, name)
if group = Group.find_by(name: name)
group_user = topic_allowed_groups.find_by(group_id: group.id)
if group_user
group_user.destroy
add_small_action(removed_by, "removed_group", group.name)
return true
end
end
false
end
def remove_allowed_user(removed_by, username)
user = username.is_a?(User) ? username : User.find_by(username: username)
if user
topic_user = topic_allowed_users.find_by(user_id: user.id)
if topic_user
topic_user.destroy
if user.id == removed_by&.id
removed_by = Discourse.system_user
add_small_action(removed_by, "user_left", user.username)
else
add_small_action(removed_by, "removed_user", user.username)
end
return true
end
end
false
end
def reached_recipients_limit?
return false unless private_message?
topic_allowed_users.count + topic_allowed_groups.count >= SiteSetting.max_allowed_message_recipients
end
def invite_group(user, group)
TopicAllowedGroup.create!(topic_id: id, group_id: group.id)
last_post = posts.order('post_number desc').where('not hidden AND posts.deleted_at IS NULL').first
if last_post
Jobs.enqueue(:post_alert, post_id: last_post.id)
add_small_action(user, "invited_group", group.name)
group_id = group.id
group.set_message_default_notification_levels!(self, ignore_existing: true)
group.users.where(
"group_users.notification_level = :level",
level: NotificationLevels.all[:tracking],
id: user.id
).find_each do |u|
PostAlerter.new.notify_group_summary(u, last_post)
end
group.users.where(