Module: Ultra7::MIME

Defined in:
lib/ultra7/mime.rb

Class Method Summary collapse

Class Method Details

.decode_utf7(text, options = {encoding: nil}) ⇒ String

Parse the given UTF-7 encoded-word text and return the corresponding decoded value.

If the :encoding name is not specified in the options hash, then the resulting string will use the default Encoding.default_external encoding.

Parameters:

  • text (String)

    UTF-7 encoded-word text

  • options (Hash) (defaults to: {encoding: nil})

Returns:

  • (String)

    UTF-7 decoded value

Raises:

  • (ArgumentError)

    if text other than UTF-7 is passed in, or the named :encoding cannot be found



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ultra7/mime.rb', line 23

def self.decode_utf7(text, options={encoding: nil})
  # only deal with UTF-7 encoding
  text.scan(/=\?(.*)\?[q]\?/im).each {
    e = $1
    if e and !(e=~/utf\-7/i)
      raise ArgumentError.new("Cannot decode #{e} as UTF-7!")
    end
  }

  # remove any opening charset and Q-encoding start/end markers
  # for MIME encoded words
  text = text.gsub(/\?=/m, '').gsub(/=\?[^?]*utf\-7\?[q]\?/im, '')

  enc = options[:encoding].nil? \
    ? Encoding.default_external \
    : Encoding.find(options[:encoding])
  
  return text.gsub(/\+(.*?)-/mn) {
    if $1.empty?
      "+"
    else
      base64 = $1
      pad = base64.length % 4
      if pad > 0
        base64 << ("=" * (4-pad))
      end
      base64.unpack("m").first.unpack("n*").pack("U*")
    end
  }.encode(enc)
end