Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python3..../email
File: utils.py
# Copyright (C) 2001-2010 Python Software Foundation
[0] Fix | Delete
# Author: Barry Warsaw
[1] Fix | Delete
# Contact: email-sig@python.org
[2] Fix | Delete
[3] Fix | Delete
"""Miscellaneous utilities."""
[4] Fix | Delete
[5] Fix | Delete
__all__ = [
[6] Fix | Delete
'collapse_rfc2231_value',
[7] Fix | Delete
'decode_params',
[8] Fix | Delete
'decode_rfc2231',
[9] Fix | Delete
'encode_rfc2231',
[10] Fix | Delete
'formataddr',
[11] Fix | Delete
'formatdate',
[12] Fix | Delete
'format_datetime',
[13] Fix | Delete
'getaddresses',
[14] Fix | Delete
'make_msgid',
[15] Fix | Delete
'mktime_tz',
[16] Fix | Delete
'parseaddr',
[17] Fix | Delete
'parsedate',
[18] Fix | Delete
'parsedate_tz',
[19] Fix | Delete
'parsedate_to_datetime',
[20] Fix | Delete
'unquote',
[21] Fix | Delete
]
[22] Fix | Delete
[23] Fix | Delete
import os
[24] Fix | Delete
import re
[25] Fix | Delete
import time
[26] Fix | Delete
import random
[27] Fix | Delete
import socket
[28] Fix | Delete
import datetime
[29] Fix | Delete
import urllib.parse
[30] Fix | Delete
[31] Fix | Delete
from email._parseaddr import quote
[32] Fix | Delete
from email._parseaddr import AddressList as _AddressList
[33] Fix | Delete
from email._parseaddr import mktime_tz
[34] Fix | Delete
[35] Fix | Delete
from email._parseaddr import parsedate, parsedate_tz, _parsedate_tz
[36] Fix | Delete
[37] Fix | Delete
# Intrapackage imports
[38] Fix | Delete
from email.charset import Charset
[39] Fix | Delete
[40] Fix | Delete
COMMASPACE = ', '
[41] Fix | Delete
EMPTYSTRING = ''
[42] Fix | Delete
UEMPTYSTRING = ''
[43] Fix | Delete
CRLF = '\r\n'
[44] Fix | Delete
TICK = "'"
[45] Fix | Delete
[46] Fix | Delete
specialsre = re.compile(r'[][\\()<>@,:;".]')
[47] Fix | Delete
escapesre = re.compile(r'[\\"]')
[48] Fix | Delete
[49] Fix | Delete
_EMAIL_CONFIG_FILE = "/etc/python/email.cfg"
[50] Fix | Delete
_cached_strict_addr_parsing = None
[51] Fix | Delete
[52] Fix | Delete
[53] Fix | Delete
def _use_strict_email_parsing():
[54] Fix | Delete
""""Cache implementation for _cached_strict_addr_parsing"""
[55] Fix | Delete
global _cached_strict_addr_parsing
[56] Fix | Delete
if _cached_strict_addr_parsing is None:
[57] Fix | Delete
_cached_strict_addr_parsing = _use_strict_email_parsing_impl()
[58] Fix | Delete
return _cached_strict_addr_parsing
[59] Fix | Delete
[60] Fix | Delete
[61] Fix | Delete
def _use_strict_email_parsing_impl():
[62] Fix | Delete
"""Returns True if strict email parsing is not disabled by
[63] Fix | Delete
config file or env variable.
[64] Fix | Delete
"""
[65] Fix | Delete
disabled = bool(os.environ.get("PYTHON_EMAIL_DISABLE_STRICT_ADDR_PARSING"))
[66] Fix | Delete
if disabled:
[67] Fix | Delete
return False
[68] Fix | Delete
[69] Fix | Delete
try:
[70] Fix | Delete
file = open(_EMAIL_CONFIG_FILE)
[71] Fix | Delete
except FileNotFoundError:
[72] Fix | Delete
pass
[73] Fix | Delete
else:
[74] Fix | Delete
with file:
[75] Fix | Delete
import configparser
[76] Fix | Delete
config = configparser.ConfigParser(
[77] Fix | Delete
interpolation=None,
[78] Fix | Delete
comment_prefixes=('#', ),
[79] Fix | Delete
[80] Fix | Delete
)
[81] Fix | Delete
config.read_file(file)
[82] Fix | Delete
disabled = config.getboolean('email_addr_parsing', "PYTHON_EMAIL_DISABLE_STRICT_ADDR_PARSING", fallback=None)
[83] Fix | Delete
[84] Fix | Delete
if disabled:
[85] Fix | Delete
return False
[86] Fix | Delete
[87] Fix | Delete
return True
[88] Fix | Delete
[89] Fix | Delete
[90] Fix | Delete
def _has_surrogates(s):
[91] Fix | Delete
"""Return True if s contains surrogate-escaped binary data."""
[92] Fix | Delete
# This check is based on the fact that unless there are surrogates, utf8
[93] Fix | Delete
# (Python's default encoding) can encode any string. This is the fastest
[94] Fix | Delete
# way to check for surrogates, see issue 11454 for timings.
[95] Fix | Delete
try:
[96] Fix | Delete
s.encode()
[97] Fix | Delete
return False
[98] Fix | Delete
except UnicodeEncodeError:
[99] Fix | Delete
return True
[100] Fix | Delete
[101] Fix | Delete
# How to deal with a string containing bytes before handing it to the
[102] Fix | Delete
# application through the 'normal' interface.
[103] Fix | Delete
def _sanitize(string):
[104] Fix | Delete
# Turn any escaped bytes into unicode 'unknown' char. If the escaped
[105] Fix | Delete
# bytes happen to be utf-8 they will instead get decoded, even if they
[106] Fix | Delete
# were invalid in the charset the source was supposed to be in. This
[107] Fix | Delete
# seems like it is not a bad thing; a defect was still registered.
[108] Fix | Delete
original_bytes = string.encode('utf-8', 'surrogateescape')
[109] Fix | Delete
return original_bytes.decode('utf-8', 'replace')
[110] Fix | Delete
[111] Fix | Delete
[112] Fix | Delete
[113] Fix | Delete
# Helpers
[114] Fix | Delete
[115] Fix | Delete
def formataddr(pair, charset='utf-8'):
[116] Fix | Delete
"""The inverse of parseaddr(), this takes a 2-tuple of the form
[117] Fix | Delete
(realname, email_address) and returns the string value suitable
[118] Fix | Delete
for an RFC 2822 From, To or Cc header.
[119] Fix | Delete
[120] Fix | Delete
If the first element of pair is false, then the second element is
[121] Fix | Delete
returned unmodified.
[122] Fix | Delete
[123] Fix | Delete
Optional charset if given is the character set that is used to encode
[124] Fix | Delete
realname in case realname is not ASCII safe. Can be an instance of str or
[125] Fix | Delete
a Charset-like object which has a header_encode method. Default is
[126] Fix | Delete
'utf-8'.
[127] Fix | Delete
"""
[128] Fix | Delete
name, address = pair
[129] Fix | Delete
# The address MUST (per RFC) be ascii, so raise a UnicodeError if it isn't.
[130] Fix | Delete
address.encode('ascii')
[131] Fix | Delete
if name:
[132] Fix | Delete
try:
[133] Fix | Delete
name.encode('ascii')
[134] Fix | Delete
except UnicodeEncodeError:
[135] Fix | Delete
if isinstance(charset, str):
[136] Fix | Delete
charset = Charset(charset)
[137] Fix | Delete
encoded_name = charset.header_encode(name)
[138] Fix | Delete
return "%s <%s>" % (encoded_name, address)
[139] Fix | Delete
else:
[140] Fix | Delete
quotes = ''
[141] Fix | Delete
if specialsre.search(name):
[142] Fix | Delete
quotes = '"'
[143] Fix | Delete
name = escapesre.sub(r'\\\g<0>', name)
[144] Fix | Delete
return '%s%s%s <%s>' % (quotes, name, quotes, address)
[145] Fix | Delete
return address
[146] Fix | Delete
[147] Fix | Delete
[148] Fix | Delete
def _iter_escaped_chars(addr):
[149] Fix | Delete
pos = 0
[150] Fix | Delete
escape = False
[151] Fix | Delete
for pos, ch in enumerate(addr):
[152] Fix | Delete
if escape:
[153] Fix | Delete
yield (pos, '\\' + ch)
[154] Fix | Delete
escape = False
[155] Fix | Delete
elif ch == '\\':
[156] Fix | Delete
escape = True
[157] Fix | Delete
else:
[158] Fix | Delete
yield (pos, ch)
[159] Fix | Delete
if escape:
[160] Fix | Delete
yield (pos, '\\')
[161] Fix | Delete
[162] Fix | Delete
[163] Fix | Delete
def _strip_quoted_realnames(addr):
[164] Fix | Delete
"""Strip real names between quotes."""
[165] Fix | Delete
if '"' not in addr:
[166] Fix | Delete
# Fast path
[167] Fix | Delete
return addr
[168] Fix | Delete
[169] Fix | Delete
start = 0
[170] Fix | Delete
open_pos = None
[171] Fix | Delete
result = []
[172] Fix | Delete
for pos, ch in _iter_escaped_chars(addr):
[173] Fix | Delete
if ch == '"':
[174] Fix | Delete
if open_pos is None:
[175] Fix | Delete
open_pos = pos
[176] Fix | Delete
else:
[177] Fix | Delete
if start != open_pos:
[178] Fix | Delete
result.append(addr[start:open_pos])
[179] Fix | Delete
start = pos + 1
[180] Fix | Delete
open_pos = None
[181] Fix | Delete
[182] Fix | Delete
if start < len(addr):
[183] Fix | Delete
result.append(addr[start:])
[184] Fix | Delete
[185] Fix | Delete
return ''.join(result)
[186] Fix | Delete
[187] Fix | Delete
[188] Fix | Delete
supports_strict_parsing = True
[189] Fix | Delete
[190] Fix | Delete
def getaddresses(fieldvalues, *, strict=None):
[191] Fix | Delete
"""Return a list of (REALNAME, EMAIL) or ('','') for each fieldvalue.
[192] Fix | Delete
[193] Fix | Delete
When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in
[194] Fix | Delete
its place.
[195] Fix | Delete
[196] Fix | Delete
If strict is true, use a strict parser which rejects malformed inputs.
[197] Fix | Delete
"""
[198] Fix | Delete
[199] Fix | Delete
# If default is used, it's True unless disabled
[200] Fix | Delete
# by env variable or config file.
[201] Fix | Delete
if strict == None:
[202] Fix | Delete
strict = _use_strict_email_parsing()
[203] Fix | Delete
[204] Fix | Delete
# If strict is true, if the resulting list of parsed addresses is greater
[205] Fix | Delete
# than the number of fieldvalues in the input list, a parsing error has
[206] Fix | Delete
# occurred and consequently a list containing a single empty 2-tuple [('',
[207] Fix | Delete
# '')] is returned in its place. This is done to avoid invalid output.
[208] Fix | Delete
#
[209] Fix | Delete
# Malformed input: getaddresses(['alice@example.com <bob@example.com>'])
[210] Fix | Delete
# Invalid output: [('', 'alice@example.com'), ('', 'bob@example.com')]
[211] Fix | Delete
# Safe output: [('', '')]
[212] Fix | Delete
[213] Fix | Delete
if not strict:
[214] Fix | Delete
all = COMMASPACE.join(str(v) for v in fieldvalues)
[215] Fix | Delete
a = _AddressList(all)
[216] Fix | Delete
return a.addresslist
[217] Fix | Delete
[218] Fix | Delete
fieldvalues = [str(v) for v in fieldvalues]
[219] Fix | Delete
fieldvalues = _pre_parse_validation(fieldvalues)
[220] Fix | Delete
addr = COMMASPACE.join(fieldvalues)
[221] Fix | Delete
a = _AddressList(addr)
[222] Fix | Delete
result = _post_parse_validation(a.addresslist)
[223] Fix | Delete
[224] Fix | Delete
# Treat output as invalid if the number of addresses is not equal to the
[225] Fix | Delete
# expected number of addresses.
[226] Fix | Delete
n = 0
[227] Fix | Delete
for v in fieldvalues:
[228] Fix | Delete
# When a comma is used in the Real Name part it is not a deliminator.
[229] Fix | Delete
# So strip those out before counting the commas.
[230] Fix | Delete
v = _strip_quoted_realnames(v)
[231] Fix | Delete
# Expected number of addresses: 1 + number of commas
[232] Fix | Delete
n += 1 + v.count(',')
[233] Fix | Delete
if len(result) != n:
[234] Fix | Delete
return [('', '')]
[235] Fix | Delete
[236] Fix | Delete
return result
[237] Fix | Delete
[238] Fix | Delete
[239] Fix | Delete
def _check_parenthesis(addr):
[240] Fix | Delete
# Ignore parenthesis in quoted real names.
[241] Fix | Delete
addr = _strip_quoted_realnames(addr)
[242] Fix | Delete
[243] Fix | Delete
opens = 0
[244] Fix | Delete
for pos, ch in _iter_escaped_chars(addr):
[245] Fix | Delete
if ch == '(':
[246] Fix | Delete
opens += 1
[247] Fix | Delete
elif ch == ')':
[248] Fix | Delete
opens -= 1
[249] Fix | Delete
if opens < 0:
[250] Fix | Delete
return False
[251] Fix | Delete
return (opens == 0)
[252] Fix | Delete
[253] Fix | Delete
[254] Fix | Delete
def _pre_parse_validation(email_header_fields):
[255] Fix | Delete
accepted_values = []
[256] Fix | Delete
for v in email_header_fields:
[257] Fix | Delete
if not _check_parenthesis(v):
[258] Fix | Delete
v = "('', '')"
[259] Fix | Delete
accepted_values.append(v)
[260] Fix | Delete
[261] Fix | Delete
return accepted_values
[262] Fix | Delete
[263] Fix | Delete
[264] Fix | Delete
def _post_parse_validation(parsed_email_header_tuples):
[265] Fix | Delete
accepted_values = []
[266] Fix | Delete
# The parser would have parsed a correctly formatted domain-literal
[267] Fix | Delete
# The existence of an [ after parsing indicates a parsing failure
[268] Fix | Delete
for v in parsed_email_header_tuples:
[269] Fix | Delete
if '[' in v[1]:
[270] Fix | Delete
v = ('', '')
[271] Fix | Delete
accepted_values.append(v)
[272] Fix | Delete
[273] Fix | Delete
return accepted_values
[274] Fix | Delete
[275] Fix | Delete
[276] Fix | Delete
[277] Fix | Delete
ecre = re.compile(r'''
[278] Fix | Delete
=\? # literal =?
[279] Fix | Delete
(?P<charset>[^?]*?) # non-greedy up to the next ? is the charset
[280] Fix | Delete
\? # literal ?
[281] Fix | Delete
(?P<encoding>[qb]) # either a "q" or a "b", case insensitive
[282] Fix | Delete
\? # literal ?
[283] Fix | Delete
(?P<atom>.*?) # non-greedy up to the next ?= is the atom
[284] Fix | Delete
\?= # literal ?=
[285] Fix | Delete
''', re.VERBOSE | re.IGNORECASE)
[286] Fix | Delete
[287] Fix | Delete
[288] Fix | Delete
def _format_timetuple_and_zone(timetuple, zone):
[289] Fix | Delete
return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
[290] Fix | Delete
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]],
[291] Fix | Delete
timetuple[2],
[292] Fix | Delete
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
[293] Fix | Delete
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1],
[294] Fix | Delete
timetuple[0], timetuple[3], timetuple[4], timetuple[5],
[295] Fix | Delete
zone)
[296] Fix | Delete
[297] Fix | Delete
def formatdate(timeval=None, localtime=False, usegmt=False):
[298] Fix | Delete
"""Returns a date string as specified by RFC 2822, e.g.:
[299] Fix | Delete
[300] Fix | Delete
Fri, 09 Nov 2001 01:08:47 -0000
[301] Fix | Delete
[302] Fix | Delete
Optional timeval if given is a floating point time value as accepted by
[303] Fix | Delete
gmtime() and localtime(), otherwise the current time is used.
[304] Fix | Delete
[305] Fix | Delete
Optional localtime is a flag that when True, interprets timeval, and
[306] Fix | Delete
returns a date relative to the local timezone instead of UTC, properly
[307] Fix | Delete
taking daylight savings time into account.
[308] Fix | Delete
[309] Fix | Delete
Optional argument usegmt means that the timezone is written out as
[310] Fix | Delete
an ascii string, not numeric one (so "GMT" instead of "+0000"). This
[311] Fix | Delete
is needed for HTTP, and is only used when localtime==False.
[312] Fix | Delete
"""
[313] Fix | Delete
# Note: we cannot use strftime() because that honors the locale and RFC
[314] Fix | Delete
# 2822 requires that day and month names be the English abbreviations.
[315] Fix | Delete
if timeval is None:
[316] Fix | Delete
timeval = time.time()
[317] Fix | Delete
if localtime or usegmt:
[318] Fix | Delete
dt = datetime.datetime.fromtimestamp(timeval, datetime.timezone.utc)
[319] Fix | Delete
else:
[320] Fix | Delete
dt = datetime.datetime.utcfromtimestamp(timeval)
[321] Fix | Delete
if localtime:
[322] Fix | Delete
dt = dt.astimezone()
[323] Fix | Delete
usegmt = False
[324] Fix | Delete
return format_datetime(dt, usegmt)
[325] Fix | Delete
[326] Fix | Delete
def format_datetime(dt, usegmt=False):
[327] Fix | Delete
"""Turn a datetime into a date string as specified in RFC 2822.
[328] Fix | Delete
[329] Fix | Delete
If usegmt is True, dt must be an aware datetime with an offset of zero. In
[330] Fix | Delete
this case 'GMT' will be rendered instead of the normal +0000 required by
[331] Fix | Delete
RFC2822. This is to support HTTP headers involving date stamps.
[332] Fix | Delete
"""
[333] Fix | Delete
now = dt.timetuple()
[334] Fix | Delete
if usegmt:
[335] Fix | Delete
if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
[336] Fix | Delete
raise ValueError("usegmt option requires a UTC datetime")
[337] Fix | Delete
zone = 'GMT'
[338] Fix | Delete
elif dt.tzinfo is None:
[339] Fix | Delete
zone = '-0000'
[340] Fix | Delete
else:
[341] Fix | Delete
zone = dt.strftime("%z")
[342] Fix | Delete
return _format_timetuple_and_zone(now, zone)
[343] Fix | Delete
[344] Fix | Delete
[345] Fix | Delete
def make_msgid(idstring=None, domain=None):
[346] Fix | Delete
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
[347] Fix | Delete
[348] Fix | Delete
<142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
[349] Fix | Delete
[350] Fix | Delete
Optional idstring if given is a string used to strengthen the
[351] Fix | Delete
uniqueness of the message id. Optional domain if given provides the
[352] Fix | Delete
portion of the message id after the '@'. It defaults to the locally
[353] Fix | Delete
defined hostname.
[354] Fix | Delete
"""
[355] Fix | Delete
timeval = int(time.time()*100)
[356] Fix | Delete
pid = os.getpid()
[357] Fix | Delete
randint = random.getrandbits(64)
[358] Fix | Delete
if idstring is None:
[359] Fix | Delete
idstring = ''
[360] Fix | Delete
else:
[361] Fix | Delete
idstring = '.' + idstring
[362] Fix | Delete
if domain is None:
[363] Fix | Delete
domain = socket.getfqdn()
[364] Fix | Delete
msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, domain)
[365] Fix | Delete
return msgid
[366] Fix | Delete
[367] Fix | Delete
[368] Fix | Delete
def parsedate_to_datetime(data):
[369] Fix | Delete
*dtuple, tz = _parsedate_tz(data)
[370] Fix | Delete
if tz is None:
[371] Fix | Delete
return datetime.datetime(*dtuple[:6])
[372] Fix | Delete
return datetime.datetime(*dtuple[:6],
[373] Fix | Delete
tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
[374] Fix | Delete
[375] Fix | Delete
[376] Fix | Delete
def parseaddr(addr, *, strict=None):
[377] Fix | Delete
"""
[378] Fix | Delete
Parse addr into its constituent realname and email address parts.
[379] Fix | Delete
[380] Fix | Delete
Return a tuple of realname and email address, unless the parse fails, in
[381] Fix | Delete
which case return a 2-tuple of ('', '').
[382] Fix | Delete
[383] Fix | Delete
If strict is True, use a strict parser which rejects malformed inputs.
[384] Fix | Delete
"""
[385] Fix | Delete
# If default is used, it's True unless disabled
[386] Fix | Delete
# by env variable or config file.
[387] Fix | Delete
if strict == None:
[388] Fix | Delete
strict = _use_strict_email_parsing()
[389] Fix | Delete
[390] Fix | Delete
if not strict:
[391] Fix | Delete
addrs = _AddressList(addr).addresslist
[392] Fix | Delete
if not addrs:
[393] Fix | Delete
return ('', '')
[394] Fix | Delete
return addrs[0]
[395] Fix | Delete
[396] Fix | Delete
if isinstance(addr, list):
[397] Fix | Delete
addr = addr[0]
[398] Fix | Delete
[399] Fix | Delete
if not isinstance(addr, str):
[400] Fix | Delete
return ('', '')
[401] Fix | Delete
[402] Fix | Delete
addr = _pre_parse_validation([addr])[0]
[403] Fix | Delete
addrs = _post_parse_validation(_AddressList(addr).addresslist)
[404] Fix | Delete
[405] Fix | Delete
if not addrs or len(addrs) > 1:
[406] Fix | Delete
return ('', '')
[407] Fix | Delete
[408] Fix | Delete
return addrs[0]
[409] Fix | Delete
[410] Fix | Delete
[411] Fix | Delete
# rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3.
[412] Fix | Delete
def unquote(str):
[413] Fix | Delete
"""Remove quotes from a string."""
[414] Fix | Delete
if len(str) > 1:
[415] Fix | Delete
if str.startswith('"') and str.endswith('"'):
[416] Fix | Delete
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
[417] Fix | Delete
if str.startswith('<') and str.endswith('>'):
[418] Fix | Delete
return str[1:-1]
[419] Fix | Delete
return str
[420] Fix | Delete
[421] Fix | Delete
[422] Fix | Delete
[423] Fix | Delete
# RFC2231-related functions - parameter encoding and decoding
[424] Fix | Delete
def decode_rfc2231(s):
[425] Fix | Delete
"""Decode string according to RFC 2231"""
[426] Fix | Delete
parts = s.split(TICK, 2)
[427] Fix | Delete
if len(parts) <= 2:
[428] Fix | Delete
return None, None, s
[429] Fix | Delete
return parts
[430] Fix | Delete
[431] Fix | Delete
[432] Fix | Delete
def encode_rfc2231(s, charset=None, language=None):
[433] Fix | Delete
"""Encode string according to RFC 2231.
[434] Fix | Delete
[435] Fix | Delete
If neither charset nor language is given, then s is returned as-is. If
[436] Fix | Delete
charset is given but not language, the string is encoded using the empty
[437] Fix | Delete
string for language.
[438] Fix | Delete
"""
[439] Fix | Delete
s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii')
[440] Fix | Delete
if charset is None and language is None:
[441] Fix | Delete
return s
[442] Fix | Delete
if language is None:
[443] Fix | Delete
language = ''
[444] Fix | Delete
return "%s'%s'%s" % (charset, language, s)
[445] Fix | Delete
[446] Fix | Delete
[447] Fix | Delete
rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$',
[448] Fix | Delete
re.ASCII)
[449] Fix | Delete
[450] Fix | Delete
def decode_params(params):
[451] Fix | Delete
"""Decode parameters list according to RFC 2231.
[452] Fix | Delete
[453] Fix | Delete
params is a sequence of 2-tuples containing (param name, string value).
[454] Fix | Delete
"""
[455] Fix | Delete
# Copy params so we don't mess with the original
[456] Fix | Delete
params = params[:]
[457] Fix | Delete
new_params = []
[458] Fix | Delete
# Map parameter's name to a list of continuations. The values are a
[459] Fix | Delete
# 3-tuple of the continuation number, the string value, and a flag
[460] Fix | Delete
# specifying whether a particular segment is %-encoded.
[461] Fix | Delete
rfc2231_params = {}
[462] Fix | Delete
name, value = params.pop(0)
[463] Fix | Delete
new_params.append((name, value))
[464] Fix | Delete
while params:
[465] Fix | Delete
name, value = params.pop(0)
[466] Fix | Delete
if name.endswith('*'):
[467] Fix | Delete
encoded = True
[468] Fix | Delete
else:
[469] Fix | Delete
encoded = False
[470] Fix | Delete
value = unquote(value)
[471] Fix | Delete
mo = rfc2231_continuation.match(name)
[472] Fix | Delete
if mo:
[473] Fix | Delete
name, num = mo.group('name', 'num')
[474] Fix | Delete
if num is not None:
[475] Fix | Delete
num = int(num)
[476] Fix | Delete
rfc2231_params.setdefault(name, []).append((num, value, encoded))
[477] Fix | Delete
else:
[478] Fix | Delete
new_params.append((name, '"%s"' % quote(value)))
[479] Fix | Delete
if rfc2231_params:
[480] Fix | Delete
for name, continuations in rfc2231_params.items():
[481] Fix | Delete
value = []
[482] Fix | Delete
extended = False
[483] Fix | Delete
# Sort by number
[484] Fix | Delete
continuations.sort()
[485] Fix | Delete
# And now append all values in numerical order, converting
[486] Fix | Delete
# %-encodings for the encoded segments. If any of the
[487] Fix | Delete
# continuation names ends in a *, then the entire string, after
[488] Fix | Delete
# decoding segments and concatenating, must have the charset and
[489] Fix | Delete
# language specifiers at the beginning of the string.
[490] Fix | Delete
for num, s, encoded in continuations:
[491] Fix | Delete
if encoded:
[492] Fix | Delete
# Decode as "latin-1", so the characters in s directly
[493] Fix | Delete
# represent the percent-encoded octet values.
[494] Fix | Delete
# collapse_rfc2231_value treats this as an octet sequence.
[495] Fix | Delete
s = urllib.parse.unquote(s, encoding="latin-1")
[496] Fix | Delete
extended = True
[497] Fix | Delete
value.append(s)
[498] Fix | Delete
value = quote(EMPTYSTRING.join(value))
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function