blob: 927d67eccca22380f76f7c611861790b84893460 [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
24from quopri import decodestring as _qdecode
25import base64
26
27# Intrapackage imports
28from Encoders import _bencode, _qencode
29
30COMMASPACE = ', '
31UEMPTYSTRING = u''
Barry Warsaw409a4c02002-04-10 21:01:31 +000032CRLF = '\r\n'
33
34specialsre = re.compile(r'[][\()<>@,:;".]')
35escapesre = re.compile(r'[][\()"]')
Barry Warsawba925802001-09-23 03:17:28 +000036
37
Barry Warsawe968ead2001-10-04 17:05:11 +000038
Barry Warsawba925802001-09-23 03:17:28 +000039# Helpers
40
41def _identity(s):
42 return s
43
44
45def _bdecode(s):
46 if not s:
47 return s
48 # We can't quite use base64.encodestring() since it tacks on a "courtesy
49 # newline". Blech!
50 if not s:
51 return s
52 hasnewline = (s[-1] == '\n')
53 value = base64.decodestring(s)
54 if not hasnewline and value[-1] == '\n':
55 return value[:-1]
56 return value
57
58
Barry Warsawe968ead2001-10-04 17:05:11 +000059
Barry Warsaw409a4c02002-04-10 21:01:31 +000060def fix_eols(s):
61 """Replace all line-ending characters with \r\n."""
62 # Fix newlines with no preceding carriage return
63 s = re.sub(r'(?<!\r)\n', CRLF, s)
64 # Fix carriage returns with no following newline
65 s = re.sub(r'\r(?!\n)', CRLF, s)
66 return s
67
68
69
70def formataddr(pair):
71 """The inverse of parseaddr(), this takes a 2-tuple of the form
72 (realname, email_address) and returns the string value suitable
73 for an RFC 2822 From:, To: or Cc:.
74
75 If the first element of pair is false, then the second element is
76 returned unmodified.
77 """
78 name, address = pair
79 if name:
80 quotes = ''
81 if specialsre.search(name):
82 quotes = '"'
83 name = escapesre.sub(r'\\\g<0>', name)
84 return '%s%s%s <%s>' % (quotes, name, quotes, address)
85 return address
86
87# For backwards compatibility
88def dump_address_pair(pair):
89 warnings.warn('Use email.Utils.formataddr() instead',
90 DeprecationWarning, 2)
91 return formataddr(pair)
92
93
94
Barry Warsawba925802001-09-23 03:17:28 +000095def getaddresses(fieldvalues):
96 """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
97 all = COMMASPACE.join(fieldvalues)
Barry Warsawe1df15c2002-04-12 20:50:05 +000098 a = _AddressList(all)
Barry Warsawba925802001-09-23 03:17:28 +000099 return a.getaddrlist()
100
101
Barry Warsawe968ead2001-10-04 17:05:11 +0000102
Barry Warsawba925802001-09-23 03:17:28 +0000103ecre = re.compile(r'''
104 =\? # literal =?
105 (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
106 \? # literal ?
107 (?P<encoding>[qb]) # either a "q" or a "b", case insensitive
108 \? # literal ?
109 (?P<atom>.*?) # non-greedy up to the next ?= is the atom
110 \?= # literal ?=
111 ''', re.VERBOSE | re.IGNORECASE)
112
113
114def decode(s):
Barry Warsaw409a4c02002-04-10 21:01:31 +0000115 """Return a decoded string according to RFC 2047, as a unicode string.
116
117 NOTE: This function is deprecated. Use Header.decode_header() instead.
118 """
119 warnings.warn('Use Header.decode_header() instead.', DeprecationWarning, 2)
120 # Intra-package import here to avoid circular import problems.
121 from Header import decode_header
122 L = decode_header(s)
123 if not isinstance(L, ListType):
124 # s wasn't decoded
125 return s
126
Barry Warsawba925802001-09-23 03:17:28 +0000127 rtn = []
Barry Warsaw409a4c02002-04-10 21:01:31 +0000128 for atom, charset in L:
129 if charset is None:
130 rtn.append(atom)
Barry Warsawba925802001-09-23 03:17:28 +0000131 else:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000132 # Convert the string to Unicode using the given encoding. Leave
133 # Unicode conversion errors to strict.
134 rtn.append(unicode(atom, charset))
Barry Warsawba925802001-09-23 03:17:28 +0000135 # Now that we've decoded everything, we just need to join all the parts
136 # together into the final string.
137 return UEMPTYSTRING.join(rtn)
138
139
Barry Warsawe968ead2001-10-04 17:05:11 +0000140
Barry Warsawba925802001-09-23 03:17:28 +0000141def encode(s, charset='iso-8859-1', encoding='q'):
142 """Encode a string according to RFC 2047."""
Barry Warsaw409a4c02002-04-10 21:01:31 +0000143 warnings.warn('Use Header.Header.encode() instead.', DeprecationWarning, 2)
Barry Warsawc44d2c52001-12-03 19:26:40 +0000144 encoding = encoding.lower()
145 if encoding == 'q':
Barry Warsawba925802001-09-23 03:17:28 +0000146 estr = _qencode(s)
Barry Warsawc44d2c52001-12-03 19:26:40 +0000147 elif encoding == 'b':
Barry Warsawba925802001-09-23 03:17:28 +0000148 estr = _bencode(s)
149 else:
150 raise ValueError, 'Illegal encoding code: ' + encoding
Barry Warsawc44d2c52001-12-03 19:26:40 +0000151 return '=?%s?%s?%s?=' % (charset.lower(), encoding, estr)
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000152
153
154
155def formatdate(timeval=None, localtime=0):
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000156 """Returns a date string as specified by RFC 2822, e.g.:
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000157
158 Fri, 09 Nov 2001 01:08:47 -0000
159
Barry Warsaw9cff0e62001-11-09 17:07:28 +0000160 Optional timeval if given is a floating point time value as accepted by
161 gmtime() and localtime(), otherwise the current time is used.
162
163 Optional localtime is a flag that when true, interprets timeval, and
164 returns a date relative to the local timezone instead of UTC, properly
165 taking daylight savings time into account.
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000166 """
167 # Note: we cannot use strftime() because that honors the locale and RFC
168 # 2822 requires that day and month names be the English abbreviations.
169 if timeval is None:
170 timeval = time.time()
171 if localtime:
172 now = time.localtime(timeval)
173 # Calculate timezone offset, based on whether the local zone has
174 # daylight savings time, and whether DST is in effect.
175 if time.daylight and now[-1]:
176 offset = time.altzone
177 else:
178 offset = time.timezone
Barry Warsawe5739a62001-11-19 18:36:43 +0000179 hours, minutes = divmod(abs(offset), 3600)
180 # Remember offset is in seconds west of UTC, but the timezone is in
181 # minutes east of UTC, so the signs differ.
182 if offset > 0:
183 sign = '-'
184 else:
185 sign = '+'
186 zone = '%s%02d%02d' % (sign, hours, minutes / 60)
Barry Warsawaa79f4d2001-11-09 16:59:56 +0000187 else:
188 now = time.gmtime(timeval)
189 # Timezone offset is always -0000
190 zone = '-0000'
191 return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
192 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
193 now[2],
194 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
195 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
196 now[0], now[3], now[4], now[5],
197 zone)
Barry Warsaw409a4c02002-04-10 21:01:31 +0000198
199
200
201def make_msgid(idstring=None):
202 """Returns a string suitable for RFC 2822 compliant Message-ID:, e.g:
203
204 <20020201195627.33539.96671@nightshade.la.mastaler.com>
205
206 Optional idstring if given is a string used to strengthen the
207 uniqueness of the Message-ID, otherwise an empty string is used.
208 """
209 timeval = time.time()
210 utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
211 pid = os.getpid()
212 randint = random.randrange(100000)
213 if idstring is None:
214 idstring = ''
215 else:
216 idstring = '.' + idstring
217 idhost = socket.getfqdn()
218 msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
219 return msgid
220
221
222
223# These functions are in the standalone mimelib version only because they've
224# subsequently been fixed in the latest Python versions. We use this to worm
225# around broken older Pythons.
226def parsedate(data):
227 if not data:
228 return None
229 return _parsedate(data)
230
231
232def parsedate_tz(data):
233 if not data:
234 return None
235 return _parsedate_tz(data)
236
237
238def parseaddr(addr):
Barry Warsaw24fd0252002-04-15 22:00:25 +0000239 addrs = _AddressList(addr).addresslist
240 if not addrs:
Barry Warsaw409a4c02002-04-10 21:01:31 +0000241 return '', ''
Barry Warsaw24fd0252002-04-15 22:00:25 +0000242 return addrs[0]