A platform for community discussion. Free, open, simple.
FIX: Scope duplicate topic title check to what the user can see (#41871)
Régis Hanol3e012af58e14
diff --git a/app/models/duplicate_topic_titles_site_setting.rb b/app/models/duplicate_topic_titles_site_setting.rbnew file mode 100644index 00000000000..911295d6c41--- /dev/null+++ b/app/models/duplicate_topic_titles_site_setting.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++class DuplicateTopicTitlesSiteSetting < EnumSiteSetting+ DISALLOWED = "disallowed"+ ALLOWED_ACROSS_CATEGORIES = "allowed_across_categories"+ ALLOWED = "allowed"++ def self.valid_value?(val)+ values.any? { |v| v[:value] == val }+ end++ def self.values+ @values ||= [+ { name: "admin.duplicate_topic_titles.disallowed", value: DISALLOWED },+ {+ name: "admin.duplicate_topic_titles.allowed_across_categories",+ value: ALLOWED_ACROSS_CATEGORIES,+ },+ { name: "admin.duplicate_topic_titles.allowed", value: ALLOWED },+ ]+ end++ def self.translate_names?+ true+ end++ wrap_values!+enddiff --git a/app/models/post_mover.rb b/app/models/post_mover.rbindex f2977530267..ce242620526 100644--- a/app/models/post_mover.rb+++ b/app/models/post_mover.rb@@ -51,6 +51,7 @@ class PostMovernew_topic =Topic.create!(user: post.user,+ acting_user: user,title: title,category_id: category_id,created_at: post.created_at,diff --git a/app/models/topic.rb b/app/models/topic.rbindex 30ebb2981bf..604172e118d 100644--- a/app/models/topic.rb+++ b/app/models/topic.rb@@ -196,18 +196,10 @@ class Topic < ActiveRecord::Basemax_emojis: true,unique_among: {unless:- Proc.new { |t| SiteSetting.allow_duplicate_topic_titles? || t.private_message? },- message: :has_already_been_used,+ Proc.new { |t| SiteSetting.duplicate_topic_titles.allowed? || t.private_message? },+ message: :topic_title_already_used,allow_blank: true,- case_sensitive: false,- collection:- Proc.new { |t|- if SiteSetting.allow_duplicate_topic_titles_category?- Topic.listable_topics.where("category_id = ?", t.category_id)- else- Topic.listable_topics- end- },+ collection: ->(t) { t.duplicate_title_candidates },}validates :category_id,@@ -1808,6 +1800,19 @@ class Topic < ActiveRecord::Base@acting_user = uend+ def duplicate_title_candidates+ candidates = Topic.listable_topics.where(category_id:)++ if SiteSetting.duplicate_topic_titles.disallowed?+ guardian = acting_user&.guardian+ visible_topics = Topic.listable_topics.secured(guardian)+ visible_topics = visible_topics.visible if !guardian&.can_see_unlisted_topics?+ candidates = candidates.or(visible_topics)+ end++ candidates+ end+def secure_group_ids@secure_group_ids ||= (category.secure_group_ids if category && category.read_restricted?)enddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex ed35873b527..89c6288002b 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -8201,6 +8201,11 @@ en:homepage:top_menu_default: "First item in top menu"+ duplicate_topic_titles:+ disallowed: "Disallowed"+ allowed_across_categories: "Allowed across categories"+ allowed: "Allowed"+backups:title: "Backups"files_title: "Backup files"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 39d5a97894a..3dc4af13ae1 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -311,7 +311,7 @@ en:exclusion: is reservedgreater_than: must be greater than %{count}greater_than_or_equal_to: must be greater than or equal to %{count}- has_already_been_used: "has already been used"+ topic_title_already_used: "This title has already been used by <a href='%{url}'>another topic</a>."in: must be in %{count}inclusion: is not included in the listinvalid: is invalid@@ -1916,6 +1916,7 @@ en:default_composer_category: "The category used to pre-populate the category dropdown when creating a new topic."allow_uncategorized_topics: "Allow topics to be created without a category. WARNING: If there are any uncategorized topics, you must recategorize them before turning this off."remove_and_replace_uncategorized: "Replaces the special Uncategorized category with a standard category of the same name, and migrates all topics over to it."+ duplicate_topic_titles: "Whether a topic can be created with a title already used by another topic. When allowed across categories, a title can be reused as long as the topics are in different categories. Topics the author cannot see are never counted as duplicates."allow_duplicate_topic_titles: "Allow topics with identical, duplicate titles."allow_duplicate_topic_titles_category: "Allow topics with identical, duplicate titles if the category is different. {{setting:allow_duplicate_topic_titles}} must be disabled."unique_posts_mins: "How many minutes before a user can make a post with the same content again"diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 7990c03ec86..367256d8068 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -1421,12 +1421,17 @@ posting:- allow_uncategorized_topics- suppress_uncategorized_badgelearn_more_url: "https://meta.discourse.org/t/-/406373"+ duplicate_topic_titles:+ default: "disallowed"+ type: enum+ enum: "DuplicateTopicTitlesSiteSetting"+ area: "posts_and_topics"allow_duplicate_topic_titles:default: false- area: "posts_and_topics"+ hidden: trueallow_duplicate_topic_titles_category:default: false- area: "posts_and_topics"+ hidden: truemin_title_similar_length:client: truedefault: 10diff --git a/db/migrate/20260721110018_migrate_duplicate_topic_titles_settings.rb b/db/migrate/20260721110018_migrate_duplicate_topic_titles_settings.rbnew file mode 100644index 00000000000..80a35d0d4da--- /dev/null+++ b/db/migrate/20260721110018_migrate_duplicate_topic_titles_settings.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++class MigrateDuplicateTopicTitlesSettings < ActiveRecord::Migration[8.0]+ def up+ allow_all =+ DB.query_single(+ "SELECT value FROM site_settings WHERE name = 'allow_duplicate_topic_titles'",+ ).first+ allow_across =+ DB.query_single(+ "SELECT value FROM site_settings WHERE name = 'allow_duplicate_topic_titles_category'",+ ).first++ new_value =+ if allow_all == "t"+ "allowed"+ elsif allow_across == "t"+ "allowed_across_categories"+ end++ DB.exec(<<~SQL, value: new_value) if new_value+ INSERT INTO site_settings (name, data_type, value, created_at, updated_at)+ VALUES ('duplicate_topic_titles', 7, :value, NOW(), NOW())+ ON CONFLICT DO NOTHING+ SQL+ end++ def down+ execute "DELETE FROM site_settings WHERE name = 'duplicate_topic_titles'"+ end+enddiff --git a/db/structure.sql b/db/structure.sqlindex c0514886d9e..7551652d219 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -22885,6 +22885,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260722140539'),('20260722140536'),('20260721122254'),+('20260721110018'),('20260721080424'),('20260721080420'),('20260721043536'),diff --git a/lib/enum_site_setting.rb b/lib/enum_site_setting.rbindex 51ce16d9e93..b8fba0fc16c 100644--- a/lib/enum_site_setting.rb+++ b/lib/enum_site_setting.rb@@ -4,4 +4,16 @@ class EnumSiteSettingdef self.translate_names?falseend++ def self.wrap_values!+ value_class = Class.new(String)++ values.each do |entry|+ value = entry[:value].to_s+ value_class.define_method("#{value}?") { self == value }+ end++ const_set(:Value, value_class)+ define_singleton_method(:wrap) { |value| self::Value.new(value) }+ endenddiff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rbindex 5363174a9f9..d49827a4a3f 100644--- a/lib/site_setting_extension.rb+++ b/lib/site_setting_extension.rb@@ -268,10 +268,10 @@ module SiteSettingExtension@deprecated_settings ||= SiteSettings::DeprecatedSettings::SETTINGS.map(&:first).to_setend- def deprecated_setting_alias(setting_name)+ def deprecated_setting_aliases(setting_name)SiteSettings::DeprecatedSettings::SETTINGS- .find { |setting| setting.second.to_s == setting_name.to_s }- &.first+ .select { |setting| setting.second.to_s == setting_name.to_s }+ .map(&:first)enddef theme_site_settings_json(theme_id)@@ -1133,6 +1133,12 @@ module SiteSettingExtensionendendelse+ enum_wrapper =+ if type_supervisor.get_type(name) == :enum+ klass = type_supervisor.get_enum_class(name)+ klass if klass.respond_to?(:wrap)+ end+define_singleton_method clean_name do |scoped_to = nil|if themeable[clean_name]if scoped_to.nil? || !scoped_to.key?(:theme_id) || scoped_to[:theme_id].nil?@@ -1145,7 +1151,8 @@ module SiteSettingExtension# then we will just fall back further down bellow to the current site setting value.settings_overridden_for_theme = theme_site_settings[scoped_to[:theme_id]]if settings_overridden_for_theme && settings_overridden_for_theme.key?(clean_name)- return settings_overridden_for_theme[clean_name]+ value = settings_overridden_for_theme[clean_name]+ return enum_wrapper ? enum_wrapper.wrap(value.to_s) : valueendend@@ -1170,6 +1177,8 @@ module SiteSettingExtensionreturn (mandatory_values[name].split("|") | value.to_s.split("|")).join("|")end+ return enum_wrapper.wrap(value.to_s) if enum_wrapper+valueendenddiff --git a/lib/site_settings/deprecated_settings.rb b/lib/site_settings/deprecated_settings.rbindex 3b71a606c72..997fb752b0f 100644--- a/lib/site_settings/deprecated_settings.rb+++ b/lib/site_settings/deprecated_settings.rb@@ -9,6 +9,8 @@ module SiteSettings::DeprecatedSettings["min_first_post_typing_time", "fast_typing_threshold", false, "3.4"],["twitter_summary_large_image", "x_summary_large_image", false, "3.4"],["external_system_avatars_enabled", "external_system_avatars_url", false, "3.5"],+ ["allow_duplicate_topic_titles", "duplicate_topic_titles", false, "2027.1"],+ ["allow_duplicate_topic_titles_category", "duplicate_topic_titles", false, "2027.1"],]def setup_deprecated_methodsdiff --git a/lib/site_settings/label_formatter.rb b/lib/site_settings/label_formatter.rbindex 8ede3ce465f..a781f52b141 100644--- a/lib/site_settings/label_formatter.rb+++ b/lib/site_settings/label_formatter.rb@@ -270,7 +270,7 @@ module SiteSettingsif translated_keywords.is_a?(Array)return((- translated_keywords + [SiteSetting.deprecated_setting_alias(setting)] ++ translated_keywords + SiteSetting.deprecated_setting_aliases(setting) +english_translated_keywords).compact)@@ -278,7 +278,7 @@ module SiteSettingstranslated_keywords.split("|")- .concat([SiteSetting.deprecated_setting_alias(setting)] + english_translated_keywords)+ .concat(SiteSetting.deprecated_setting_aliases(setting) + english_translated_keywords).compactenddiff --git a/lib/validators/unique_among_validator.rb b/lib/validators/unique_among_validator.rbindex 99e79d1d4a4..0043f4e3550 100644--- a/lib/validators/unique_among_validator.rb+++ b/lib/validators/unique_among_validator.rb@@ -1,27 +1,18 @@# frozen_string_literal: true-class UniqueAmongValidator < ActiveRecord::Validations::UniquenessValidator+class UniqueAmongValidator < ActiveModel::EachValidatordef validate_each(record, attribute, value)- old_errors = []- record.errors.each { |error| old_errors << error if error.attribute == attribute }+ return if !duplicates(record.class, record, attribute, value).exists?- # look for any duplicates at all- super-- new_errors = []- record.errors.each { |error| new_errors << error if error.attribute == attribute }+ dupe = duplicates(options[:collection].call(record), record, attribute, value).first+ record.errors.add(:base, options[:message], url: dupe.url) if dupe+ end- # do nothing further unless there were some duplicates.- if new_errors.size - old_errors.size != 0- # now look only in the collection we care about.- dupes = options[:collection].call(record).where("lower(#{attribute}) = ?", value.downcase)- dupes = dupes.where.not(id: record.id) if record.persisted?+ private- # pop off the error, if it was a false positive- if !dupes.exists?- record.errors.delete(attribute)- old_errors.each { |error| record.errors.add(error.attribute, error.type, **error.options) }- end- end+ def duplicates(scope, record, attribute, value)+ scope = scope.where("lower(#{attribute}) = ?", value.downcase)+ scope = scope.where.not(id: record.id) if record.persisted?+ scopeendenddiff --git a/plugins/automation/spec/scripts/topic_spec.rb b/plugins/automation/spec/scripts/topic_spec.rbindex 136df680aed..fe3f1d65726 100644--- a/plugins/automation/spec/scripts/topic_spec.rb+++ b/plugins/automation/spec/scripts/topic_spec.rb@@ -181,7 +181,7 @@ describe "Topic" doTopic.count}- expect(Rails.logger.errors.first).to match(/Title has already been used/)+ expect(Rails.logger.errors.first).to match(/This title has already been used/)endendenddiff --git a/plugins/discourse-templates/lib/tasks/discourse-templates.rake b/plugins/discourse-templates/lib/tasks/discourse-templates.rakeindex 755cc65aa84..ef406d203d4 100644--- a/plugins/discourse-templates/lib/tasks/discourse-templates.rake+++ b/plugins/discourse-templates/lib/tasks/discourse-templates.rake@@ -136,9 +136,9 @@ def migrate_data# duplicate topic titles must be temporarily enabled to ensure that all# canned replies can be imported since there is no guarantee that a previous# topic does not exist with the same title- allow_duplicate_topic_titles = SiteSetting.allow_duplicate_topic_titles+ duplicate_topic_titles = SiteSetting.duplicate_topic_titles- SiteSetting.allow_duplicate_topic_titles = true+ SiteSetting.duplicate_topic_titles = "allowed"(replies_v1 || {}).each_with_index do |(_, reply), index|position = index + 1@@ -157,7 +157,7 @@ def migrate_dataend# restores the setting to the previous value after importing the topics- SiteSetting.allow_duplicate_topic_titles = allow_duplicate_topic_titles+ SiteSetting.duplicate_topic_titles = duplicate_topic_titlesendputs "", "Canned replies migration to templates finished!"rescue StandardError => ediff --git a/script/import_scripts/base.rb b/script/import_scripts/base.rbindex 7656168cd24..d19465c38a1 100644--- a/script/import_scripts/base.rb+++ b/script/import_scripts/base.rb@@ -75,8 +75,7 @@ class ImportScripts::Basemin_first_post_length: 1,min_personal_message_post_length: 1,min_personal_message_title_length: 1,- allow_duplicate_topic_titles: true,- allow_duplicate_topic_titles_category: false,+ duplicate_topic_titles: "allowed",disable_emails: "yes",max_attachment_size_kb: 102_400,max_image_size_kb: 102_400,diff --git a/spec/lib/site_setting_extension_spec.rb b/spec/lib/site_setting_extension_spec.rbindex 644ca37e206..319ddbaf2a9 100644--- a/spec/lib/site_setting_extension_spec.rb+++ b/spec/lib/site_setting_extension_spec.rb@@ -1897,7 +1897,7 @@ RSpec.describe SiteSettingExtension doendcontext "when a setting also has an alias after renaming" do- before { SiteSetting.stubs(:deprecated_setting_alias).returns("some_old_setting") }+ before { SiteSetting.stubs(:deprecated_setting_aliases).returns(["some_old_setting"]) }it "is included with the keywords" doexpect(SiteSetting.keywords(:clean_up_inactive_users_after_days)).to include(diff --git a/spec/lib/topic_creator_spec.rb b/spec/lib/topic_creator_spec.rbindex 2a3e3cfded9..06df9dc61b9 100644--- a/spec/lib/topic_creator_spec.rb+++ b/spec/lib/topic_creator_spec.rb@@ -29,7 +29,7 @@ RSpec.describe TopicCreator dobefore doTopicCreator.any_instance.expects(:save_topic).returns(true)TopicCreator.any_instance.expects(:apply_pm_recipient_notification_levels).returns(true)- SiteSetting.allow_duplicate_topic_titles = true+ SiteSetting.duplicate_topic_titles = "allowed"endit "should be possible for an admin to create a topic" do@@ -551,7 +551,7 @@ RSpec.describe TopicCreator dobefore doTopicCreator.any_instance.expects(:save_topic).returns(true)TopicCreator.any_instance.expects(:apply_pm_recipient_notification_levels).returns(true)- SiteSetting.allow_duplicate_topic_titles = true+ SiteSetting.duplicate_topic_titles = "allowed"SiteSetting.enable_staged_users = trueenddiff --git a/spec/models/duplicate_topic_titles_site_setting_spec.rb b/spec/models/duplicate_topic_titles_site_setting_spec.rbnew file mode 100644index 00000000000..7f67b21d615--- /dev/null+++ b/spec/models/duplicate_topic_titles_site_setting_spec.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++RSpec.describe DuplicateTopicTitlesSiteSetting do+ it "exposes predicates on the setting value" do+ SiteSetting.duplicate_topic_titles = "allowed_across_categories"+ expect(SiteSetting.duplicate_topic_titles.allowed_across_categories?).to eq(true)+ expect(SiteSetting.duplicate_topic_titles.allowed?).to eq(false)+ expect(SiteSetting.duplicate_topic_titles.disallowed?).to eq(false)+ expect(SiteSetting.duplicate_topic_titles).to eq("allowed_across_categories")+ end++ it "wraps the default value" do+ expect(SiteSetting.duplicate_topic_titles.disallowed?).to eq(true)+ end+enddiff --git a/spec/models/post_mover_spec.rb b/spec/models/post_mover_spec.rbindex c8850a5425b..d164418cac7 100644--- a/spec/models/post_mover_spec.rb+++ b/spec/models/post_mover_spec.rb@@ -138,6 +138,15 @@ RSpec.describe PostMover doendcontext "with errors" do+ it "raises when the mover can see a duplicate title the first post's author cannot" do+ SiteSetting.duplicate_topic_titles = "disallowed"+ secure_topic =+ Fabricate(:topic, category: Fabricate(:private_category, group: Fabricate(:group)))+ expect { topic.move_posts(user, [p2.id], title: secure_topic.title) }.to raise_error(+ ActiveRecord::RecordInvalid,+ )+ end+it "raises an error when one of the posts doesn't exist" donon_existent_post_id = Post.maximum(:id)&.next || 1expect {diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rbindex e5bca79e540..2825edb35d5 100644--- a/spec/models/topic_spec.rb+++ b/spec/models/topic_spec.rb@@ -405,11 +405,10 @@ RSpec.describe Topic doFabricate.build(:topic, title: topic.title, category: category2)end- context "when duplicates aren't allowed" do- before do- SiteSetting.allow_duplicate_topic_titles = false- SiteSetting.allow_duplicate_topic_titles_category = false- end+ context "when duplicate_topic_titles is disallowed" do+ fab!(:admin)++ before { SiteSetting.duplicate_topic_titles = "disallowed" }it "won't allow another topic to be created with the same name" doexpect(new_topic).not_to be_valid@@ -433,24 +432,94 @@ RSpec.describe Topic donew_topic.archetype = Archetype.private_messageexpect(new_topic).to be_validend- end- context "when duplicates are allowed" do- before do- SiteSetting.allow_duplicate_topic_titles = true- SiteSetting.allow_duplicate_topic_titles_category = false+ it "includes a link to the topic already using the title in the error" do+ expect(new_topic).not_to be_valid+ expect(new_topic.errors[:base]).to include(+ I18n.t("errors.messages.topic_title_already_used", url: topic.url),+ )+ end++ context "when the duplicate is in a read-restricted category" do+ fab!(:group)+ fab!(:secure_category) { Fabricate(:private_category, group: group) }+ fab!(:secure_topic) { Fabricate(:topic, category: secure_category) }++ it "allows the title when the author can't see the duplicate" do+ attempt = Fabricate.build(:topic, title: secure_topic.title, category: category1)+ expect(attempt).to be_valid+ end++ it "won't allow the title when the author is a member of the restricted group" do+ group_member = Fabricate(:user)+ group.add(group_member)+ attempt =+ Fabricate.build(+ :topic,+ title: secure_topic.title,+ category: category1,+ user: group_member,+ )+ expect(attempt).not_to be_valid+ end++ it "won't allow the title when the author is an admin" do+ attempt =+ Fabricate.build(:topic, title: secure_topic.title, category: category1, user: admin)+ expect(attempt).not_to be_valid+ end++ it "won't allow a topic to be moved into the restricted category holding the duplicate" do+ public_topic = Fabricate(:topic, title: secure_topic.title, category: category1)+ public_topic.category_id = secure_category.id+ expect(public_topic).not_to be_valid+ end++ it "won't allow the title when the acting user can see the duplicate but the author can't" do+ topic.acting_user = admin+ topic.title = secure_topic.title+ expect(topic).not_to be_valid+ end++ it "allows the title when the acting user can't see the duplicate but the author can" do+ staff_topic = Fabricate(:topic, category: category1, user: admin)+ staff_topic.acting_user = Fabricate(:user)+ staff_topic.title = secure_topic.title+ expect(staff_topic).to be_valid+ end+ end++ context "when the duplicate is unlisted" do+ fab!(:unlisted_topic) { Fabricate(:topic, category: category2, visible: false) }++ it "allows the title when the author can't see unlisted topics" do+ attempt = Fabricate.build(:topic, title: unlisted_topic.title, category: category1)+ expect(attempt).to be_valid+ end++ it "won't allow the title when the author can see unlisted topics" do+ attempt =+ Fabricate.build(:topic, title: unlisted_topic.title, category: category1, user: admin)+ expect(attempt).not_to be_valid+ end++ it "won't allow the title in the same category even when the author can't see unlisted topics" do+ attempt = Fabricate.build(:topic, title: unlisted_topic.title, category: category2)+ expect(attempt).not_to be_valid+ endend+ end++ context "when duplicate_topic_titles is allowed" do+ before { SiteSetting.duplicate_topic_titles = "allowed" }it "will allow another topic to be created with the same name" doexpect(new_topic).to be_validendend- context "when duplicates are allowed if the category is different" do- before do- SiteSetting.allow_duplicate_topic_titles = false- SiteSetting.allow_duplicate_topic_titles_category = true- end+ context "when duplicate_topic_titles is allowed_across_categories" do+ before { SiteSetting.duplicate_topic_titles = "allowed_across_categories" }it "will allow another topic to be created with the same name but different category" doexpect(new_topic_different_cat).to be_valid@@ -459,17 +528,6 @@ RSpec.describe Topic doit "won't allow another topic to be created with the same name in same category" doexpect(new_topic).not_to be_validend-- it "other errors will not be cleared" do- SiteSetting.min_topic_title_length = 5- topic.update!(title: "more than 5 characters but less than 134")- SiteSetting.min_topic_title_length = 134- new_topic_different_cat.title = "more than 5 characters but less than 134"- expect(new_topic_different_cat).not_to be_valid- expect(new_topic_different_cat.errors[:title]).to include(- I18n.t("errors.messages.too_short", count: 134),- )- endendenddiff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rbindex bee9bd68680..f74bbe9fc3d 100644--- a/spec/requests/topics_controller_spec.rb+++ b/spec/requests/topics_controller_spec.rb@@ -6408,14 +6408,14 @@ RSpec.describe TopicsController docontext "with some errors" doit "returns the error messages" do- Fabricate(:topic, title: topic.title, category: category)+ existing_topic = Fabricate(:topic, title: topic.title, category: category)sign_in(admin)put "/t/#{topic.id}/convert-topic/public.json?category_id=#{category.id}"expect(response.status).to eq(422)expect(response.parsed_body["errors"][0]).to end_with(- I18n.t("errors.messages.has_already_been_used"),+ I18n.t("errors.messages.topic_title_already_used", url: existing_topic.url),)endend