home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / email / header.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  13.2 KB  |  419 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Header encoding and decoding functionality.'''
  5. __all__ = [
  6.     'Header',
  7.     'decode_header',
  8.     'make_header']
  9. import re
  10. import binascii
  11. import email.quoprimime as email
  12. import email.base64mime as email
  13. from email.errors import HeaderParseError
  14. from email.charset import Charset
  15. NL = '\n'
  16. SPACE = ' '
  17. USPACE = u' '
  18. SPACE8 = ' ' * 8
  19. UEMPTYSTRING = u''
  20. MAXLINELEN = 76
  21. USASCII = Charset('us-ascii')
  22. UTF8 = Charset('utf-8')
  23. ecre = re.compile('\n  =\\?                   # literal =?\n  (?P<charset>[^?]*?)   # non-greedy up to the next ? is the charset\n  \\?                    # literal ?\n  (?P<encoding>[qb])    # either a "q" or a "b", case insensitive\n  \\?                    # literal ?\n  (?P<encoded>.*?)      # non-greedy up to the next ?= is the encoded string\n  \\?=                   # literal ?=\n  (?=[ \\t]|$)           # whitespace or the end of the string\n  ', re.VERBOSE | re.IGNORECASE | re.MULTILINE)
  24. fcre = re.compile('[\\041-\\176]+:$')
  25. _max_append = email.quoprimime._max_append
  26.  
  27. def decode_header(header):
  28.     '''Decode a message header value without converting charset.
  29.  
  30.     Returns a list of (decoded_string, charset) pairs containing each of the
  31.     decoded parts of the header.  Charset is None for non-encoded parts of the
  32.     header, otherwise a lower-case string containing the name of the character
  33.     set specified in the encoded string.
  34.  
  35.     An email.Errors.HeaderParseError may be raised when certain decoding error
  36.     occurs (e.g. a base64 decoding exception).
  37.     '''
  38.     header = str(header)
  39.     if not ecre.search(header):
  40.         return [
  41.             (header, None)]
  42.     
  43.     decoded = []
  44.     dec = ''
  45.     for line in header.splitlines():
  46.         if not ecre.search(line):
  47.             decoded.append((line, None))
  48.             continue
  49.         
  50.         parts = ecre.split(line)
  51.         while parts:
  52.             unenc = parts.pop(0).strip()
  53.             if unenc:
  54.                 if decoded and decoded[-1][1] is None:
  55.                     decoded[-1] = (decoded[-1][0] + SPACE + unenc, None)
  56.                 else:
  57.                     decoded.append((unenc, None))
  58.             
  59.             if parts:
  60.                 (charset, encoding) = [ s.lower() for s in parts[0:2] ]
  61.                 encoded = parts[2]
  62.                 dec = None
  63.                 if encoding == 'q':
  64.                     dec = email.quoprimime.header_decode(encoded)
  65.                 elif encoding == 'b':
  66.                     
  67.                     try:
  68.                         dec = email.base64mime.decode(encoded)
  69.                     except binascii.Error:
  70.                         []
  71.                         []
  72.                         raise HeaderParseError
  73.                     except:
  74.                         []<EXCEPTION MATCH>binascii.Error
  75.                     
  76.  
  77.                 []
  78.                 if dec is None:
  79.                     dec = encoded
  80.                 
  81.                 if decoded and decoded[-1][1] == charset:
  82.                     decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1])
  83.                 else:
  84.                     decoded.append((dec, charset))
  85.             
  86.             del parts[0:3]
  87.     
  88.     return decoded
  89.  
  90.  
  91. def make_header(decoded_seq, maxlinelen = None, header_name = None, continuation_ws = ' '):
  92.     '''Create a Header from a sequence of pairs as returned by decode_header()
  93.  
  94.     decode_header() takes a header value string and returns a sequence of
  95.     pairs of the format (decoded_string, charset) where charset is the string
  96.     name of the character set.
  97.  
  98.     This function takes one of those sequence of pairs and returns a Header
  99.     instance.  Optional maxlinelen, header_name, and continuation_ws are as in
  100.     the Header constructor.
  101.     '''
  102.     h = Header(maxlinelen = maxlinelen, header_name = header_name, continuation_ws = continuation_ws)
  103.     for s, charset in decoded_seq:
  104.         if charset is not None and not isinstance(charset, Charset):
  105.             charset = Charset(charset)
  106.         
  107.         h.append(s, charset)
  108.     
  109.     return h
  110.  
  111.  
  112. class Header:
  113.     
  114.     def __init__(self, s = None, charset = None, maxlinelen = None, header_name = None, continuation_ws = ' ', errors = 'strict'):
  115.         """Create a MIME-compliant header that can contain many character sets.
  116.  
  117.         Optional s is the initial header value.  If None, the initial header
  118.         value is not set.  You can later append to the header with .append()
  119.         method calls.  s may be a byte string or a Unicode string, but see the
  120.         .append() documentation for semantics.
  121.  
  122.         Optional charset serves two purposes: it has the same meaning as the
  123.         charset argument to the .append() method.  It also sets the default
  124.         character set for all subsequent .append() calls that omit the charset
  125.         argument.  If charset is not provided in the constructor, the us-ascii
  126.         charset is used both as s's initial charset and as the default for
  127.         subsequent .append() calls.
  128.  
  129.         The maximum line length can be specified explicit via maxlinelen.  For
  130.         splitting the first line to a shorter value (to account for the field
  131.         header which isn't included in s, e.g. `Subject') pass in the name of
  132.         the field in header_name.  The default maxlinelen is 76.
  133.  
  134.         continuation_ws must be RFC 2822 compliant folding whitespace (usually
  135.         either a space or a hard tab) which will be prepended to continuation
  136.         lines.
  137.  
  138.         errors is passed through to the .append() call.
  139.         """
  140.         if charset is None:
  141.             charset = USASCII
  142.         
  143.         if not isinstance(charset, Charset):
  144.             charset = Charset(charset)
  145.         
  146.         self._charset = charset
  147.         self._continuation_ws = continuation_ws
  148.         cws_expanded_len = len(continuation_ws.replace('\t', SPACE8))
  149.         self._chunks = []
  150.         if s is not None:
  151.             self.append(s, charset, errors)
  152.         
  153.         if maxlinelen is None:
  154.             maxlinelen = MAXLINELEN
  155.         
  156.         if header_name is None:
  157.             self._firstlinelen = maxlinelen
  158.         else:
  159.             self._firstlinelen = maxlinelen - len(header_name) - 2
  160.         self._maxlinelen = maxlinelen - cws_expanded_len
  161.  
  162.     
  163.     def __str__(self):
  164.         '''A synonym for self.encode().'''
  165.         return self.encode()
  166.  
  167.     
  168.     def __unicode__(self):
  169.         '''Helper for the built-in unicode function.'''
  170.         uchunks = []
  171.         lastcs = None
  172.         for s, charset in self._chunks:
  173.             nextcs = charset
  174.             if uchunks:
  175.                 if lastcs not in (None, 'us-ascii'):
  176.                     if nextcs in (None, 'us-ascii'):
  177.                         uchunks.append(USPACE)
  178.                         nextcs = None
  179.                     
  180.                 elif nextcs not in (None, 'us-ascii'):
  181.                     uchunks.append(USPACE)
  182.                 
  183.             
  184.             lastcs = nextcs
  185.             uchunks.append(unicode(s, str(charset)))
  186.         
  187.         return UEMPTYSTRING.join(uchunks)
  188.  
  189.     
  190.     def __eq__(self, other):
  191.         return other == self.encode()
  192.  
  193.     
  194.     def __ne__(self, other):
  195.         return not (self == other)
  196.  
  197.     
  198.     def append(self, s, charset = None, errors = 'strict'):
  199.         """Append a string to the MIME header.
  200.  
  201.         Optional charset, if given, should be a Charset instance or the name
  202.         of a character set (which will be converted to a Charset instance).  A
  203.         value of None (the default) means that the charset given in the
  204.         constructor is used.
  205.  
  206.         s may be a byte string or a Unicode string.  If it is a byte string
  207.         (i.e. isinstance(s, str) is true), then charset is the encoding of
  208.         that byte string, and a UnicodeError will be raised if the string
  209.         cannot be decoded with that charset.  If s is a Unicode string, then
  210.         charset is a hint specifying the character set of the characters in
  211.         the string.  In this case, when producing an RFC 2822 compliant header
  212.         using RFC 2047 rules, the Unicode string will be encoded using the
  213.         following charsets in order: us-ascii, the charset hint, utf-8.  The
  214.         first character set not to provoke a UnicodeError is used.
  215.  
  216.         Optional `errors' is passed as the third argument to any unicode() or
  217.         ustr.encode() call.
  218.         """
  219.         if charset is None:
  220.             charset = self._charset
  221.         elif not isinstance(charset, Charset):
  222.             charset = Charset(charset)
  223.         
  224.         if charset != '8bit':
  225.             if isinstance(s, str):
  226.                 if not charset.input_codec:
  227.                     pass
  228.                 incodec = 'us-ascii'
  229.                 ustr = unicode(s, incodec, errors)
  230.                 if not charset.output_codec:
  231.                     pass
  232.                 outcodec = 'us-ascii'
  233.                 ustr.encode(outcodec, errors)
  234.             elif isinstance(s, unicode):
  235.                 for charset in (USASCII, charset, UTF8):
  236.                     
  237.                     try:
  238.                         if not charset.output_codec:
  239.                             pass
  240.                         outcodec = 'us-ascii'
  241.                         s = s.encode(outcodec, errors)
  242.                     continue
  243.                     except UnicodeError:
  244.                         continue
  245.                     
  246.  
  247.                 elif not False:
  248.                     raise AssertionError, 'utf-8 conversion failed'
  249.                 None<EXCEPTION MATCH>UnicodeError
  250.             
  251.         
  252.         self._chunks.append((s, charset))
  253.  
  254.     
  255.     def _split(self, s, charset, maxlinelen, splitchars):
  256.         splittable = charset.to_splittable(s)
  257.         encoded = charset.from_splittable(splittable, True)
  258.         elen = charset.encoded_header_len(encoded)
  259.         if elen <= maxlinelen:
  260.             return [
  261.                 (encoded, charset)]
  262.         
  263.         if charset == '8bit':
  264.             return [
  265.                 (s, charset)]
  266.         elif charset == 'us-ascii':
  267.             return self._split_ascii(s, charset, maxlinelen, splitchars)
  268.         elif elen == len(s):
  269.             splitpnt = maxlinelen
  270.             first = charset.from_splittable(splittable[:splitpnt], False)
  271.             last = charset.from_splittable(splittable[splitpnt:], False)
  272.         else:
  273.             (first, last) = _binsplit(splittable, charset, maxlinelen)
  274.         fsplittable = charset.to_splittable(first)
  275.         fencoded = charset.from_splittable(fsplittable, True)
  276.         chunk = [
  277.             (fencoded, charset)]
  278.         return chunk + self._split(last, charset, self._maxlinelen, splitchars)
  279.  
  280.     
  281.     def _split_ascii(self, s, charset, firstlen, splitchars):
  282.         chunks = _split_ascii(s, firstlen, self._maxlinelen, self._continuation_ws, splitchars)
  283.         return zip(chunks, [
  284.             charset] * len(chunks))
  285.  
  286.     
  287.     def _encode_chunks(self, newchunks, maxlinelen):
  288.         chunks = []
  289.         for header, charset in newchunks:
  290.             if not header:
  291.                 continue
  292.             
  293.             if charset is None or charset.header_encoding is None:
  294.                 s = header
  295.             else:
  296.                 s = charset.header_encode(header)
  297.             if chunks and chunks[-1].endswith(' '):
  298.                 extra = ''
  299.             else:
  300.                 extra = ' '
  301.             _max_append(chunks, s, maxlinelen, extra)
  302.         
  303.         joiner = NL + self._continuation_ws
  304.         return joiner.join(chunks)
  305.  
  306.     
  307.     def encode(self, splitchars = ';, '):
  308.         """Encode a message header into an RFC-compliant format.
  309.  
  310.         There are many issues involved in converting a given string for use in
  311.         an email header.  Only certain character sets are readable in most
  312.         email clients, and as header strings can only contain a subset of
  313.         7-bit ASCII, care must be taken to properly convert and encode (with
  314.         Base64 or quoted-printable) header strings.  In addition, there is a
  315.         75-character length limit on any given encoded header field, so
  316.         line-wrapping must be performed, even with double-byte character sets.
  317.  
  318.         This method will do its best to convert the string to the correct
  319.         character set used in email, and encode and line wrap it safely with
  320.         the appropriate scheme for that character set.
  321.  
  322.         If the given charset is not known or an error occurs during
  323.         conversion, this function will return the header untouched.
  324.  
  325.         Optional splitchars is a string containing characters to split long
  326.         ASCII lines on, in rough support of RFC 2822's `highest level
  327.         syntactic breaks'.  This doesn't affect RFC 2047 encoded lines.
  328.         """
  329.         newchunks = []
  330.         maxlinelen = self._firstlinelen
  331.         lastlen = 0
  332.         for s, charset in self._chunks:
  333.             targetlen = maxlinelen - lastlen - 1
  334.             if targetlen < charset.encoded_header_len(''):
  335.                 targetlen = maxlinelen
  336.             
  337.             newchunks += self._split(s, charset, targetlen, splitchars)
  338.             (lastchunk, lastcharset) = newchunks[-1]
  339.             lastlen = lastcharset.encoded_header_len(lastchunk)
  340.         
  341.         return self._encode_chunks(newchunks, maxlinelen)
  342.  
  343.  
  344.  
  345. def _split_ascii(s, firstlen, restlen, continuation_ws, splitchars):
  346.     lines = []
  347.     maxlen = firstlen
  348.     for line in s.splitlines():
  349.         line = line.lstrip()
  350.         if len(line) < maxlen:
  351.             lines.append(line)
  352.             maxlen = restlen
  353.             continue
  354.         
  355.         for ch in splitchars:
  356.             if ch in line:
  357.                 break
  358.                 continue
  359.         else:
  360.             maxlen = restlen
  361.         cre = re.compile('%s\\s*' % ch)
  362.         if ch in ';,':
  363.             eol = ch
  364.         else:
  365.             eol = ''
  366.         joiner = eol + ' '
  367.         joinlen = len(joiner)
  368.         wslen = len(continuation_ws.replace('\t', SPACE8))
  369.         this = []
  370.         linelen = 0
  371.         for part in cre.split(line):
  372.             curlen = linelen + max(0, len(this) - 1) * joinlen
  373.             partlen = len(part)
  374.             onfirstline = not lines
  375.             if ch == ' ' and onfirstline and len(this) == 1 and fcre.match(this[0]):
  376.                 this.append(part)
  377.                 linelen += partlen
  378.                 continue
  379.             if curlen + partlen > maxlen:
  380.                 if this:
  381.                     lines.append(joiner.join(this) + eol)
  382.                 
  383.                 if partlen > maxlen and ch != ' ':
  384.                     subl = _split_ascii(part, maxlen, restlen, continuation_ws, ' ')
  385.                     lines.extend(subl[:-1])
  386.                     this = [
  387.                         subl[-1]]
  388.                 else:
  389.                     this = [
  390.                         part]
  391.                 linelen = wslen + len(this[-1])
  392.                 maxlen = restlen
  393.                 continue
  394.             this.append(part)
  395.             linelen += partlen
  396.         
  397.         if this:
  398.             lines.append(joiner.join(this))
  399.             continue
  400.     
  401.     return lines
  402.  
  403.  
  404. def _binsplit(splittable, charset, maxlinelen):
  405.     i = 0
  406.     j = len(splittable)
  407.     while i < j:
  408.         m = i + j + 1 >> 1
  409.         chunk = charset.from_splittable(splittable[:m], True)
  410.         chunklen = charset.encoded_header_len(chunk)
  411.         if chunklen <= maxlinelen:
  412.             i = m
  413.             continue
  414.         j = m - 1
  415.     first = charset.from_splittable(splittable[:i], False)
  416.     last = charset.from_splittable(splittable[i:], False)
  417.     return (first, last)
  418.  
  419.