A platform for community discussion. Free, open, simple.
DEV: Stop converting ICO uploads to PNG (#43671)
Alan Guo Xiang Tan366eb235ccf8
diff --git a/app/controllers/metadata_controller.rb b/app/controllers/metadata_controller.rbindex 0e6e491f267..20c4b2847b5 100644--- a/app/controllers/metadata_controller.rb+++ b/app/controllers/metadata_controller.rb@@ -113,7 +113,7 @@ class MetadataController < ApplicationController}logo = SiteSetting.site_manifest_icon_url- if logo+ if logo.present?icon_entry = {src: UrlHelper.absolute(logo),sizes: "512x512",diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rbindex 79250766527..8ad593b3ca2 100644--- a/app/controllers/static_controller.rb+++ b/app/controllers/static_controller.rb@@ -238,7 +238,9 @@ class StaticController < ApplicationControllerresponse.headers["Expires"] = 1.year.from_now.httpdateresponse.headers["Content-Length"] = data.bytesize.to_sresponse.headers["Last-Modified"] = Time.new(2000, 01, 01).httpdate- render body: data, content_type: "image/png"+ content_type =+ MiniMime.lookup_by_filename(SiteIconManager.favicon_url)&.content_type || "image/png"+ render body: data, content_type: content_typeendendenddiff --git a/app/models/optimized_image.rb b/app/models/optimized_image.rbindex 35f563403e0..24d35d32c5c 100644--- a/app/models/optimized_image.rb+++ b/app/models/optimized_image.rb@@ -195,7 +195,7 @@ class OptimizedImage < ActiveRecord::Basepaths.each { |path| raise Discourse::InvalidAccess unless safe_path?(path) }end- IM_DECODERS = /\A(jpe?g|png|ico|gif|webp|avif|svg)\z/i+ IM_DECODERS = /\A(jpe?g|png|gif|webp|avif|svg)\z/idef self.prepend_decoder!(path, ext_path = nil, opts = nil)opts ||= {}diff --git a/app/models/upload.rb b/app/models/upload.rbindex 486d8731994..ac9de820916 100644--- a/app/models/upload.rb+++ b/app/models/upload.rb@@ -382,8 +382,8 @@ class Upload < ActiveRecord::Basedef calculate_dominant_color!(local_path = nil)color = nil- color = "" if !FileHelper.is_supported_image?("image.#{extension}") || extension == "svg" ||- (GlobalSetting.enable_vips_image_processing && extension == "ico")+ color = "" if !FileHelper.is_supported_image?("image.#{extension}") ||+ %w[svg ico].include?(extension)if color.nil?local_path ||=diff --git a/app/views/layouts/_head.html.erb b/app/views/layouts/_head.html.erbindex 5995b84ad6c..6cfce07cad8 100644--- a/app/views/layouts/_head.html.erb+++ b/app/views/layouts/_head.html.erb@@ -1,6 +1,6 @@<meta name="generator" content="Discourse <%= Discourse::VERSION::STRING %> - https://github.com/discourse/discourse version <%= Discourse.git_version %>"><%- if SiteSetting.site_favicon_url.present? %>-<link rel="icon" type="image/png" href="<%=SiteSetting.site_favicon_url%>">+<link rel="icon" type="<%= MiniMime.lookup_by_filename(SiteSetting.site_favicon_url)&.content_type || "image/png" %>" href="<%=SiteSetting.site_favicon_url%>"><%- end %><% site_apple_touch_icon_url = SiteSetting.site_apple_touch_icon_url %><%- if site_apple_touch_icon_url.present? %>diff --git a/config/imagemagick/policy.xml b/config/imagemagick/policy.xmlindex a29d02c021b..c4aac049b08 100644--- a/config/imagemagick/policy.xml+++ b/config/imagemagick/policy.xml@@ -28,7 +28,7 @@<!-- deny all coders, then allow only the formats Discourse uses --><policy domain="coder" rights="none" pattern="*"/><!-- upload/thumbnail raster formats -->- <policy domain="coder" rights="read|write" pattern="{GIF,JPEG,JPG,PNG,WEBP,AVIF,ICO}"/>+ <policy domain="coder" rights="read|write" pattern="{GIF,JPEG,JPG,PNG,WEBP,AVIF}"/><!-- HEIC/HEIF: UploadCreator#convert_heif! transcodes to JPEG --><policy domain="coder" rights="read|write" pattern="{HEIC,HEIF}"/><!-- MSVG: SVG dimension reads; the plain SVG coder stays denied -->diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 5c55e14b415..0cda5346fb5 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -5342,6 +5342,7 @@ en:file_missing: "Sorry, you must provide a file to upload."empty: "Sorry, but the file you provided is empty."failed: "Sorry, but your upload failed. Please try again."+ ico_as_avatar: "Sorry, ICO images cannot be used as avatars."png_to_jpg_conversion_failure_message: "An error happened when converting from PNG to JPG."optimize_failure_message: "An error occurred while optimizing the uploaded image."download_failure: "Downloading the file from the external provider failed."diff --git a/frontend/discourse/admin/components/admin-logo-form.gjs b/frontend/discourse/admin/components/admin-logo-form.gjsindex a48f2b91490..e76200e958d 100644--- a/frontend/discourse/admin/components/admin-logo-form.gjs+++ b/frontend/discourse/admin/components/admin-logo-form.gjs@@ -1,6 +1,6 @@import Component from "@glimmer/component";import { cached, tracked } from "@glimmer/tracking";-import { fn } from "@ember/helper";+import { fn, hash } from "@ember/helper";import { action } from "@ember/object";import { trackedObject } from "@ember/reactive/collections";import { service } from "@ember/service";@@ -187,6 +187,10 @@ export default class AdminLogoForm extends Component {as |field|><field.Control+ @additionalParams={{hash+ for_site_setting=true+ site_setting_name="favicon"+ }}@placeholderUrl={{this.placeholders.favicon}}@type="branding"/>diff --git a/frontend/discourse/app/form-kit/components/fk/control/image.gjs b/frontend/discourse/app/form-kit/components/fk/control/image.gjsindex d1424d4dcf1..6a1b9629d63 100644--- a/frontend/discourse/app/form-kit/components/fk/control/image.gjs+++ b/frontend/discourse/app/form-kit/components/fk/control/image.gjs@@ -23,6 +23,7 @@ export default class FKControlImage extends FKBaseControl {<template><UppyImageUploaderclass="form-kit__control-image no-repeat contain-image"+ @additionalParams={{@additionalParams}}@disabled={{@field.disabled}}@id="{{@field.id}}-{{@field.name}}"@imageUrl={{this.imageUrl}}diff --git a/lib/upload_creator.rb b/lib/upload_creator.rbindex 40b03b6e79f..4e61d770746 100644--- a/lib/upload_creator.rb+++ b/lib/upload_creator.rb@@ -81,6 +81,12 @@ class UploadCreatorrescue StandardErrornilend++ if @opts[:type] == "avatar" && @image_info&.type == :ico+ @upload.errors.add(:base, I18n.t("upload.ico_as_avatar"))+ return @upload+ end+is_image = FileHelper.is_supported_image?(@filename)is_image ||= @image_info && FileHelper.is_supported_image?("test.#{@image_info.type}")is_image = false if @opts[:for_theme]@@ -106,9 +112,7 @@ class UploadCreatorif @image_info.type == :svgclean_svg!- elsif @image_info.type == :ico- convert_favicon_to_png!- elsif !Rails.env.test? || @opts[:force_optimize]+ elsif @image_info.type != :ico && (!Rails.env.test? || @opts[:force_optimize])convert_heif! if %i[heic heif].include?(@image_info.type)convert_to_jpeg! if convert_png_to_jpeg? || should_alter_quality?fix_orientation! if should_fix_orientation?@@ -343,36 +347,6 @@ class UploadCreatorMIN_CONVERT_TO_JPEG_BYTES_SAVED = 75_000MIN_CONVERT_TO_JPEG_SAVING_RATIO = 0.70- def convert_favicon_to_png!- png_tempfile = Tempfile.new(%w[image .png])-- from = @file.path- to = png_tempfile.path-- OptimizedImage.ensure_safe_paths!(from, to)-- from = OptimizedImage.prepend_decoder!(from, nil, filename: "image.#{@image_info.type}")- to = OptimizedImage.prepend_decoder!(to)-- from = "#{from}[-1]" # We only want the last(largest) image of the .ico file-- opts = { flatten: false } # Preserve transparency-- read = [@file.path]- write = [File.dirname(png_tempfile.path)]-- begin- execute_convert(from, to, opts, read:, write:)- rescue StandardError- # retry with debugging enabled- execute_convert(from, to, opts.merge(debug: true), read:, write:)- end-- @file.respond_to?(:close!) ? @file.close! : @file.close- @file = png_tempfile- extract_image_info!- end-def convert_to_jpeg!return if @opts[:type] == "topic_og_image"return if @opts[:for_site_setting] || ADMIN_ASSET_TYPES.include?(@opts[:type])diff --git a/spec/lib/upload_creator_spec.rb b/spec/lib/upload_creator_spec.rbindex 5b3d2be2549..7da7349a2fc 100644--- a/spec/lib/upload_creator_spec.rb+++ b/spec/lib/upload_creator_spec.rb@@ -916,21 +916,29 @@ RSpec.describe UploadCreator doendend- context "when the upload is an ICO favicon" do+ context "when the file contains an ICO image" dolet(:filename) { "smallest.ico" }let(:file) { file_from_fixtures(filename, "images") }before { SiteSetting.authorized_extensions = "png|jpg|ico" }- it "stores it as a PNG" do+ it "stores the original file without conversion" do+ original_contents = File.binread(file.path)+upload = described_class.new(file, filename).create_for(user.id)stored_path = Discourse.store.path_for(upload)expect(upload).to be_persisted- expect(upload.extension).to eq("png")- expect(upload.original_filename).to eq("smallest.png")- expect(FastImage.type(stored_path)).to eq(:png)- expect(FastImage.size(stored_path)).to eq([1, 1])+ expect(upload.extension).to eq("ico")+ expect(upload.original_filename).to eq(filename)+ expect(File.binread(stored_path)).to eq(original_contents)+ end++ it "rejects ICO images for avatar uploads" do+ upload = described_class.new(file, filename, type: "avatar").create_for(user.id)++ expect(upload).not_to be_persisted+ expect(upload.errors.full_messages).to contain_exactly(I18n.t("upload.ico_as_avatar"))endenddiff --git a/spec/models/optimized_image_spec.rb b/spec/models/optimized_image_spec.rbindex 1dcccfc880b..3da4ce05651 100644--- a/spec/models/optimized_image_spec.rb+++ b/spec/models/optimized_image_spec.rb@@ -245,6 +245,17 @@ RSpec.describe OptimizedImage doenddescribe ".create_for" do+ it "returns nil for an ICO upload" do+ upload.extension = "ico"+ optimized_image = nil++ expect { optimized_image = described_class.create_for(upload, 10, 10) }.not_to change(+ OptimizedImage,+ :count,+ )+ expect(optimized_image).to be_nil+ end+context "with versioning" dolet(:filename) { "logo.png" }let(:file) { file_from_fixtures(filename) }diff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rbindex c3bea94e064..965f2e62f7e 100644--- a/spec/models/upload_spec.rb+++ b/spec/models/upload_spec.rb@@ -1060,8 +1060,6 @@ RSpec.describe Upload doendit "stores an empty dominant color for ICO images" do- global_setting :enable_vips_image_processing, true-expect(ico_image.dominant_color(calculate_if_missing: true)).to eq("")expect(ico_image.dominant_color).to eq("")enddiff --git a/spec/requests/metadata_controller_spec.rb b/spec/requests/metadata_controller_spec.rbindex b6ca1a8bbbc..c614aa2057d 100644--- a/spec/requests/metadata_controller_spec.rb+++ b/spec/requests/metadata_controller_spec.rb@@ -80,6 +80,21 @@ RSpec.describe MetadataController doexpect(manifest["icons"].first["type"]).to eq("image/png")end+ it "returns a manifest without icons when the configured icon is an ICO image" do+ ico =+ UploadCreator.new(+ file_from_fixtures("smallest.ico", "images"),+ "smallest.ico",+ for_site_setting: true,+ ).create_for(Discourse.system_user.id)+ SiteSetting.manifest_icon = ico++ get "/manifest.webmanifest"++ expect(response.status).to eq(200)+ expect(JSON.parse(response.body)["icons"]).to be_empty+ end+it "defaults to display standalone for Android" doget "/manifest.webmanifest",params: {diff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rbindex 3ac945c64d4..d0daaceb834 100644--- a/spec/requests/static_controller_spec.rb+++ b/spec/requests/static_controller_spec.rb@@ -40,6 +40,22 @@ RSpec.describe StaticController doexpect(response.media_type).to eq("image/png")expect(response.body.bytesize).to eq(upload.filesize)end++ it "serves the original ICO favicon with its content type" do+ ico =+ UploadCreator.new(+ file_from_fixtures("smallest.ico", "images"),+ "smallest.ico",+ for_site_setting: true,+ ).create_for(Discourse.system_user.id)+ SiteSetting.favicon = ico++ get "/favicon/proxied"++ expect(response.status).to eq(200)+ expect(response.media_type).to eq("image/vnd.microsoft.icon")+ expect(response.body.b).to eq(File.binread(file_from_fixtures("smallest.ico", "images")))+ endendcontext "with external store" dodiff --git a/spec/system/admin_logo_spec.rb b/spec/system/admin_logo_spec.rbindex f4191179744..2a5d3d34481 100644--- a/spec/system/admin_logo_spec.rb+++ b/spec/system/admin_logo_spec.rb@@ -61,6 +61,20 @@ describe "Admin Logo Page" doprimary_section_logos.each { |image_type| expect(SiteSetting.send(image_type)).to eq(nil) }end++ it "lets an administrator upload an ICO favicon" do+ logo_page.visit+ logo_page.form.upload_image(:favicon, file_from_fixtures("smallest.ico", "images"))++ expect(logo_page.form.image_uploader(:favicon)).to have_uploaded_image++ logo_page.form.submit+ expect(logo_page.form).to have_saved_successfully++ logo_page.visit++ expect(logo_page.form.image_uploader(:favicon)).to have_uploaded_image+ endenddescribe "mobile section" do