home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / email / Utils.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  9.4 KB  |  309 lines

  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4.  
  5. """Miscellaneous utilities."""
  6.  
  7. import os
  8. import re
  9. import time
  10. import base64
  11. import random
  12. import socket
  13. import urllib
  14. import warnings
  15. from cStringIO import StringIO
  16.  
  17. from email._parseaddr import quote
  18. from email._parseaddr import AddressList as _AddressList
  19. from email._parseaddr import mktime_tz
  20.  
  21. # We need wormarounds for bugs in these methods in older Pythons (see below)
  22. from email._parseaddr import parsedate as _parsedate
  23. from email._parseaddr import parsedate_tz as _parsedate_tz
  24.  
  25. from quopri import decodestring as _qdecode
  26.  
  27. # Intrapackage imports
  28. from email.Encoders import _bencode, _qencode
  29.  
  30. COMMASPACE = ', '
  31. EMPTYSTRING = ''
  32. UEMPTYSTRING = u''
  33. CRLF = '\r\n'
  34. TICK = "'"
  35.  
  36. specialsre = re.compile(r'[][\\()<>@,:;".]')
  37. escapesre = re.compile(r'[][\\()"]')
  38.  
  39.  
  40.  
  41. # Helpers
  42.  
  43. def _identity(s):
  44.     return s
  45.  
  46.  
  47. def _bdecode(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.     value = base64.decodestring(s)
  53.     if not s.endswith('\n') and value.endswith('\n'):
  54.         return value[:-1]
  55.     return value
  56.  
  57.  
  58.  
  59. def fix_eols(s):
  60.     """Replace all line-ending characters with \r\n."""
  61.     # Fix newlines with no preceding carriage return
  62.     s = re.sub(r'(?<!\r)\n', CRLF, s)
  63.     # Fix carriage returns with no following newline
  64.     s = re.sub(r'\r(?!\n)', CRLF, s)
  65.     return s
  66.  
  67.  
  68.  
  69. def formataddr(pair):
  70.     """The inverse of parseaddr(), this takes a 2-tuple of the form
  71.     (realname, email_address) and returns the string value suitable
  72.     for an RFC 2822 From, To or Cc header.
  73.  
  74.     If the first element of pair is false, then the second element is
  75.     returned unmodified.
  76.     """
  77.     name, address = pair
  78.     if name:
  79.         quotes = ''
  80.         if specialsre.search(name):
  81.             quotes = '"'
  82.         name = escapesre.sub(r'\\\g<0>', name)
  83.         return '%s%s%s <%s>' % (quotes, name, quotes, address)
  84.     return address
  85.  
  86.  
  87.  
  88. def getaddresses(fieldvalues):
  89.     """Return a list of (REALNAME, EMAIL) for each fieldvalue."""
  90.     all = COMMASPACE.join(fieldvalues)
  91.     a = _AddressList(all)
  92.     return a.addresslist
  93.  
  94.  
  95.  
  96. ecre = re.compile(r'''
  97.   =\?                   # literal =?
  98.   (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset
  99.   \?                    # literal ?
  100.   (?P<encoding>[qb])    # either a "q" or a "b", case insensitive
  101.   \?                    # literal ?
  102.   (?P<atom>.*?)         # non-greedy up to the next ?= is the atom
  103.   \?=                   # literal ?=
  104.   ''', re.VERBOSE | re.IGNORECASE)
  105.  
  106.  
  107.  
  108. def formatdate(timeval=None, localtime=False, usegmt=False):
  109.     """Returns a date string as specified by RFC 2822, e.g.:
  110.  
  111.     Fri, 09 Nov 2001 01:08:47 -0000
  112.  
  113.     Optional timeval if given is a floating point time value as accepted by
  114.     gmtime() and localtime(), otherwise the current time is used.
  115.  
  116.     Optional localtime is a flag that when True, interprets timeval, and
  117.     returns a date relative to the local timezone instead of UTC, properly
  118.     taking daylight savings time into account.
  119.  
  120.     Optional argument usegmt means that the timezone is written out as
  121.     an ascii string, not numeric one (so "GMT" instead of "+0000"). This
  122.     is needed for HTTP, and is only used when localtime==False.
  123.     """
  124.     # Note: we cannot use strftime() because that honors the locale and RFC
  125.     # 2822 requires that day and month names be the English abbreviations.
  126.     if timeval is None:
  127.         timeval = time.time()
  128.     if localtime:
  129.         now = time.localtime(timeval)
  130.         # Calculate timezone offset, based on whether the local zone has
  131.         # daylight savings time, and whether DST is in effect.
  132.         if time.daylight and now[-1]:
  133.             offset = time.altzone
  134.         else:
  135.             offset = time.timezone
  136.         hours, minutes = divmod(abs(offset), 3600)
  137.         # Remember offset is in seconds west of UTC, but the timezone is in
  138.         # minutes east of UTC, so the signs differ.
  139.         if offset > 0:
  140.             sign = '-'
  141.         else:
  142.             sign = '+'
  143.         zone = '%s%02d%02d' % (sign, hours, minutes // 60)
  144.     else:
  145.         now = time.gmtime(timeval)
  146.         # Timezone offset is always -0000
  147.         if usegmt:
  148.             zone = 'GMT'
  149.         else:
  150.             zone = '-0000'
  151.     return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
  152.         ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
  153.         now[2],
  154.         ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  155.          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
  156.         now[0], now[3], now[4], now[5],
  157.         zone)
  158.  
  159.  
  160.  
  161. def make_msgid(idstring=None):
  162.     """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
  163.  
  164.     <20020201195627.33539.96671@nightshade.la.mastaler.com>
  165.  
  166.     Optional idstring if given is a string used to strengthen the
  167.     uniqueness of the message id.
  168.     """
  169.     timeval = time.time()
  170.     utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
  171.     pid = os.getpid()
  172.     randint = random.randrange(100000)
  173.     if idstring is None:
  174.         idstring = ''
  175.     else:
  176.         idstring = '.' + idstring
  177.     idhost = socket.getfqdn()
  178.     msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
  179.     return msgid
  180.  
  181.  
  182.  
  183. # These functions are in the standalone mimelib version only because they've
  184. # subsequently been fixed in the latest Python versions.  We use this to worm
  185. # around broken older Pythons.
  186. def parsedate(data):
  187.     if not data:
  188.         return None
  189.     return _parsedate(data)
  190.  
  191.  
  192. def parsedate_tz(data):
  193.     if not data:
  194.         return None
  195.     return _parsedate_tz(data)
  196.  
  197.  
  198. def parseaddr(addr):
  199.     addrs = _AddressList(addr).addresslist
  200.     if not addrs:
  201.         return '', ''
  202.     return addrs[0]
  203.  
  204.  
  205. # rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
  206. def unquote(str):
  207.     """Remove quotes from a string."""
  208.     if len(str) > 1:
  209.         if str.startswith('"') and str.endswith('"'):
  210.             return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
  211.         if str.startswith('<') and str.endswith('>'):
  212.             return str[1:-1]
  213.     return str
  214.  
  215.  
  216.  
  217. # RFC2231-related functions - parameter encoding and decoding
  218. def decode_rfc2231(s):
  219.     """Decode string according to RFC 2231"""
  220.     parts = s.split(TICK, 2)
  221.     if len(parts) <= 2:
  222.         return None, None, urllib.unquote(s)
  223.     return parts
  224.  
  225.  
  226. def encode_rfc2231(s, charset=None, language=None):
  227.     """Encode string according to RFC 2231.
  228.  
  229.     If neither charset nor language is given, then s is returned as-is.  If
  230.     charset is given but not language, the string is encoded using the empty
  231.     string for language.
  232.     """
  233.     import urllib
  234.     s = urllib.quote(s, safe='')
  235.     if charset is None and language is None:
  236.         return s
  237.     if language is None:
  238.         language = ''
  239.     return "%s'%s'%s" % (charset, language, s)
  240.  
  241.  
  242. rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$')
  243.  
  244. def decode_params(params):
  245.     """Decode parameters list according to RFC 2231.
  246.  
  247.     params is a sequence of 2-tuples containing (param name, string value).
  248.     """
  249.     # Copy params so we don't mess with the original
  250.     params = params[:]
  251.     new_params = []
  252.     # Map parameter's name to a list of continuations.  The values are a
  253.     # 3-tuple of the continuation number, the string value, and a flag
  254.     # specifying whether a particular segment is %-encoded.
  255.     rfc2231_params = {}
  256.     name, value = params.pop(0)
  257.     new_params.append((name, value))
  258.     while params:
  259.         name, value = params.pop(0)
  260.         if name.endswith('*'):
  261.             encoded = True
  262.         else:
  263.             encoded = False
  264.         value = unquote(value)
  265.         mo = rfc2231_continuation.match(name)
  266.         if mo:
  267.             name, num = mo.group('name', 'num')
  268.             if num is not None:
  269.                 num = int(num)
  270.             rfc2231_params.setdefault(name, []).append((num, value, encoded))
  271.         else:
  272.             new_params.append((name, '"%s"' % quote(value)))
  273.     if rfc2231_params:
  274.         for name, continuations in rfc2231_params.items():
  275.             value = []
  276.             extended = False
  277.             # Sort by number
  278.             continuations.sort()
  279.             # And now append all values in numerical order, converting
  280.             # %-encodings for the encoded segments.  If any of the
  281.             # continuation names ends in a *, then the entire string, after
  282.             # decoding segments and concatenating, must have the charset and
  283.             # language specifiers at the beginning of the string.
  284.             for num, s, encoded in continuations:
  285.                 if encoded:
  286.                     s = urllib.unquote(s)
  287.                     extended = True
  288.                 value.append(s)
  289.             value = quote(EMPTYSTRING.join(value))
  290.             if extended:
  291.                 charset, language, value = decode_rfc2231(value)
  292.                 new_params.append((name, (charset, language, '"%s"' % value)))
  293.             else:
  294.                 new_params.append((name, '"%s"' % value))
  295.     return new_params
  296.  
  297. def collapse_rfc2231_value(value, errors='replace',
  298.                            fallback_charset='us-ascii'):
  299.     if isinstance(value, tuple):
  300.         rawval = unquote(value[2])
  301.         charset = value[0] or 'us-ascii'
  302.         try:
  303.             return unicode(rawval, charset, errors)
  304.         except LookupError:
  305.             # XXX charset is unknown to Python.
  306.             return unicode(rawval, fallback_charset, errors)
  307.     else:
  308.         return unquote(value)
  309.