Skip to content

A platform for community discussion. Free, open, simple.

UX: Link to required settings from language switcher validation error (#38374)

Kris24278059d282
diff --git a/app/controllers/admin/site_settings_controller.rb b/app/controllers/admin/site_settings_controller.rb
index 43bb570b2bd..fad00816d70 100644
--- a/app/controllers/admin/site_settings_controller.rb
+++ b/app/controllers/admin/site_settings_controller.rb
@@ -5,6 +5,10 @@ class Admin::SiteSettingsController < Admin::AdminController
render_json_error e.message, status: 422
end
+ rescue_from Discourse::InvalidHTMLParameters do |e|
+ render_json_error e.html_message, html_message: true, status: 422
+ end
+
def index
params.permit(:categories, :plugin, :names)
render_json_dump(
@@ -43,7 +47,10 @@ class Admin::SiteSettingsController < Admin::AdminController
},
) do
on_success { head :no_content }
- on_exceptions { |e| raise Discourse::InvalidParameters, e }
+ on_exceptions do |e|
+ raise e if e.is_a?(Discourse::InvalidParameters)
+ raise Discourse::InvalidParameters, e.message
+ end
on_failed_policy(:settings_are_not_deprecated) do |policy|
raise Discourse::InvalidParameters, policy.reason
end
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index b38d2eb388c..fc02b68adf0 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -3019,7 +3019,7 @@ en:
invalid_uncategorized_category_setting: 'The "Uncategorized" category cannot be selected if ''allow uncategorized topics'' is not enabled.'
invalid_search_ranking_weights: "Value is invalid for search_ranking_weights site setting. Example: '{0.1,0.2,0.3,1.0}'. Note that maximum value for each weight is 1.0."
content_localization_locale_limit: "The number of supported locales cannot exceed %{max}."
- content_localization_language_switcher_requirements: "The language switcher requires the 'set locale from cookie' and 'allow user locale' site settings to be enabled, and 'content localization supported locales' to have at least one language."
+ content_localization_language_switcher_requirements: "The language switcher requires {{setting:set_locale_from_cookie}} and {{setting:allow_user_locale}} to be enabled, and {{setting:content_localization_supported_locales}} to have at least one language. {{settings:content_localization_language_switcher,set_locale_from_cookie,allow_user_locale,content_localization_supported_locales|All required settings}}"
content_localization_crawler_param_requirements: "You must first enable 'set locale from param' before enabling this setting."
mediaconvert_role_arn_required: "AWS IAM role ARN is required when using AWS MediaConvert for video conversion."
mediaconvert_output_subdirectory_required: "MediaConvert output subdirectory is required."
diff --git a/frontend/discourse/admin/components/site-setting.gjs b/frontend/discourse/admin/components/site-setting.gjs
index fad07dd3d5c..e1684dd3d26 100644
--- a/frontend/discourse/admin/components/site-setting.gjs
+++ b/frontend/discourse/admin/components/site-setting.gjs
@@ -493,7 +493,8 @@ export default class SiteSettingComponent extends Component {
let errorString = json.errors[0];
if (json.html_message) {
- errorString = trustHTML(errorString);
+ errorString = trustHTML(sanitize(errorString));
+ settings.forEach((setting) => setting.buffered.discardChanges());
}
settings.forEach(
diff --git a/frontend/discourse/admin/lib/site-setting-matcher.js b/frontend/discourse/admin/lib/site-setting-matcher.js
index 1f8f0a9034e..c78e4ed0967 100644
--- a/frontend/discourse/admin/lib/site-setting-matcher.js
+++ b/frontend/discourse/admin/lib/site-setting-matcher.js
@@ -3,10 +3,28 @@
// appears as a contiguous block in the stripped name (see isFuzzyNameMatch).
const MIN_FUZZY_NAME_MATCH_STRENGTH = -2;
+const OR_FILTER_PREFIX = "any:";
+
export default class SiteSettingMatcher {
constructor(filter, siteSetting) {
this.filter = filter;
this.siteSetting = siteSetting;
+
+ // `any:one|two` matches settings hitting any of the pipe-separated terms
+ // — the syntax machine-generated "related settings" links use. Without
+ // the prefix, pipes are literal characters, so admins can still search
+ // pipe-delimited list values (e.g. `jpg|png`) exactly.
+ const orTerms = filter.startsWith(OR_FILTER_PREFIX)
+ ? filter
+ .slice(OR_FILTER_PREFIX.length)
+ .split("|")
+ .map((f) => f.trim())
+ .filter(Boolean)
+ : [];
+ this.isOrMode = orTerms.length > 0;
+ this.terms = this.isOrMode ? orTerms : [filter];
+ this.spacedTerms = this.terms.map((term) => term.replace(/_/g, " "));
+
this.strippedQuery = filter.replace(/[^a-z0-9]/gi, "");
this.fuzzyRegex = new RegExp(this.strippedQuery.split("").join(".*"), "i");
this.fuzzyRegexGaps = new RegExp(
@@ -18,34 +36,38 @@ export default class SiteSettingMatcher {
get isNameMatch() {
const name = this.siteSetting.setting.toLowerCase();
+ const spacedName = name.replace(/_/g, " ");
- return (
- name.includes(this.filter) ||
- name.replace(/_/g, " ").includes(this.filter)
+ return this.terms.some(
+ (term) => name.includes(term) || spacedName.includes(term)
);
}
get isKeywordMatch() {
- return (this.siteSetting.keywords || []).some((keyword) =>
- keyword
- .replace(/_/g, " ")
- .toLowerCase()
- .includes(this.filter.replace(/_/g, " "))
- );
+ return (this.siteSetting.keywords || []).some((keyword) => {
+ const spacedKeyword = keyword.replace(/_/g, " ").toLowerCase();
+
+ return this.spacedTerms.some((term) => spacedKeyword.includes(term));
+ });
}
get isDescriptionMatch() {
- return this.siteSetting.description.toLowerCase().includes(this.filter);
+ const desc = this.siteSetting.description.toLowerCase();
+
+ return this.terms.some((term) => desc.includes(term));
}
get isValueMatch() {
- return (this.siteSetting.value || "")
- .toString()
- .toLowerCase()
- .includes(this.filter);
+ const value = (this.siteSetting.value || "").toString().toLowerCase();
+
+ return this.terms.some((term) => value.includes(term));
}
get isFuzzyNameMatch() {
+ if (this.isOrMode) {
+ return false;
+ }
+
const name = this.siteSetting.setting.toLowerCase();
if (this.strippedQuery.length < 3) {
diff --git a/frontend/discourse/tests/integration/components/site-setting-test.gjs b/frontend/discourse/tests/integration/components/site-setting-test.gjs
index 59eafddd8d7..f52e8e9234c 100644
--- a/frontend/discourse/tests/integration/components/site-setting-test.gjs
+++ b/frontend/discourse/tests/integration/components/site-setting-test.gjs
@@ -78,6 +78,32 @@ module("Integration | Component | SiteSetting", function (hooks) {
assert.dom(".validation-error h1").doesNotExist();
});
+ test("error response with html_message discards changes", async function (assert) {
+ this.set(
+ "setting",
+ SiteSetting.create({
+ setting: "test_setting",
+ value: "original",
+ type: "input-setting-string",
+ })
+ );
+
+ pretender.put("/admin/site_settings/test_setting", () => {
+ return response(422, {
+ html_message: true,
+ errors: ["<a href='/somewhere'>Fix this</a>"],
+ });
+ });
+
+ await render(
+ <template><SiteSettingComponent @setting={{this.setting}} /></template>
+ );
+ await fillIn(".setting input", "new value");
+ await click(".setting .d-icon-check");
+
+ assert.dom(".setting input").hasValue("original");
+ });
+
test("displays file types list setting", async function (assert) {
this.set(
"setting",
diff --git a/frontend/discourse/tests/unit/lib/site-setting-matcher-test.js b/frontend/discourse/tests/unit/lib/site-setting-matcher-test.js
index 0cf5089566e..bbe38be1204 100644
--- a/frontend/discourse/tests/unit/lib/site-setting-matcher-test.js
+++ b/frontend/discourse/tests/unit/lib/site-setting-matcher-test.js
@@ -93,4 +93,78 @@ module("Unit | Lib | SiteSettingMatcher", function (hooks) {
"order-only match on a different long token is dropped"
);
});
+
+ module("OR filter (any: prefix)", function () {
+ test("#isNameMatch returns true if any term matches", function (assert) {
+ assert.true(
+ new SiteSettingMatcher("any:short_title|foo", shortTitle).isNameMatch
+ );
+ assert.true(
+ new SiteSettingMatcher("any:foo|short_title", shortTitle).isNameMatch
+ );
+ assert.false(
+ new SiteSettingMatcher("any:foo|bar", shortTitle).isNameMatch
+ );
+ });
+
+ test("#isKeywordMatch returns true if any term matches a keyword", function (assert) {
+ assert.true(
+ new SiteSettingMatcher("any:intro|foo", shortTitle).isKeywordMatch
+ );
+ assert.false(
+ new SiteSettingMatcher("any:foo|bar", shortTitle).isKeywordMatch
+ );
+ });
+
+ test("#isDescriptionMatch returns true if any term matches the description", function (assert) {
+ assert.true(
+ new SiteSettingMatcher("any:launcher|foo", shortTitle)
+ .isDescriptionMatch
+ );
+ assert.false(
+ new SiteSettingMatcher("any:foo|bar", shortTitle).isDescriptionMatch
+ );
+ });
+
+ test("#isValueMatch returns true if any term matches the value", function (assert) {
+ assert.true(
+ new SiteSettingMatcher("any:heckers|foo", shortTitle).isValueMatch
+ );
+ assert.false(
+ new SiteSettingMatcher("any:foo|bar", shortTitle).isValueMatch
+ );
+ });
+
+ test("#isFuzzyNameMatch always returns false in OR mode", function (assert) {
+ assert.false(
+ new SiteSettingMatcher("any:s tle|foo", shortTitle).isFuzzyNameMatch
+ );
+ });
+
+ test("pipes without the any: prefix are literal, so exact list values are searchable", function (assert) {
+ const pipeValue = SiteSetting.create({
+ setting: "some_list",
+ description: "x",
+ value: "jpg|png",
+ });
+ const jpgOnly = SiteSetting.create({
+ setting: "other_list",
+ description: "x",
+ value: "jpg",
+ });
+
+ assert.true(new SiteSettingMatcher("jpg|png", pipeValue).isValueMatch);
+ assert.false(new SiteSettingMatcher("jpg|png", jpgOnly).isValueMatch);
+ assert.true(new SiteSettingMatcher("|", pipeValue).isValueMatch);
+ assert.false(
+ new SiteSettingMatcher("jpg|png", pipeValue).isFuzzyNameMatch
+ );
+ });
+
+ test("a trailing pipe keeps single-term semantics including fuzzy matching", function (assert) {
+ assert.true(
+ new SiteSettingMatcher("s tle|", shortTitle).isFuzzyNameMatch
+ );
+ });
+ });
});
diff --git a/lib/discourse.rb b/lib/discourse.rb
index d7d45346011..f5b19044a3d 100644
--- a/lib/discourse.rb
+++ b/lib/discourse.rb
@@ -261,6 +261,18 @@ module Discourse
class InvalidParameters < StandardError
end
+ # Same as InvalidParameters, but carries an HTML-rendered variant of the
+ # message for surfaces that can render it (e.g. the admin settings UI).
+ # The plain #message stays free of markup so generic rescuers can display it.
+ class InvalidHTMLParameters < InvalidParameters
+ attr_reader :html_message
+
+ def initialize(message = nil, html_message: nil)
+ super(message)
+ @html_message = html_message || message
+ end
+ end
+
# When they don't have permission to do something
class InvalidAccess < StandardError
attr_reader :obj
diff --git a/lib/json_error.rb b/lib/json_error.rb
index d8867684a06..384efe336b2 100644
--- a/lib/json_error.rb
+++ b/lib/json_error.rb
@@ -7,6 +7,7 @@ module JsonError
errors = create_errors_array obj
errors[:error_type] = opts[:type] if opts[:type]
errors[:extras] = opts[:extras] if opts[:extras]
+ errors[:html_message] = true if opts[:html_message]
errors
end
diff --git a/lib/site_settings/label_formatter.rb b/lib/site_settings/label_formatter.rb
index 8ac7dd9350a..8ede3ce465f 100644
--- a/lib/site_settings/label_formatter.rb
+++ b/lib/site_settings/label_formatter.rb
@@ -131,6 +131,8 @@ module SiteSettings
HUMANIZED_MIXED_CASE.map { |key, value| [/\b#{Regexp.escape(key)}\b/i, value] }.freeze
SETTING_LINK_PATTERN = /\{\{setting:([a-z][a-z0-9_]*)\}\}/
+ SETTINGS_LINK_PATTERN =
+ /\{\{settings:([a-z][a-z0-9_]*(?:,[a-z][a-z0-9_]*)*)(?:\|([^{}|]+))?\}\}/
LINK_ATTRIBUTES = %w[
class
@@ -146,6 +148,10 @@ module SiteSettings
expand_setting_links(desc)
end
+ def settings_filter_href(filter)
+ "#{Discourse.base_path}/admin/site_settings/category/all_results?filter=#{CGI.escape(filter)}"
+ end
+
def linkify(setting)
setting = setting.to_sym
@@ -155,8 +161,7 @@ module SiteSettings
# data attributes below so it doesn't have to look the metadata up.
attributes = {
"class" => "site-setting-link",
- "href" =>
- "#{Discourse.base_path}/admin/site_settings/category/all_results?filter=#{CGI.escape(setting.to_s)}",
+ "href" => settings_filter_href(setting.to_s),
"data-setting-name" => setting,
}
@@ -176,9 +181,51 @@ module SiteSettings
%(<a #{attribute_string}>#{CGI.escapeHTML(humanized_name(setting))}</a>).html_safe
end
- def expand_setting_links(text)
- return text if text.blank? || !text.include?("{{setting:")
- text.gsub(SETTING_LINK_PATTERN) { linkify(Regexp.last_match(1)) }.html_safe
+ # Links a group of settings as a single anchor pointing at the
+ # all-settings page filtered to every name at once, via the explicit
+ # `any:one|two` OR filter syntax (unprefixed pipes stay literal so
+ # admins can search pipe-delimited list values exactly). Unlike #linkify
+ # there is no per-setting config page to rewrite the href to, so no data
+ # attributes are emitted for the linkify-setting-links modifier.
+ def linkify_settings(settings, label: nil)
+ filter = "any:#{settings.map(&:to_s).join("|")}"
+ label ||= settings.map { |setting| humanized_name(setting) }.join(", ")
+
+ %(<a class="site-setting-link" href="#{CGI.escapeHTML(settings_filter_href(filter))}">#{CGI.escapeHTML(label)}</a>).html_safe
+ end
+
+ def contains_setting_links?(text)
+ return false if text.blank?
+ text.match?(SETTING_LINK_PATTERN) || text.match?(SETTINGS_LINK_PATTERN)
+ end
+
+ def expand_setting_links(text, escape_text: false)
+ return text if text.blank? || !text.include?("{{setting")
+
+ text = CGI.escapeHTML(text) if escape_text
+
+ text
+ .gsub(SETTINGS_LINK_PATTERN) do
+ label = Regexp.last_match(2)&.strip
+ label = CGI.unescapeHTML(label) if escape_text && label
+ linkify_settings(Regexp.last_match(1).split(","), label:)
+ end
+ .gsub(SETTING_LINK_PATTERN) { linkify(Regexp.last_match(1)) }
+ .html_safe
+ end
+
+ # Renders markers as plain text — the humanized setting names (quoted)
+ # for {{setting:...}}, and the label or name list for {{settings:...}} —
+ # for surfaces that display error messages outside the admin UI.
+ def plain_setting_links(text)
+ return text if text.blank? || !text.include?("{{setting")
+
+ text
+ .gsub(SETTINGS_LINK_PATTERN) do
+ Regexp.last_match(2)&.strip ||
+ Regexp.last_match(1).split(",").map { |s| humanized_name(s) }.join(", ")
+ end
+ .gsub(SETTING_LINK_PATTERN) { "'#{humanized_name(Regexp.last_match(1))}'" }
end
def humanized_name(setting)
diff --git a/lib/site_settings/type_supervisor.rb b/lib/site_settings/type_supervisor.rb
index 9172ca3960d..5b36a1a30ad 100644
--- a/lib/site_settings/type_supervisor.rb
+++ b/lib/site_settings/type_supervisor.rb
@@ -306,7 +306,16 @@ class SiteSettings::TypeSupervisor
if (v = @validators[name])
validator = v[:class].new(v[:opts])
unless validator.valid_value?(val)
- raise Discourse::InvalidParameters, "#{name}: #{validator.error_message}"
+ error = validator.error_message
+ if SiteSettings::LabelFormatter.contains_setting_links?(error)
+ raise Discourse::InvalidHTMLParameters.new(
+ "#{name}: #{SiteSettings::LabelFormatter.plain_setting_links(error)}",
+ html_message:
+ "#{name}: #{SiteSettings::LabelFormatter.expand_setting_links(error, escape_text: true)}",
+ )
+ end
+
+ raise Discourse::InvalidParameters, "#{name}: #{error}"
end
end
diff --git a/script/i18n_lint.rb b/script/i18n_lint.rb
index 21c6d502712..b7e4767433c 100755
--- a/script/i18n_lint.rb
+++ b/script/i18n_lint.rb
@@ -42,6 +42,8 @@ class LocaleFileValidator
"The file is not a valid YAML format or does not contain a valid locale structure.",
invalid_one_keys:
"The following keys contain the number 1 instead of the interpolation key %{count}:",
+ invalid_setting_link_format:
+ "The following keys contain malformed setting link markers.\nUse {{setting:setting_name}} or {{settings:name_one,name_two|Link label}} (lowercase snake_case names, no spaces around commas):",
}.merge(
BANNED_PHRASES
.map do |banned, recommendation|
@@ -53,6 +55,15 @@ class LocaleFileValidator
.to_h,
)
+ # Must stay in sync with SETTING_LINK_PATTERN and SETTINGS_LINK_PATTERN in
+ # lib/site_settings/label_formatter.rb — markers that don't match there are
+ # rendered verbatim, so lint anything that only looks like one.
+ VALID_SETTING_LINK_REGEX =
+ /\{\{setting:[a-z][a-z0-9_]*\}\}|\{\{settings:[a-z][a-z0-9_]*(?:,[a-z][a-z0-9_]*)*(?:\|[^{}|]+)?\}\}/
+
+ SETTING_LINK_START_REGEX = /{{settings?:/
+ VALID_SETTING_LINK_AT_START_REGEX = /\A(?:#{VALID_SETTING_LINK_REGEX})/
+
PLURALIZATION_KEYS = %w[zero one two few many other]
ENGLISH_KEYS = %w[one other]
@@ -112,11 +123,18 @@ class LocaleFileValidator
@errors[:invalid_relative_image_sources] << key if value.match?(%r{src\s*=\s*["']/[^/]}i)
- if value.match?(/{{(?!setting:).+?}}/)
+ if value.match?(/{{(?!settings?:).+?}}/)
exempt = key.end_with?("_MF") || EXEMPTED_DOUBLE_CURLY_BRACKET_KEYS.include?(key)
@errors[:invalid_interpolation_key_format] << key unless exempt
end
+ if value
+ .enum_for(:scan, SETTING_LINK_START_REGEX)
+ .map { Regexp.last_match.begin(0) }
+ .any? { |start| !value[start..].match?(VALID_SETTING_LINK_AT_START_REGEX) }
+ @errors[:invalid_setting_link_format] << key
+ end
+
BANNED_PHRASES.keys.each do |banned|
@errors["banned_phrase_#{banned}"] << key if value.downcase.include?(banned.downcase)
end
@@ -153,4 +171,4 @@ class LocaleFileValidator
end
end
-I18nLinter.new(ARGV).run
+I18nLinter.new(ARGV).run if $PROGRAM_NAME == __FILE__
diff --git a/spec/lib/site_setting_extension_spec.rb b/spec/lib/site_setting_extension_spec.rb
index a061b3e1b8d..f1fbdc57854 100644
--- a/spec/lib/site_setting_extension_spec.rb
+++ b/spec/lib/site_setting_extension_spec.rb
@@ -1941,6 +1941,26 @@ RSpec.describe SiteSettingExtension do
end
end
+ describe "linkify_settings" do
+ it "links to the all-settings page filtered to every name with the given label" do
+ result =
+ SiteSettings::LabelFormatter.linkify_settings(
+ %w[title logo],
+ label: "View related settings",
+ )
+ expect(result).to eq(
+ '<a class="site-setting-link" href="/admin/site_settings/category/all_results?filter=any%3Atitle%7Clogo">View related settings</a>',
+ )
+ expect(result).to be_html_safe
+ end
+
+ it "falls back to the humanized names joined with commas when no label is given" do
+ expect(SiteSettings::LabelFormatter.linkify_settings(%w[title opengraph_image])).to eq(
+ '<a class="site-setting-link" href="/admin/site_settings/category/all_results?filter=any%3Atitle%7Copengraph_image">Title, OpenGraph image</a>',
+ )
+ end
+ end
+
describe "expand_setting_links" do
it "expands {{setting:foo}} markers into linkified HTML" do
expanded =
@@ -1964,18 +1984,84 @@ RSpec.describe SiteSettingExtension do
expect(expanded).to include(">Logo</a>")
end
+ it "expands {{settings:a,b|label}} markers into a single link filtered to every setting" do
+ expanded =
+ SiteSettings::LabelFormatter.expand_setting_links(
+ "Something went wrong. {{settings:title,logo|View related settings}}",
+ )
+ expect(expanded).to eq(
+ 'Something went wrong. <a class="site-setting-link" href="/admin/site_settings/category/all_results?filter=any%3Atitle%7Clogo">View related settings</a>',
+ )
+ expect(expanded).to be_html_safe
+ end
+
+ it "expands {{settings:...}} markers without a label using the humanized names" do
+ expanded = SiteSettings::LabelFormatter.expand_setting_links("See {{settings:title,logo}}.")
+ expect(expanded).to include(">Title, Logo</a>")
+ end
+
+ it "expands singular and plural markers in the same string" do
+ expanded =
+ SiteSettings::LabelFormatter.expand_setting_links(
+ "Enable {{setting:title}} first. {{settings:title,logo|View related settings}}",
+ )
+ expect(expanded).to include('data-setting-name="title"')
+ expect(expanded).to include(">View related settings</a>")
+ end
+
it "returns input unchanged when no markers are present" do
expect(SiteSettings::LabelFormatter.expand_setting_links("nothing to expand")).to eq(
"nothing to expand",
)
end
+ it "escapes the surrounding text with escape_text so only generated anchors are HTML" do
+ expanded =
+ SiteSettings::LabelFormatter.expand_setting_links(
+ "<img src=x onerror=alert(1)> {{settings:title,logo|View & fix}}",
+ escape_text: true,
+ )
+ expect(expanded).to eq(
+ '&lt;img src=x onerror=alert(1)&gt; <a class="site-setting-link" href="/admin/site_settings/category/all_results?filter=any%3Atitle%7Clogo">View &amp; fix</a>',
+ )
+ end
+
it "handles blank input safely" do
expect(SiteSettings::LabelFormatter.expand_setting_links("")).to eq("")
expect(SiteSettings::LabelFormatter.expand_setting_links(nil)).to be_nil
end
end
+ describe "contains_setting_links?" do
+ it "detects both marker forms and rejects lookalikes" do
+ expect(SiteSettings::LabelFormatter.contains_setting_links?("See {{setting:title}}.")).to eq(
+ true,
+ )
+ expect(
+ SiteSettings::LabelFormatter.contains_setting_links?("See {{settings:title,logo|All}}."),
+ ).to eq(true)
+ expect(SiteSettings::LabelFormatter.contains_setting_links?("See {{settings}}.")).to eq(false)
+ expect(SiteSettings::LabelFormatter.contains_setting_links?("plain text")).to eq(false)
+ expect(SiteSettings::LabelFormatter.contains_setting_links?(nil)).to eq(false)
+ end
+ end
+
+ describe "plain_setting_links" do
+ it "renders singular markers as quoted humanized names and plural markers as their label" do
+ expect(
+ SiteSettings::LabelFormatter.plain_setting_links(
+ "Enable {{setting:title}} first. {{settings:title,logo|View related settings}}",
+ ),
+ ).to eq("Enable 'Title' first. View related settings")
+ end
+
+ it "falls back to the humanized name list when a plural marker has no label" do
+ expect(
+ SiteSettings::LabelFormatter.plain_setting_links("See {{settings:title,logo}}."),
+ ).to eq("See Title, Logo.")
+ end
+ end
+
describe "description" do
it "expands {{setting:foo}} markers in the translated description" do
expect(SiteSetting.description(:logo_dark)).to eq(
diff --git a/spec/requests/admin/site_settings_controller_spec.rb b/spec/requests/admin/site_settings_controller_spec.rb
index aae964e67f1..ab83632dde4 100644
--- a/spec/requests/admin/site_settings_controller_spec.rb
+++ b/spec/requests/admin/site_settings_controller_spec.rb
@@ -720,6 +720,35 @@ RSpec.describe Admin::SiteSettingsController do
)
end
+ it "returns html_message: true with linkified errors when a validator message references settings" do
+ SiteSetting.set_locale_from_cookie = false
+
+ put "/admin/site_settings/content_localization_language_switcher.json",
+ params: {
+ content_localization_language_switcher: "all",
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["html_message"]).to eq(true)
+ expect(response.parsed_body["errors"].first).to include(
+ 'class="site-setting-link"',
+ ">All required settings</a>",
+ )
+ expect(response.parsed_body["errors"].first).not_to include("{{setting")
+ end
+
+ it "keeps the exception message plain text for non-admin-UI consumers" do
+ SiteSetting.set_locale_from_cookie = false
+
+ expect { SiteSetting.set("content_localization_language_switcher", "all") }.to raise_error(
+ Discourse::InvalidHTMLParameters,
+ ) do |error|
+ expect(error.message).to include("'Set locale from cookie'")
+ expect(error.message).not_to include("<a", "{{setting")
+ expect(error.html_message).to include('class="site-setting-link"')
+ end
+ end
+
context "with an plugin" do
it "allows changing settings of configurable plugins" do
SiteSetting::SAMPLE_TEST_PLUGIN.stubs(:configurable?).returns(true)
diff --git a/spec/script/i18n_lint_spec.rb b/spec/script/i18n_lint_spec.rb
new file mode 100644
index 00000000000..779c786bdcf
--- /dev/null
+++ b/spec/script/i18n_lint_spec.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+require "tmpdir"
+
+load Rails.root.join("script/i18n_lint.rb")
+
+RSpec.describe LocaleFileValidator do
+ def errors_for(value)
+ Dir.mktmpdir("i18n-lint") do |dir|
+ path = File.join(dir, "server.en.yml")
+ File.write(path, { "en" => { "test_key" => value } }.to_yaml)
+
+ validator = described_class.new(path)
+ validator.has_errors?
+ validator.instance_variable_get(:@errors)
+ end
+ end
+
+ describe "setting link markers" do
+ VALID_MARKERS = [
+ "{{setting:title}}",
+ "{{setting:s3_upload_bucket}}",
+ "{{settings:title,logo}}",
+ "{{settings:title,logo|All required settings}}",
+ "{{settings:set_locale_from_cookie,allow_user_locale,title|View them}}",
+ ]
+
+ MALFORMED_MARKERS = [
+ "{{setting:Title}}", # uppercase name
+ "{{setting:title }}", # trailing space
+ "{{setting:}}", # empty name
+ "{{settings:title, logo|label}}", # space after comma
+ "{{settings:title;logo|label}}", # wrong separator
+ "{{settings:title,logo|}}", # empty label
+ "{{settings:title,logo|la|bel}}", # pipe inside label
+ "{{settings:title,logo|la{bel}}", # brace inside label
+ "{{settings:,title}}", # leading comma
+ "{{setting:title}", # unclosed singular marker
+ "{{settings:title,logo|All}", # unclosed plural marker
+ "{{setting:title", # no closing braces at all
+ ]
+
+ VALID_MARKERS.each do |marker|
+ it "accepts #{marker}" do
+ errors = errors_for("Some text with #{marker} in it.")
+ expect(errors[:invalid_setting_link_format]).to be_empty
+ expect(errors[:invalid_interpolation_key_format]).to be_empty
+ end
+ end
+
+ MALFORMED_MARKERS.each do |marker|
+ it "flags #{marker} as malformed" do
+ errors = errors_for("Some text with #{marker} in it.")
+ expect(
+ errors[:invalid_setting_link_format].presence ||
+ errors[:invalid_interpolation_key_format].presence,
+ ).to eq(["test_key"])
+ end
+ end
+
+ it "still flags handlebars-style interpolation that isn't a setting marker" do
+ expect(errors_for("Hello {{username}}!")[:invalid_interpolation_key_format]).to eq(
+ ["test_key"],
+ )
+ end
+
+ it "accepts %{}-style interpolation untouched" do
+ errors = errors_for("Hello %{username}, see {{setting:title}}.")
+ expect(errors.values.flatten).to be_empty
+ end
+
+ (VALID_MARKERS + MALFORMED_MARKERS).each do |marker|
+ it "agrees with LabelFormatter about #{marker}" do
+ text = "Some text with #{marker} in it."
+
+ lint_accepts = errors_for(text).values.flatten.empty?
+ formatter_expands = SiteSettings::LabelFormatter.expand_setting_links(text) != text
+
+ expect(lint_accepts).to eq(formatter_expands)
+ end
+ end
+ end
+end