1 ## from: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/101949
3 # $Id: rfc2047.rb,v 1.4 2003/04/18 20:55:56 sam Exp $
4 # MODIFIED slightly by William Morgan
6 # An implementation of RFC 2047 decoding.
8 # This module depends on the iconv library by Nobuyoshi Nakada, which I've
9 # heard may be distributed as a standard part of Ruby 1.8. Many thanks to him
10 # for helping with building and using iconv.
12 # Thanks to "Josef 'Jupp' Schugt" <jupp / gmx.de> for pointing out an error with
13 # stateful character sets.
15 # Copyright (c) Sam Roberts <sroberts / uniserve.com> 2004
17 # This file is distributed under the same terms as Ruby.
22 WORD = %r{=\?([!\#$%&'*+-/0-9A-Z\\^\`a-z{|}~]+)\?([BbQq])\?([!->@-~]+)\?=} # :nodoc: 'stupid ruby-mode
23 WORDSEQ = %r{(#{WORD.source})\s+(?=#{WORD.source})}
25 def Rfc2047.is_encoded? s; s =~ WORD end
27 # Decodes a string, +from+, containing RFC 2047 encoded words into a target
28 # character set, +target+. See iconv_open(3) for information on the
29 # supported target encodings. If one of the encoded words cannot be
30 # converted to the target encoding, it is left in its encoded form.
31 def Rfc2047.decode_to(target, from)
32 from = from.gsub(WORDSEQ, '\1')
33 out = from.gsub(WORD) do
35 charset, encoding, text = $1, $2, $3
37 # B64 or QP decode, as necessary:
41 text = text.unpack('m*')[0]
45 # RFC 2047 has a variant of quoted printable where a ' ' character
46 # can be represented as an '_', rather than =32, so convert
47 # any of these that we find before doing the QP decoding.
48 text = text.tr("_", " ")
49 text = text.unpack('M*')[0]
51 # Don't need an else, because no other values can be matched in a
57 # Remember - Iconv.open(to, from)!
58 text = Iconv.iconv(target, charset, text).join