Skip to content

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

FEATURE: Support non-image file uploads in site settings (#37005)

Régis Hanol6212b0b73627
diff --git a/app/assets/stylesheets/admin/admin_config_area.scss b/app/assets/stylesheets/admin/admin_config_area.scss
index 904e5901783..eafb2ea7a12 100644
--- a/app/assets/stylesheets/admin/admin_config_area.scss
+++ b/app/assets/stylesheets/admin/admin_config_area.scss
@@ -170,7 +170,7 @@
}
}
- #control-logo_dark .image-uploader.has-image .uploaded-image-preview {
+ #control-logo_dark .file-uploader.has-image .file-uploader__preview {
background-color: #333;
background-clip: border-box;
}
diff --git a/app/assets/stylesheets/admin/settings.scss b/app/assets/stylesheets/admin/settings.scss
index 86c4c6fbf87..8d4dbaccd58 100644
--- a/app/assets/stylesheets/admin/settings.scss
+++ b/app/assets/stylesheets/admin/settings.scss
@@ -56,21 +56,6 @@
width: 100% !important; // !important overrides hard-coded mobile width of 68px
}
}
-
- .image-uploader {
- display: flex;
- flex-direction: column;
-
- .image-upload-controls {
- display: flex;
- gap: 0.5em;
- margin: 0 0 0.5em;
- }
- }
-
- .uploaded-image-preview {
- background-color: var(--primary-medium);
- }
}
.setting-theme-warning {
diff --git a/app/assets/stylesheets/common/base/group.scss b/app/assets/stylesheets/common/base/group.scss
index ef750fe2527..3b07a4900d5 100644
--- a/app/assets/stylesheets/common/base/group.scss
+++ b/app/assets/stylesheets/common/base/group.scss
@@ -253,7 +253,7 @@ table.group-manage-logs {
align-items: center;
}
- .uploaded-image-preview {
+ .file-uploader__preview {
height: 75px;
width: 275px;
}
diff --git a/app/assets/stylesheets/common/base/upload.scss b/app/assets/stylesheets/common/base/upload.scss
index 164f7f4cbbd..2b1d6a41c4b 100644
--- a/app/assets/stylesheets/common/base/upload.scss
+++ b/app/assets/stylesheets/common/base/upload.scss
@@ -1,46 +1,22 @@
-.uploaded-image-preview {
- position: relative;
- max-width: 400px;
- width: 100%;
- height: 80px;
- margin-bottom: 0.5em;
- box-sizing: border-box;
- border-radius: var(--d-input-border-radius);
- background-origin: content-box;
- background-clip: content-box;
-
- .meta {
- display: none;
+.file-uploader {
+ display: flex;
+ flex-direction: column;
+
+ &__restrictions {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ margin-top: 0.25em;
}
- .placeholder-overlay {
- background-size: contain;
- background-repeat: no-repeat;
- background-position: left center;
- position: absolute;
- top: 0;
- left: 0;
+ &__preview {
+ position: relative;
+ max-width: 400px;
width: 100%;
- height: 100%;
- opacity: 0.2;
- pointer-events: none;
- box-shadow: inset 0 0 0 var(--space-1) var(--secondary);
- }
-
- &:hover .expand-overlay,
- &:focus-within .expand-overlay {
- opacity: 1;
- pointer-events: auto;
- }
-}
-
-.has-image {
- .uploaded-image-preview {
- background-size: contain;
- background-repeat: no-repeat;
- background-position: left center;
- border: 1px solid var(--primary-low-mid);
- padding: var(--space-1);
+ height: 80px;
+ box-sizing: border-box;
+ border-radius: var(--d-input-border-radius);
+ background-origin: content-box;
+ background-clip: content-box;
&:focus,
&:focus-within {
@@ -49,96 +25,182 @@
outline-offset: -2px;
}
- &.--bg-size-cover {
- background-size: cover;
- background-position: center;
+ &:hover {
+ background-color: var(--tertiary-very-low);
+
+ .has-image &,
+ .has-file & {
+ background-color: unset;
+ }
}
- }
- .image-upload-controls {
- margin-top: var(--space-2);
- }
-}
+ .no-image &,
+ .no-file & {
+ position: relative;
+ border: 1px dashed var(--primary-medium);
+ background-color: var(--primary-very-low);
-.no-image .uploaded-image-preview {
- position: relative;
- border: 1px dashed var(--primary-medium);
- background-color: var(--primary-very-low);
+ &:hover {
+ background-color: var(--tertiary-very-low);
+ }
- &:focus,
- &:focus-within {
- border-color: var(--tertiary);
- outline: 2px dashed var(--tertiary);
- outline-offset: -2px;
- }
+ &:focus,
+ &:focus-within {
+ outline: 2px dashed var(--tertiary);
+ }
+ }
- .image-upload-controls {
- height: 100%;
- background-color: var(--primary-very-low);
- transition: background 0.25s;
- border-radius: var(--d-input-border-radius);
+ .has-image & {
+ background-size: contain;
+ background-repeat: no-repeat;
+ background-position: left center;
+ border: 1px solid var(--primary-low-mid);
+ padding: var(--space-1);
- &:hover {
- background-color: var(--tertiary-very-low);
+ &.--bg-size-cover {
+ background-size: cover;
+ background-position: center;
+ }
}
- label {
+ .has-file & {
+ background-size: contain;
+ background-repeat: no-repeat;
+ background-position: left center;
+ border: 1px solid var(--primary-low-mid);
+ padding: var(--space-1);
+
+ &:focus,
+ &:focus-within {
+ border-color: var(--tertiary);
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ }
+ }
+
+ .file-info {
display: flex;
- font-weight: normal;
- color: var(--primary-very-high);
- width: 100%;
+ align-items: center;
+ gap: var(--space-3);
+ padding: var(--space-4);
+ background: var(--primary-very-low);
+ border-radius: var(--d-input-border-radius);
height: 100%;
box-sizing: border-box;
- border-radius: var(--d-input-border-radius);
- svg {
- color: var(--primary-high);
+ .file-icon {
+ color: var(--primary-medium);
+ font-size: var(--font-up-3);
+ }
+
+ .file-details {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-width: 0;
+
+ .file-name {
+ font-weight: 500;
+ word-break: break-all;
+ }
+
+ .file-size {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
}
}
- }
-}
-.expand-overlay {
- position: absolute;
- top: 10px;
- right: 10px;
- z-index: 30;
- opacity: 0;
- transition: opacity 0.3s ease;
- pointer-events: none;
-}
+ .meta {
+ display: none;
+ }
-.progress-status {
- position: absolute;
- top: 60%;
- left: 50%;
- transform: translate(-50%, -50%);
- width: 90%;
-
- .progress-bar-container {
- --d-border-radius: 10px;
- background: var(--primary-low-mid);
- border-radius: var(--d-border-radius);
- height: 5px;
- position: relative;
+ .expand-overlay {
+ position: absolute;
+ top: 10px;
+ right: 10px;
+ z-index: 30;
+ opacity: 0;
+ transition: opacity 0.3s ease;
+ pointer-events: none;
+ }
- .progress-bar {
+ &:hover .expand-overlay,
+ &:focus-within .expand-overlay {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ }
+
+ &__progress-status {
+ position: absolute;
+ top: 60%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ width: 90%;
+
+ .progress-bar-container {
+ --d-border-radius: 10px;
+ background: var(--primary-low-mid);
border-radius: var(--d-border-radius);
- height: 100%;
- background: var(--tertiary);
- transition: width 0.3s ease;
- position: absolute;
- left: 0;
- top: 0%;
+ height: 5px;
+ position: relative;
+
+ .progress-bar {
+ border-radius: var(--d-border-radius);
+ height: 100%;
+ background: var(--tertiary);
+ transition: width 0.3s ease;
+ position: absolute;
+ left: 0;
+ top: 0%;
+ }
+ }
+
+ span {
+ font-size: var(--font-down-2);
+ margin-top: 8px;
+ display: block;
+ text-align: center;
+ color: var(--primary-high);
}
}
- span {
- font-size: var(--font-down-2);
- margin-top: 8px;
- display: block;
- text-align: center;
- color: var(--primary-high);
+ &__controls {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100%;
+
+ .has-file &,
+ .has-image & {
+ gap: var(--space-2);
+ margin-top: var(--space-2);
+ justify-content: flex-start;
+ }
+
+ label {
+ display: flex;
+ font-weight: normal;
+ box-sizing: border-box;
+ color: var(--primary-very-high);
+ border-radius: var(--d-button-border-radius);
+ cursor: pointer;
+
+ .no-image &,
+ .no-file & {
+ height: 100%;
+ width: 100%;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-1);
+
+ &:hover,
+ &:focus-visible {
+ color: var(--primary-very-high);
+ }
+ }
+ }
}
}
diff --git a/app/assets/stylesheets/common/form-kit/_control-image.scss b/app/assets/stylesheets/common/form-kit/_control-image.scss
index 4cfe4e57c1d..b669da24762 100644
--- a/app/assets/stylesheets/common/form-kit/_control-image.scss
+++ b/app/assets/stylesheets/common/form-kit/_control-image.scss
@@ -1,7 +1,7 @@
.form-kit__control-image {
width: 100%;
- .uploaded-image-preview {
+ .file-uploader-preview {
max-width: 100%;
width: 100%;
margin: 0;
diff --git a/app/assets/stylesheets/wcag.scss b/app/assets/stylesheets/wcag.scss
index e7675027f56..42a37bf9d41 100644
--- a/app/assets/stylesheets/wcag.scss
+++ b/app/assets/stylesheets/wcag.scss
@@ -257,14 +257,11 @@ html {
color: dark-light-choose($primary, $secondary);
}
- .uploaded-image-preview
- .image-upload-controls
- .image-uploader-lightbox-btn
- .d-icon {
+ .uploaded-file-preview .expand-overlay .file-uploader-lightbox-btn .d-icon {
color: var(--primary);
}
- .settings .setting .setting-value .uploaded-image-preview {
+ .settings .setting .setting-value .uploaded-file-preview {
background-color: var(--primary-very-low);
}
diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb
index 092e09a6a83..f0092eaeea7 100644
--- a/app/controllers/uploads_controller.rb
+++ b/app/controllers/uploads_controller.rb
@@ -61,6 +61,7 @@ class UploadsController < ApplicationController
pasted = params[:pasted] == "true"
for_private_message = params[:for_private_message] == "true"
for_site_setting = params[:for_site_setting] == "true"
+ site_setting_name = for_site_setting ? params[:site_setting_name] : nil
is_api = is_api?
retain_hours = params[:retain_hours].to_i
@@ -71,14 +72,15 @@ class UploadsController < ApplicationController
info =
UploadsController.create_upload(
current_user: me,
- file: file,
- url: url,
- type: type,
- for_private_message: for_private_message,
- for_site_setting: for_site_setting,
- pasted: pasted,
- is_api: is_api,
- retain_hours: retain_hours,
+ file:,
+ url:,
+ type:,
+ for_private_message:,
+ for_site_setting:,
+ site_setting_name:,
+ pasted:,
+ is_api:,
+ retain_hours:,
)
rescue => e
render json: failed_json.merge(message: e.message&.split("\n")&.first),
@@ -280,6 +282,7 @@ class UploadsController < ApplicationController
type:,
for_private_message:,
for_site_setting:,
+ site_setting_name: nil,
pasted:,
is_api:,
retain_hours:
@@ -310,12 +313,7 @@ class UploadsController < ApplicationController
return { errors: [I18n.t("upload.file_missing")] } if tempfile.nil?
- opts = {
- type: type,
- for_private_message: for_private_message,
- for_site_setting: for_site_setting,
- pasted: pasted,
- }
+ opts = { type:, for_private_message:, for_site_setting:, site_setting_name:, pasted: }
upload = UploadCreator.new(tempfile, filename, opts).create_for(current_user.id)
diff --git a/app/models/upload.rb b/app/models/upload.rb
index f4ccf470766..2cda4c821d6 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -38,6 +38,7 @@ class Upload < ActiveRecord::Base
attr_accessor :for_export
attr_accessor :for_site_setting
attr_accessor :for_gravatar
+ attr_accessor :site_setting_name
attr_accessor :validate_file_size
attr_accessor :skip_video_conversion
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 443e83e8592..bc529be5fa0 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -8487,6 +8487,10 @@ en:
upload:
label: "Upload"
title: "Upload images"
+ download_file: "Download"
+ upload_restrictions:
+ extensions: "Accepted: %{extensions}"
+ max_size: "Max: %{size}"
selectable_avatars:
title: "List of avatars users can choose from"
table_column_heading:
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 84ef4bfb6d6..998f427e874 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -1913,6 +1913,7 @@ en:
blocked_crawler_user_agents: "Unique case insensitive word in the user agent string identifying web crawlers that should not be allowed to access the site. Does not apply if allowlist is defined."
slow_down_crawler_user_agents: 'User agents of web crawlers that should be rate limited as configured in the "slow down crawler rate" setting. Each value must be at least 3 characters long.'
slow_down_crawler_rate: "If slow_down_crawler_user_agents is specified this rate will apply to all the crawlers (number of seconds delay between requests)"
+ llms_txt: "Upload a text file to be served at /llms.txt for LLM crawlers. See <a href='https://llmstxt.org/' target='_blank'>llmstxt.org</a> for more information."
content_security_policy: "Enable Content-Security-Policy (CSP). CSP is an additional layer of security that helps to prevent certain types of attacks, including Cross Site Scripting (XSS) and data injection."
content_security_policy_report_only: "Enable Content-Security-Policy-Report-Only (CSP)"
content_security_policy_collect_reports: "Enable CSP violation report collection at /csp_reports"
@@ -4746,6 +4747,7 @@ en:
upload:
edit_reason: "downloaded local copies of images"
unauthorized: "Sorry, the file you are trying to upload is not authorized (authorized extensions: %{authorized_extensions})."
+ images_only: "Sorry, you can only upload images for this setting."
pasted_image_filename: "Pasted image"
store_failure: "Failed to store upload #%{upload_id} for user #%{user_id}."
file_missing: "Sorry, you must provide a file to upload."
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 0ddf63b0573..fca1b66053e 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -49,7 +49,12 @@
# type: category_list - A list of category ids, which shows a special picker in the UI.
# type: category - A single category ID, which shows a special picker in the UI.
# type: uploaded_image_list - A list of upload IDs that should be images.
-# type: upload - A single upload ID.
+# type: upload - A single upload ID. Optional attributes:
+# - authorized_extensions: pipe-separated list of allowed extensions
+# without dots (e.g., "txt|json"). If not specified, only images
+# are allowed based on authorized_extensions setting.
+# - max_file_size_kb: maximum file size in KB. If not specified,
+# uses max_image_size_kb or max_attachment_size_kb.
# type: group - A single group ID.
# type: group_list - A list of group IDs.
# type: tag_list - A list of tag names.
@@ -2712,6 +2717,12 @@ security:
list_type: compact
requires_confirmation: "simple"
slow_down_crawler_rate: 60
+ llms_txt:
+ default: ""
+ type: upload
+ authorized_extensions: "txt|md"
+ max_file_size_kb: 512
+ hidden: true
content_security_policy:
default: true
content_security_policy_report_only:
diff --git a/frontend/discourse/admin/components/site-settings/upload.gjs b/frontend/discourse/admin/components/site-settings/upload.gjs
index 91814329e62..0cdb8ca8c94 100644
--- a/frontend/discourse/admin/components/site-settings/upload.gjs
+++ b/frontend/discourse/admin/components/site-settings/upload.gjs
@@ -1,32 +1,377 @@
-/* eslint-disable ember/no-classic-components */
-import Component from "@ember/component";
-import { concat, fn, hash } from "@ember/helper";
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
import { action } from "@ember/object";
-import UppyImageUploader from "discourse/components/uppy-image-uploader";
-import { includes } from "discourse/truth-helpers";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { htmlSafe } from "@ember/template";
+import { modifier } from "ember-modifier";
+import DButton from "discourse/components/d-button";
+import PickFilesButton from "discourse/components/pick-files-button";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import { getURLWithCDN } from "discourse/lib/get-url";
+import lightbox from "discourse/lib/lightbox";
+import { authorizesOneOrMoreExtensions, isImage } from "discourse/lib/uploads";
+import UppyUpload from "discourse/lib/uppy/uppy-upload";
+import { i18n } from "discourse-i18n";
-const BACKGROUND_SIZE_COVER = ["welcome_banner_image"];
+const BACKGROUND_SIZE_COVER_SETTINGS = ["welcome_banner_image"];
+
+const ImagePreview = <template>
+ <a
+ {{@applyLightbox}}
+ href={{@cdnUrl}}
+ title={{@fileName}}
+ rel="nofollow ugc noopener"
+ class="lightbox"
+ >
+ <div class="meta">
+ <span class="informations">
+ {{#if @width}}
+ {{@width}}x{{@height}}
+ {{/if}}
+ {{@filesize}}
+ </span>
+ </div>
+ </a>
+
+ <div class="expand-overlay">
+ <DButton
+ @action={{@onToggleLightbox}}
+ @icon="discourse-expand"
+ @title="expand"
+ class="btn-default btn-small file-uploader-lightbox-btn"
+ />
+ </div>
+</template>;
+
+const FilePreview = <template>
+ <div class="file-info">
+ <div class="file-icon">
+ {{icon "file"}}
+ </div>
+ <div class="file-details">
+ <span class="file-name">{{@fileName}}</span>
+ {{#if @filesize}}
+ <span class="file-size">{{@filesize}}</span>
+ {{/if}}
+ </div>
+ <a
+ href={{@cdnUrl}}
+ download={{@fileName}}
+ target="_blank"
+ rel="nofollow ugc noopener noreferrer"
+ class="btn btn-default btn-small no-text download-btn"
+ title={{i18n "admin.site_settings.download_file"}}
+ >
+ {{icon "download"}}
+ </a>
+ </div>
+</template>;
+
+export default class SiteSettingUpload extends Component {
+ @service currentUser;
+ @service siteSettings;
+
+ @tracked uploadedFile = null;
+
+ uppyUpload = new UppyUpload(getOwner(this), {
+ id: this.settingId,
+ type: "site_setting",
+ additionalParams: () => ({
+ for_site_setting: true,
+ site_setting_name: this.args.setting.setting,
+ }),
+ validateUploadedFilesOptions: this.validationOptions,
+ uploadDropTargetOptions: () => ({
+ target: document.querySelector(
+ `#${this.settingId} .file-uploader__preview`
+ ),
+ }),
+ uploadDone: (upload) => {
+ this.uploadedFile = upload;
+ this.args.changeValueCallback(upload.url);
+ },
+ });
+
+ applyLightbox = modifier(() =>
+ lightbox(
+ document.querySelector(`#${this.settingId}.file-uploader`),
+ this.siteSettings
+ )
+ );
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ window.pswp?.close();
+ }
+
+ get settingId() {
+ return `site-setting-file-uploader-${this.args.setting.setting}`;
+ }
+
+ get inputId() {
+ return `${this.settingId}__input`;
+ }
+
+ get validationOptions() {
+ return this.args.setting.authorized_extensions
+ ? { skipValidation: true }
+ : { imagesOnly: true };
+ }
+
+ formatExtensions(separator = ", ") {
+ return this.args.setting.authorized_extensions
+ .split("|")
+ .map((ext) => `.${ext}`)
+ .join(separator);
+ }
+
+ get acceptedFormats() {
+ if (this.args.setting.authorized_extensions) {
+ return this.formatExtensions(",");
+ }
+ return "image/*";
+ }
+
+ get isImageFile() {
+ return this.args.value && isImage(this.args.value);
+ }
+
+ get disabled() {
+ return (
+ this.args.disabled ||
+ this.notAllowed ||
+ this.uppyUpload?.uploading ||
+ this.uppyUpload?.processing
+ );
+ }
+
+ get disabledReason() {
+ if (this.disabled && this.notAllowed) {
+ return i18n("post.errors.no_uploads_authorized");
+ }
+ }
+
+ get notAllowed() {
+ if (this.args.setting.authorized_extensions) {
+ return false;
+ }
+ return !authorizesOneOrMoreExtensions(
+ this.currentUser?.staff,
+ this.siteSettings
+ );
+ }
+
+ get fileCdnUrl() {
+ return this.args.value ? getURLWithCDN(this.args.value) : "";
+ }
+
+ get previewSizeClass() {
+ return BACKGROUND_SIZE_COVER_SETTINGS.includes(this.args.setting.setting)
+ ? "--bg-size-cover"
+ : "";
+ }
+
+ get backgroundStyle() {
+ return this.isImageFile
+ ? htmlSafe(`background-image: url(${this.fileCdnUrl})`)
+ : htmlSafe("");
+ }
+
+ get fileName() {
+ const filename =
+ this.uploadedFile?.original_filename ??
+ this.args.setting.upload?.original_filename;
+ return filename || this.args.value?.split("/").pop();
+ }
+
+ get filesize() {
+ return (
+ this.uploadedFile?.human_filesize ??
+ this.args.setting.upload?.human_filesize
+ );
+ }
+
+ get imageWidth() {
+ return this.uploadedFile?.width ?? this.args.setting.upload?.width;
+ }
+
+ get imageHeight() {
+ return this.uploadedFile?.height ?? this.args.setting.upload?.height;
+ }
+
+ get isUploading() {
+ return this.uppyUpload?.uploading || this.uppyUpload?.processing;
+ }
+
+ get uploadStatusLabel() {
+ if (this.uppyUpload?.processing) {
+ return i18n("upload_selector.processing");
+ }
+ return `${i18n("upload_selector.uploading")} ${this.uppyUpload.uploadProgress}%`;
+ }
+
+ get progressBarStyle() {
+ const progress = this.uppyUpload?.processing
+ ? 100
+ : this.uppyUpload.uploadProgress || 0;
+ return htmlSafe(`width: ${progress}%`);
+ }
+
+ get restrictionsInfo() {
+ const parts = [];
+
+ if (this.args.setting.authorized_extensions) {
+ parts.push(
+ i18n("admin.site_settings.upload_restrictions.extensions", {
+ extensions: this.formatExtensions(),
+ })
+ );
+ }
+
+ if (this.args.setting.max_file_size_kb) {
+ const sizeKb = this.args.setting.max_file_size_kb;
+ const size =
+ sizeKb >= 1024 ? `${(sizeKb / 1024).toFixed(1)} MB` : `${sizeKb} KB`;
+ parts.push(
+ i18n("admin.site_settings.upload_restrictions.max_size", { size })
+ );
+ }
+
+ return parts.length > 0 ? parts.join(" · ") : null;
+ }
+
+ @action
+ toggleLightbox() {
+ const link = document.querySelector(`#${this.settingId} a.lightbox`);
+ if (link) {
+ lightbox(link);
+ link.click();
+ }
+ }
-export default class Upload extends Component {
@action
- uploadDone(upload) {
- this.set("value", upload.url);
+ onKeydown(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ document.getElementById(this.inputId)?.click();
+ }
+ }
+
+ @action
+ deleteUpload() {
+ this.uploadedFile = null;
+ this.args.changeValueCallback(null);
}
<template>
- <UppyImageUploader
- @imageUrl={{this.value}}
- @placeholderUrl={{this.setting.placeholder}}
- @previewSize={{if
- (includes BACKGROUND_SIZE_COVER this.setting.setting)
- "cover"
+ <div
+ id={{this.settingId}}
+ class={{concatClass
+ "file-uploader"
+ (if @value "has-file" "no-file")
+ (if this.isImageFile "has-image")
}}
- @onUploadDone={{this.uploadDone}}
- @onUploadDeleted={{fn (mut this.value) null}}
- @additionalParams={{hash for_site_setting=true}}
- @type="site_setting"
- @id={{concat "site-setting-image-uploader-" this.setting.setting}}
- @disabled={{@disabled}}
- />
+ >
+ <div
+ class={{concatClass
+ "file-uploader__preview input-xxlarge"
+ this.previewSizeClass
+ }}
+ style={{this.backgroundStyle}}
+ >
+ {{#if @value}}
+ {{#if this.isImageFile}}
+ <ImagePreview
+ @applyLightbox={{this.applyLightbox}}
+ @cdnUrl={{this.fileCdnUrl}}
+ @fileName={{this.fileName}}
+ @filesize={{this.filesize}}
+ @width={{this.imageWidth}}
+ @height={{this.imageHeight}}
+ @onToggleLightbox={{this.toggleLightbox}}
+ />
+ {{else}}
+ <FilePreview
+ @cdnUrl={{this.fileCdnUrl}}
+ @fileName={{this.fileName}}
+ @filesize={{this.filesize}}
+ />
+ {{/if}}
+ {{else}}
+ <div class="file-uploader__controls">
+ <label
+ class="btn btn-transparent
+ {{if this.disabled 'disabled'}}
+ {{if this.isUploading 'hidden'}}"
+ title={{this.disabledReason}}
+ for={{this.inputId}}
+ tabindex="0"
+ {{on "keydown" this.onKeydown}}
+ >
+ {{icon "upload"}}
+ <PickFilesButton
+ @registerFileInput={{this.uppyUpload.setup}}
+ @fileInputDisabled={{this.disabled}}
+ @acceptedFormatsOverride={{this.acceptedFormats}}
+ @fileInputId={{this.inputId}}
+ />
+ {{i18n "upload_selector.select_file"}}
+ </label>
+
+ <div
+ class="file-uploader__progress-status
+ {{unless this.isUploading 'hidden'}}"
+ >
+ <div
+ aria-label={{this.uploadStatusLabel}}
+ role="progressbar"
+ class="progress-bar-container"
+ >
+ <div class="progress-bar" style={{this.progressBarStyle}}></div>
+ </div>
+
+ <span>{{this.uploadStatusLabel}}</span>
+ </div>
+ </div>
+ {{/if}}
+ </div>
+
+ {{#if this.restrictionsInfo}}
+ <div class="file-uploader__restrictions">
+ {{this.restrictionsInfo}}
+ </div>
+ {{/if}}
+
+ {{#if @value}}
+ <div class="file-uploader__controls">
+ <label
+ class="btn btn-default btn-small {{if this.disabled 'disabled'}}"
+ title={{this.disabledReason}}
+ for={{this.inputId}}
+ tabindex="0"
+ {{on "keydown" this.onKeydown}}
+ >
+ {{icon "upload"}}
+ <PickFilesButton
+ @registerFileInput={{this.uppyUpload.setup}}
+ @fileInputDisabled={{this.disabled}}
+ @acceptedFormatsOverride={{this.acceptedFormats}}
+ @fileInputId={{this.inputId}}
+ />
+ {{i18n "upload_selector.change"}}
+ </label>
+ <DButton
+ @action={{this.deleteUpload}}
+ @icon="trash-can"
+ @disabled={{this.disabled}}
+ @label="upload_selector.delete"
+ class="btn-danger btn-small"
+ />
+ </div>
+ {{/if}}
+ </div>
</template>
}
diff --git a/frontend/discourse/app/components/uppy-image-uploader.gjs b/frontend/discourse/app/components/uppy-image-uploader.gjs
index 80bab33da85..13f5eb43403 100644
--- a/frontend/discourse/app/components/uppy-image-uploader.gjs
+++ b/frontend/discourse/app/components/uppy-image-uploader.gjs
@@ -37,7 +37,7 @@ export default class UppyImageUploader extends Component {
: { imagesOnly: true },
uploadDropTargetOptions: () => ({
target: document.querySelector(
- `#${this.args.id} .uploaded-image-preview`
+ `#${this.args.id} .file-uploader__preview`
),
}),
uploadDone: (upload) => {
@@ -52,7 +52,7 @@ export default class UppyImageUploader extends Component {
applyLightbox = modifier(() =>
lightbox(
- document.querySelector(`#${this.args.id}.image-uploader`),
+ document.querySelector(`#${this.args.id}.file-uploader`),
this.siteSettings
)
);
@@ -169,12 +169,12 @@ export default class UppyImageUploader extends Component {
<template>
<div
id={{@id}}
- class="image-uploader {{if @imageUrl 'has-image' 'no-image'}}"
+ class="file-uploader {{if @imageUrl 'has-image' 'no-image'}}"
...attributes
>
<div
class={{concatClass
- "uploaded-image-preview input-xxlarge"
+ "file-uploader__preview input-xxlarge"
this.previewSizeClass
}}
style={{this.backgroundStyle}}
@@ -230,7 +230,7 @@ export default class UppyImageUploader extends Component {
</div>
{{/if}}
{{else}}
- <div class="image-upload-controls">
+ <div class="file-uploader__controls">
<label
class="btn btn-transparent
{{if this.disabled 'disabled'}}
@@ -251,7 +251,7 @@ export default class UppyImageUploader extends Component {
</label>
<div
- class="progress-status
+ class="file-uploader__progress-status
{{unless this.uppyUpload.uploading 'hidden'}}"
>
<div
@@ -273,7 +273,7 @@ export default class UppyImageUploader extends Component {
</div>
{{#if @imageUrl}}
- <div class="image-upload-controls">
+ <div class="file-uploader__controls">
<label
class="btn btn-default btn-small {{if this.disabled 'disabled'}}"
title={{this.disabledReason}}
diff --git a/frontend/discourse/tests/acceptance/admin-site-settings-test.js b/frontend/discourse/tests/acceptance/admin-site-settings-test.js
index 5b5a7430255..04c455b0038 100644
--- a/frontend/discourse/tests/acceptance/admin-site-settings-test.js
+++ b/frontend/discourse/tests/acceptance/admin-site-settings-test.js
@@ -40,8 +40,8 @@ acceptance("Admin - Site Settings", function (needs) {
await visit("/admin/site_settings");
assert
- .dom(".row.setting.upload .image-uploader")
- .exists("image uploader is present");
+ .dom(".row.setting.upload .file-uploader")
+ .exists("file uploader is present");
assert.dom(".row.setting.upload .undo").exists("undo button is present");
});
diff --git a/frontend/discourse/tests/integration/components/form-kit/controls/image-test.gjs b/frontend/discourse/tests/integration/components/form-kit/controls/image-test.gjs
index 587747933cd..f4f20514a32 100644
--- a/frontend/discourse/tests/integration/components/form-kit/controls/image-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-kit/controls/image-test.gjs
@@ -94,8 +94,8 @@ module(
</template>
);
- assert.dom(".image-upload-controls input[type='file']").isDisabled();
- assert.dom(".image-upload-controls .btn-danger").isDisabled();
+ assert.dom(".file-uploader__controls input[type='file']").isDisabled();
+ assert.dom(".file-uploader__controls .btn-danger").isDisabled();
});
}
);
diff --git a/frontend/discourse/tests/integration/components/site-settings/upload-test.gjs b/frontend/discourse/tests/integration/components/site-settings/upload-test.gjs
new file mode 100644
index 00000000000..2abaa91ec38
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/site-settings/upload-test.gjs
@@ -0,0 +1,228 @@
+import { click, render, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import SiteSettingUpload from "discourse/admin/components/site-settings/upload";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+module("Integration | Component | site-settings/upload", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("with image file shows preview and lightbox", async function (assert) {
+ const setting = { setting: "logo", placeholder: "/images/placeholder.png" };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value="/images/logo.png"
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert.dom(".file-uploader").hasClass("has-file", "file present");
+ assert.dom(".file-uploader").hasClass("has-image", "image file detected");
+ assert.dom(".lightbox").exists("images can be expanded");
+ assert.dom(".file-info").doesNotExist("images use preview, not file info");
+ assert.dom(".d-icon-upload").exists("can replace file");
+ assert.dom(".d-icon-trash-can").exists("can remove file");
+
+ await click(".file-uploader-lightbox-btn");
+ await waitFor(".pswp--open");
+ assert.dom(".pswp").exists("lightbox opens on click");
+ });
+
+ test("with non-image file shows file info and download link", async function (assert) {
+ const setting = {
+ setting: "llms_txt",
+ authorized_extensions: "txt",
+ upload: {
+ original_filename: "my-llms-file.txt",
+ human_filesize: "4.68 KB",
+ },
+ };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value="/uploads/default/original/1X/abc123.txt"
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert.dom(".file-uploader").hasClass("has-file", "file present");
+ assert.dom(".file-uploader").doesNotHaveClass("has-image", "not an image");
+ assert
+ .dom(".file-info")
+ .exists("non-images show file details instead of preview");
+ assert.dom(".file-icon").exists("visual indicator of file type");
+ assert
+ .dom(".file-name")
+ .hasText("my-llms-file.txt", "displays original filename from metadata");
+ assert.dom(".file-size").hasText("4.68 KB", "displays file size");
+ assert.dom(".download-btn").exists("user can retrieve file contents");
+ assert
+ .dom(".download-btn")
+ .hasAttribute(
+ "download",
+ "my-llms-file.txt",
+ "triggers download vs navigation"
+ );
+ assert
+ .dom(".download-btn")
+ .hasAttribute("target", "_blank", "opens in new tab");
+ assert
+ .dom(".download-btn")
+ .hasAttribute(
+ "rel",
+ "nofollow ugc noopener noreferrer",
+ "security attributes present"
+ );
+ assert.dom(".lightbox").doesNotExist("no preview for non-images");
+ });
+
+ test("without file shows upload control", async function (assert) {
+ const setting = { setting: "logo" };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value=""
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert.dom(".file-uploader").hasClass("no-file", "empty state styling");
+ assert.dom(".d-icon-upload").exists("can upload file");
+ assert.dom(".d-icon-trash-can").doesNotExist("nothing to delete");
+ assert.dom(".lightbox").doesNotExist("nothing to preview");
+ assert.dom(".file-info").doesNotExist("no file to show info for");
+ });
+
+ test("accepts only images by default", async function (assert) {
+ const setting = { setting: "logo" };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value=""
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert
+ .dom("[id$='__input']")
+ .hasAttribute("accept", "image/*", "restricts to images for security");
+ });
+
+ test("uses authorized_extensions when specified", async function (assert) {
+ const setting = { setting: "llms_txt", authorized_extensions: "txt|json" };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value=""
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert
+ .dom("[id$='__input']")
+ .hasAttribute(
+ "accept",
+ ".txt,.json",
+ "converts pipe-separated extensions to HTML accept format"
+ );
+ });
+
+ test("delete button calls changeValueCallback with null", async function (assert) {
+ const setting = { setting: "logo" };
+ let callbackValue = "not called";
+ this.set("handleChange", (value) => (callbackValue = value));
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value="/images/logo.png"
+ @changeValueCallback={{this.handleChange}}
+ />
+ </template>
+ );
+
+ await click(".btn-danger");
+
+ assert.strictEqual(callbackValue, null, "signals removal to parent");
+ });
+
+ test("shows upload restrictions when configured", async function (assert) {
+ const setting = {
+ setting: "llms_txt",
+ authorized_extensions: "txt|json",
+ max_file_size_kb: 512,
+ };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value=""
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".file-uploader__restrictions")
+ .exists("displays restrictions info when configured");
+ assert
+ .dom(".file-uploader__restrictions")
+ .includesText(".txt", "shows accepted extensions");
+ assert
+ .dom(".file-uploader__restrictions")
+ .includesText("512 KB", "shows max file size");
+ });
+
+ test("does not show restrictions for default image uploads", async function (assert) {
+ const setting = { setting: "logo" };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value=""
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".file-uploader__restrictions")
+ .doesNotExist("no restrictions for standard image uploads");
+ });
+
+ test("applies background-size cover for welcome_banner_image", async function (assert) {
+ const setting = { setting: "welcome_banner_image" };
+
+ await render(
+ <template>
+ <SiteSettingUpload
+ @setting={{setting}}
+ @value="/images/banner.png"
+ @changeValueCallback={{this.noop}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".file-uploader__preview")
+ .hasClass("--bg-size-cover", "banner images use cover sizing");
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/uppy-image-uploader-test.gjs b/frontend/discourse/tests/integration/components/uppy-image-uploader-test.gjs
index d6d9dd151fb..155d8b49797 100644
--- a/frontend/discourse/tests/integration/components/uppy-image-uploader-test.gjs
+++ b/frontend/discourse/tests/integration/components/uppy-image-uploader-test.gjs
@@ -90,24 +90,24 @@ module("Integration | Component | uppy-image-uploader", function (hooks) {
};
};
- const leave1 = await dropImage("#uploader1 .uploaded-image-preview");
+ const leave1 = await dropImage("#uploader1 .file-uploader__preview");
assert
- .dom("#uploader1 .uploaded-image-preview")
+ .dom("#uploader1 .file-uploader__preview")
.hasClass("uppy-is-drag-over");
assert
- .dom("#uploader2 .uploaded-image-preview")
+ .dom("#uploader2 .file-uploader__preview")
.hasNoClass("uppy-is-drag-over");
await leave1();
- await dropImage("#uploader2 .uploaded-image-preview");
+ await dropImage("#uploader2 .file-uploader__preview");
assert
- .dom("#uploader2 .uploaded-image-preview")
+ .dom("#uploader2 .file-uploader__preview")
.hasClass("uppy-is-drag-over");
assert
- .dom("#uploader1 .uploaded-image-preview")
+ .dom("#uploader1 .file-uploader__preview")
.hasNoClass("uppy-is-drag-over");
});
diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rb
index 0d9fa8fd00d..ec5b031c8b3 100644
--- a/lib/site_setting_extension.rb
+++ b/lib/site_setting_extension.rb
@@ -392,6 +392,18 @@ module SiteSettingExtension
default = default_uploads[default.to_i]
end
+ # For upload type settings, include the upload metadata
+ # public_send returns the Upload object directly (not a URL string)
+ upload_metadata = nil
+ if type_hash[:type].to_s == "upload" && value.is_a?(Upload)
+ upload_metadata = {
+ original_filename: value.original_filename,
+ human_filesize: value.human_filesize,
+ width: value.width,
+ height: value.height,
+ }
+ end
+
# For uploads nested in objects type, hydrate upload IDs to URLs
if type_hash[:type].to_s == "objects" && type_hash[:schema]
parsed_value = JSON.parse(value)
@@ -431,6 +443,7 @@ module SiteSettingExtension
end
opts[:plugin] = plugins[s] if plugins[s]
+ opts[:upload] = upload_metadata if upload_metadata
opts
end
diff --git a/lib/site_settings/type_supervisor.rb b/lib/site_settings/type_supervisor.rb
index 7d4ad239e44..08ec948849c 100644
--- a/lib/site_settings/type_supervisor.rb
+++ b/lib/site_settings/type_supervisor.rb
@@ -23,6 +23,8 @@ class SiteSettings::TypeSupervisor
schema
requires_confirmation
depends_on
+ authorized_extensions
+ max_file_size_kb
].freeze
VALIDATOR_OPTS = %i[min max regex hidden regex_error json_schema schema].freeze
@@ -101,6 +103,8 @@ class SiteSettings::TypeSupervisor
@textareas = {}
@json_schemas = {}
@schemas = {}
+ @authorized_extensions = {}
+ @max_file_size_kb = {}
@dependencies = SiteSettings::DependencyGraph.new
end
@@ -110,6 +114,8 @@ class SiteSettings::TypeSupervisor
name = name_arg.to_sym
@textareas[name] = opts[:textarea] if opts[:textarea]
+ @authorized_extensions[name] = opts[:authorized_extensions] if opts[:authorized_extensions]
+ @max_file_size_kb[name] = opts[:max_file_size_kb] if opts[:max_file_size_kb]
@json_schemas[name] = opts[:json_schema].constantize if opts[:json_schema]
@schemas[name] = opts[:schema] if opts[:schema]
@@ -220,6 +226,10 @@ class SiteSettings::TypeSupervisor
result[:list_type] = @list_type[name] if @list_type.has_key? name
result[:textarea] = @textareas[name] if @textareas.has_key? name
result[:schema] = @schemas[name] if @schemas.has_key? name
+ result[:authorized_extensions] = @authorized_extensions[
+ name
+ ] if @authorized_extensions.has_key? name
+ result[:max_file_size_kb] = @max_file_size_kb[name] if @max_file_size_kb.has_key? name
if @json_schemas.has_key?(name) && json_klass = json_schema_class(name)
result[:json_schema] = json_klass.schema
diff --git a/lib/upload_creator.rb b/lib/upload_creator.rb
index 33cc2775a16..4f3682b7cdb 100644
--- a/lib/upload_creator.rb
+++ b/lib/upload_creator.rb
@@ -647,6 +647,7 @@ class UploadCreator
@upload.for_theme = true if @opts[:for_theme]
@upload.for_export = true if @opts[:for_export]
@upload.for_site_setting = true if @opts[:for_site_setting]
+ @upload.site_setting_name = @opts[:site_setting_name] if @opts[:site_setting_name]
@upload.for_gravatar = true if @opts[:for_gravatar]
end
diff --git a/lib/validators/upload_validator.rb b/lib/validators/upload_validator.rb
index d85068a1d18..77ab7ce7a7a 100644
--- a/lib/validators/upload_validator.rb
+++ b/lib/validators/upload_validator.rb
@@ -16,10 +16,7 @@ class UploadValidator < ActiveModel::Validator
extension = File.extname(upload.original_filename)[1..-1] || ""
- if upload.for_site_setting && upload.user&.staff? &&
- FileHelper.is_supported_image?(upload.original_filename)
- return true
- end
+ return validate_site_setting_upload(upload, extension) if upload.for_site_setting
if upload.for_gravatar && FileHelper.supported_gravatar_extensions.include?(extension)
maximum_image_file_size(upload)
@@ -39,6 +36,37 @@ class UploadValidator < ActiveModel::Validator
end
end
+ def validate_site_setting_upload(upload, extension)
+ unless upload.user&.staff?
+ upload.errors.add(:base, I18n.t("upload.unauthorized"))
+ return false
+ end
+
+ setting_opts = site_setting_type_hash(upload.site_setting_name)
+ authorized_extensions = setting_opts[:authorized_extensions]
+
+ if authorized_extensions.present?
+ unless extension_allowed_for_site_setting?(extension, authorized_extensions)
+ upload.errors.add(
+ :original_filename,
+ I18n.t("upload.unauthorized", authorized_extensions: authorized_extensions),
+ )
+ return false
+ end
+
+ validate_site_setting_file_size(upload, setting_opts)
+ else
+ unless FileHelper.is_supported_image?(upload.original_filename)
+ upload.errors.add(:original_filename, I18n.t("upload.images_only"))
+ return false
+ end
+
+ validate_site_setting_file_size(upload, setting_opts)
+ end
+
+ upload.errors.empty?
+ end
+
# this should only be run on existing records, and covers cases of
# upload.update_secure_status being run outside of the creation flow,
# where some cases e.g. have exemptions on the extension enforcement
@@ -71,6 +99,38 @@ class UploadValidator < ActiveModel::Validator
private
+ def site_setting_type_hash(setting_name)
+ return {} if setting_name.blank?
+ SiteSetting.type_supervisor.type_hash(setting_name.to_sym)
+ end
+
+ def validate_site_setting_file_size(upload, setting_opts)
+ return if !upload.validate_file_size
+
+ max_size_kb = setting_opts[:max_file_size_kb]
+
+ if max_size_kb.present?
+ max_size_bytes = max_size_kb.to_i.kilobytes
+ if upload.filesize > max_size_bytes
+ upload.errors.add(
+ :filesize,
+ I18n.t(
+ "upload.attachments.too_large_humanized",
+ max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size_bytes),
+ ),
+ )
+ end
+ elsif FileHelper.is_supported_image?(upload.original_filename)
+ maximum_image_file_size(upload)
+ else
+ maximum_attachment_file_size(upload)
+ end
+ end
+
+ def extension_allowed_for_site_setting?(extension, authorized_extensions)
+ extensions_to_set(authorized_extensions).include?(extension.downcase)
+ end
+
def extensions_to_set(exts)
extensions = Set.new
diff --git a/spec/lib/site_settings/type_supervisor_spec.rb b/spec/lib/site_settings/type_supervisor_spec.rb
index 0162301ca6a..7a461bc78ab 100644
--- a/spec/lib/site_settings/type_supervisor_spec.rb
+++ b/spec/lib/site_settings/type_supervisor_spec.rb
@@ -554,6 +554,52 @@ RSpec.describe SiteSettings::TypeSupervisor do
expect(settings.type_supervisor.type_hash(:type_int)[:min]).to eq(-10)
expect(settings.type_supervisor.type_hash(:type_int)[:max]).to eq(10)
end
+
+ it "returns authorized_extensions for upload type" do
+ settings.setting(
+ :type_upload_with_extensions,
+ "",
+ type: "upload",
+ authorized_extensions: ".txt",
+ )
+ settings.refresh!
+
+ hash = settings.type_supervisor.type_hash(:type_upload_with_extensions)
+ expect(hash[:type]).to eq "upload"
+ expect(hash[:authorized_extensions]).to eq ".txt"
+ end
+
+ it "does not return authorized_extensions when not specified" do
+ settings.setting(:type_upload_no_extensions, "", type: "upload")
+ settings.refresh!
+
+ hash = settings.type_supervisor.type_hash(:type_upload_no_extensions)
+ expect(hash[:type]).to eq "upload"
+ expect(hash[:authorized_extensions]).to be_nil
+ end
+
+ it "returns max_file_size_kb for upload type" do
+ settings.setting(
+ :type_upload_with_max_size,
+ "",
+ type: "upload",
+ authorized_extensions: ".txt",
+ max_file_size_kb: 512,
+ )
+ settings.refresh!
+
+ hash = settings.type_supervisor.type_hash(:type_upload_with_max_size)
+ expect(hash[:type]).to eq "upload"
+ expect(hash[:max_file_size_kb]).to eq 512
+ end
+
+ it "does not return max_file_size_kb when not specified" do
+ settings.setting(:type_upload_no_max_size, "", type: "upload")
+ settings.refresh!
+
+ hash = settings.type_supervisor.type_hash(:type_upload_no_max_size)
+ expect(hash[:max_file_size_kb]).to be_nil
+ end
end
describe "list type with enum class" do
diff --git a/spec/lib/upload_creator_spec.rb b/spec/lib/upload_creator_spec.rb
index d5589a2c9a0..259a9452669 100644
--- a/spec/lib/upload_creator_spec.rb
+++ b/spec/lib/upload_creator_spec.rb
@@ -4,6 +4,7 @@ require "file_store/s3_store"
RSpec.describe UploadCreator do
fab!(:user)
+ fab!(:admin)
describe "#create_for" do
describe "when upload is not an image" do
@@ -207,7 +208,7 @@ RSpec.describe UploadCreator do
large_filename,
for_site_setting: true,
force_optimize: true,
- ).create_for(user.id)
+ ).create_for(admin.id)
expect(upload.extension).to eq("png")
expect(File.extname(upload.url)).to eq(".png")
@@ -468,7 +469,7 @@ RSpec.describe UploadCreator do
file_from_fixtures(filename),
filename,
for_site_setting: true,
- ).create_for(user.id)
+ ).create_for(admin.id)
expect(upload.secure).to eq(false)
upload.destroy!
diff --git a/spec/lib/validators/upload_validator_spec.rb b/spec/lib/validators/upload_validator_spec.rb
index edf581e80f7..ce1d1e1b893 100644
--- a/spec/lib/validators/upload_validator_spec.rb
+++ b/spec/lib/validators/upload_validator_spec.rb
@@ -81,32 +81,137 @@ RSpec.describe UploadValidator do
end
describe "upload for site settings" do
- fab!(:user, :admin)
+ fab!(:admin)
+ fab!(:user)
let(:upload) do
- Fabricate.build(:upload, user: user, original_filename: "test.ico", for_site_setting: true)
+ Fabricate.build(:upload, user: admin, original_filename: "test.png", for_site_setting: true)
end
- before { SiteSetting.authorized_extensions = "png" }
+ it "allows image uploads for staff" do
+ expect(validator.validate(upload)).to eq(true)
+ end
+
+ it "rejects non-image uploads when no authorized_extensions specified" do
+ upload.original_filename = "test.txt"
+ validator.validate(upload)
+ expect(upload.errors[:original_filename]).to include(I18n.t("upload.images_only"))
+ end
- describe "for admin user" do
- it "should allow the upload" do
+ it "rejects uploads from non-staff users" do
+ upload.user = user
+ validator.validate(upload)
+ expect(upload.errors[:base]).to include(I18n.t("upload.unauthorized"))
+ end
+
+ it "validates image file size" do
+ SiteSetting.max_image_size_kb = 1
+ upload.filesize = 10.kilobytes
+ validator.validate(upload)
+ expect(upload.errors[:filesize]).to be_present
+ end
+
+ context "with authorized_extensions" do
+ before do
+ upload.site_setting_name = "test_setting"
+ SiteSetting
+ .type_supervisor
+ .stubs(:type_hash)
+ .with(:test_setting)
+ .returns({ type: "upload", authorized_extensions: "txt|md" })
+ end
+
+ it "allows matching extensions" do
+ upload.original_filename = "file.txt"
+ expect(validator.validate(upload)).to eq(true)
+
+ upload.original_filename = "file.md"
expect(validator.validate(upload)).to eq(true)
end
- describe "when filename is invalid" do
- it "should not allow the upload" do
- upload.original_filename = "test.txt"
- expect(validator.validate(upload)).to eq(nil)
- end
+ it "rejects non-matching extensions" do
+ upload.original_filename = "script.js"
+ validator.validate(upload)
+ expect(upload.errors[:original_filename]).to include(
+ I18n.t("upload.unauthorized", authorized_extensions: "txt|md"),
+ )
+ end
+
+ it "validates attachment file size for non-images" do
+ SiteSetting.max_attachment_size_kb = 1
+ upload.original_filename = "file.txt"
+ upload.filesize = 10.kilobytes
+ validator.validate(upload)
+ expect(upload.errors[:filesize]).to be_present
+ end
+
+ it "validates image file size for images" do
+ SiteSetting
+ .type_supervisor
+ .stubs(:type_hash)
+ .with(:test_setting)
+ .returns({ type: "upload", authorized_extensions: "png" })
+ SiteSetting.max_image_size_kb = 1
+ upload.original_filename = "image.png"
+ upload.filesize = 10.kilobytes
+ validator.validate(upload)
+ expect(upload.errors[:filesize]).to be_present
end
end
- describe "for normal user" do
- fab!(:user)
+ context "with site_setting_name but no authorized_extensions" do
+ before do
+ upload.site_setting_name = "image_only_setting"
+ SiteSetting
+ .type_supervisor
+ .stubs(:type_hash)
+ .with(:image_only_setting)
+ .returns({ type: "upload" })
+ end
+
+ it "falls back to images only" do
+ upload.original_filename = "test.txt"
+ validator.validate(upload)
+ expect(upload.errors[:original_filename]).to include(I18n.t("upload.images_only"))
+ end
+ end
- it "should not allow the upload" do
- expect(validator.validate(upload)).to eq(nil)
+ context "with max_file_size_kb" do
+ before do
+ upload.site_setting_name = "limited_upload"
+ upload.original_filename = "file.txt"
+ end
+
+ it "enforces the setting-specific file size limit" do
+ SiteSetting
+ .type_supervisor
+ .stubs(:type_hash)
+ .with(:limited_upload)
+ .returns({ type: "upload", authorized_extensions: "txt", max_file_size_kb: 5 })
+ upload.filesize = 10.kilobytes
+ validator.validate(upload)
+ expect(upload.errors[:filesize]).to be_present
+ end
+
+ it "allows files within the limit" do
+ SiteSetting
+ .type_supervisor
+ .stubs(:type_hash)
+ .with(:limited_upload)
+ .returns({ type: "upload", authorized_extensions: "txt", max_file_size_kb: 100 })
+ upload.filesize = 50.kilobytes
+ expect(validator.validate(upload)).to eq(true)
+ end
+
+ it "uses setting limit instead of global attachment limit" do
+ SiteSetting.max_attachment_size_kb = 1
+ SiteSetting
+ .type_supervisor
+ .stubs(:type_hash)
+ .with(:limited_upload)
+ .returns({ type: "upload", authorized_extensions: "txt", max_file_size_kb: 100 })
+ upload.filesize = 50.kilobytes
+ expect(validator.validate(upload)).to eq(true)
end
end
end
diff --git a/spec/system/edit_category_images_spec.rb b/spec/system/edit_category_images_spec.rb
index 5bacf53950f..98ac868ab02 100644
--- a/spec/system/edit_category_images_spec.rb
+++ b/spec/system/edit_category_images_spec.rb
@@ -18,7 +18,7 @@ describe "Edit Category Images", type: :system do
it "displays and updates new counter" do
category_page.visit_images(category)
- find("#category-logo-uploader .image-upload-controls").click
+ find("#category-logo-uploader .file-uploader__controls").click
attach_file(
"category-logo-uploader__input",
"#{Rails.root}/spec/fixtures/images/logo.png",
@@ -26,7 +26,7 @@ describe "Edit Category Images", type: :system do
)
expect(page).to have_content("uploaded successfully").or have_css(
- ".has-image .uploaded-image-preview.input-xxlarge",
+ ".has-image .file-uploader__preview.input-xxlarge",
)
upload = Upload.last
diff --git a/spec/system/page_objects/components/admin_about_config_area_general_settings_card.rb b/spec/system/page_objects/components/admin_about_config_area_general_settings_card.rb
index 08840640916..dbd788b9548 100644
--- a/spec/system/page_objects/components/admin_about_config_area_general_settings_card.rb
+++ b/spec/system/page_objects/components/admin_about_config_area_general_settings_card.rb
@@ -20,7 +20,7 @@ module PageObjects
end
def banner_image_uploader
- PageObjects::Components::UppyImageUploader.new(card.find(".image-uploader"))
+ PageObjects::Components::UppyImageUploader.new(card.find(".file-uploader"))
end
def submit
diff --git a/spec/system/page_objects/components/form_kit.rb b/spec/system/page_objects/components/form_kit.rb
index 276c0c806e6..80dc89f26fa 100644
--- a/spec/system/page_objects/components/form_kit.rb
+++ b/spec/system/page_objects/components/form_kit.rb
@@ -45,7 +45,7 @@ module PageObjects
when "composer", "textarea"
component.find("textarea").value
when "image"
- url = component.find(".uploaded-image-preview a.lightbox", wait: 10)[:href]
+ url = component.find(".file-uploader__preview a.lightbox", wait: 10)[:href]
sha1 = url.match(/(\h{40})/).captures.first
Upload.find_by(sha1:)
when "toggle"
@@ -180,7 +180,7 @@ module PageObjects
def upload_image(image_path)
if control_type == "image"
attach_file(image_path) do
- component.find(".image-upload-controls .btn.btn-default").click
+ component.find(".file-uploader__controls .btn.btn-default").click
end
else
raise "'upload_image' is not supported for control type: #{control_type}"
diff --git a/spec/system/page_objects/pages/admin_badges.rb b/spec/system/page_objects/pages/admin_badges.rb
index 73739d294a5..0f59d3ef977 100644
--- a/spec/system/page_objects/pages/admin_badges.rb
+++ b/spec/system/page_objects/pages/admin_badges.rb
@@ -49,7 +49,7 @@ module PageObjects
form.choose_conditional("upload-image")
attach_file(File.absolute_path(file_from_fixtures(name))) do
- form.field("image_url").find(".image-upload-controls .btn").click
+ form.field("image_url").find(".file-uploader__controls .btn").click
end
expect(form.field("image_url")).to have_css(".btn-danger")