blob: cc02f5e131e5614279cef15437537e0854d4f641 [file] [log] [blame]
Barry Warsaw409a4c02002-04-10 21:01:31 +00001# Copyright (C) 2001,2002 Python Software Foundation
Barry Warsawba925802001-09-23 03:17:28 +00002# Author: barry@zope.com (Barry Warsaw)
3
4"""Miscellaneous utilities.
5"""
6
Barry Warsaw9aa64352001-11-09 17:45:48 +00007import time
Barry Warsaw409a4c02002-04-10 21:01:31 +00008import socket
Barry Warsawba925802001-09-23 03:17:28 +00009import re
Barry Warsaw409a4c02002-04-10 21:01:31 +000010import random
11import os
12import warnings
13from cStringIO import StringIO
14from types import ListType
Barry Warsawba925802001-09-23 03:17:28 +000015
Barry Warsaw409a4c02002-04-10 21:01:31 +000016from rfc822 import unquote, quote
Barry Warsawe1df15c2002-04-12 20:50:05 +000017from rfc822 import AddressList as _AddressList
Barry Warsaw409a4c02002-04-10 21:01:31 +000018from rfc822 import mktime_tz
19
20# We need wormarounds for bugs in these methods in older Pythons (see below)
21from rfc822 import parsedate as _parsedate
22from rfc822 import parsedate_tz as _parsedate_tz
Barry Warsawba925802001-09-23 03:17:28 +000023
Barry Warsaw8c1aac22002-05-19 23:44:19 +000024try:
25 from quopri import decodestring as _qdecode
26except ImportError:
27 # Python 2.1 doesn't have quopri.decodestring()
28 def _qdecode(s):
29 import quopri as _quopri
30
31 if not s:
32 return s
33 hasnewline = (s[-1] == '\n')
34 infp = StringIO(s)
35 outfp = StringIO()
36 _quopri.decode(infp, outfp)
37 value = outfp.getvalue()
38 if not hasnewline and value[-1] =='\n':
39 return value[:-1]
40 return value
41
Barry Warsawba925802001-09-23 03:17:28 +000042import base64
43
44# Intrapackage imports
Barry Warsaw21f77ac2002-06-02 19:07:16 +000045from email.Encoders import _bencode, _qencode
Barry Warsawba925802001-09-23 03:17:28 +000046
47COMMASPACE = ', '
Barry Warsaw12566a82002-06-29 05:58:04 +000048EMPTYSTRING = ''
Barry Warsawba925802001-09-23 03:17:28 +000049UEMPTYSTRING = u''
Barry Warsaw409a4c02002-04-10 21:01:31 +000050CRLF = '\r\n'
51
52specialsre = re.compile(r'[][\()<>@,:;".]')
53escapesre = re.compile(r'[][\()"]')
Barry Warsawba925802001-09-23 03:17:28 +000054
55
Barry Warsawe968ead2001-10-04 17:05:11 +000056
Barry Warsawba925802001-09-23 03:17:28 +000057# Helpers
58
59def _identity(s):
60 return s
61
62
63def _bdecode(s):
64 if not s:
65 return s
66 # We can't quite use base64.encodestring() since it tacks on a "courtesy
67 # newline". Blech!
68 if not s:
69 return s
70 hasnewline = (s[-1] == '\n')
71 value = base64.decodestring(s)
72 if not hasnewline and value[-1] == '\n':
73 return value[:-1]
74 return value
75
76
Barry Warsawe968ead2001-10-04 17:05:11 +000077
Barry Warsaw409a4c02002-04-10 21:01:31 +000078def fix_eols(s):
79 """Replace all line-ending characters with \r\n."""
80 # Fix newlines with no preceding carriage return
81 s = re.sub(r'(?<!\r)\n', CRLF, s)
82 # Fix carriage returns with no following newline
83 s = re.sub(r'\r(?!\n)', CRLF, s)
84 return s
85
86
87
88def formataddr(pair):
89 """The inverse of parseaddr(), this takes a 2-tuple of the form
90 (realname, email_address) and returns the string value suitable
91 for an RFC 2822 From:, To: or Cc:.
Tim Peters8ac14952002-05-23 15:15:30 +000092
Barry Warsaw409a4c02002-04-10 21:01:31 +000093 If the first element of pair is false, then the second element is
94 returned unmodified.
95 """
96 name, address = pair
97 if name:
98 quotes = ''
99 if specialsre.search(name):
100 quotes = '"'
101 name = escapesre.sub(r'\\\g<0>', name)
102 return '%s%s%s <%s>' % (quotes, name, quotes, address)
103 return address
104
105# For backwards compatibility
106def dump_address_pair(pair):
107 warnings.warn('Use email.Utils.formataddr() instead',
108 DeprecationWarning, 2)
109 return formataddr(pair)
110
111
112
Barry Warsawba925802001-09-23 03:17:28 +0000113def getaddresses(fieldvalues):
114 """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
115 all = COMMASPACE.join(fieldvalues)
Barry Warsawe1df15c2002-04-12 20:50:05 +0000116 a = _AddressList(all)
Barry Warsaw4be9ecc2002-05-22 01:52:10 +0000117 return a.addresslist
Barry Warsawba925802001-09-23 03:17:28 +0000118
119
Barry Warsawe968ead2001-10-04 17:05:11 +0000120
Barry Warsawba925802001-09-23 03:17:28 +0000121ecre = re.compile(r'''
122 =\? # literal =?
123 (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
124 \? # literal ?
125 (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
126 \? # literal ?
127 (?P<atom>.*?) # non-greedy up to the next ?= is the atom
128 \?= # literal ?=
129 ''', re.VERBOSE | re.IGNORECASE)
130
131
132def decode(s):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000133 """Return a decoded string according to RFC 2047, as a unicode string.
134
135 NOTE: This function is deprecated. Use Header.decode_header() instead.
136 """
137 warnings.warn('Use Header.decode_header() instead.', DeprecationWarning, 2)
138 # Intra-package import here to avoid circular import problems.
Barry Warsaw21f77ac2002-06-02 19:07:16 +0000139 from email.Header import decode_header
Barry Warsaw409a4c02002-04-10 21:01:31 +0000140 L = decode_header(s)
141 if not isinstance(L, ListType):
142 # s wasn't decoded
143 return s
144
Barry Warsawba925802001-09-23 03:17:28 +0000145 rtn = []
Barry Warsaw409a4c02002-04-10 21:01:31 +0000146 for atom, charset in L:
147 if charset is None:
148 rtn.append(atom)
Barry Warsawba925802001-09-23 03:17:28 +0000149 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000150 # Convert the string to Unicode using the given encoding. Leave
151 # Unicode conversion errors to strict.
152 rtn.append(unicode(atom, charset))
Barry Warsawba925802001-09-23 03:17:28 +0000153 # Now that we've decoded everything, we just need to join all the parts
154 # together into the final string.
155 return UEMPTYSTRING.join(rtn)
156
157
Barry Warsawe968ead2001-10-04 17:05:11 +0000158
Barry Warsawba925802001-09-23 03:17:28 +0000159def encode(s, charset='iso-8859-1', encoding='q'):
160 """Encode a string according to RFC 2047."""
Barry Warsaw409a4c02002-04-10 21:01:31 +0000161 warnings.warn('Use Header.Header.encode() instead.', DeprecationWarning, 2)
Barry Warsawc44d2c52001-12-03 19:26:40 +0000162 encoding = encoding.lower()
163 if encoding == 'q':
Barry Warsawba925802001-09-23 03:17:28 +0000164 estr = _qencode(s)
Barry Warsawc44d2c52001-12-03 19:26:40 +0000165 elif encoding == 'b':
Barry Warsawba925802001-09-23 03:17:28 +0000166 estr = _bencode(s)
167 else:
168 raise ValueError, 'Illegal encoding code: ' + encoding
Barry Warsawc44d2c52001-12-03 19:26:40 +0000169 return '=?%s?%s?%s?=' % (charset.lower(), encoding, estr)
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000170
171
172
173def formatdate(timeval=None, localtime=0):
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000174 """Returns a date string as specified by RFC 2822, e.g.:
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000175
176 Fri, 09 Nov 2001 01:08:47 -0000
177
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000178 Optional timeval if given is a floating point time value as accepted by
179 gmtime() and localtime(), otherwise the current time is used.
180
181 Optional localtime is a flag that when true, interprets timeval, and
182 returns a date relative to the local timezone instead of UTC, properly
183 taking daylight savings time into account.
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000184 """
185 # Note: we cannot use strftime() because that honors the locale and RFC
186 # 2822 requires that day and month names be the English abbreviations.
187 if timeval is None:
188 timeval = time.time()
189 if localtime:
190 now = time.localtime(timeval)
191 # Calculate timezone offset, based on whether the local zone has
192 # daylight savings time, and whether DST is in effect.
193 if time.daylight and now[-1]:
194 offset = time.altzone
195 else:
196 offset = time.timezone
Barry Warsawe5739a62001-11-19 18:36:43 +0000197 hours, minutes = divmod(abs(offset), 3600)
198 # Remember offset is in seconds west of UTC, but the timezone is in
199 # minutes east of UTC, so the signs differ.
200 if offset > 0:
201 sign = '-'
202 else:
203 sign = '+'
204 zone = '%s%02d%02d' % (sign, hours, minutes / 60)
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000205 else:
206 now = time.gmtime(timeval)
207 # Timezone offset is always -0000
208 zone = '-0000'
209 return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
210 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
211 now[2],
212 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
213 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
214 now[0], now[3], now[4], now[5],
215 zone)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000216
217
218
219def make_msgid(idstring=None):
220 """Returns a string suitable for RFC 2822 compliant Message-ID:, e.g:
221
222 <20020201195627.33539.96671@nightshade.la.mastaler.com>
223
224 Optional idstring if given is a string used to strengthen the
225 uniqueness of the Message-ID, otherwise an empty string is used.
226 """
227 timeval = time.time()
228 utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
229 pid = os.getpid()
230 randint = random.randrange(100000)
231 if idstring is None:
232 idstring = ''
233 else:
234 idstring = '.' + idstring
235 idhost = socket.getfqdn()
236 msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
237 return msgid
238
239
240
241# These functions are in the standalone mimelib version only because they've
242# subsequently been fixed in the latest Python versions. We use this to worm
243# around broken older Pythons.
244def parsedate(data):
245 if not data:
246 return None
247 return _parsedate(data)
248
249
250def parsedate_tz(data):
251 if not data:
252 return None
253 return _parsedate_tz(data)
254
255
256def parseaddr(addr):
Barry Warsaw24fd0252002-04-15 22:00:25 +0000257 addrs = _AddressList(addr).addresslist
258 if not addrs:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000259 return '', ''
Barry Warsaw24fd0252002-04-15 22:00:25 +0000260 return addrs[0]
Barry Warsaw12566a82002-06-29 05:58:04 +0000261
262
263
264# RFC2231-related functions - parameter encoding and decoding
265def decode_rfc2231(s):
266 """Decode string according to RFC 2231"""
267 import urllib
268 charset, language, s = s.split("'", 2)
269 s = urllib.unquote(s)
270 return charset, language, s
271
272
273def encode_rfc2231(s, charset=None, language=None):
274 """Encode string according to RFC 2231"""
275 import urllib
276 s = urllib.quote(s, safe='')
277 if charset is None and language is None:
278 return s
279 else:
280 return "%s'%s'%s" % (charset, language, s)
281
282
283rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$')
284
285def decode_params(params):
286 """Decode parameters list according to RFC 2231"""
287 new_params = []
288 # maps parameter's name to a list of continuations
289 rfc2231_params = {}
290 # params is a sequence of 2-tuples containing (content_type, string value)
291 name, value = params[0]
292 new_params.append((name, value))
293 # Cycle through each of the rest of the parameters.
294 for name, value in params[1:]:
295 value = unquote(value)
296 mo = rfc2231_continuation.match(name)
297 if mo:
298 name, num = mo.group('name', 'num')
299 if num is not None:
300 num = int(num)
301 rfc2231_param1 = rfc2231_params.setdefault(name, [])
302 rfc2231_param1.append((num, value))
303 else:
304 new_params.append((name, '"%s"' % quote(value)))
305 if rfc2231_params:
306 for name, continuations in rfc2231_params.items():
307 value = []
308 # Sort by number
309 continuations.sort()
310 # And now append all values in num order
311 for num, continuation in continuations:
312 value.append(continuation)
313 charset, language, value = decode_rfc2231(EMPTYSTRING.join(value))
314 new_params.append((name,
315 (charset, language, '"%s"' % quote(value))))
316 return new_params