aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_dispatch/http/content_disposition.rb
blob: 58164c15225d8caeae7be588ea11e7f34b5ca645 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

module ActionDispatch
  module Http
    class ContentDisposition # :nodoc:
      def self.format(disposition:, filename:)
        new(disposition: disposition, filename: filename).to_s
      end

      attr_reader :disposition, :filename

      def initialize(disposition:, filename:)
        @disposition = disposition
        @filename = filename
      end

      TRADITIONAL_ESCAPED_CHAR = /[^ A-Za-z0-9!#$+.^_`|~-]/

      def ascii_filename
        'filename="' + percent_escape(I18n.transliterate(filename), TRADITIONAL_ESCAPED_CHAR) + '"'
      end

      RFC_5987_ESCAPED_CHAR = /[^A-Za-z0-9!#$&+.^_`|~-]/

      def utf8_filename
        "filename*=UTF-8''" + percent_escape(filename, RFC_5987_ESCAPED_CHAR)
      end

      def to_s
        if filename
          "#{disposition}; #{ascii_filename}; #{utf8_filename}"
        else
          "#{disposition}"
        end
      end

      private
        def percent_escape(string, pattern)
          string.gsub(pattern) do |char|
            char.bytes.map { |byte| "%%%02X" % byte }.join
          end
        end
    end
  end
end