PageRenderTime 109ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/utils/feedparser.py

https://github.com/samuelclay/NewsBlur
Python | 3798 lines | 3466 code | 138 blank | 194 comment | 253 complexity | 9078d25558f9ab7276798be9ee90b553 MD5 | raw file
Possible License(s): MIT, GPL-2.0, BSD-3-Clause
  1. """Universal feed parser
  2. Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds
  3. Visit https://code.google.com/p/feedparser/ for the latest version
  4. Visit http://packages.python.org/feedparser/ for the latest documentation
  5. Required: Python 2.4 or later
  6. Recommended: iconv_codec <http://cjkpython.i18n.org/>
  7. """
  8. __version__ = "5.1.3"
  9. __license__ = """
  10. Copyright (c) 2010-2013 Kurt McKee <contactme@kurtmckee.org>
  11. Copyright (c) 2002-2008 Mark Pilgrim
  12. All rights reserved.
  13. Redistribution and use in source and binary forms, with or without modification,
  14. are permitted provided that the following conditions are met:
  15. * Redistributions of source code must retain the above copyright notice,
  16. this list of conditions and the following disclaimer.
  17. * Redistributions in binary form must reproduce the above copyright notice,
  18. this list of conditions and the following disclaimer in the documentation
  19. and/or other materials provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
  21. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. POSSIBILITY OF SUCH DAMAGE."""
  31. __author__ = "Mark Pilgrim <http://diveintomark.org/>"
  32. __contributors__ = ["Jason Diamond <http://injektilo.org/>",
  33. "John Beimler <http://john.beimler.org/>",
  34. "Fazal Majid <http://www.majid.info/mylos/weblog/>",
  35. "Aaron Swartz <http://aaronsw.com/>",
  36. "Kevin Marks <http://epeus.blogspot.com/>",
  37. "Sam Ruby <http://intertwingly.net/>",
  38. "Ade Oshineye <http://blog.oshineye.com/>",
  39. "Martin Pool <http://sourcefrog.net/>",
  40. "Kurt McKee <http://kurtmckee.org/>",
  41. "Bernd Schlapsi <https://github.com/brot>",]
  42. # HTTP "User-Agent" header to send to servers when downloading feeds.
  43. # If you are embedding feedparser in a larger application, you should
  44. # change this to your application name and URL.
  45. USER_AGENT = "UniversalFeedParser/%s +https://code.google.com/p/feedparser/" % __version__
  46. # HTTP "Accept" header to send to servers when downloading feeds. If you don't
  47. # want to send an Accept header, set this to None.
  48. ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1"
  49. # List of preferred XML parsers, by SAX driver name. These will be tried first,
  50. # but if they're not installed, Python will keep searching through its own list
  51. # of pre-installed parsers until it finds one that supports everything we need.
  52. PREFERRED_XML_PARSERS = ["drv_libxml2"]
  53. # If you want feedparser to automatically resolve all relative URIs, set this
  54. # to 1.
  55. RESOLVE_RELATIVE_URIS = 1
  56. # If you want feedparser to automatically sanitize all potentially unsafe
  57. # HTML content, set this to 1.
  58. SANITIZE_HTML = 1
  59. # ---------- Python 3 modules (make it work if possible) ----------
  60. try:
  61. import rfc822
  62. except ImportError:
  63. from email import _parseaddr as rfc822
  64. try:
  65. # Python 3.1 introduces bytes.maketrans and simultaneously
  66. # deprecates string.maketrans; use bytes.maketrans if possible
  67. _maketrans = bytes.maketrans
  68. except (NameError, AttributeError):
  69. import string
  70. _maketrans = string.maketrans
  71. # base64 support for Atom feeds that contain embedded binary data
  72. try:
  73. import base64, binascii
  74. except ImportError:
  75. base64 = binascii = None
  76. else:
  77. # Python 3.1 deprecates decodestring in favor of decodebytes
  78. _base64decode = getattr(base64, 'decodebytes', base64.decodestring)
  79. # _s2bytes: convert a UTF-8 str to bytes if the interpreter is Python 3
  80. # _l2bytes: convert a list of ints to bytes if the interpreter is Python 3
  81. try:
  82. if bytes is str:
  83. # In Python 2.5 and below, bytes doesn't exist (NameError)
  84. # In Python 2.6 and above, bytes and str are the same type
  85. raise NameError
  86. except NameError:
  87. # Python 2
  88. def _s2bytes(s):
  89. return s
  90. def _l2bytes(l):
  91. return ''.join(map(chr, l))
  92. else:
  93. # Python 3
  94. def _s2bytes(s):
  95. return bytes(s, 'utf8')
  96. def _l2bytes(l):
  97. return bytes(l)
  98. # If you want feedparser to allow all URL schemes, set this to ()
  99. # List culled from Python's urlparse documentation at:
  100. # http://docs.python.org/library/urlparse.html
  101. # as well as from "URI scheme" at Wikipedia:
  102. # https://secure.wikimedia.org/wikipedia/en/wiki/URI_scheme
  103. # Many more will likely need to be added!
  104. ACCEPTABLE_URI_SCHEMES = (
  105. 'file', 'ftp', 'gopher', 'h323', 'hdl', 'http', 'https', 'imap', 'magnet',
  106. 'mailto', 'mms', 'news', 'nntp', 'prospero', 'rsync', 'rtsp', 'rtspu',
  107. 'sftp', 'shttp', 'sip', 'sips', 'snews', 'svn', 'svn+ssh', 'telnet',
  108. 'wais',
  109. # Additional common-but-unofficial schemes
  110. 'aim', 'callto', 'cvs', 'facetime', 'feed', 'git', 'gtalk', 'irc', 'ircs',
  111. 'irc6', 'itms', 'mms', 'msnim', 'skype', 'ssh', 'smb', 'svn', 'ymsg',
  112. )
  113. #ACCEPTABLE_URI_SCHEMES = ()
  114. # ---------- required modules (should come with any Python distribution) ----------
  115. import cgi
  116. import codecs
  117. import copy
  118. import datetime
  119. import itertools
  120. import re
  121. import struct
  122. import time
  123. import types
  124. import urllib
  125. import urllib2
  126. import urlparse
  127. import warnings
  128. from htmlentitydefs import name2codepoint, codepoint2name, entitydefs
  129. try:
  130. from io import BytesIO as _StringIO
  131. except ImportError:
  132. try:
  133. from cStringIO import StringIO as _StringIO
  134. except ImportError:
  135. from StringIO import StringIO as _StringIO
  136. # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
  137. # gzip is included with most Python distributions, but may not be available if you compiled your own
  138. try:
  139. import gzip
  140. except ImportError:
  141. gzip = None
  142. try:
  143. import zlib
  144. except ImportError:
  145. zlib = None
  146. # If a real XML parser is available, feedparser will attempt to use it. feedparser has
  147. # been tested with the built-in SAX parser and libxml2. On platforms where the
  148. # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
  149. # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
  150. try:
  151. import xml.sax
  152. from xml.sax.saxutils import escape as _xmlescape
  153. except ImportError:
  154. _XML_AVAILABLE = 0
  155. def _xmlescape(data,entities={}):
  156. data = data.replace('&', '&amp;')
  157. data = data.replace('>', '&gt;')
  158. data = data.replace('<', '&lt;')
  159. for char, entity in entities:
  160. data = data.replace(char, entity)
  161. return data
  162. else:
  163. try:
  164. xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
  165. except xml.sax.SAXReaderNotAvailable:
  166. _XML_AVAILABLE = 0
  167. else:
  168. _XML_AVAILABLE = 1
  169. # sgmllib is not available by default in Python 3; if the end user doesn't have
  170. # it available then we'll lose illformed XML parsing and content santizing
  171. try:
  172. import sgmllib
  173. except ImportError:
  174. # This is probably Python 3, which doesn't include sgmllib anymore
  175. _SGML_AVAILABLE = 0
  176. # Mock sgmllib enough to allow subclassing later on
  177. class sgmllib(object):
  178. class SGMLParser(object):
  179. def goahead(self, i):
  180. pass
  181. def parse_starttag(self, i):
  182. pass
  183. else:
  184. _SGML_AVAILABLE = 1
  185. # sgmllib defines a number of module-level regular expressions that are
  186. # insufficient for the XML parsing feedparser needs. Rather than modify
  187. # the variables directly in sgmllib, they're defined here using the same
  188. # names, and the compiled code objects of several sgmllib.SGMLParser
  189. # methods are copied into _BaseHTMLProcessor so that they execute in
  190. # feedparser's scope instead of sgmllib's scope.
  191. charref = re.compile('&#(\d+|[xX][0-9a-fA-F]+);')
  192. tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  193. attrfind = re.compile(
  194. r'\s*([a-zA-Z_][-:.a-zA-Z_0-9]*)[$]?(\s*=\s*'
  195. r'(\'[^\']*\'|"[^"]*"|[][\-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~\'"@]*))?'
  196. )
  197. # Unfortunately, these must be copied over to prevent NameError exceptions
  198. entityref = sgmllib.entityref
  199. incomplete = sgmllib.incomplete
  200. interesting = sgmllib.interesting
  201. shorttag = sgmllib.shorttag
  202. shorttagopen = sgmllib.shorttagopen
  203. starttagopen = sgmllib.starttagopen
  204. class _EndBracketRegEx:
  205. def __init__(self):
  206. # Overriding the built-in sgmllib.endbracket regex allows the
  207. # parser to find angle brackets embedded in element attributes.
  208. self.endbracket = re.compile('''([^'"<>]|"[^"]*"(?=>|/|\s|\w+=)|'[^']*'(?=>|/|\s|\w+=))*(?=[<>])|.*?(?=[<>])''')
  209. def search(self, target, index=0):
  210. match = self.endbracket.match(target, index)
  211. if match is not None:
  212. # Returning a new object in the calling thread's context
  213. # resolves a thread-safety.
  214. return EndBracketMatch(match)
  215. return None
  216. class EndBracketMatch:
  217. def __init__(self, match):
  218. self.match = match
  219. def start(self, n):
  220. return self.match.end(n)
  221. endbracket = _EndBracketRegEx()
  222. # iconv_codec provides support for more character encodings.
  223. # It's available from http://cjkpython.i18n.org/
  224. try:
  225. import iconv_codec
  226. except ImportError:
  227. pass
  228. # chardet library auto-detects character encodings
  229. # Download from http://chardet.feedparser.org/
  230. try:
  231. import chardet
  232. except ImportError:
  233. chardet = None
  234. # ---------- don't touch these ----------
  235. class ThingsNobodyCaresAboutButMe(Exception): pass
  236. class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
  237. class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
  238. class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
  239. class UndeclaredNamespace(Exception): pass
  240. SUPPORTED_VERSIONS = {'': u'unknown',
  241. 'rss090': u'RSS 0.90',
  242. 'rss091n': u'RSS 0.91 (Netscape)',
  243. 'rss091u': u'RSS 0.91 (Userland)',
  244. 'rss092': u'RSS 0.92',
  245. 'rss093': u'RSS 0.93',
  246. 'rss094': u'RSS 0.94',
  247. 'rss20': u'RSS 2.0',
  248. 'rss10': u'RSS 1.0',
  249. 'rss': u'RSS (unknown version)',
  250. 'atom01': u'Atom 0.1',
  251. 'atom02': u'Atom 0.2',
  252. 'atom03': u'Atom 0.3',
  253. 'atom10': u'Atom 1.0',
  254. 'atom': u'Atom (unknown version)',
  255. 'cdf': u'CDF',
  256. }
  257. class FeedParserDict(dict):
  258. keymap = {'channel': 'feed',
  259. 'items': 'entries',
  260. 'guid': 'id',
  261. 'date': 'updated',
  262. 'date_parsed': 'updated_parsed',
  263. 'description': ['summary', 'subtitle'],
  264. 'description_detail': ['summary_detail', 'subtitle_detail'],
  265. 'url': ['href'],
  266. 'modified': 'updated',
  267. 'modified_parsed': 'updated_parsed',
  268. 'issued': 'published',
  269. 'issued_parsed': 'published_parsed',
  270. 'copyright': 'rights',
  271. 'copyright_detail': 'rights_detail',
  272. 'tagline': 'subtitle',
  273. 'tagline_detail': 'subtitle_detail'}
  274. def __getitem__(self, key):
  275. if key == 'category':
  276. try:
  277. return dict.__getitem__(self, 'tags')[0]['term']
  278. except IndexError:
  279. raise KeyError, "object doesn't have key 'category'"
  280. elif key == 'enclosures':
  281. norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel'])
  282. return [norel(link) for link in dict.__getitem__(self, 'links') if link['rel']==u'enclosure']
  283. elif key == 'license':
  284. for link in dict.__getitem__(self, 'links'):
  285. if link['rel']==u'license' and 'href' in link:
  286. return link['href']
  287. elif key == 'updated':
  288. # Temporarily help developers out by keeping the old
  289. # broken behavior that was reported in issue 310.
  290. # This fix was proposed in issue 328.
  291. if not dict.__contains__(self, 'updated') and \
  292. dict.__contains__(self, 'published'):
  293. warnings.warn("To avoid breaking existing software while "
  294. "fixing issue 310, a temporary mapping has been created "
  295. "from `updated` to `published` if `updated` doesn't "
  296. "exist. This fallback will be removed in a future version "
  297. "of feedparser.", DeprecationWarning)
  298. return dict.__getitem__(self, 'published')
  299. return dict.__getitem__(self, 'updated')
  300. elif key == 'updated_parsed':
  301. if not dict.__contains__(self, 'updated_parsed') and \
  302. dict.__contains__(self, 'published_parsed'):
  303. warnings.warn("To avoid breaking existing software while "
  304. "fixing issue 310, a temporary mapping has been created "
  305. "from `updated_parsed` to `published_parsed` if "
  306. "`updated_parsed` doesn't exist. This fallback will be "
  307. "removed in a future version of feedparser.",
  308. DeprecationWarning)
  309. return dict.__getitem__(self, 'published_parsed')
  310. return dict.__getitem__(self, 'updated_parsed')
  311. else:
  312. realkey = self.keymap.get(key, key)
  313. if isinstance(realkey, list):
  314. for k in realkey:
  315. if dict.__contains__(self, k):
  316. return dict.__getitem__(self, k)
  317. elif dict.__contains__(self, realkey):
  318. return dict.__getitem__(self, realkey)
  319. return dict.__getitem__(self, key)
  320. def __contains__(self, key):
  321. if key in ('updated', 'updated_parsed'):
  322. # Temporarily help developers out by keeping the old
  323. # broken behavior that was reported in issue 310.
  324. # This fix was proposed in issue 328.
  325. return dict.__contains__(self, key)
  326. try:
  327. self.__getitem__(key)
  328. except KeyError:
  329. return False
  330. else:
  331. return True
  332. has_key = __contains__
  333. def get(self, key, default=None):
  334. try:
  335. return self.__getitem__(key)
  336. except KeyError:
  337. return default
  338. def __setitem__(self, key, value):
  339. key = self.keymap.get(key, key)
  340. if isinstance(key, list):
  341. key = key[0]
  342. return dict.__setitem__(self, key, value)
  343. def setdefault(self, key, value):
  344. if key not in self:
  345. self[key] = value
  346. return value
  347. return self[key]
  348. def __getattr__(self, key):
  349. # __getattribute__() is called first; this will be called
  350. # only if an attribute was not already found
  351. try:
  352. return self.__getitem__(key)
  353. except KeyError:
  354. raise AttributeError, "object has no attribute '%s'" % key
  355. def __hash__(self):
  356. return id(self)
  357. _cp1252 = {
  358. 128: unichr(8364), # euro sign
  359. 130: unichr(8218), # single low-9 quotation mark
  360. 131: unichr( 402), # latin small letter f with hook
  361. 132: unichr(8222), # double low-9 quotation mark
  362. 133: unichr(8230), # horizontal ellipsis
  363. 134: unichr(8224), # dagger
  364. 135: unichr(8225), # double dagger
  365. 136: unichr( 710), # modifier letter circumflex accent
  366. 137: unichr(8240), # per mille sign
  367. 138: unichr( 352), # latin capital letter s with caron
  368. 139: unichr(8249), # single left-pointing angle quotation mark
  369. 140: unichr( 338), # latin capital ligature oe
  370. 142: unichr( 381), # latin capital letter z with caron
  371. 145: unichr(8216), # left single quotation mark
  372. 146: unichr(8217), # right single quotation mark
  373. 147: unichr(8220), # left double quotation mark
  374. 148: unichr(8221), # right double quotation mark
  375. 149: unichr(8226), # bullet
  376. 150: unichr(8211), # en dash
  377. 151: unichr(8212), # em dash
  378. 152: unichr( 732), # small tilde
  379. 153: unichr(8482), # trade mark sign
  380. 154: unichr( 353), # latin small letter s with caron
  381. 155: unichr(8250), # single right-pointing angle quotation mark
  382. 156: unichr( 339), # latin small ligature oe
  383. 158: unichr( 382), # latin small letter z with caron
  384. 159: unichr( 376), # latin capital letter y with diaeresis
  385. }
  386. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  387. def _urljoin(base, uri):
  388. uri = _urifixer.sub(r'\1\3', uri)
  389. if not isinstance(uri, unicode):
  390. uri = uri.decode('utf-8', 'ignore')
  391. try:
  392. uri = urlparse.urljoin(base, uri)
  393. except ValueError:
  394. uri = u''
  395. if not isinstance(uri, unicode):
  396. return uri.decode('utf-8', 'ignore')
  397. return uri
  398. class _FeedParserMixin:
  399. namespaces = {
  400. '': '',
  401. 'http://backend.userland.com/rss': '',
  402. 'http://blogs.law.harvard.edu/tech/rss': '',
  403. 'http://purl.org/rss/1.0/': '',
  404. 'http://my.netscape.com/rdf/simple/0.9/': '',
  405. 'http://example.com/newformat#': '',
  406. 'http://example.com/necho': '',
  407. 'http://purl.org/echo/': '',
  408. 'uri/of/echo/namespace#': '',
  409. 'http://purl.org/pie/': '',
  410. 'http://purl.org/atom/ns#': '',
  411. 'http://www.w3.org/2005/Atom': '',
  412. 'http://purl.org/rss/1.0/modules/rss091#': '',
  413. 'http://webns.net/mvcb/': 'admin',
  414. 'http://purl.org/rss/1.0/modules/aggregation/': 'ag',
  415. 'http://purl.org/rss/1.0/modules/annotate/': 'annotate',
  416. 'http://media.tangent.org/rss/1.0/': 'audio',
  417. 'http://backend.userland.com/blogChannelModule': 'blogChannel',
  418. 'http://web.resource.org/cc/': 'cc',
  419. 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  420. 'http://purl.org/rss/1.0/modules/company': 'co',
  421. 'http://purl.org/rss/1.0/modules/content/': 'content',
  422. 'http://my.theinfo.org/changed/1.0/rss/': 'cp',
  423. 'http://purl.org/dc/elements/1.1/': 'dc',
  424. 'http://purl.org/dc/terms/': 'dcterms',
  425. 'http://purl.org/rss/1.0/modules/email/': 'email',
  426. 'http://purl.org/rss/1.0/modules/event/': 'ev',
  427. 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner',
  428. 'http://freshmeat.net/rss/fm/': 'fm',
  429. 'http://xmlns.com/foaf/0.1/': 'foaf',
  430. 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo',
  431. 'http://www.georss.org/georss': 'georss',
  432. 'http://www.opengis.net/gml': 'gml',
  433. 'http://postneo.com/icbm/': 'icbm',
  434. 'http://purl.org/rss/1.0/modules/image/': 'image',
  435. 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
  436. 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
  437. 'http://purl.org/rss/1.0/modules/link/': 'l',
  438. 'http://search.yahoo.com/mrss': 'media',
  439. # Version 1.1.2 of the Media RSS spec added the trailing slash on the namespace
  440. 'http://search.yahoo.com/mrss/': 'media',
  441. 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  442. 'http://prismstandard.org/namespaces/1.2/basic/': 'prism',
  443. 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
  444. 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs',
  445. 'http://purl.org/rss/1.0/modules/reference/': 'ref',
  446. 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv',
  447. 'http://purl.org/rss/1.0/modules/search/': 'search',
  448. 'http://purl.org/rss/1.0/modules/slash/': 'slash',
  449. 'http://schemas.xmlsoap.org/soap/envelope/': 'soap',
  450. 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss',
  451. 'http://hacks.benhammersley.com/rss/streaming/': 'str',
  452. 'http://purl.org/rss/1.0/modules/subscription/': 'sub',
  453. 'http://purl.org/rss/1.0/modules/syndication/': 'sy',
  454. 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf',
  455. 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo',
  456. 'http://purl.org/rss/1.0/modules/threading/': 'thr',
  457. 'http://purl.org/rss/1.0/modules/textinput/': 'ti',
  458. 'http://madskills.com/public/xml/rss/module/trackback/': 'trackback',
  459. 'http://wellformedweb.org/commentAPI/': 'wfw',
  460. 'http://purl.org/rss/1.0/modules/wiki/': 'wiki',
  461. 'http://www.w3.org/1999/xhtml': 'xhtml',
  462. 'http://www.w3.org/1999/xlink': 'xlink',
  463. 'http://www.w3.org/XML/1998/namespace': 'xml',
  464. 'http://podlove.org/simple-chapters': 'psc',
  465. }
  466. _matchnamespaces = {}
  467. can_be_relative_uri = set(['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'icon', 'logo'])
  468. can_contain_relative_uris = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description'])
  469. can_contain_dangerous_markup = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description'])
  470. html_types = [u'text/html', u'application/xhtml+xml']
  471. def __init__(self, baseuri=None, baselang=None, encoding=u'utf-8'):
  472. if not self._matchnamespaces:
  473. for k, v in self.namespaces.items():
  474. self._matchnamespaces[k.lower()] = v
  475. self.feeddata = FeedParserDict() # feed-level data
  476. self.encoding = encoding # character encoding
  477. self.entries = [] # list of entry-level data
  478. self.version = u'' # feed type/version, see SUPPORTED_VERSIONS
  479. self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  480. # the following are used internally to track state;
  481. # this is really out of control and should be refactored
  482. self.infeed = 0
  483. self.inentry = 0
  484. self.incontent = 0
  485. self.intextinput = 0
  486. self.inimage = 0
  487. self.inauthor = 0
  488. self.incontributor = 0
  489. self.inpublisher = 0
  490. self.insource = 0
  491. # georss
  492. self.ingeometry = 0
  493. self.sourcedata = FeedParserDict()
  494. self.contentparams = FeedParserDict()
  495. self._summaryKey = None
  496. self.namespacemap = {}
  497. self.elementstack = []
  498. self.basestack = []
  499. self.langstack = []
  500. self.baseuri = baseuri or u''
  501. self.lang = baselang or None
  502. self.svgOK = 0
  503. self.title_depth = -1
  504. self.depth = 0
  505. # psc_chapters_flag prevents multiple psc_chapters from being
  506. # captured in a single entry or item. The transition states are
  507. # None -> True -> False. psc_chapter elements will only be
  508. # captured while it is True.
  509. self.psc_chapters_flag = None
  510. if baselang:
  511. self.feeddata['language'] = baselang.replace('_','-')
  512. # A map of the following form:
  513. # {
  514. # object_that_value_is_set_on: {
  515. # property_name: depth_of_node_property_was_extracted_from,
  516. # other_property: depth_of_node_property_was_extracted_from,
  517. # },
  518. # }
  519. self.property_depth_map = {}
  520. def _normalize_attributes(self, kv):
  521. k = kv[0].lower()
  522. v = k in ('rel', 'type') and kv[1].lower() or kv[1]
  523. # the sgml parser doesn't handle entities in attributes, nor
  524. # does it pass the attribute values through as unicode, while
  525. # strict xml parsers do -- account for this difference
  526. if isinstance(self, _LooseFeedParser):
  527. v = v.replace('&amp;', '&')
  528. if not isinstance(v, unicode):
  529. v = v.decode('utf-8')
  530. return (k, v)
  531. def unknown_starttag(self, tag, attrs):
  532. # increment depth counter
  533. self.depth += 1
  534. # normalize attrs
  535. attrs = map(self._normalize_attributes, attrs)
  536. # track xml:base and xml:lang
  537. attrsD = dict(attrs)
  538. baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  539. if not isinstance(baseuri, unicode):
  540. baseuri = baseuri.decode(self.encoding, 'ignore')
  541. # ensure that self.baseuri is always an absolute URI that
  542. # uses a whitelisted URI scheme (e.g. not `javscript:`)
  543. if self.baseuri:
  544. self.baseuri = _makeSafeAbsoluteURI(self.baseuri, baseuri) or self.baseuri
  545. else:
  546. self.baseuri = _urljoin(self.baseuri, baseuri)
  547. lang = attrsD.get('xml:lang', attrsD.get('lang'))
  548. if lang == '':
  549. # xml:lang could be explicitly set to '', we need to capture that
  550. lang = None
  551. elif lang is None:
  552. # if no xml:lang is specified, use parent lang
  553. lang = self.lang
  554. if lang:
  555. if tag in ('feed', 'rss', 'rdf:RDF'):
  556. self.feeddata['language'] = lang.replace('_','-')
  557. self.lang = lang
  558. self.basestack.append(self.baseuri)
  559. self.langstack.append(lang)
  560. # track namespaces
  561. for prefix, uri in attrs:
  562. if prefix.startswith('xmlns:'):
  563. self.trackNamespace(prefix[6:], uri)
  564. elif prefix == 'xmlns':
  565. self.trackNamespace(None, uri)
  566. # track inline content
  567. if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'):
  568. if tag in ('xhtml:div', 'div'):
  569. return # typepad does this 10/2007
  570. # element declared itself as escaped markup, but it isn't really
  571. self.contentparams['type'] = u'application/xhtml+xml'
  572. if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml':
  573. if tag.find(':') <> -1:
  574. prefix, tag = tag.split(':', 1)
  575. namespace = self.namespacesInUse.get(prefix, '')
  576. if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
  577. attrs.append(('xmlns',namespace))
  578. if tag=='svg' and namespace=='http://www.w3.org/2000/svg':
  579. attrs.append(('xmlns',namespace))
  580. if tag == 'svg':
  581. self.svgOK += 1
  582. return self.handle_data('<%s%s>' % (tag, self.strattrs(attrs)), escape=0)
  583. # match namespaces
  584. if tag.find(':') <> -1:
  585. prefix, suffix = tag.split(':', 1)
  586. else:
  587. prefix, suffix = '', tag
  588. prefix = self.namespacemap.get(prefix, prefix)
  589. if prefix:
  590. prefix = prefix + '_'
  591. # special hack for better tracking of empty textinput/image elements in illformed feeds
  592. if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  593. self.intextinput = 0
  594. if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  595. self.inimage = 0
  596. # call special handler (if defined) or default handler
  597. methodname = '_start_' + prefix + suffix
  598. try:
  599. method = getattr(self, methodname)
  600. return method(attrsD)
  601. except AttributeError:
  602. # Since there's no handler or something has gone wrong we explicitly add the element and its attributes
  603. unknown_tag = prefix + suffix
  604. if len(attrsD) == 0:
  605. # No attributes so merge it into the encosing dictionary
  606. return self.push(unknown_tag, 1)
  607. else:
  608. # Has attributes so create it in its own dictionary
  609. context = self._getContext()
  610. context[unknown_tag] = attrsD
  611. def unknown_endtag(self, tag):
  612. # match namespaces
  613. if tag.find(':') <> -1:
  614. prefix, suffix = tag.split(':', 1)
  615. else:
  616. prefix, suffix = '', tag
  617. prefix = self.namespacemap.get(prefix, prefix)
  618. if prefix:
  619. prefix = prefix + '_'
  620. if suffix == 'svg' and self.svgOK:
  621. self.svgOK -= 1
  622. # call special handler (if defined) or default handler
  623. methodname = '_end_' + prefix + suffix
  624. try:
  625. if self.svgOK:
  626. raise AttributeError()
  627. method = getattr(self, methodname)
  628. method()
  629. except AttributeError:
  630. self.pop(prefix + suffix)
  631. # track inline content
  632. if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'):
  633. # element declared itself as escaped markup, but it isn't really
  634. if tag in ('xhtml:div', 'div'):
  635. return # typepad does this 10/2007
  636. self.contentparams['type'] = u'application/xhtml+xml'
  637. if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml':
  638. tag = tag.split(':')[-1]
  639. self.handle_data('</%s>' % tag, escape=0)
  640. # track xml:base and xml:lang going out of scope
  641. if self.basestack:
  642. self.basestack.pop()
  643. if self.basestack and self.basestack[-1]:
  644. self.baseuri = self.basestack[-1]
  645. if self.langstack:
  646. self.langstack.pop()
  647. if self.langstack: # and (self.langstack[-1] is not None):
  648. self.lang = self.langstack[-1]
  649. self.depth -= 1
  650. def handle_charref(self, ref):
  651. # called for each character reference, e.g. for '&#160;', ref will be '160'
  652. if not self.elementstack:
  653. return
  654. ref = ref.lower()
  655. if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  656. text = '&#%s;' % ref
  657. else:
  658. if ref[0] == 'x':
  659. c = int(ref[1:], 16)
  660. else:
  661. c = int(ref)
  662. text = unichr(c).encode('utf-8')
  663. self.elementstack[-1][2].append(text)
  664. def handle_entityref(self, ref):
  665. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  666. if not self.elementstack:
  667. return
  668. if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  669. text = '&%s;' % ref
  670. elif ref in self.entities:
  671. text = self.entities[ref]
  672. if text.startswith('&#') and text.endswith(';'):
  673. return self.handle_entityref(text)
  674. else:
  675. try:
  676. name2codepoint[ref]
  677. except KeyError:
  678. text = '&%s;' % ref
  679. else:
  680. text = unichr(name2codepoint[ref]).encode('utf-8')
  681. self.elementstack[-1][2].append(text)
  682. def handle_data(self, text, escape=1):
  683. # called for each block of plain text, i.e. outside of any tag and
  684. # not containing any character or entity references
  685. if not self.elementstack:
  686. return
  687. if escape and self.contentparams.get('type') == u'application/xhtml+xml':
  688. text = _xmlescape(text)
  689. self.elementstack[-1][2].append(text)
  690. def handle_comment(self, text):
  691. # called for each comment, e.g. <!-- insert message here -->
  692. pass
  693. def handle_pi(self, text):
  694. # called for each processing instruction, e.g. <?instruction>
  695. pass
  696. def handle_decl(self, text):
  697. pass
  698. def parse_declaration(self, i):
  699. # override internal declaration handler to handle CDATA blocks
  700. if self.rawdata[i:i+9] == '<![CDATA[':
  701. k = self.rawdata.find(']]>', i)
  702. if k == -1:
  703. # CDATA block began but didn't finish
  704. k = len(self.rawdata)
  705. return k
  706. self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  707. return k+3
  708. else:
  709. k = self.rawdata.find('>', i)
  710. if k >= 0:
  711. return k+1
  712. else:
  713. # We have an incomplete CDATA block.
  714. return k
  715. def mapContentType(self, contentType):
  716. contentType = contentType.lower()
  717. if contentType == 'text' or contentType == 'plain':
  718. contentType = u'text/plain'
  719. elif contentType == 'html':
  720. contentType = u'text/html'
  721. elif contentType == 'xhtml':
  722. contentType = u'application/xhtml+xml'
  723. return contentType
  724. def trackNamespace(self, prefix, uri):
  725. loweruri = uri.lower()
  726. if not self.version:
  727. if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/'):
  728. self.version = u'rss090'
  729. elif loweruri == 'http://purl.org/rss/1.0/':
  730. self.version = u'rss10'
  731. elif loweruri == 'http://www.w3.org/2005/atom':
  732. self.version = u'atom10'
  733. if loweruri.find(u'backend.userland.com/rss') <> -1:
  734. # match any backend.userland.com namespace
  735. uri = u'http://backend.userland.com/rss'
  736. loweruri = uri
  737. if loweruri in self._matchnamespaces:
  738. self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  739. self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  740. else:
  741. self.namespacesInUse[prefix or ''] = uri
  742. def resolveURI(self, uri):
  743. return _urljoin(self.baseuri or u'', uri)
  744. def decodeEntities(self, element, data):
  745. return data
  746. def strattrs(self, attrs):
  747. return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'&quot;'})) for t in attrs])
  748. def push(self, element, expectingText):
  749. self.elementstack.append([element, expectingText, []])
  750. def pop(self, element, stripWhitespace=1):
  751. if not self.elementstack:
  752. return
  753. if self.elementstack[-1][0] != element:
  754. return
  755. element, expectingText, pieces = self.elementstack.pop()
  756. if self.version == u'atom10' and self.contentparams.get('type', u'text') == u'application/xhtml+xml':
  757. # remove enclosing child element, but only if it is a <div> and
  758. # only if all the remaining content is nested underneath it.
  759. # This means that the divs would be retained in the following:
  760. # <div>foo</div><div>bar</div>
  761. while pieces and len(pieces)>1 and not pieces[-1].strip():
  762. del pieces[-1]
  763. while pieces and len(pieces)>1 and not pieces[0].strip():
  764. del pieces[0]
  765. if pieces and (pieces[0] == '<div>' or pieces[0].startswith('<div ')) and pieces[-1]=='</div>':
  766. depth = 0
  767. for piece in pieces[:-1]:
  768. if piece.startswith('</'):
  769. depth -= 1
  770. if depth == 0:
  771. break
  772. elif piece.startswith('<') and not piece.endswith('/>'):
  773. depth += 1
  774. else:
  775. pieces = pieces[1:-1]
  776. # Ensure each piece is a str for Python 3
  777. for (i, v) in enumerate(pieces):
  778. if not isinstance(v, unicode):
  779. pieces[i] = v.decode('utf-8')
  780. output = u''.join(pieces)
  781. if stripWhitespace:
  782. output = output.strip()
  783. if not expectingText:
  784. return output
  785. # decode base64 content
  786. if base64 and self.contentparams.get('base64', 0):
  787. try:
  788. output = _base64decode(output)
  789. except binascii.Error:
  790. pass
  791. except binascii.Incomplete:
  792. pass
  793. except TypeError:
  794. # In Python 3, base64 takes and outputs bytes, not str
  795. # This may not be the most correct way to accomplish this
  796. output = _base64decode(output.encode('utf-8')).decode('utf-8')
  797. # resolve relative URIs
  798. if (element in self.can_be_relative_uri) and output:
  799. # do not resolve guid elements with isPermalink="false"
  800. if not element == 'id' or self.guidislink:
  801. output = self.resolveURI(output)
  802. # decode entities within embedded markup
  803. if not self.contentparams.get('base64', 0):
  804. output = self.decodeEntities(element, output)
  805. # some feed formats require consumers to guess
  806. # whether the content is html or plain text
  807. if not self.version.startswith(u'atom') and self.contentparams.get('type') == u'text/plain':
  808. if self.lookslikehtml(output):
  809. self.contentparams['type'] = u'text/html'
  810. # remove temporary cruft from contentparams
  811. try:
  812. del self.contentparams['mode']
  813. except KeyError:
  814. pass
  815. try:
  816. del self.contentparams['base64']
  817. except KeyError:
  818. pass
  819. is_htmlish = self.mapContentType(self.contentparams.get('type', u'text/html')) in self.html_types
  820. # resolve relative URIs within embedded markup
  821. if is_htmlish and RESOLVE_RELATIVE_URIS:
  822. if element in self.can_contain_relative_uris:
  823. output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', u'text/html'))
  824. # sanitize embedded markup
  825. if is_htmlish and SANITIZE_HTML:
  826. if element in self.can_contain_dangerous_markup:
  827. output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', u'text/html'))
  828. if self.encoding and not isinstance(output, unicode):
  829. output = output.decode(self.encoding, 'ignore')
  830. # address common error where people take data that is already
  831. # utf-8, presume that it is iso-8859-1, and re-encode it.
  832. if self.encoding in (u'utf-8', u'utf-8_INVALID_PYTHON_3') and isinstance(output, unicode):
  833. try:
  834. output = output.encode('iso-8859-1').decode('utf-8')
  835. except (UnicodeEncodeError, UnicodeDecodeError):
  836. pass
  837. # map win-1252 extensions to the proper code points
  838. if isinstance(output, unicode):
  839. output = output.translate(_cp1252)
  840. # categories/tags/keywords/whatever are handled in _end_category
  841. if element == 'category':
  842. return output
  843. if element == 'title' and -1 < self.title_depth <= self.depth:
  844. return output
  845. # store output in appropriate place(s)
  846. if self.inentry and not self.insource:
  847. if element == 'content':
  848. self.entries[-1].setdefault(element, [])
  849. contentparams = copy.deepcopy(self.contentparams)
  850. contentparams['value'] = output
  851. self.entries[-1][element].append(contentparams)
  852. elif element == 'link':
  853. if not self.inimage:
  854. # query variables in urls in link elements are improperly
  855. # converted from `?a=1&b=2` to `?a=1&b;=2` as if they're
  856. # unhandled character references. fix this special case.
  857. output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output)
  858. self.entries[-1][element] = output
  859. if output:
  860. self.entries[-1]['links'][-1]['href'] = output
  861. else:
  862. if element == 'description':
  863. element = 'summary'
  864. old_value_depth = self.property_depth_map.setdefault(self.entries[-1], {}).get(element)
  865. if old_value_depth is None or self.depth <= old_value_depth:
  866. self.property_depth_map[self.entries[-1]][element] = self.depth
  867. self.entries[-1][element] = output
  868. if self.incontent:
  869. contentparams = copy.deepcopy(self.contentparams)
  870. contentparams['value'] = output
  871. self.entries[-1][element + '_detail'] = contentparams
  872. elif (self.infeed or self.insource):# and (not self.intextinput) and (not self.inimage):
  873. context = self._getContext()
  874. if element == 'description':
  875. element = 'subtitle'
  876. context[element] = output
  877. if element == 'link':
  878. # fix query variables; see above for the explanation
  879. output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output)
  880. context[element] = output
  881. context['links'][-1]['href'] = output
  882. elif self.incontent:
  883. contentparams = copy.deepcopy(self.contentparams)
  884. contentparams['value'] = output
  885. context[element + '_detail'] = contentparams
  886. return output
  887. def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  888. self.incontent += 1
  889. if self.lang:
  890. self.lang=self.lang.replace('_','-')
  891. self.contentparams = FeedParserDict({
  892. 'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  893. 'language': self.lang,
  894. 'base': self.baseuri})
  895. self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  896. self.push(tag, expectingText)
  897. def popContent(self, tag):
  898. value = self.pop(tag)
  899. self.incontent -= 1
  900. self.contentparams.clear()
  901. return value
  902. # a number of elements in a number of RSS variants are nominally plain
  903. # text, but this is routinely ignored. This is an attempt to detect
  904. # the most common cases. As false positives often result in silent
  905. # data loss, this function errs on the conservative side.
  906. @staticmethod
  907. def lookslikehtml(s):
  908. # must have a close tag or an entity reference to qualify
  909. if not (re.search(r'</(\w+)>',s) or re.search("&#?\w+;",s)):
  910. return
  911. # all tags must be in a restricted subset of valid HTML tags
  912. if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements,
  913. re.findall(r'</?(\w+)',s)):
  914. return
  915. # all entities must have been defined as valid HTML entities
  916. if filter(lambda e: e not in entitydefs.keys(), re.findall(r'&(\w+);', s)):
  917. return
  918. return 1
  919. def _mapToStandardPrefix(self, name):
  920. colonpos = name.find(':')
  921. if colonpos <> -1:
  922. prefix = name[:colonpos]
  923. suffix = name[colonpos+1:]
  924. prefix = self.namespacemap.get(prefix, prefix)
  925. name = prefix + ':' + suffix
  926. return name
  927. def _getAttribute(self, attrsD, name):
  928. return attrsD.get(self._mapToStandardPrefix(name))
  929. def _isBase64(self, attrsD, contentparams):
  930. if attrsD.get('mode', '') == 'base64':
  931. return 1
  932. if self.contentparams['type'].startswith(u'text/'):
  933. return 0
  934. if self.contentparams['type'].endswith(u'+xml'):
  935. return 0
  936. if self.contentparams['type'].endswith(u'/xml'):
  937. return 0
  938. return 1
  939. def _itsAnHrefDamnIt(self, attrsD):
  940. href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  941. if href:
  942. try:
  943. del attrsD['url']
  944. except KeyError:
  945. pass
  946. try:
  947. del attrsD['uri']
  948. except KeyError:
  949. pass
  950. attrsD['href'] = href
  951. return attrsD
  952. def _save(self, key, value, overwrite=False):
  953. context = self._getContext()
  954. if overwrite:
  955. context[key] = value
  956. else:
  957. context.setdefault(key, value)
  958. def _start_rss(self, attrsD):
  959. versionmap = {'0.91': u'rss091u',
  960. '0.92': u'rss092',
  961. '0.93': u'rss093',
  962. '0.94': u'rss094'}
  963. #If we're here then this is an RSS feed.
  964. #If we don't have a version or have a version that starts with something
  965. #other than RSS then there's been a mistake. Correct it.
  966. if not self.version or not self.version.startswith(u'rss'):
  967. attr_version = attrsD.get('version', '')
  968. version = versionmap.get(attr_version)
  969. if version:
  970. self.version = version
  971. elif attr_version.startswith('2.'):
  972. self.version = u'rss20'
  973. else:
  974. self.version = u'rss'
  975. def _start_channel(self, attrsD):
  976. self.infeed = 1
  977. self._cdf_common(attrsD)
  978. def _cdf_common(self, attrsD):
  979. if 'lastmod' in attrsD:
  980. self._start_modified({})
  981. self.elementstack[-1][-1] = attrsD['lastmod']
  982. self._end_modified()
  983. if 'href' in attrsD:
  984. self._start_link({})
  985. self.elementstack[-1][-1] = attrsD['href']
  986. self._end_link()
  987. def _start_feed(self, attrsD):
  988. self.infeed = 1
  989. versionmap = {'0.1': u'atom01',
  990. '0.2': u'atom02',
  991. '0.3': u'atom03'}
  992. if not self.version:
  993. attr_version = attrsD.get('version')
  994. version = versionmap.get(attr_version)
  995. if version:
  996. self.version = version
  997. else:
  998. self.version = u'atom'
  999. def _end_channel(self):
  1000. self.infeed = 0
  1001. _end_feed = _end_channel
  1002. def _start_image(self, attrsD):
  1003. context = self._getContext()
  1004. if not self.inentry:
  1005. context.setdefault('image', FeedParserDict())
  1006. self.inimage = 1
  1007. self.title_depth = -1
  1008. self.push('image', 0)
  1009. def _end_image(self):
  1010. self.pop('image')
  1011. self.inimage = 0
  1012. def _start_textinput(self, attrsD):
  1013. context = self._getContext()
  1014. context.setdefault('textinput', FeedParserDict())
  1015. self.intextinput = 1
  1016. self.title_depth = -1
  1017. self.push('textinput', 0)
  1018. _start_textInput = _start_textinput
  1019. def _end_textinput(self):
  1020. self.pop('textinput')
  1021. self.intextinput = 0
  1022. _end_textInput = _end_textinput
  1023. def _start_author(self, attrsD):
  1024. self.inauthor = 1
  1025. self.push('author', 1)
  1026. # Append a new FeedParserDict when expecting an author
  1027. context = self._getContext()
  1028. context.setdefault('authors', [])
  1029. context['authors'].append(FeedParserDict())
  1030. _start_managingeditor = _start_author
  1031. _start_dc_author = _start_author
  1032. _start_dc_creator = _start_author
  1033. _start_itunes_author = _start_author
  1034. def _end_author(self):
  1035. self.pop('author')
  1036. self.inauthor = 0
  1037. self._sync_author_detail()
  1038. _end_managingeditor = _end_author
  1039. _end_dc_author = _end_author
  1040. _end_dc_creator = _end_author
  1041. _end_itunes_author = _end_author
  1042. def _start_itunes_owner(self, attrsD):
  1043. self.inpublisher = 1
  1044. self.push('publisher', 0)
  1045. def _end_itunes_owner(self):
  1046. self.pop('publisher')
  1047. self.inpublisher = 0
  1048. self._sync_author_detail('publisher')
  1049. def _start_contributor(self, attrsD):
  1050. self.incontributor = 1
  1051. context = self._getContext()
  1052. context.setdefault('contributors', [])
  1053. context['contributors'].append(FeedParserDict())
  1054. self.push('contributor', 0)
  1055. def _end_contributor(self):
  1056. self.pop('contributor')
  1057. self.incontributor = 0
  1058. def _start_dc_contributor(self, attrsD):
  1059. self.incontributor = 1
  1060. context = self._getContext()
  1061. context.setdefault('contributors', [])
  1062. context['contributors'].append(FeedParserDict())
  1063. self.push('name', 0)
  1064. def _end_dc_contributor(self):
  1065. self._end_name()
  1066. self.incontributor = 0
  1067. def _start_name(self, attrsD):
  1068. self.push('name', 0)
  1069. _start_itunes_name = _start_name
  1070. def _end_name(self):
  1071. value = self.pop('name')
  1072. if self.inpublisher:
  1073. self._save_author('name', value, 'publisher')
  1074. elif self.inauthor:
  1075. self._save_author('name', value)
  1076. elif self.incontributor:
  1077. self._save_contributor('name', value)
  1078. elif self.intextinput:
  1079. context = self._getContext()
  1080. context['name'] = value
  1081. _end_itunes_name = _end_name
  1082. def _start_width(self, attrsD):
  1083. self.push('width', 0)
  1084. def _end_width(self):
  1085. value = self.pop('width')
  1086. try:
  1087. value = int(value)
  1088. except ValueError:
  1089. value = 0
  1090. if self.inimage:
  1091. context = self._getContext()
  1092. context['width'] = value
  1093. def _start_height(self, attrsD):
  1094. self.push('height', 0)
  1095. def _end_height(self):
  1096. value = self.pop('height')
  1097. try:
  1098. value = int(value)
  1099. except ValueError:
  1100. value = 0
  1101. if self.inimage:
  1102. context = self._getContext()
  1103. context['height'] = value
  1104. def _start_url(self, attrsD):
  1105. self.push('href', 1)
  1106. _start_homepage = _start_url
  1107. _start_uri = _start_url
  1108. def _end_url(self):
  1109. value = self.pop('href')
  1110. if self.inauthor:
  1111. self._save_author('href', value)
  1112. elif self.incontributor:
  1113. self._save_contributor('href', value)
  1114. _end_homepage = _end_url
  1115. _end_uri = _end_url
  1116. def _start_email(self, attrsD):
  1117. self.push('email', 0)
  1118. _start_itunes_email = _start_email
  1119. def _end_email(self):
  1120. value = self.pop('email')
  1121. if self.inpublisher:
  1122. self._save_author('email', value, 'publisher')
  1123. elif self.inauthor:
  1124. self._save_author('email', value)
  1125. elif self.incontributor:
  1126. self._save_contributor('email', value)
  1127. _end_itunes_email = _end_email
  1128. def _getContext(self):
  1129. if self.insource:
  1130. context = self.sourcedata
  1131. elif self.inimage and 'image' in self.feeddata:
  1132. context = self.feeddata['image']
  1133. elif self.intextinput:
  1134. context = self.feeddata['textinput']
  1135. elif self.inentry:
  1136. context = self.entries[-1]
  1137. else:
  1138. context = self.feeddata
  1139. return context
  1140. def _save_author(self, key, value, prefix='author'):
  1141. context = self._getContext()
  1142. context.setdefault(prefix + '_detail', FeedParserDict())
  1143. context[prefix + '_detail'][key] = value
  1144. self._sync_author_detail()
  1145. context.setdefault('authors', [FeedParserDict()])
  1146. context['authors'][-1][key] = value
  1147. def _save_contributor(self, key, value):
  1148. context = self._getContext()
  1149. context.setdefault('contributors', [FeedParserDict()])
  1150. context['contributors'][-1][key] = value
  1151. def _sync_author_detail(self, key='author'):
  1152. context = self._getContext()
  1153. detail = context.get('%s_detail' % key)
  1154. if detail:
  1155. name = detail.get('name')
  1156. email = detail.get('email')
  1157. if name and email:
  1158. context[key] = u'%s (%s)' % (name, email)
  1159. elif name:
  1160. context[key] = name
  1161. elif email:
  1162. context[key] = email
  1163. else:
  1164. author, email = context.get(key), None
  1165. if not author:
  1166. return
  1167. emailmatch = re.search(ur'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))(\?subject=\S+)?''', author)
  1168. if emailmatch:
  1169. email = emailmatch.group(0)
  1170. # probably a better way to do the following, but it passes all the tests
  1171. author = author.replace(email, u'')
  1172. author = author.replace(u'()', u'')
  1173. author = author.replace(u'<>', u'')
  1174. author = author.replace(u'&lt;&gt;', u'')
  1175. author = author.strip()
  1176. if author and (author[0] == u'('):
  1177. author = author[1:]
  1178. if author and (author[-1] == u')'):
  1179. author = author[:-1]
  1180. author = author.strip()
  1181. if author or email:
  1182. context.setdefault('%s_detail' % key, FeedParserDict())
  1183. if author:
  1184. context['%s_detail' % key]['name'] = author
  1185. if email:
  1186. context['%s_detail' % key]['email'] = email
  1187. def _start_subtitle(self, attrsD):
  1188. self.pushContent('subtitle', attrsD, u'text/plain', 1)
  1189. _start_tagline = _start_subtitle
  1190. _start_itunes_subtitle = _start_subtitle
  1191. def _end_subtitle(self):
  1192. self.popContent('subtitle')
  1193. _end_tagline = _end_subtitle
  1194. _end_itunes_subtitle = _end_subtitle
  1195. def _start_rights(self, attrsD):
  1196. self.pushContent('rights', attrsD, u'text/plain', 1)
  1197. _start_dc_rights = _start_rights
  1198. _start_copyright = _start_rights
  1199. def _end_rights(self):
  1200. self.popContent('rights')
  1201. _end_dc_rights = _end_rights
  1202. _end_copyright = _end_rights
  1203. def _start_item(self, attrsD):
  1204. self.entries.append(FeedParserDict())
  1205. self.push('item', 0)
  1206. self.inentry = 1
  1207. self.guidislink = 0
  1208. self.title_depth = -1
  1209. self.psc_chapters_flag = None
  1210. id = self._getAttribute(attrsD, 'rdf:about')
  1211. if id:
  1212. context = self._getContext()
  1213. context['id'] = id
  1214. self._cdf_common(attrsD)
  1215. _start_entry = _start_item
  1216. def _end_item(self):
  1217. self.pop('item')
  1218. self.inentry = 0
  1219. _end_entry = _end_item
  1220. def _start_dc_language(self, attrsD):
  1221. self.push('language', 1)
  1222. _start_language = _start_dc_language
  1223. def _end_dc_language(self):
  1224. self.lang = self.pop('language')
  1225. _end_language = _end_dc_language
  1226. def _start_dc_publisher(self, attrsD):
  1227. self.push('publisher', 1)
  1228. _start_webmaster = _start_dc_publisher
  1229. def _end_dc_publisher(self):
  1230. self.pop('publisher')
  1231. self._sync_author_detail('publisher')
  1232. _end_webmaster = _end_dc_publisher
  1233. def _start_published(self, attrsD):
  1234. self.push('published', 1)
  1235. _start_dcterms_issued = _start_published
  1236. _start_issued = _start_published
  1237. _start_pubdate = _start_published
  1238. def _end_published(self):
  1239. value = self.pop('published')
  1240. self._save('published_parsed', _parse_date(value), overwrite=True)
  1241. _end_dcterms_issued = _end_published
  1242. _end_issued = _end_published
  1243. _end_pubdate = _end_published
  1244. def _start_updated(self, attrsD):
  1245. self.push('updated', 1)
  1246. _start_modified = _start_updated
  1247. _start_dcterms_modified = _start_updated
  1248. _start_dc_date = _start_updated
  1249. _start_lastbuilddate = _start_updated
  1250. def _end_updated(self):
  1251. value = self.pop('updated')
  1252. parsed_value = _parse_date(value)
  1253. self._save('updated_parsed', parsed_value, overwrite=True)
  1254. _end_modified = _end_updated
  1255. _end_dcterms_modified = _end_updated
  1256. _end_dc_date = _end_updated
  1257. _end_lastbuilddate = _end_updated
  1258. def _start_created(self, attrsD):
  1259. self.push('created', 1)
  1260. _start_dcterms_created = _start_created
  1261. def _end_created(self):
  1262. value = self.pop('created')
  1263. self._save('created_parsed', _parse_date(value), overwrite=True)
  1264. _end_dcterms_created = _end_created
  1265. def _start_expirationdate(self, attrsD):
  1266. self.push('expired', 1)
  1267. def _end_expirationdate(self):
  1268. self._save('expired_parsed', _parse_date(self.pop('expired')), overwrite=True)
  1269. # geospatial location, or "where", from georss.org
  1270. def _start_georssgeom(self, attrsD):
  1271. self.push('geometry', 0)
  1272. context = self._getContext()
  1273. context['where'] = FeedParserDict()
  1274. _start_georss_point = _start_georssgeom
  1275. _start_georss_line = _start_georssgeom
  1276. _start_georss_polygon = _start_georssgeom
  1277. _start_georss_box = _start_georssgeom
  1278. def _save_where(self, geometry):
  1279. context = self._getContext()
  1280. context['where'].update(geometry)
  1281. def _end_georss_point(self):
  1282. geometry = _parse_georss_point(self.pop('geometry'))
  1283. if geometry:
  1284. self._save_where(geometry)
  1285. def _end_georss_line(self):
  1286. geometry = _parse_georss_line(self.pop('geometry'))
  1287. if geometry:
  1288. self._save_where(geometry)
  1289. def _end_georss_polygon(self):
  1290. this = self.pop('geometry')
  1291. geometry = _parse_georss_polygon(this)
  1292. if geometry:
  1293. self._save_where(geometry)
  1294. def _end_georss_box(self):
  1295. geometry = _parse_georss_box(self.pop('geometry'))
  1296. if geometry:
  1297. self._save_where(geometry)
  1298. def _start_where(self, attrsD):
  1299. self.push('where', 0)
  1300. context = self._getContext()
  1301. context['where'] = FeedParserDict()
  1302. _start_georss_where = _start_where
  1303. def _parse_srs_attrs(self, attrsD):
  1304. srsName = attrsD.get('srsname')
  1305. try:
  1306. srsDimension = int(attrsD.get('srsdimension', '2'))
  1307. except ValueError:
  1308. srsDimension = 2
  1309. context = self._getContext()
  1310. context['where']['srsName'] = srsName
  1311. context['where']['srsDimension'] = srsDimension
  1312. def _start_gml_point(self, attrsD):
  1313. self._parse_srs_attrs(attrsD)
  1314. self.ingeometry = 1
  1315. self.push('geometry', 0)
  1316. def _start_gml_linestring(self, attrsD):
  1317. self._parse_srs_attrs(attrsD)
  1318. self.ingeometry = 'linestring'
  1319. self.push('geometry', 0)
  1320. def _start_gml_polygon(self, attrsD):
  1321. self._parse_srs_attrs(attrsD)
  1322. self.push('geometry', 0)
  1323. def _start_gml_exterior(self, attrsD):
  1324. self.push('geometry', 0)
  1325. def _start_gml_linearring(self, attrsD):
  1326. self.ingeometry = 'polygon'
  1327. self.push('geometry', 0)
  1328. def _start_gml_pos(self, attrsD):
  1329. self.push('pos', 0)
  1330. def _end_gml_pos(self):
  1331. this = self.pop('pos')
  1332. context = self._getContext()
  1333. srsName = context['where'].get('srsName')
  1334. srsDimension = context['where'].get('srsDimension', 2)
  1335. swap = True
  1336. if srsName and "EPSG" in srsName:
  1337. epsg = int(srsName.split(":")[-1])
  1338. swap = bool(epsg in _geogCS)
  1339. geometry = _parse_georss_point(this, swap=swap, dims=srsDimension)
  1340. if geometry:
  1341. self._save_where(geometry)
  1342. def _start_gml_poslist(self, attrsD):
  1343. self.push('pos', 0)
  1344. def _end_gml_poslist(self):
  1345. this = self.pop('pos')
  1346. context = self._getContext()
  1347. srsName = context['where'].get('srsName')
  1348. srsDimension = context['where'].get('srsDimension', 2)
  1349. swap = True
  1350. if srsName and "EPSG" in srsName:
  1351. epsg = int(srsName.split(":")[-1])
  1352. swap = bool(epsg in _geogCS)
  1353. geometry = _parse_poslist(
  1354. this, self.ingeometry, swap=swap, dims=srsDimension)
  1355. if geometry:
  1356. self._save_where(geometry)
  1357. def _end_geom(self):
  1358. self.ingeometry = 0
  1359. self.pop('geometry')
  1360. _end_gml_point = _end_geom
  1361. _end_gml_linestring = _end_geom
  1362. _end_gml_linearring = _end_geom
  1363. _end_gml_exterior = _end_geom
  1364. _end_gml_polygon = _end_geom
  1365. def _end_where(self):
  1366. self.pop('where')
  1367. _end_georss_where = _end_where
  1368. # end geospatial
  1369. def _start_cc_license(self, attrsD):
  1370. context = self._getContext()
  1371. value = self._getAttribute(attrsD, 'rdf:resource')
  1372. attrsD = FeedParserDict()
  1373. attrsD['rel'] = u'license'
  1374. if value:
  1375. attrsD['href']=value
  1376. context.setdefault('links', []).append(attrsD)
  1377. def _start_creativecommons_license(self, attrsD):
  1378. self.push('license', 1)
  1379. _start_creativeCommons_license = _start_creativecommons_license
  1380. def _end_creativecommons_license(self):
  1381. value = self.pop('license')
  1382. context = self._getContext()
  1383. attrsD = FeedParserDict()
  1384. attrsD['rel'] = u'license'
  1385. if value:
  1386. attrsD['href'] = value
  1387. context.setdefault('links', []).append(attrsD)
  1388. del context['license']
  1389. _end_creativeCommons_license = _end_creativecommons_license
  1390. def _addTag(self, term, scheme, label):
  1391. context = self._getContext()
  1392. tags = context.setdefault('tags', [])
  1393. if (not term) and (not scheme) and (not label):
  1394. return
  1395. value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
  1396. if value not in tags:
  1397. tags.append(value)
  1398. def _start_category(self, attrsD):
  1399. term = attrsD.get('term')
  1400. scheme = attrsD.get('scheme', attrsD.get('domain'))
  1401. label = attrsD.get('label')
  1402. self._addTag(term, scheme, label)
  1403. self.push('category', 1)
  1404. _start_dc_subject = _start_category
  1405. _start_keywords = _start_category
  1406. def _start_media_category(self, attrsD):
  1407. attrsD.setdefault('scheme', u'http://search.yahoo.com/mrss/category_schema')
  1408. self._start_category(attrsD)
  1409. def _end_itunes_keywords(self):
  1410. for term in self.pop('itunes_keywords').split(','):
  1411. if term.strip():
  1412. self._addTag(term.strip(), u'http://www.itunes.com/', None)
  1413. def _start_itunes_category(self, attrsD):
  1414. self._addTag(attrsD.get('text'), u'http://www.itunes.com/', None)
  1415. self.push('category', 1)
  1416. def _end_category(self):
  1417. value = self.pop('category')
  1418. if not value:
  1419. return
  1420. context = self._getContext()
  1421. tags = context['tags']
  1422. if value and len(tags) and not tags[-1]['term']:
  1423. tags[-1]['term'] = value
  1424. else:
  1425. self._addTag(value, None, None)
  1426. _end_dc_subject = _end_category
  1427. _end_keywords = _end_category
  1428. _end_itunes_category = _end_category
  1429. _end_media_category = _end_category
  1430. def _start_cloud(self, attrsD):
  1431. self._getContext()['cloud'] = FeedParserDict(attrsD)
  1432. def _start_link(self, attrsD):
  1433. attrsD.setdefault('rel', u'alternate')
  1434. if attrsD['rel'] == u'self':
  1435. attrsD.setdefault('type', u'application/atom+xml')
  1436. else:
  1437. attrsD.setdefault('type', u'text/html')
  1438. context = self._getContext()
  1439. attrsD = self._itsAnHrefDamnIt(attrsD)
  1440. if 'href' in attrsD:
  1441. attrsD['href'] = self.resolveURI(attrsD['href'])
  1442. expectingText = self.infeed or self.inentry or self.insource
  1443. context.setdefault('links', [])
  1444. if not (self.inentry and self.inimage):
  1445. context['links'].append(FeedParserDict(attrsD))
  1446. if 'href' in attrsD:
  1447. expectingText = 0
  1448. if (attrsD.get('rel') == u'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
  1449. context['link'] = attrsD['href']
  1450. else:
  1451. self.push('link', expectingText)
  1452. def _end_link(self):
  1453. value = self.pop('link')
  1454. def _start_guid(self, attrsD):
  1455. self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
  1456. self.push('id', 1)
  1457. _start_id = _start_guid
  1458. def _end_guid(self):
  1459. value = self.pop('id')
  1460. self._save('guidislink', self.guidislink and 'link' not in self._getContext())
  1461. if self.guidislink:
  1462. # guid acts as link, but only if 'ispermalink' is not present or is 'true',
  1463. # and only if the item doesn't already have a link element
  1464. self._save('link', value)
  1465. _end_id = _end_guid
  1466. def _start_title(self, attrsD):
  1467. if self.svgOK:
  1468. return self.unknown_starttag('title', attrsD.items())
  1469. self.pushContent('title', attrsD, u'text/plain', self.infeed or self.inentry or self.insource)
  1470. _start_dc_title = _start_title
  1471. _start_media_title = _start_title
  1472. def _end_title(self):
  1473. if self.svgOK:
  1474. return
  1475. value = self.popContent('title')
  1476. if not value:
  1477. return
  1478. self.title_depth = self.depth
  1479. _end_dc_title = _end_title
  1480. def _end_media_title(self):
  1481. title_depth = self.title_depth
  1482. self._end_title()
  1483. self.title_depth = title_depth
  1484. def _start_description(self, attrsD):
  1485. context = self._getContext()
  1486. if 'summary' in context:
  1487. self._summaryKey = 'content'
  1488. self._start_content(attrsD)
  1489. else:
  1490. self.pushContent('description', attrsD, u'text/html', self.infeed or self.inentry or self.insource)
  1491. _start_dc_description = _start_description
  1492. _start_media_description = _start_description
  1493. def _start_abstract(self, attrsD):
  1494. self.pushContent('description', attrsD, u'text/plain', self.infeed or self.inentry or self.insource)
  1495. def _end_description(self):
  1496. if self._summaryKey == 'content':
  1497. self._end_content()
  1498. else:
  1499. value = self.popContent('description')
  1500. self._summaryKey = None
  1501. _end_abstract = _end_description
  1502. _end_dc_description = _end_description
  1503. _end_media_description = _end_description
  1504. def _start_info(self, attrsD):
  1505. self.pushContent('info', attrsD, u'text/plain', 1)
  1506. _start_feedburner_browserfriendly = _start_info
  1507. def _end_info(self):
  1508. self.popContent('info')
  1509. _end_feedburner_browserfriendly = _end_info
  1510. def _start_generator(self, attrsD):
  1511. if attrsD:
  1512. attrsD = self._itsAnHrefDamnIt(attrsD)
  1513. if 'href' in attrsD:
  1514. attrsD['href'] = self.resolveURI(attrsD['href'])
  1515. self._getContext()['generator_detail'] = FeedParserDict(attrsD)
  1516. self.push('generator', 1)
  1517. def _end_generator(self):
  1518. value = self.pop('generator')
  1519. context = self._getContext()
  1520. if 'generator_detail' in context:
  1521. context['generator_detail']['name'] = value
  1522. def _start_admin_generatoragent(self, attrsD):
  1523. self.push('generator', 1)
  1524. value = self._getAttribute(attrsD, 'rdf:resource')
  1525. if value:
  1526. self.elementstack[-1][2].append(value)
  1527. self.pop('generator')
  1528. self._getContext()['generator_detail'] = FeedParserDict({'href': value})
  1529. def _start_admin_errorreportsto(self, attrsD):
  1530. self.push('errorreportsto', 1)
  1531. value = self._getAttribute(attrsD, 'rdf:resource')
  1532. if value:
  1533. self.elementstack[-1][2].append(value)
  1534. self.pop('errorreportsto')
  1535. def _start_summary(self, attrsD):
  1536. context = self._getContext()
  1537. if 'summary' in context:
  1538. self._summaryKey = 'content'
  1539. self._start_content(attrsD)
  1540. else:
  1541. self._summaryKey = 'summary'
  1542. self.pushContent(self._summaryKey, attrsD, u'text/plain', 1)
  1543. _start_itunes_summary = _start_summary
  1544. def _end_summary(self):
  1545. if self._summaryKey == 'content':
  1546. self._end_content()
  1547. else:
  1548. self.popContent(self._summaryKey or 'summary')
  1549. self._summaryKey = None
  1550. _end_itunes_summary = _end_summary
  1551. def _start_enclosure(self, attrsD):
  1552. attrsD = self._itsAnHrefDamnIt(attrsD)
  1553. context = self._getContext()
  1554. attrsD['rel'] = u'enclosure'
  1555. context.setdefault('links', []).append(FeedParserDict(attrsD))
  1556. def _start_source(self, attrsD):
  1557. if 'url' in attrsD:
  1558. # This means that we're processing a source element from an RSS 2.0 feed
  1559. self.sourcedata['href'] = attrsD[u'url']
  1560. self.push('source', 1)
  1561. self.insource = 1
  1562. self.title_depth = -1
  1563. def _end_source(self):
  1564. self.insource = 0
  1565. value = self.pop('source')
  1566. if value:
  1567. self.sourcedata['title'] = value
  1568. self._getContext()['source'] = copy.deepcopy(self.sourcedata)
  1569. self.sourcedata.clear()
  1570. def _start_content(self, attrsD):
  1571. self.pushContent('content', attrsD, u'text/plain', 1)
  1572. src = attrsD.get('src')
  1573. if src:
  1574. self.contentparams['src'] = src
  1575. self.push('content', 1)
  1576. def _start_body(self, attrsD):
  1577. self.pushContent('content', attrsD, u'application/xhtml+xml', 1)
  1578. _start_xhtml_body = _start_body
  1579. def _start_content_encoded(self, attrsD):
  1580. self.pushContent('content', attrsD, u'text/html', 1)
  1581. _start_fullitem = _start_content_encoded
  1582. def _end_content(self):
  1583. copyToSummary = self.mapContentType(self.contentparams.get('type')) in ([u'text/plain'] + self.html_types)
  1584. value = self.popContent('content')
  1585. if copyToSummary:
  1586. self._save('summary', value)
  1587. _end_body = _end_content
  1588. _end_xhtml_body = _end_content
  1589. _end_content_encoded = _end_content
  1590. _end_fullitem = _end_content
  1591. def _start_itunes_image(self, attrsD):
  1592. self.push('itunes_image', 0)
  1593. if attrsD.get('href'):
  1594. self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
  1595. elif attrsD.get('url'):
  1596. self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')})
  1597. _start_itunes_link = _start_itunes_image
  1598. def _end_itunes_block(self):
  1599. value = self.pop('itunes_block', 0)
  1600. self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
  1601. def _end_itunes_explicit(self):
  1602. value = self.pop('itunes_explicit', 0)
  1603. # Convert 'yes' -> True, 'clean' to False, and any other value to None
  1604. # False and None both evaluate as False, so the difference can be ignored
  1605. # by applications that only need to know if the content is explicit.
  1606. self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0]
  1607. def _start_media_group(self, attrsD):
  1608. # don't do anything, but don't break the enclosed tags either
  1609. pass
  1610. def _start_media_credit(self, attrsD):
  1611. context = self._getContext()
  1612. context.setdefault('media_credit', [])
  1613. context['media_credit'].append(attrsD)
  1614. self.push('credit', 1)
  1615. def _end_media_credit(self):
  1616. credit = self.pop('credit')
  1617. if credit != None and len(credit.strip()) != 0:
  1618. context = self._getContext()
  1619. context['media_credit'][-1]['content'] = credit
  1620. def _start_media_restriction(self, attrsD):
  1621. context = self._getContext()
  1622. context.setdefault('media_restriction', attrsD)
  1623. self.push('restriction', 1)
  1624. def _end_media_restriction(self):
  1625. restriction = self.pop('restriction')
  1626. if restriction != None and len(restriction.strip()) != 0:
  1627. context = self._getContext()
  1628. context['media_restriction']['content'] = restriction
  1629. def _start_media_license(self, attrsD):
  1630. context = self._getContext()
  1631. context.setdefault('media_license', attrsD)
  1632. self.push('license', 1)
  1633. def _end_media_license(self):
  1634. license = self.pop('license')
  1635. if license != None and len(license.strip()) != 0:
  1636. context = self._getContext()
  1637. context['media_license']['content'] = license
  1638. def _start_media_content(self, attrsD):
  1639. context = self._getContext()
  1640. context.setdefault('media_content', [])
  1641. context['media_content'].append(attrsD)
  1642. def _start_media_thumbnail(self, attrsD):
  1643. context = self._getContext()
  1644. context.setdefault('media_thumbnail', [])
  1645. self.push('url', 1) # new
  1646. context['media_thumbnail'].append(attrsD)
  1647. def _end_media_thumbnail(self):
  1648. url = self.pop('url')
  1649. context = self._getContext()
  1650. if url != None and len(url.strip()) != 0:
  1651. if 'url' not in context['media_thumbnail'][-1]:
  1652. context['media_thumbnail'][-1]['url'] = url
  1653. def _start_media_player(self, attrsD):
  1654. self.push('media_player', 0)
  1655. self._getContext()['media_player'] = FeedParserDict(attrsD)
  1656. def _end_media_player(self):
  1657. value = self.pop('media_player')
  1658. context = self._getContext()
  1659. context['media_player']['content'] = value
  1660. def _start_newlocation(self, attrsD):
  1661. self.push('newlocation', 1)
  1662. def _end_newlocation(self):
  1663. url = self.pop('newlocation')
  1664. context = self._getContext()
  1665. # don't set newlocation if the context isn't right
  1666. if context is not self.feeddata:
  1667. return
  1668. context['newlocation'] = _makeSafeAbsoluteURI(self.baseuri, url.strip())
  1669. def _start_psc_chapters(self, attrsD):
  1670. if self.psc_chapters_flag is None:
  1671. # Transition from None -> True
  1672. self.psc_chapters_flag = True
  1673. attrsD['chapters'] = []
  1674. self._getContext()['psc_chapters'] = FeedParserDict(attrsD)
  1675. def _end_psc_chapters(self):
  1676. # Transition from True -> False
  1677. self.psc_chapters_flag = False
  1678. def _start_psc_chapter(self, attrsD):
  1679. if self.psc_chapters_flag:
  1680. start = self._getAttribute(attrsD, 'start')
  1681. attrsD['start_parsed'] = _parse_psc_chapter_start(start)
  1682. context = self._getContext()['psc_chapters']
  1683. context['chapters'].append(FeedParserDict(attrsD))
  1684. if _XML_AVAILABLE:
  1685. class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler):
  1686. def __init__(self, baseuri, baselang, encoding):
  1687. xml.sax.handler.ContentHandler.__init__(self)
  1688. _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1689. self.bozo = 0
  1690. self.exc = None
  1691. self.decls = {}
  1692. def startPrefixMapping(self, prefix, uri):
  1693. if not uri:
  1694. return
  1695. # Jython uses '' instead of None; standardize on None
  1696. prefix = prefix or None
  1697. self.trackNamespace(prefix, uri)
  1698. if prefix and uri == 'http://www.w3.org/1999/xlink':
  1699. self.decls['xmlns:' + prefix] = uri
  1700. def startElementNS(self, name, qname, attrs):
  1701. namespace, localname = name
  1702. lowernamespace = str(namespace or '').lower()
  1703. if lowernamespace.find(u'backend.userland.com/rss') <> -1:
  1704. # match any backend.userland.com namespace
  1705. namespace = u'http://backend.userland.com/rss'
  1706. lowernamespace = namespace
  1707. if qname and qname.find(':') > 0:
  1708. givenprefix = qname.split(':')[0]
  1709. else:
  1710. givenprefix = None
  1711. prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1712. if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and givenprefix not in self.namespacesInUse:
  1713. raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix
  1714. localname = str(localname).lower()
  1715. # qname implementation is horribly broken in Python 2.1 (it
  1716. # doesn't report any), and slightly broken in Python 2.2 (it
  1717. # doesn't report the xml: namespace). So we match up namespaces
  1718. # with a known list first, and then possibly override them with
  1719. # the qnames the SAX parser gives us (if indeed it gives us any
  1720. # at all). Thanks to MatejC for helping me test this and
  1721. # tirelessly telling me that it didn't work yet.
  1722. attrsD, self.decls = self.decls, {}
  1723. if localname=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
  1724. attrsD['xmlns']=namespace
  1725. if localname=='svg' and namespace=='http://www.w3.org/2000/svg':
  1726. attrsD['xmlns']=namespace
  1727. if prefix:
  1728. localname = prefix.lower() + ':' + localname
  1729. elif namespace and not qname: #Expat
  1730. for name,value in self.namespacesInUse.items():
  1731. if name and value == namespace:
  1732. localname = name + ':' + localname
  1733. break
  1734. for (namespace, attrlocalname), attrvalue in attrs.items():
  1735. lowernamespace = (namespace or '').lower()
  1736. prefix = self._matchnamespaces.get(lowernamespace, '')
  1737. if prefix:
  1738. attrlocalname = prefix + ':' + attrlocalname
  1739. attrsD[str(attrlocalname).lower()] = attrvalue
  1740. for qname in attrs.getQNames():
  1741. attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
  1742. localname = str(localname).lower()
  1743. self.unknown_starttag(localname, attrsD.items())
  1744. def characters(self, text):
  1745. self.handle_data(text)
  1746. def endElementNS(self, name, qname):
  1747. namespace, localname = name
  1748. lowernamespace = str(namespace or '').lower()
  1749. if qname and qname.find(':') > 0:
  1750. givenprefix = qname.split(':')[0]
  1751. else:
  1752. givenprefix = ''
  1753. prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1754. if prefix:
  1755. localname = prefix + ':' + localname
  1756. elif namespace and not qname: #Expat
  1757. for name,value in self.namespacesInUse.items():
  1758. if name and value == namespace:
  1759. localname = name + ':' + localname
  1760. break
  1761. localname = str(localname).lower()
  1762. self.unknown_endtag(localname)
  1763. def error(self, exc):
  1764. self.bozo = 1
  1765. self.exc = exc
  1766. # drv_libxml2 calls warning() in some cases
  1767. warning = error
  1768. def fatalError(self, exc):
  1769. self.error(exc)
  1770. raise exc
  1771. class _BaseHTMLProcessor(sgmllib.SGMLParser):
  1772. special = re.compile('''[<>'"]''')
  1773. bare_ampersand = re.compile("&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)")
  1774. elements_no_end_tag = set([
  1775. 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame',
  1776. 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param',
  1777. 'source', 'track', 'wbr'
  1778. ])
  1779. def __init__(self, encoding, _type):
  1780. self.encoding = encoding
  1781. self._type = _type
  1782. sgmllib.SGMLParser.__init__(self)
  1783. def reset(self):
  1784. self.pieces = []
  1785. sgmllib.SGMLParser.reset(self)
  1786. def _shorttag_replace(self, match):
  1787. tag = match.group(1)
  1788. if tag in self.elements_no_end_tag:
  1789. return '<' + tag + ' />'
  1790. else:
  1791. return '<' + tag + '></' + tag + '>'
  1792. # By declaring these methods and overriding their compiled code
  1793. # with the code from sgmllib, the original code will execute in
  1794. # feedparser's scope instead of sgmllib's. This means that the
  1795. # `tagfind` and `charref` regular expressions will be found as
  1796. # they're declared above, not as they're declared in sgmllib.
  1797. def goahead(self, i):
  1798. pass
  1799. goahead.func_code = sgmllib.SGMLParser.goahead.func_code
  1800. def __parse_starttag(self, i):
  1801. pass
  1802. __parse_starttag.func_code = sgmllib.SGMLParser.parse_starttag.func_code
  1803. def parse_starttag(self,i):
  1804. j = self.__parse_starttag(i)
  1805. if self._type == 'application/xhtml+xml':
  1806. if j>2 and self.rawdata[j-2:j]=='/>':
  1807. self.unknown_endtag(self.lasttag)
  1808. return j
  1809. def feed(self, data):
  1810. data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data)
  1811. data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data)
  1812. data = data.replace('&#39;', "'")
  1813. data = data.replace('&#34;', '"')
  1814. try:
  1815. bytes
  1816. if bytes is str:
  1817. raise NameError
  1818. self.encoding = self.encoding + u'_INVALID_PYTHON_3'
  1819. except NameError:
  1820. if self.encoding and isinstance(data, unicode):
  1821. data = data.encode(self.encoding)
  1822. sgmllib.SGMLParser.feed(self, data)
  1823. sgmllib.SGMLParser.close(self)
  1824. def normalize_attrs(self, attrs):
  1825. if not attrs:
  1826. return attrs
  1827. # utility method to be called by descendants
  1828. attrs = dict([(k.lower(), v) for k, v in attrs]).items()
  1829. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  1830. attrs.sort()
  1831. return attrs
  1832. def unknown_starttag(self, tag, attrs):
  1833. # called for each start tag
  1834. # attrs is a list of (attr, value) tuples
  1835. # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
  1836. uattrs = []
  1837. strattrs=''
  1838. if attrs:
  1839. for key, value in attrs:
  1840. value=value.replace('>','&gt;').replace('<','&lt;').replace('"','&quot;')
  1841. value = self.bare_ampersand.sub("&amp;", value)
  1842. # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
  1843. if not isinstance(value, unicode):
  1844. value = value.decode(self.encoding, 'ignore')
  1845. try:
  1846. # Currently, in Python 3 the key is already a str, and cannot be decoded again
  1847. uattrs.append((unicode(key, self.encoding), value))
  1848. except TypeError:
  1849. uattrs.append((key, value))
  1850. strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs])
  1851. if self.encoding:
  1852. try:
  1853. strattrs = strattrs.encode(self.encoding)
  1854. except (UnicodeEncodeError, LookupError):
  1855. pass
  1856. if tag in self.elements_no_end_tag:
  1857. self.pieces.append('<%s%s />' % (tag, strattrs))
  1858. else:
  1859. self.pieces.append('<%s%s>' % (tag, strattrs))
  1860. def unknown_endtag(self, tag):
  1861. # called for each end tag, e.g. for </pre>, tag will be 'pre'
  1862. # Reconstruct the original end tag.
  1863. if tag not in self.elements_no_end_tag:
  1864. self.pieces.append("</%s>" % tag)
  1865. def handle_charref(self, ref):
  1866. # called for each character reference, e.g. for '&#160;', ref will be '160'
  1867. # Reconstruct the original character reference.
  1868. ref = ref.lower()
  1869. if ref.startswith('x'):
  1870. value = int(ref[1:], 16)
  1871. else:
  1872. value = int(ref)
  1873. if value in _cp1252:
  1874. self.pieces.append('&#%s;' % hex(ord(_cp1252[value]))[1:])
  1875. else:
  1876. self.pieces.append('&#%s;' % ref)
  1877. def handle_entityref(self, ref):
  1878. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  1879. # Reconstruct the original entity reference.
  1880. if ref in name2codepoint or ref == 'apos':
  1881. self.pieces.append('&%s;' % ref)
  1882. else:
  1883. self.pieces.append('&amp;%s' % ref)
  1884. def handle_data(self, text):
  1885. # called for each block of plain text, i.e. outside of any tag and
  1886. # not containing any character or entity references
  1887. # Store the original text verbatim.
  1888. self.pieces.append(text)
  1889. def handle_comment(self, text):
  1890. # called for each HTML comment, e.g. <!-- insert Javascript code here -->
  1891. # Reconstruct the original comment.
  1892. self.pieces.append('<!--%s-->' % text)
  1893. def handle_pi(self, text):
  1894. # called for each processing instruction, e.g. <?instruction>
  1895. # Reconstruct original processing instruction.
  1896. self.pieces.append('<?%s>' % text)
  1897. def handle_decl(self, text):
  1898. # called for the DOCTYPE, if present, e.g.
  1899. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  1900. # "http://www.w3.org/TR/html4/loose.dtd">
  1901. # Reconstruct original DOCTYPE
  1902. self.pieces.append('<!%s>' % text)
  1903. _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
  1904. def _scan_name(self, i, declstartpos):
  1905. rawdata = self.rawdata
  1906. n = len(rawdata)
  1907. if i == n:
  1908. return None, -1
  1909. m = self._new_declname_match(rawdata, i)
  1910. if m:
  1911. s = m.group()
  1912. name = s.strip()
  1913. if (i + len(s)) == n:
  1914. return None, -1 # end of buffer
  1915. return name.lower(), m.end()
  1916. else:
  1917. self.handle_data(rawdata)
  1918. # self.updatepos(declstartpos, i)
  1919. return None, -1
  1920. def convert_charref(self, name):
  1921. return '&#%s;' % name
  1922. def convert_entityref(self, name):
  1923. return '&%s;' % name
  1924. def output(self):
  1925. '''Return processed HTML as a single string'''
  1926. return ''.join([str(p) for p in self.pieces])
  1927. def parse_declaration(self, i):
  1928. try:
  1929. return sgmllib.SGMLParser.parse_declaration(self, i)
  1930. except sgmllib.SGMLParseError:
  1931. # escape the doctype declaration and continue parsing
  1932. self.handle_data('&lt;')
  1933. return i+1
  1934. class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor):
  1935. def __init__(self, baseuri, baselang, encoding, entities):
  1936. sgmllib.SGMLParser.__init__(self)
  1937. _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1938. _BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml')
  1939. self.entities=entities
  1940. def decodeEntities(self, element, data):
  1941. data = data.replace('&#60;', '&lt;')
  1942. data = data.replace('&#x3c;', '&lt;')
  1943. data = data.replace('&#x3C;', '&lt;')
  1944. data = data.replace('&#62;', '&gt;')
  1945. data = data.replace('&#x3e;', '&gt;')
  1946. data = data.replace('&#x3E;', '&gt;')
  1947. data = data.replace('&#38;', '&amp;')
  1948. data = data.replace('&#x26;', '&amp;')
  1949. data = data.replace('&#34;', '&quot;')
  1950. data = data.replace('&#x22;', '&quot;')
  1951. data = data.replace('&#39;', '&apos;')
  1952. data = data.replace('&#x27;', '&apos;')
  1953. if not self.contentparams.get('type', u'xml').endswith(u'xml'):
  1954. data = data.replace('&lt;', '<')
  1955. data = data.replace('&gt;', '>')
  1956. data = data.replace('&amp;', '&')
  1957. data = data.replace('&quot;', '"')
  1958. data = data.replace('&apos;', "'")
  1959. return data
  1960. def strattrs(self, attrs):
  1961. return ''.join([' %s="%s"' % (n,v.replace('"','&quot;')) for n,v in attrs])
  1962. class _RelativeURIResolver(_BaseHTMLProcessor):
  1963. relative_uris = set([('a', 'href'),
  1964. ('applet', 'codebase'),
  1965. ('area', 'href'),
  1966. ('blockquote', 'cite'),
  1967. ('body', 'background'),
  1968. ('del', 'cite'),
  1969. ('form', 'action'),
  1970. ('frame', 'longdesc'),
  1971. ('frame', 'src'),
  1972. ('iframe', 'longdesc'),
  1973. ('iframe', 'src'),
  1974. ('head', 'profile'),
  1975. ('img', 'longdesc'),
  1976. ('img', 'src'),
  1977. ('img', 'usemap'),
  1978. ('input', 'src'),
  1979. ('input', 'usemap'),
  1980. ('ins', 'cite'),
  1981. ('link', 'href'),
  1982. ('object', 'classid'),
  1983. ('object', 'codebase'),
  1984. ('object', 'data'),
  1985. ('object', 'usemap'),
  1986. ('q', 'cite'),
  1987. ('script', 'src'),
  1988. ('video', 'poster')])
  1989. def __init__(self, baseuri, encoding, _type):
  1990. _BaseHTMLProcessor.__init__(self, encoding, _type)
  1991. self.baseuri = baseuri
  1992. def resolveURI(self, uri):
  1993. return _makeSafeAbsoluteURI(self.baseuri, uri.strip())
  1994. def unknown_starttag(self, tag, attrs):
  1995. attrs = self.normalize_attrs(attrs)
  1996. attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
  1997. _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1998. def _resolveRelativeURIs(htmlSource, baseURI, encoding, _type):
  1999. if not _SGML_AVAILABLE:
  2000. return htmlSource
  2001. p = _RelativeURIResolver(baseURI, encoding, _type)
  2002. p.feed(htmlSource)
  2003. return p.output()
  2004. def _makeSafeAbsoluteURI(base, rel=None):
  2005. # bail if ACCEPTABLE_URI_SCHEMES is empty
  2006. if not ACCEPTABLE_URI_SCHEMES:
  2007. return _urljoin(base, rel or u'')
  2008. if not base:
  2009. return rel or u''
  2010. if not rel:
  2011. try:
  2012. scheme = urlparse.urlparse(base)[0]
  2013. except ValueError:
  2014. return u''
  2015. if not scheme or scheme in ACCEPTABLE_URI_SCHEMES:
  2016. return base
  2017. return u''
  2018. uri = _urljoin(base, rel)
  2019. if uri.strip().split(':', 1)[0] not in ACCEPTABLE_URI_SCHEMES:
  2020. return u''
  2021. return uri
  2022. class _HTMLSanitizer(_BaseHTMLProcessor):
  2023. acceptable_elements = set(['a', 'abbr', 'acronym', 'address', 'area',
  2024. 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button',
  2025. 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
  2026. 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn',
  2027. 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset',
  2028. 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1',
  2029. 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins',
  2030. 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter',
  2031. 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option',
  2032. 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
  2033. 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
  2034. 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',
  2035. 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript',
  2036. 'object', 'embed', 'iframe', 'param'])
  2037. acceptable_attributes = set(['abbr', 'accept', 'accept-charset', 'accesskey',
  2038. 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',
  2039. 'background', 'balance', 'bgcolor', 'bgproperties', 'border',
  2040. 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
  2041. 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
  2042. 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols',
  2043. 'colspan', 'compact', 'contenteditable', 'controls', 'coords', 'data',
  2044. 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', 'delay',
  2045. 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for',
  2046. 'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus',
  2047. 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode',
  2048. 'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc',
  2049. 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max',
  2050. 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref',
  2051. 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size',
  2052. 'poster', 'pqg', 'preload', 'prompt', 'radiogroup', 'readonly', 'rel',
  2053. 'repeat-max', 'repeat-min', 'replace', 'required', 'rev', 'rightspacing',
  2054. 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span',
  2055. 'src', 'start', 'step', 'summary', 'suppress', 'tabindex', 'target',
  2056. 'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap',
  2057. 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml',
  2058. 'width', 'wrap', 'xml:lang',
  2059. 'allowfullscreen'])
  2060. unacceptable_elements_with_end_tag = set(['script', 'applet', 'style'])
  2061. acceptable_css_properties = set(['azimuth', 'background-color',
  2062. 'border-bottom-color', 'border-collapse', 'border-color',
  2063. 'border-left-color', 'border-right-color', 'border-top-color', 'clear',
  2064. 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
  2065. 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
  2066. 'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
  2067. 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
  2068. 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
  2069. 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
  2070. 'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
  2071. 'white-space', 'width'])
  2072. # survey of common keywords found in feeds
  2073. acceptable_css_keywords = set(['auto', 'aqua', 'black', 'block', 'blue',
  2074. 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
  2075. 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
  2076. 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
  2077. 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
  2078. 'transparent', 'underline', 'white', 'yellow'])
  2079. valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' +
  2080. '\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$')
  2081. mathml_elements = set(['annotation', 'annotation-xml', 'maction', 'math',
  2082. 'merror', 'mfenced', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
  2083. 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle',
  2084. 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
  2085. 'munderover', 'none', 'semantics'])
  2086. mathml_attributes = set(['actiontype', 'align', 'columnalign', 'columnalign',
  2087. 'columnalign', 'close', 'columnlines', 'columnspacing', 'columnspan', 'depth',
  2088. 'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows',
  2089. 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness',
  2090. 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant',
  2091. 'maxsize', 'minsize', 'open', 'other', 'rowalign', 'rowalign', 'rowalign',
  2092. 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
  2093. 'separator', 'separators', 'stretchy', 'width', 'width', 'xlink:href',
  2094. 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink'])
  2095. # svgtiny - foreignObject + linearGradient + radialGradient + stop
  2096. svg_elements = set(['a', 'animate', 'animateColor', 'animateMotion',
  2097. 'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'foreignObject',
  2098. 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
  2099. 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath',
  2100. 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop',
  2101. 'svg', 'switch', 'text', 'title', 'tspan', 'use'])
  2102. # svgtiny + class + opacity + offset + xmlns + xmlns:xlink
  2103. svg_attributes = set(['accent-height', 'accumulate', 'additive', 'alphabetic',
  2104. 'arabic-form', 'ascent', 'attributeName', 'attributeType',
  2105. 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
  2106. 'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx',
  2107. 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity',
  2108. 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style',
  2109. 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2',
  2110. 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x',
  2111. 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines',
  2112. 'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid',
  2113. 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max',
  2114. 'min', 'name', 'offset', 'opacity', 'orient', 'origin',
  2115. 'overline-position', 'overline-thickness', 'panose-1', 'path',
  2116. 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY',
  2117. 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures',
  2118. 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv',
  2119. 'stop-color', 'stop-opacity', 'strikethrough-position',
  2120. 'strikethrough-thickness', 'stroke', 'stroke-dasharray',
  2121. 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
  2122. 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage',
  2123. 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2',
  2124. 'underline-position', 'underline-thickness', 'unicode', 'unicode-range',
  2125. 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width',
  2126. 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
  2127. 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
  2128. 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1',
  2129. 'y2', 'zoomAndPan'])
  2130. svg_attr_map = None
  2131. svg_elem_map = None
  2132. acceptable_svg_properties = set([ 'fill', 'fill-opacity', 'fill-rule',
  2133. 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
  2134. 'stroke-opacity'])
  2135. def reset(self):
  2136. _BaseHTMLProcessor.reset(self)
  2137. self.unacceptablestack = 0
  2138. self.mathmlOK = 0
  2139. self.svgOK = 0
  2140. def unknown_starttag(self, tag, attrs):
  2141. acceptable_attributes = self.acceptable_attributes
  2142. keymap = {}
  2143. if not tag in self.acceptable_elements or self.svgOK:
  2144. if tag in self.unacceptable_elements_with_end_tag:
  2145. self.unacceptablestack += 1
  2146. # add implicit namespaces to html5 inline svg/mathml
  2147. if self._type.endswith('html'):
  2148. if not dict(attrs).get('xmlns'):
  2149. if tag=='svg':
  2150. attrs.append( ('xmlns','http://www.w3.org/2000/svg') )
  2151. if tag=='math':
  2152. attrs.append( ('xmlns','http://www.w3.org/1998/Math/MathML') )
  2153. # not otherwise acceptable, perhaps it is MathML or SVG?
  2154. if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs:
  2155. self.mathmlOK += 1
  2156. if tag=='svg' and ('xmlns','http://www.w3.org/2000/svg') in attrs:
  2157. self.svgOK += 1
  2158. # chose acceptable attributes based on tag class, else bail
  2159. if self.mathmlOK and tag in self.mathml_elements:
  2160. acceptable_attributes = self.mathml_attributes
  2161. elif self.svgOK and tag in self.svg_elements:
  2162. # for most vocabularies, lowercasing is a good idea. Many
  2163. # svg elements, however, are camel case
  2164. if not self.svg_attr_map:
  2165. lower=[attr.lower() for attr in self.svg_attributes]
  2166. mix=[a for a in self.svg_attributes if a not in lower]
  2167. self.svg_attributes = lower
  2168. self.svg_attr_map = dict([(a.lower(),a) for a in mix])
  2169. lower=[attr.lower() for attr in self.svg_elements]
  2170. mix=[a for a in self.svg_elements if a not in lower]
  2171. self.svg_elements = lower
  2172. self.svg_elem_map = dict([(a.lower(),a) for a in mix])
  2173. acceptable_attributes = self.svg_attributes
  2174. tag = self.svg_elem_map.get(tag,tag)
  2175. keymap = self.svg_attr_map
  2176. elif not tag in self.acceptable_elements:
  2177. return
  2178. # declare xlink namespace, if needed
  2179. if self.mathmlOK or self.svgOK:
  2180. if filter(lambda (n,v): n.startswith('xlink:'),attrs):
  2181. if not ('xmlns:xlink','http://www.w3.org/1999/xlink') in attrs:
  2182. attrs.append(('xmlns:xlink','http://www.w3.org/1999/xlink'))
  2183. clean_attrs = []
  2184. for key, value in self.normalize_attrs(attrs):
  2185. if key in acceptable_attributes:
  2186. key=keymap.get(key,key)
  2187. # make sure the uri uses an acceptable uri scheme
  2188. if key == u'href':
  2189. value = _makeSafeAbsoluteURI(value)
  2190. clean_attrs.append((key,value))
  2191. elif key=='style':
  2192. clean_value = self.sanitize_style(value)
  2193. if clean_value:
  2194. clean_attrs.append((key,clean_value))
  2195. _BaseHTMLProcessor.unknown_starttag(self, tag, clean_attrs)
  2196. def unknown_endtag(self, tag):
  2197. if not tag in self.acceptable_elements:
  2198. if tag in self.unacceptable_elements_with_end_tag:
  2199. self.unacceptablestack -= 1
  2200. if self.mathmlOK and tag in self.mathml_elements:
  2201. if tag == 'math' and self.mathmlOK:
  2202. self.mathmlOK -= 1
  2203. elif self.svgOK and tag in self.svg_elements:
  2204. tag = self.svg_elem_map.get(tag,tag)
  2205. if tag == 'svg' and self.svgOK:
  2206. self.svgOK -= 1
  2207. else:
  2208. return
  2209. _BaseHTMLProcessor.unknown_endtag(self, tag)
  2210. def handle_pi(self, text):
  2211. pass
  2212. def handle_decl(self, text):
  2213. pass
  2214. def handle_data(self, text):
  2215. if not self.unacceptablestack:
  2216. _BaseHTMLProcessor.handle_data(self, text)
  2217. def sanitize_style(self, style):
  2218. # disallow urls
  2219. style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style)
  2220. # gauntlet
  2221. if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style):
  2222. return ''
  2223. # This replaced a regexp that used re.match and was prone to pathological back-tracking.
  2224. if re.sub("\s*[-\w]+\s*:\s*[^:;]*;?", '', style).strip():
  2225. return ''
  2226. clean = []
  2227. for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style):
  2228. if not value:
  2229. continue
  2230. if prop.lower() in self.acceptable_css_properties:
  2231. clean.append(prop + ': ' + value + ';')
  2232. elif prop.split('-')[0].lower() in ['background','border','margin','padding']:
  2233. for keyword in value.split():
  2234. if not keyword in self.acceptable_css_keywords and \
  2235. not self.valid_css_values.match(keyword):
  2236. break
  2237. else:
  2238. clean.append(prop + ': ' + value + ';')
  2239. elif self.svgOK and prop.lower() in self.acceptable_svg_properties:
  2240. clean.append(prop + ': ' + value + ';')
  2241. return ' '.join(clean)
  2242. def parse_comment(self, i, report=1):
  2243. ret = _BaseHTMLProcessor.parse_comment(self, i, report)
  2244. if ret >= 0:
  2245. return ret
  2246. # if ret == -1, this may be a malicious attempt to circumvent
  2247. # sanitization, or a page-destroying unclosed comment
  2248. match = re.compile(r'--[^>]*>').search(self.rawdata, i+4)
  2249. if match:
  2250. return match.end()
  2251. # unclosed comment; deliberately fail to handle_data()
  2252. return len(self.rawdata)
  2253. def _sanitizeHTML(htmlSource, encoding, _type):
  2254. if not _SGML_AVAILABLE:
  2255. return htmlSource
  2256. p = _HTMLSanitizer(encoding, _type)
  2257. htmlSource = htmlSource.replace('<![CDATA[', '&lt;![CDATA[')
  2258. p.feed(htmlSource)
  2259. data = p.output()
  2260. data = data.strip().replace('\r\n', '\n')
  2261. return data
  2262. class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
  2263. def http_error_default(self, req, fp, code, msg, headers):
  2264. # The default implementation just raises HTTPError.
  2265. # Forget that.
  2266. fp.status = code
  2267. return fp
  2268. def http_error_301(self, req, fp, code, msg, hdrs):
  2269. result = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp,
  2270. code, msg, hdrs)
  2271. result.status = code
  2272. result.newurl = result.geturl()
  2273. return result
  2274. # The default implementations in urllib2.HTTPRedirectHandler
  2275. # are identical, so hardcoding a http_error_301 call above
  2276. # won't affect anything
  2277. http_error_300 = http_error_301
  2278. http_error_302 = http_error_301
  2279. http_error_303 = http_error_301
  2280. http_error_307 = http_error_301
  2281. def http_error_401(self, req, fp, code, msg, headers):
  2282. # Check if
  2283. # - server requires digest auth, AND
  2284. # - we tried (unsuccessfully) with basic auth, AND
  2285. # If all conditions hold, parse authentication information
  2286. # out of the Authorization header we sent the first time
  2287. # (for the username and password) and the WWW-Authenticate
  2288. # header the server sent back (for the realm) and retry
  2289. # the request with the appropriate digest auth headers instead.
  2290. # This evil genius hack has been brought to you by Aaron Swartz.
  2291. host = urlparse.urlparse(req.get_full_url())[1]
  2292. if base64 is None or 'Authorization' not in req.headers \
  2293. or 'WWW-Authenticate' not in headers:
  2294. return self.http_error_default(req, fp, code, msg, headers)
  2295. auth = _base64decode(req.headers['Authorization'].split(' ')[1])
  2296. user, passw = auth.split(':')
  2297. realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0]
  2298. self.add_password(realm, host, user, passw)
  2299. retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  2300. self.reset_retry_count()
  2301. return retry
  2302. def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers):
  2303. """URL, filename, or string --> stream
  2304. This function lets you define parsers that take any input source
  2305. (URL, pathname to local or network file, or actual data as a string)
  2306. and deal with it in a uniform manner. Returned object is guaranteed
  2307. to have all the basic stdio read methods (read, readline, readlines).
  2308. Just .close() the object when you're done with it.
  2309. If the etag argument is supplied, it will be used as the value of an
  2310. If-None-Match request header.
  2311. If the modified argument is supplied, it can be a tuple of 9 integers
  2312. (as returned by gmtime() in the standard Python time module) or a date
  2313. string in any format supported by feedparser. Regardless, it MUST
  2314. be in GMT (Greenwich Mean Time). It will be reformatted into an
  2315. RFC 1123-compliant date and used as the value of an If-Modified-Since
  2316. request header.
  2317. If the agent argument is supplied, it will be used as the value of a
  2318. User-Agent request header.
  2319. If the referrer argument is supplied, it will be used as the value of a
  2320. Referer[sic] request header.
  2321. If handlers is supplied, it is a list of handlers used to build a
  2322. urllib2 opener.
  2323. if request_headers is supplied it is a dictionary of HTTP request headers
  2324. that will override the values generated by FeedParser.
  2325. """
  2326. if hasattr(url_file_stream_or_string, 'read'):
  2327. return url_file_stream_or_string
  2328. if isinstance(url_file_stream_or_string, basestring) \
  2329. and urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp', 'file', 'feed'):
  2330. # Deal with the feed URI scheme
  2331. if url_file_stream_or_string.startswith('feed:http'):
  2332. url_file_stream_or_string = url_file_stream_or_string[5:]
  2333. elif url_file_stream_or_string.startswith('feed:'):
  2334. url_file_stream_or_string = 'http:' + url_file_stream_or_string[5:]
  2335. if not agent:
  2336. agent = USER_AGENT
  2337. # Test for inline user:password credentials for HTTP basic auth
  2338. auth = None
  2339. if base64 and not url_file_stream_or_string.startswith('ftp:'):
  2340. urltype, rest = urllib.splittype(url_file_stream_or_string)
  2341. realhost, rest = urllib.splithost(rest)
  2342. if realhost:
  2343. user_passwd, realhost = urllib.splituser(realhost)
  2344. if user_passwd:
  2345. url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest)
  2346. auth = base64.standard_b64encode(user_passwd).strip()
  2347. # iri support
  2348. if isinstance(url_file_stream_or_string, unicode):
  2349. url_file_stream_or_string = _convert_to_idn(url_file_stream_or_string)
  2350. # try to open with urllib2 (to use optional headers)
  2351. request = _build_urllib2_request(url_file_stream_or_string, agent, etag, modified, referrer, auth, request_headers)
  2352. opener = urllib2.build_opener(*tuple(handlers + [_FeedURLHandler()]))
  2353. opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
  2354. try:
  2355. return opener.open(request)
  2356. finally:
  2357. opener.close() # JohnD
  2358. # try to open with native open function (if url_file_stream_or_string is a filename)
  2359. try:
  2360. return open(url_file_stream_or_string, 'rb')
  2361. except (IOError, UnicodeEncodeError, TypeError):
  2362. # if url_file_stream_or_string is a unicode object that
  2363. # cannot be converted to the encoding returned by
  2364. # sys.getfilesystemencoding(), a UnicodeEncodeError
  2365. # will be thrown
  2366. # If url_file_stream_or_string is a string that contains NULL
  2367. # (such as an XML document encoded in UTF-32), TypeError will
  2368. # be thrown.
  2369. pass
  2370. # treat url_file_stream_or_string as string
  2371. if isinstance(url_file_stream_or_string, unicode):
  2372. return _StringIO(url_file_stream_or_string.encode('utf-8'))
  2373. return _StringIO(url_file_stream_or_string)
  2374. def _convert_to_idn(url):
  2375. """Convert a URL to IDN notation"""
  2376. # this function should only be called with a unicode string
  2377. # strategy: if the host cannot be encoded in ascii, then
  2378. # it'll be necessary to encode it in idn form
  2379. parts = list(urlparse.urlsplit(url))
  2380. try:
  2381. parts[1].encode('ascii')
  2382. except UnicodeEncodeError:
  2383. # the url needs to be converted to idn notation
  2384. host = parts[1].rsplit(':', 1)
  2385. newhost = []
  2386. port = u''
  2387. if len(host) == 2:
  2388. port = host.pop()
  2389. for h in host[0].split('.'):
  2390. newhost.append(h.encode('idna').decode('utf-8'))
  2391. parts[1] = '.'.join(newhost)
  2392. if port:
  2393. parts[1] += ':' + port
  2394. return urlparse.urlunsplit(parts)
  2395. else:
  2396. return url
  2397. def _build_urllib2_request(url, agent, etag, modified, referrer, auth, request_headers):
  2398. request = urllib2.Request(url)
  2399. request.add_header('User-Agent', agent)
  2400. if etag:
  2401. request.add_header('If-None-Match', etag)
  2402. if isinstance(modified, basestring):
  2403. modified = _parse_date(modified)
  2404. elif isinstance(modified, datetime.datetime):
  2405. modified = modified.utctimetuple()
  2406. if modified:
  2407. # format into an RFC 1123-compliant timestamp. We can't use
  2408. # time.strftime() since the %a and %b directives can be affected
  2409. # by the current locale, but RFC 2616 states that dates must be
  2410. # in English.
  2411. short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  2412. months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  2413. request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % (short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5]))
  2414. if referrer:
  2415. request.add_header('Referer', referrer)
  2416. if gzip and zlib:
  2417. request.add_header('Accept-encoding', 'gzip, deflate')
  2418. elif gzip:
  2419. request.add_header('Accept-encoding', 'gzip')
  2420. elif zlib:
  2421. request.add_header('Accept-encoding', 'deflate')
  2422. else:
  2423. request.add_header('Accept-encoding', '')
  2424. if auth:
  2425. request.add_header('Authorization', 'Basic %s' % auth)
  2426. if ACCEPT_HEADER:
  2427. request.add_header('Accept', ACCEPT_HEADER)
  2428. # use this for whatever -- cookies, special headers, etc
  2429. # [('Cookie','Something'),('x-special-header','Another Value')]
  2430. for header_name, header_value in request_headers.items():
  2431. request.add_header(header_name, header_value)
  2432. request.add_header('A-IM', 'feed') # RFC 3229 support
  2433. return request
  2434. def _parse_psc_chapter_start(start):
  2435. FORMAT = r'^((\d{2}):)?(\d{2}):(\d{2})(\.(\d{3}))?$'
  2436. m = re.compile(FORMAT).match(start)
  2437. if m is None:
  2438. return None
  2439. _, h, m, s, _, ms = m.groups()
  2440. h, m, s, ms = (int(h or 0), int(m), int(s), int(ms or 0))
  2441. return datetime.timedelta(0, h*60*60 + m*60 + s, ms*1000)
  2442. _date_handlers = []
  2443. def registerDateHandler(func):
  2444. '''Register a date handler function (takes string, returns 9-tuple date in GMT)'''
  2445. _date_handlers.insert(0, func)
  2446. # ISO-8601 date parsing routines written by Fazal Majid.
  2447. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
  2448. # parser is beyond the scope of feedparser and would be a worthwhile addition
  2449. # to the Python library.
  2450. # A single regular expression cannot parse ISO 8601 date formats into groups
  2451. # as the standard is highly irregular (for instance is 030104 2003-01-04 or
  2452. # 0301-04-01), so we use templates instead.
  2453. # Please note the order in templates is significant because we need a
  2454. # greedy match.
  2455. _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-0MM?-?DD', 'YYYY-MM', 'YYYY-?OOO',
  2456. 'YY-?MM-?DD', 'YY-?OOO', 'YYYY',
  2457. '-YY-?MM', '-OOO', '-YY',
  2458. '--MM-?DD', '--MM',
  2459. '---DD',
  2460. 'CC', '']
  2461. _iso8601_re = [
  2462. tmpl.replace(
  2463. 'YYYY', r'(?P<year>\d{4})').replace(
  2464. 'YY', r'(?P<year>\d\d)').replace(
  2465. 'MM', r'(?P<month>[01]\d)').replace(
  2466. 'DD', r'(?P<day>[0123]\d)').replace(
  2467. 'OOO', r'(?P<ordinal>[0123]\d\d)').replace(
  2468. 'CC', r'(?P<century>\d\d$)')
  2469. + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
  2470. + r'(:(?P<second>\d{2}))?'
  2471. + r'(\.(?P<fracsecond>\d+))?'
  2472. + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
  2473. for tmpl in _iso8601_tmpl]
  2474. try:
  2475. del tmpl
  2476. except NameError:
  2477. pass
  2478. _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
  2479. try:
  2480. del regex
  2481. except NameError:
  2482. pass
  2483. def _parse_date_iso8601(dateString):
  2484. '''Parse a variety of ISO-8601-compatible formats like 20040105'''
  2485. m = None
  2486. for _iso8601_match in _iso8601_matches:
  2487. m = _iso8601_match(dateString)
  2488. if m:
  2489. break
  2490. if not m:
  2491. return
  2492. if m.span() == (0, 0):
  2493. return
  2494. params = m.groupdict()
  2495. ordinal = params.get('ordinal', 0)
  2496. if ordinal:
  2497. ordinal = int(ordinal)
  2498. else:
  2499. ordinal = 0
  2500. year = params.get('year', '--')
  2501. if not year or year == '--':
  2502. year = time.gmtime()[0]
  2503. elif len(year) == 2:
  2504. # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
  2505. year = 100 * int(time.gmtime()[0] / 100) + int(year)
  2506. else:
  2507. year = int(year)
  2508. month = params.get('month', '-')
  2509. if not month or month == '-':
  2510. # ordinals are NOT normalized by mktime, we simulate them
  2511. # by setting month=1, day=ordinal
  2512. if ordinal:
  2513. month = 1
  2514. else:
  2515. month = time.gmtime()[1]
  2516. month = int(month)
  2517. day = params.get('day', 0)
  2518. if not day:
  2519. # see above
  2520. if ordinal:
  2521. day = ordinal
  2522. elif params.get('century', 0) or \
  2523. params.get('year', 0) or params.get('month', 0):
  2524. day = 1
  2525. else:
  2526. day = time.gmtime()[2]
  2527. else:
  2528. day = int(day)
  2529. # special case of the century - is the first year of the 21st century
  2530. # 2000 or 2001 ? The debate goes on...
  2531. if 'century' in params:
  2532. year = (int(params['century']) - 1) * 100 + 1
  2533. # in ISO 8601 most fields are optional
  2534. for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
  2535. if not params.get(field, None):
  2536. params[field] = 0
  2537. hour = int(params.get('hour', 0))
  2538. minute = int(params.get('minute', 0))
  2539. second = int(float(params.get('second', 0)))
  2540. # weekday is normalized by mktime(), we can ignore it
  2541. weekday = 0
  2542. daylight_savings_flag = -1
  2543. tm = [year, month, day, hour, minute, second, weekday,
  2544. ordinal, daylight_savings_flag]
  2545. # ISO 8601 time zone adjustments
  2546. tz = params.get('tz')
  2547. if tz and tz != 'Z':
  2548. if tz[0] == '-':
  2549. tm[3] += int(params.get('tzhour', 0))
  2550. tm[4] += int(params.get('tzmin', 0))
  2551. elif tz[0] == '+':
  2552. tm[3] -= int(params.get('tzhour', 0))
  2553. tm[4] -= int(params.get('tzmin', 0))
  2554. else:
  2555. return None
  2556. # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
  2557. # which is guaranteed to normalize d/m/y/h/m/s.
  2558. # Many implementations have bugs, but we'll pretend they don't.
  2559. return time.localtime(time.mktime(tuple(tm)))
  2560. registerDateHandler(_parse_date_iso8601)
  2561. # 8-bit date handling routines written by ytrewq1.
  2562. _korean_year = u'\ub144' # b3e2 in euc-kr
  2563. _korean_month = u'\uc6d4' # bff9 in euc-kr
  2564. _korean_day = u'\uc77c' # c0cf in euc-kr
  2565. _korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr
  2566. _korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr
  2567. _korean_onblog_date_re = \
  2568. re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \
  2569. (_korean_year, _korean_month, _korean_day))
  2570. _korean_nate_date_re = \
  2571. re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \
  2572. (_korean_am, _korean_pm))
  2573. def _parse_date_onblog(dateString):
  2574. '''Parse a string according to the OnBlog 8-bit date format'''
  2575. m = _korean_onblog_date_re.match(dateString)
  2576. if not m:
  2577. return
  2578. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2579. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2580. 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  2581. 'zonediff': '+09:00'}
  2582. return _parse_date_w3dtf(w3dtfdate)
  2583. registerDateHandler(_parse_date_onblog)
  2584. def _parse_date_nate(dateString):
  2585. '''Parse a string according to the Nate 8-bit date format'''
  2586. m = _korean_nate_date_re.match(dateString)
  2587. if not m:
  2588. return
  2589. hour = int(m.group(5))
  2590. ampm = m.group(4)
  2591. if (ampm == _korean_pm):
  2592. hour += 12
  2593. hour = str(hour)
  2594. if len(hour) == 1:
  2595. hour = '0' + hour
  2596. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2597. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2598. 'hour': hour, 'minute': m.group(6), 'second': m.group(7),\
  2599. 'zonediff': '+09:00'}
  2600. return _parse_date_w3dtf(w3dtfdate)
  2601. registerDateHandler(_parse_date_nate)
  2602. # Unicode strings for Greek date strings
  2603. _greek_months = \
  2604. { \
  2605. u'\u0399\u03b1\u03bd': u'Jan', # c9e1ed in iso-8859-7
  2606. u'\u03a6\u03b5\u03b2': u'Feb', # d6e5e2 in iso-8859-7
  2607. u'\u039c\u03ac\u03ce': u'Mar', # ccdcfe in iso-8859-7
  2608. u'\u039c\u03b1\u03ce': u'Mar', # cce1fe in iso-8859-7
  2609. u'\u0391\u03c0\u03c1': u'Apr', # c1f0f1 in iso-8859-7
  2610. u'\u039c\u03ac\u03b9': u'May', # ccdce9 in iso-8859-7
  2611. u'\u039c\u03b1\u03ca': u'May', # cce1fa in iso-8859-7
  2612. u'\u039c\u03b1\u03b9': u'May', # cce1e9 in iso-8859-7
  2613. u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7
  2614. u'\u0399\u03bf\u03bd': u'Jun', # c9efed in iso-8859-7
  2615. u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7
  2616. u'\u0399\u03bf\u03bb': u'Jul', # c9f9eb in iso-8859-7
  2617. u'\u0391\u03cd\u03b3': u'Aug', # c1fde3 in iso-8859-7
  2618. u'\u0391\u03c5\u03b3': u'Aug', # c1f5e3 in iso-8859-7
  2619. u'\u03a3\u03b5\u03c0': u'Sep', # d3e5f0 in iso-8859-7
  2620. u'\u039f\u03ba\u03c4': u'Oct', # cfeaf4 in iso-8859-7
  2621. u'\u039d\u03bf\u03ad': u'Nov', # cdefdd in iso-8859-7
  2622. u'\u039d\u03bf\u03b5': u'Nov', # cdefe5 in iso-8859-7
  2623. u'\u0394\u03b5\u03ba': u'Dec', # c4e5ea in iso-8859-7
  2624. }
  2625. _greek_wdays = \
  2626. { \
  2627. u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7
  2628. u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7
  2629. u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7
  2630. u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7
  2631. u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7
  2632. u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7
  2633. u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7
  2634. }
  2635. _greek_date_format_re = \
  2636. re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)')
  2637. def _parse_date_greek(dateString):
  2638. '''Parse a string according to a Greek 8-bit date format.'''
  2639. m = _greek_date_format_re.match(dateString)
  2640. if not m:
  2641. return
  2642. wday = _greek_wdays[m.group(1)]
  2643. month = _greek_months[m.group(3)]
  2644. rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
  2645. {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\
  2646. 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\
  2647. 'zonediff': m.group(8)}
  2648. return _parse_date_rfc822(rfc822date)
  2649. registerDateHandler(_parse_date_greek)
  2650. # Unicode strings for Hungarian date strings
  2651. _hungarian_months = \
  2652. { \
  2653. u'janu\u00e1r': u'01', # e1 in iso-8859-2
  2654. u'febru\u00e1ri': u'02', # e1 in iso-8859-2
  2655. u'm\u00e1rcius': u'03', # e1 in iso-8859-2
  2656. u'\u00e1prilis': u'04', # e1 in iso-8859-2
  2657. u'm\u00e1ujus': u'05', # e1 in iso-8859-2
  2658. u'j\u00fanius': u'06', # fa in iso-8859-2
  2659. u'j\u00falius': u'07', # fa in iso-8859-2
  2660. u'augusztus': u'08',
  2661. u'szeptember': u'09',
  2662. u'okt\u00f3ber': u'10', # f3 in iso-8859-2
  2663. u'november': u'11',
  2664. u'december': u'12',
  2665. }
  2666. _hungarian_date_format_re = \
  2667. re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))')
  2668. def _parse_date_hungarian(dateString):
  2669. '''Parse a string according to a Hungarian 8-bit date format.'''
  2670. m = _hungarian_date_format_re.match(dateString)
  2671. if not m or m.group(2) not in _hungarian_months:
  2672. return None
  2673. month = _hungarian_months[m.group(2)]
  2674. day = m.group(3)
  2675. if len(day) == 1:
  2676. day = '0' + day
  2677. hour = m.group(4)
  2678. if len(hour) == 1:
  2679. hour = '0' + hour
  2680. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \
  2681. {'year': m.group(1), 'month': month, 'day': day,\
  2682. 'hour': hour, 'minute': m.group(5),\
  2683. 'zonediff': m.group(6)}
  2684. return _parse_date_w3dtf(w3dtfdate)
  2685. registerDateHandler(_parse_date_hungarian)
  2686. timezonenames = {
  2687. 'ut': 0, 'gmt': 0, 'z': 0,
  2688. 'adt': -3, 'ast': -4, 'at': -4,
  2689. 'edt': -4, 'est': -5, 'et': -5,
  2690. 'cdt': -5, 'cst': -6, 'ct': -6,
  2691. 'mdt': -6, 'mst': -7, 'mt': -7,
  2692. 'pdt': -7, 'pst': -8, 'pt': -8,
  2693. 'a': -1, 'n': 1,
  2694. 'm': -12, 'y': 12,
  2695. }
  2696. # W3 date and time format parser
  2697. # http://www.w3.org/TR/NOTE-datetime
  2698. # Also supports MSSQL-style datetimes as defined at:
  2699. # http://msdn.microsoft.com/en-us/library/ms186724.aspx
  2700. # (basically, allow a space as a date/time/timezone separator)
  2701. def _parse_date_w3dtf(datestr):
  2702. if not datestr.strip():
  2703. return None
  2704. parts = datestr.lower().split('t')
  2705. if len(parts) == 1:
  2706. # This may be a date only, or may be an MSSQL-style date
  2707. parts = parts[0].split()
  2708. if len(parts) == 1:
  2709. # Treat this as a date only
  2710. parts.append('00:00:00z')
  2711. elif len(parts) > 2:
  2712. return None
  2713. date = parts[0].split('-', 2)
  2714. if not date or len(date[0]) != 4:
  2715. return None
  2716. # Ensure that `date` has 3 elements. Using '1' sets the default
  2717. # month to January and the default day to the 1st of the month.
  2718. date.extend(['1'] * (3 - len(date)))
  2719. try:
  2720. year, month, day = [int(i) for i in date]
  2721. except ValueError:
  2722. # `date` may have more than 3 elements or may contain
  2723. # non-integer strings.
  2724. return None
  2725. if parts[1].endswith('z'):
  2726. parts[1] = parts[1][:-1]
  2727. parts.append('z')
  2728. # Append the numeric timezone offset, if any, to parts.
  2729. # If this is an MSSQL-style date then parts[2] already contains
  2730. # the timezone information, so `append()` will not affect it.
  2731. # Add 1 to each value so that if `find()` returns -1 it will be
  2732. # treated as False.
  2733. loc = parts[1].find('-') + 1 or parts[1].find('+') + 1 or len(parts[1]) + 1
  2734. loc = loc - 1
  2735. parts.append(parts[1][loc:])
  2736. parts[1] = parts[1][:loc]
  2737. time = parts[1].split(':', 2)
  2738. # Ensure that time has 3 elements. Using '0' means that the
  2739. # minutes and seconds, if missing, will default to 0.
  2740. time.extend(['0'] * (3 - len(time)))
  2741. tzhour = 0
  2742. tzmin = 0
  2743. if parts[2][:1] in ('-', '+'):
  2744. try:
  2745. tzhour = int(parts[2][1:3])
  2746. tzmin = int(parts[2][4:])
  2747. except ValueError:
  2748. return None
  2749. if parts[2].startswith('-'):
  2750. tzhour = tzhour * -1
  2751. tzmin = tzmin * -1
  2752. else:
  2753. tzhour = timezonenames.get(parts[2], 0)
  2754. try:
  2755. hour, minute, second = [int(float(i)) for i in time]
  2756. except ValueError:
  2757. return None
  2758. # Create the datetime object and timezone delta objects
  2759. try:
  2760. stamp = datetime.datetime(year, month, day, hour, minute, second)
  2761. except ValueError:
  2762. return None
  2763. delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour)
  2764. # Return the date and timestamp in a UTC 9-tuple
  2765. try:
  2766. return (stamp - delta).utctimetuple()
  2767. except (OverflowError, ValueError):
  2768. # IronPython throws ValueErrors instead of OverflowErrors
  2769. return None
  2770. registerDateHandler(_parse_date_w3dtf)
  2771. def _parse_date_rfc822(date):
  2772. """Parse RFC 822 dates and times
  2773. http://tools.ietf.org/html/rfc822#section-5
  2774. There are some formatting differences that are accounted for:
  2775. 1. Years may be two or four digits.
  2776. 2. The month and day can be swapped.
  2777. 3. Additional timezone names are supported.
  2778. 4. A default time and timezone are assumed if only a date is present.
  2779. """
  2780. daynames = set(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])
  2781. months = {
  2782. 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
  2783. 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
  2784. }
  2785. parts = date.lower().split()
  2786. if len(parts) < 5:
  2787. # Assume that the time and timezone are missing
  2788. parts.extend(('00:00:00', '0000'))
  2789. # Remove the day name
  2790. if parts[0][:3] in daynames:
  2791. parts = parts[1:]
  2792. if len(parts) < 5:
  2793. # If there are still fewer than five parts, there's not enough
  2794. # information to interpret this
  2795. return None
  2796. try:
  2797. day = int(parts[0])
  2798. except ValueError:
  2799. # Check if the day and month are swapped
  2800. if months.get(parts[0][:3]):
  2801. try:
  2802. day = int(parts[1])
  2803. except ValueError:
  2804. return None
  2805. else:
  2806. parts[1] = parts[0]
  2807. else:
  2808. return None
  2809. month = months.get(parts[1][:3])
  2810. if not month:
  2811. return None
  2812. try:
  2813. year = int(parts[2])
  2814. except ValueError:
  2815. return None
  2816. # Normalize two-digit years:
  2817. # Anything in the 90's is interpreted as 1990 and on
  2818. # Anything 89 or less is interpreted as 2089 or before
  2819. if len(parts[2]) <= 2:
  2820. year += (1900, 2000)[year < 90]
  2821. timeparts = parts[3].split(':')
  2822. timeparts = timeparts + ([0] * (3 - len(timeparts)))
  2823. try:
  2824. (hour, minute, second) = map(int, timeparts)
  2825. except ValueError:
  2826. return None
  2827. tzhour = 0
  2828. tzmin = 0
  2829. # Strip 'Etc/' from the timezone
  2830. if parts[4].startswith('etc/'):
  2831. parts[4] = parts[4][4:]
  2832. # Normalize timezones that start with 'gmt':
  2833. # GMT-05:00 => -0500
  2834. # GMT => GMT
  2835. if parts[4].startswith('gmt'):
  2836. parts[4] = ''.join(parts[4][3:].split(':')) or 'gmt'
  2837. # Handle timezones like '-0500', '+0500', and 'EST'
  2838. if parts[4] and parts[4][0] in ('-', '+'):
  2839. try:
  2840. tzhour = int(parts[4][1:3])
  2841. tzmin = int(parts[4][3:])
  2842. except ValueError:
  2843. return None
  2844. if parts[4].startswith('-'):
  2845. tzhour = tzhour * -1
  2846. tzmin = tzmin * -1
  2847. else:
  2848. tzhour = timezonenames.get(parts[4], 0)
  2849. # Create the datetime object and timezone delta objects
  2850. try:
  2851. stamp = datetime.datetime(year, month, day, hour, minute, second)
  2852. except ValueError:
  2853. return None
  2854. delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour)
  2855. # Return the date and timestamp in a UTC 9-tuple
  2856. try:
  2857. return (stamp - delta).utctimetuple()
  2858. except (OverflowError, ValueError):
  2859. # IronPython throws ValueErrors instead of OverflowErrors
  2860. return None
  2861. registerDateHandler(_parse_date_rfc822)
  2862. _months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
  2863. 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
  2864. def _parse_date_asctime(dt):
  2865. """Parse asctime-style dates"""
  2866. dayname, month, day, remainder = dt.split(None, 3)
  2867. # Convert month and day into zero-padded integers
  2868. month = '%02i ' % (_months.index(month.lower()) + 1)
  2869. day = '%02i ' % (int(day),)
  2870. dt = month + day + remainder
  2871. return time.strptime(dt, '%m %d %H:%M:%S %Y')[:-1] + (0, )
  2872. registerDateHandler(_parse_date_asctime)
  2873. def _parse_date_perforce(aDateString):
  2874. """parse a date in yyyy/mm/dd hh:mm:ss TTT format"""
  2875. # Fri, 2006/09/15 08:19:53 EDT
  2876. _my_date_pattern = re.compile( \
  2877. r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})')
  2878. m = _my_date_pattern.search(aDateString)
  2879. if m is None:
  2880. return None
  2881. dow, year, month, day, hour, minute, second, tz = m.groups()
  2882. months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  2883. dateString = "%s, %s %s %s %s:%s:%s %s" % (dow, day, months[int(month) - 1], year, hour, minute, second, tz)
  2884. tm = rfc822.parsedate_tz(dateString)
  2885. if tm:
  2886. return time.gmtime(rfc822.mktime_tz(tm))
  2887. registerDateHandler(_parse_date_perforce)
  2888. def _parse_date(dateString):
  2889. '''Parses a variety of date formats into a 9-tuple in GMT'''
  2890. if not dateString:
  2891. return None
  2892. for handler in _date_handlers:
  2893. try:
  2894. date9tuple = handler(dateString)
  2895. except (KeyError, OverflowError, ValueError):
  2896. continue
  2897. if not date9tuple:
  2898. continue
  2899. if len(date9tuple) != 9:
  2900. continue
  2901. return date9tuple
  2902. return None
  2903. # Each marker represents some of the characters of the opening XML
  2904. # processing instruction ('<?xm') in the specified encoding.
  2905. EBCDIC_MARKER = _l2bytes([0x4C, 0x6F, 0xA7, 0x94])
  2906. UTF16BE_MARKER = _l2bytes([0x00, 0x3C, 0x00, 0x3F])
  2907. UTF16LE_MARKER = _l2bytes([0x3C, 0x00, 0x3F, 0x00])
  2908. UTF32BE_MARKER = _l2bytes([0x00, 0x00, 0x00, 0x3C])
  2909. UTF32LE_MARKER = _l2bytes([0x3C, 0x00, 0x00, 0x00])
  2910. ZERO_BYTES = _l2bytes([0x00, 0x00])
  2911. # Match the opening XML declaration.
  2912. # Example: <?xml version="1.0" encoding="utf-8"?>
  2913. RE_XML_DECLARATION = re.compile('^<\?xml[^>]*?>')
  2914. # Capture the value of the XML processing instruction's encoding attribute.
  2915. # Example: <?xml version="1.0" encoding="utf-8"?>
  2916. RE_XML_PI_ENCODING = re.compile(_s2bytes('^<\?.*encoding=[\'"](.*?)[\'"].*\?>'))
  2917. def convert_to_utf8(http_headers, data):
  2918. '''Detect and convert the character encoding to UTF-8.
  2919. http_headers is a dictionary
  2920. data is a raw string (not Unicode)'''
  2921. # This is so much trickier than it sounds, it's not even funny.
  2922. # According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type
  2923. # is application/xml, application/*+xml,
  2924. # application/xml-external-parsed-entity, or application/xml-dtd,
  2925. # the encoding given in the charset parameter of the HTTP Content-Type
  2926. # takes precedence over the encoding given in the XML prefix within the
  2927. # document, and defaults to 'utf-8' if neither are specified. But, if
  2928. # the HTTP Content-Type is text/xml, text/*+xml, or
  2929. # text/xml-external-parsed-entity, the encoding given in the XML prefix
  2930. # within the document is ALWAYS IGNORED and only the encoding given in
  2931. # the charset parameter of the HTTP Content-Type header should be
  2932. # respected, and it defaults to 'us-ascii' if not specified.
  2933. # Furthermore, discussion on the atom-syntax mailing list with the
  2934. # author of RFC 3023 leads me to the conclusion that any document
  2935. # served with a Content-Type of text/* and no charset parameter
  2936. # must be treated as us-ascii. (We now do this.) And also that it
  2937. # must always be flagged as non-well-formed. (We now do this too.)
  2938. # If Content-Type is unspecified (input was local file or non-HTTP source)
  2939. # or unrecognized (server just got it totally wrong), then go by the
  2940. # encoding given in the XML prefix of the document and default to
  2941. # 'iso-8859-1' as per the HTTP specification (RFC 2616).
  2942. # Then, assuming we didn't find a character encoding in the HTTP headers
  2943. # (and the HTTP Content-type allowed us to look in the body), we need
  2944. # to sniff the first few bytes of the XML data and try to determine
  2945. # whether the encoding is ASCII-compatible. Section F of the XML
  2946. # specification shows the way here:
  2947. # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2948. # If the sniffed encoding is not ASCII-compatible, we need to make it
  2949. # ASCII compatible so that we can sniff further into the XML declaration
  2950. # to find the encoding attribute, which will tell us the true encoding.
  2951. # Of course, none of this guarantees that we will be able to parse the
  2952. # feed in the declared character encoding (assuming it was declared
  2953. # correctly, which many are not). iconv_codec can help a lot;
  2954. # you should definitely install it if you can.
  2955. # http://cjkpython.i18n.org/
  2956. bom_encoding = u''
  2957. xml_encoding = u''
  2958. rfc3023_encoding = u''
  2959. # Look at the first few bytes of the document to guess what
  2960. # its encoding may be. We only need to decode enough of the
  2961. # document that we can use an ASCII-compatible regular
  2962. # expression to search for an XML encoding declaration.
  2963. # The heuristic follows the XML specification, section F:
  2964. # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2965. # Check for BOMs first.
  2966. if data[:4] == codecs.BOM_UTF32_BE:
  2967. bom_encoding = u'utf-32be'
  2968. data = data[4:]
  2969. elif data[:4] == codecs.BOM_UTF32_LE:
  2970. bom_encoding = u'utf-32le'
  2971. data = data[4:]
  2972. elif data[:2] == codecs.BOM_UTF16_BE and data[2:4] != ZERO_BYTES:
  2973. bom_encoding = u'utf-16be'
  2974. data = data[2:]
  2975. elif data[:2] == codecs.BOM_UTF16_LE and data[2:4] != ZERO_BYTES:
  2976. bom_encoding = u'utf-16le'
  2977. data = data[2:]
  2978. elif data[:3] == codecs.BOM_UTF8:
  2979. bom_encoding = u'utf-8'
  2980. data = data[3:]
  2981. # Check for the characters '<?xm' in several encodings.
  2982. elif data[:4] == EBCDIC_MARKER:
  2983. bom_encoding = u'cp037'
  2984. elif data[:4] == UTF16BE_MARKER:
  2985. bom_encoding = u'utf-16be'
  2986. elif data[:4] == UTF16LE_MARKER:
  2987. bom_encoding = u'utf-16le'
  2988. elif data[:4] == UTF32BE_MARKER:
  2989. bom_encoding = u'utf-32be'
  2990. elif data[:4] == UTF32LE_MARKER:
  2991. bom_encoding = u'utf-32le'
  2992. tempdata = data
  2993. try:
  2994. if bom_encoding:
  2995. tempdata = data.decode(bom_encoding).encode('utf-8')
  2996. except (UnicodeDecodeError, LookupError):
  2997. # feedparser recognizes UTF-32 encodings that aren't
  2998. # available in Python 2.4 and 2.5, so it's possible to
  2999. # encounter a LookupError during decoding.
  3000. xml_encoding_match = None
  3001. else:
  3002. xml_encoding_match = RE_XML_PI_ENCODING.match(tempdata)
  3003. if xml_encoding_match:
  3004. xml_encoding = xml_encoding_match.groups()[0].decode('utf-8').lower()
  3005. # Normalize the xml_encoding if necessary.
  3006. if bom_encoding and (xml_encoding in (
  3007. u'u16', u'utf-16', u'utf16', u'utf_16',
  3008. u'u32', u'utf-32', u'utf32', u'utf_32',
  3009. u'iso-10646-ucs-2', u'iso-10646-ucs-4',
  3010. u'csucs4', u'csunicode', u'ucs-2', u'ucs-4'
  3011. )):
  3012. xml_encoding = bom_encoding
  3013. # Find the HTTP Content-Type and, hopefully, a character
  3014. # encoding provided by the server. The Content-Type is used
  3015. # to choose the "correct" encoding among the BOM encoding,
  3016. # XML declaration encoding, and HTTP encoding, following the
  3017. # heuristic defined in RFC 3023.
  3018. http_content_type = http_headers.get('content-type') or ''
  3019. http_content_type, params = cgi.parse_header(http_content_type)
  3020. http_encoding = params.get('charset', '').replace("'", "")
  3021. if not isinstance(http_encoding, unicode):
  3022. http_encoding = http_encoding.decode('utf-8', 'ignore')
  3023. acceptable_content_type = 0
  3024. application_content_types = (u'application/xml', u'application/xml-dtd',
  3025. u'application/xml-external-parsed-entity')
  3026. text_content_types = (u'text/xml', u'text/xml-external-parsed-entity')
  3027. if (http_content_type in application_content_types) or \
  3028. (http_content_type.startswith(u'application/') and
  3029. http_content_type.endswith(u'+xml')):
  3030. acceptable_content_type = 1
  3031. rfc3023_encoding = http_encoding or xml_encoding or u'utf-8'
  3032. elif (http_content_type in text_content_types) or \
  3033. (http_content_type.startswith(u'text/') and
  3034. http_content_type.endswith(u'+xml')):
  3035. acceptable_content_type = 1
  3036. rfc3023_encoding = http_encoding or u'us-ascii'
  3037. elif http_content_type.startswith(u'text/'):
  3038. rfc3023_encoding = http_encoding or u'us-ascii'
  3039. elif http_headers and 'content-type' not in http_headers:
  3040. rfc3023_encoding = xml_encoding or u'iso-8859-1'
  3041. else:
  3042. rfc3023_encoding = xml_encoding or u'utf-8'
  3043. # gb18030 is a superset of gb2312, so always replace gb2312
  3044. # with gb18030 for greater compatibility.
  3045. if rfc3023_encoding.lower() == u'gb2312':
  3046. rfc3023_encoding = u'gb18030'
  3047. if xml_encoding.lower() == u'gb2312':
  3048. xml_encoding = u'gb18030'
  3049. # there are four encodings to keep track of:
  3050. # - http_encoding is the encoding declared in the Content-Type HTTP header
  3051. # - xml_encoding is the encoding declared in the <?xml declaration
  3052. # - bom_encoding is the encoding sniffed from the first 4 bytes of the XML data
  3053. # - rfc3023_encoding is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications
  3054. error = None
  3055. if http_headers and (not acceptable_content_type):
  3056. if 'content-type' in http_headers:
  3057. msg = '%s is not an XML media type' % http_headers['content-type']
  3058. else:
  3059. msg = 'no Content-type specified'
  3060. error = NonXMLContentType(msg)
  3061. # determine character encoding
  3062. known_encoding = 0
  3063. chardet_encoding = None
  3064. tried_encodings = []
  3065. if chardet:
  3066. chardet_encoding = chardet.detect(data)['encoding']
  3067. if not chardet_encoding:
  3068. chardet_encoding = ''
  3069. if not isinstance(chardet_encoding, unicode):
  3070. chardet_encoding = unicode(chardet_encoding, 'ascii', 'ignore')
  3071. # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM
  3072. for proposed_encoding in (rfc3023_encoding, xml_encoding, bom_encoding,
  3073. chardet_encoding, u'utf-8', u'windows-1252', u'iso-8859-2'):
  3074. if not proposed_encoding:
  3075. continue
  3076. if proposed_encoding in tried_encodings:
  3077. continue
  3078. tried_encodings.append(proposed_encoding)
  3079. try:
  3080. data = data.decode(proposed_encoding)
  3081. except (UnicodeDecodeError, LookupError):
  3082. pass
  3083. else:
  3084. known_encoding = 1
  3085. # Update the encoding in the opening XML processing instruction.
  3086. new_declaration = '''<?xml version='1.0' encoding='utf-8'?>'''
  3087. if RE_XML_DECLARATION.search(data):
  3088. data = RE_XML_DECLARATION.sub(new_declaration, data)
  3089. else:
  3090. data = new_declaration + u'\n' + data
  3091. data = data.encode('utf-8')
  3092. break
  3093. # if still no luck, give up
  3094. if not known_encoding:
  3095. error = CharacterEncodingUnknown(
  3096. 'document encoding unknown, I tried ' +
  3097. '%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' %
  3098. (rfc3023_encoding, xml_encoding))
  3099. rfc3023_encoding = u''
  3100. elif proposed_encoding != rfc3023_encoding:
  3101. error = CharacterEncodingOverride(
  3102. 'document declared as %s, but parsed as %s' %
  3103. (rfc3023_encoding, proposed_encoding))
  3104. rfc3023_encoding = proposed_encoding
  3105. return data, rfc3023_encoding, error
  3106. # Match XML entity declarations.
  3107. # Example: <!ENTITY copyright "(C)">
  3108. RE_ENTITY_PATTERN = re.compile(_s2bytes(r'^\s*<!ENTITY([^>]*?)>'), re.MULTILINE)
  3109. # Match XML DOCTYPE declarations.
  3110. # Example: <!DOCTYPE feed [ ]>
  3111. RE_DOCTYPE_PATTERN = re.compile(_s2bytes(r'^\s*<!DOCTYPE([^>]*?)>'), re.MULTILINE)
  3112. # Match safe entity declarations.
  3113. # This will allow hexadecimal character references through,
  3114. # as well as text, but not arbitrary nested entities.
  3115. # Example: cubed "&#179;"
  3116. # Example: copyright "(C)"
  3117. # Forbidden: explode1 "&explode2;&explode2;"
  3118. RE_SAFE_ENTITY_PATTERN = re.compile(_s2bytes('\s+(\w+)\s+"(&#\w+;|[^&"]*)"'))
  3119. def replace_doctype(data):
  3120. '''Strips and replaces the DOCTYPE, returns (rss_version, stripped_data)
  3121. rss_version may be 'rss091n' or None
  3122. stripped_data is the same XML document with a replaced DOCTYPE
  3123. '''
  3124. # Divide the document into two groups by finding the location
  3125. # of the first element that doesn't begin with '<?' or '<!'.
  3126. start = re.search(_s2bytes('<\w'), data)
  3127. start = start and start.start() or -1
  3128. head, data = data[:start+1], data[start+1:]
  3129. # Save and then remove all of the ENTITY declarations.
  3130. entity_results = RE_ENTITY_PATTERN.findall(head)
  3131. head = RE_ENTITY_PATTERN.sub(_s2bytes(''), head)
  3132. # Find the DOCTYPE declaration and check the feed type.
  3133. doctype_results = RE_DOCTYPE_PATTERN.findall(head)
  3134. doctype = doctype_results and doctype_results[0] or _s2bytes('')
  3135. if _s2bytes('netscape') in doctype.lower():
  3136. version = u'rss091n'
  3137. else:
  3138. version = None
  3139. # Re-insert the safe ENTITY declarations if a DOCTYPE was found.
  3140. replacement = _s2bytes('')
  3141. if len(doctype_results) == 1 and entity_results:
  3142. match_safe_entities = lambda e: RE_SAFE_ENTITY_PATTERN.match(e)
  3143. safe_entities = filter(match_safe_entities, entity_results)
  3144. if safe_entities:
  3145. replacement = _s2bytes('<!DOCTYPE feed [\n<!ENTITY') \
  3146. + _s2bytes('>\n<!ENTITY ').join(safe_entities) \
  3147. + _s2bytes('>\n]>')
  3148. data = RE_DOCTYPE_PATTERN.sub(replacement, head) + data
  3149. # Precompute the safe entities for the loose parser.
  3150. safe_entities = dict((k.decode('utf-8'), v.decode('utf-8'))
  3151. for k, v in RE_SAFE_ENTITY_PATTERN.findall(replacement))
  3152. return version, data, safe_entities
  3153. # GeoRSS geometry parsers. Each return a dict with 'type' and 'coordinates'
  3154. # items, or None in the case of a parsing error.
  3155. def _parse_poslist(value, geom_type, swap=True, dims=2):
  3156. if geom_type == 'linestring':
  3157. return _parse_georss_line(value, swap, dims)
  3158. elif geom_type == 'polygon':
  3159. ring = _parse_georss_line(value, swap, dims)
  3160. return {'type': u'Polygon', 'coordinates': (ring['coordinates'],)}
  3161. else:
  3162. return None
  3163. def _gen_georss_coords(value, swap=True, dims=2):
  3164. # A generator of (lon, lat) pairs from a string of encoded GeoRSS
  3165. # coordinates. Converts to floats and swaps order.
  3166. latlons = itertools.imap(float, value.strip().replace(',', ' ').split())
  3167. nxt = latlons.next
  3168. while True:
  3169. t = [nxt(), nxt()][::swap and -1 or 1]
  3170. if dims == 3:
  3171. t.append(nxt())
  3172. yield tuple(t)
  3173. def _parse_georss_point(value, swap=True, dims=2):
  3174. # A point contains a single latitude-longitude pair, separated by
  3175. # whitespace. We'll also handle comma separators.
  3176. try:
  3177. coords = list(_gen_georss_coords(value, swap, dims))
  3178. return {u'type': u'Point', u'coordinates': coords[0]}
  3179. except (IndexError, ValueError):
  3180. return None
  3181. def _parse_georss_line(value, swap=True, dims=2):
  3182. # A line contains a space separated list of latitude-longitude pairs in
  3183. # WGS84 coordinate reference system, with each pair separated by
  3184. # whitespace. There must be at least two pairs.
  3185. try:
  3186. coords = list(_gen_georss_coords(value, swap, dims))
  3187. return {u'type': u'LineString', u'coordinates': coords}
  3188. except (IndexError, ValueError):
  3189. return None
  3190. def _parse_georss_polygon(value, swap=True, dims=2):
  3191. # A polygon contains a space separated list of latitude-longitude pairs,
  3192. # with each pair separated by whitespace. There must be at least four
  3193. # pairs, with the last being identical to the first (so a polygon has a
  3194. # minimum of three actual points).
  3195. try:
  3196. ring = list(_gen_georss_coords(value, swap, dims))
  3197. except (IndexError, ValueError):
  3198. return None
  3199. if len(ring) < 4:
  3200. return None
  3201. return {u'type': u'Polygon', u'coordinates': (ring,)}
  3202. def _parse_georss_box(value, swap=True, dims=2):
  3203. # A bounding box is a rectangular region, often used to define the extents
  3204. # of a map or a rough area of interest. A box contains two space seperate
  3205. # latitude-longitude pairs, with each pair separated by whitespace. The
  3206. # first pair is the lower corner, the second is the upper corner.
  3207. try:
  3208. coords = list(_gen_georss_coords(value, swap, dims))
  3209. return {u'type': u'Box', u'coordinates': tuple(coords)}
  3210. except (IndexError, ValueError):
  3211. return None
  3212. # end geospatial parsers
  3213. def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=None, request_headers=None, response_headers=None):
  3214. '''Parse a feed from a URL, file, stream, or string.
  3215. request_headers, if given, is a dict from http header name to value to add
  3216. to the request; this overrides internally generated values.
  3217. '''
  3218. if handlers is None:
  3219. handlers = []
  3220. if request_headers is None:
  3221. request_headers = {}
  3222. if response_headers is None:
  3223. response_headers = {}
  3224. result = FeedParserDict()
  3225. result['feed'] = FeedParserDict()
  3226. result['entries'] = []
  3227. result['bozo'] = 0
  3228. if not isinstance(handlers, list):
  3229. handlers = [handlers]
  3230. try:
  3231. f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers)
  3232. data = f.read()
  3233. except Exception, e:
  3234. result['bozo'] = 1
  3235. result['bozo_exception'] = e
  3236. data = None
  3237. f = None
  3238. if hasattr(f, 'headers'):
  3239. result['headers'] = dict(f.headers)
  3240. # overwrite existing headers using response_headers
  3241. if 'headers' in result:
  3242. result['headers'].update(response_headers)
  3243. elif response_headers:
  3244. result['headers'] = copy.deepcopy(response_headers)
  3245. # lowercase all of the HTTP headers for comparisons per RFC 2616
  3246. if 'headers' in result:
  3247. http_headers = dict((k.lower(), v) for k, v in result['headers'].items())
  3248. else:
  3249. http_headers = {}
  3250. # if feed is gzip-compressed, decompress it
  3251. if f and data and http_headers:
  3252. if gzip and 'gzip' in http_headers.get('content-encoding', ''):
  3253. try:
  3254. data = gzip.GzipFile(fileobj=_StringIO(data)).read()
  3255. except (IOError, struct.error), e:
  3256. # IOError can occur if the gzip header is bad.
  3257. # struct.error can occur if the data is damaged.
  3258. result['bozo'] = 1
  3259. result['bozo_exception'] = e
  3260. if isinstance(e, struct.error):
  3261. # A gzip header was found but the data is corrupt.
  3262. # Ideally, we should re-request the feed without the
  3263. # 'Accept-encoding: gzip' header, but we don't.
  3264. data = None
  3265. elif zlib and 'deflate' in http_headers.get('content-encoding', ''):
  3266. try:
  3267. data = zlib.decompress(data)
  3268. except zlib.error, e:
  3269. try:
  3270. # The data may have no headers and no checksum.
  3271. data = zlib.decompress(data, -15)
  3272. except zlib.error, e:
  3273. result['bozo'] = 1
  3274. result['bozo_exception'] = e
  3275. # save HTTP headers
  3276. if http_headers:
  3277. if 'etag' in http_headers:
  3278. etag = http_headers.get('etag', u'')
  3279. if not isinstance(etag, unicode):
  3280. etag = etag.decode('utf-8', 'ignore')
  3281. if etag:
  3282. result['etag'] = etag
  3283. if 'last-modified' in http_headers:
  3284. modified = http_headers.get('last-modified', u'')
  3285. if modified:
  3286. result['modified'] = modified
  3287. result['modified_parsed'] = _parse_date(modified)
  3288. if hasattr(f, 'url'):
  3289. if not isinstance(f.url, unicode):
  3290. result['href'] = f.url.decode('utf-8', 'ignore')
  3291. else:
  3292. result['href'] = f.url
  3293. result['status'] = 200
  3294. if hasattr(f, 'status'):
  3295. result['status'] = f.status
  3296. if hasattr(f, 'close'):
  3297. f.close()
  3298. if data is None:
  3299. return result
  3300. # Stop processing if the server sent HTTP 304 Not Modified.
  3301. if getattr(f, 'code', 0) == 304:
  3302. result['version'] = u''
  3303. result['debug_message'] = 'The feed has not changed since you last checked, ' + \
  3304. 'so the server sent no data. This is a feature, not a bug!'
  3305. return result
  3306. data, result['encoding'], error = convert_to_utf8(http_headers, data)
  3307. use_strict_parser = result['encoding'] and True or False
  3308. if error is not None:
  3309. result['bozo'] = 1
  3310. result['bozo_exception'] = error
  3311. result['version'], data, entities = replace_doctype(data)
  3312. # Ensure that baseuri is an absolute URI using an acceptable URI scheme.
  3313. contentloc = http_headers.get('content-location', u'')
  3314. href = result.get('href', u'')
  3315. baseuri = _makeSafeAbsoluteURI(href, contentloc) or _makeSafeAbsoluteURI(contentloc) or href
  3316. baselang = http_headers.get('content-language', None)
  3317. if not isinstance(baselang, unicode) and baselang is not None:
  3318. baselang = baselang.decode('utf-8', 'ignore')
  3319. if not _XML_AVAILABLE:
  3320. use_strict_parser = 0
  3321. if use_strict_parser:
  3322. # initialize the SAX parser
  3323. feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8')
  3324. saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
  3325. saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
  3326. try:
  3327. # disable downloading external doctype references, if possible
  3328. saxparser.setFeature(xml.sax.handler.feature_external_ges, 0)
  3329. except xml.sax.SAXNotSupportedException:
  3330. pass
  3331. saxparser.setContentHandler(feedparser)
  3332. saxparser.setErrorHandler(feedparser)
  3333. source = xml.sax.xmlreader.InputSource()
  3334. source.setByteStream(_StringIO(data))
  3335. try:
  3336. saxparser.parse(source)
  3337. except xml.sax.SAXException, e:
  3338. result['bozo'] = 1
  3339. result['bozo_exception'] = feedparser.exc or e
  3340. use_strict_parser = 0
  3341. if not use_strict_parser and _SGML_AVAILABLE:
  3342. feedparser = _LooseFeedParser(baseuri, baselang, 'utf-8', entities)
  3343. feedparser.feed(data.decode('utf-8', 'replace'))
  3344. result['feed'] = feedparser.feeddata
  3345. result['entries'] = feedparser.entries
  3346. result['version'] = result['version'] or feedparser.version
  3347. result['namespaces'] = feedparser.namespacesInUse
  3348. return result
  3349. # The list of EPSG codes for geographic (latitude/longitude) coordinate
  3350. # systems to support decoding of GeoRSS GML profiles.
  3351. _geogCS = [
  3352. 3819, 3821, 3824, 3889, 3906, 4001, 4002, 4003, 4004, 4005, 4006, 4007, 4008,
  3353. 4009, 4010, 4011, 4012, 4013, 4014, 4015, 4016, 4018, 4019, 4020, 4021, 4022,
  3354. 4023, 4024, 4025, 4027, 4028, 4029, 4030, 4031, 4032, 4033, 4034, 4035, 4036,
  3355. 4041, 4042, 4043, 4044, 4045, 4046, 4047, 4052, 4053, 4054, 4055, 4075, 4081,
  3356. 4120, 4121, 4122, 4123, 4124, 4125, 4126, 4127, 4128, 4129, 4130, 4131, 4132,
  3357. 4133, 4134, 4135, 4136, 4137, 4138, 4139, 4140, 4141, 4142, 4143, 4144, 4145,
  3358. 4146, 4147, 4148, 4149, 4150, 4151, 4152, 4153, 4154, 4155, 4156, 4157, 4158,
  3359. 4159, 4160, 4161, 4162, 4163, 4164, 4165, 4166, 4167, 4168, 4169, 4170, 4171,
  3360. 4172, 4173, 4174, 4175, 4176, 4178, 4179, 4180, 4181, 4182, 4183, 4184, 4185,
  3361. 4188, 4189, 4190, 4191, 4192, 4193, 4194, 4195, 4196, 4197, 4198, 4199, 4200,
  3362. 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, 4212, 4213,
  3363. 4214, 4215, 4216, 4218, 4219, 4220, 4221, 4222, 4223, 4224, 4225, 4226, 4227,
  3364. 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240,
  3365. 4241, 4242, 4243, 4244, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4252, 4253,
  3366. 4254, 4255, 4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266,
  3367. 4267, 4268, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279,
  3368. 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4291, 4292, 4293,
  3369. 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301, 4302, 4303, 4304, 4306, 4307,
  3370. 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, 4322,
  3371. 4324, 4326, 4463, 4470, 4475, 4483, 4490, 4555, 4558, 4600, 4601, 4602, 4603,
  3372. 4604, 4605, 4606, 4607, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616,
  3373. 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 4626, 4627, 4628, 4629,
  3374. 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642,
  3375. 4643, 4644, 4645, 4646, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665,
  3376. 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678,
  3377. 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691,
  3378. 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4699, 4700, 4701, 4702, 4703, 4704,
  3379. 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714, 4715, 4716, 4717,
  3380. 4718, 4719, 4720, 4721, 4722, 4723, 4724, 4725, 4726, 4727, 4728, 4729, 4730,
  3381. 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743,
  3382. 4744, 4745, 4746, 4747, 4748, 4749, 4750, 4751, 4752, 4753, 4754, 4755, 4756,
  3383. 4757, 4758, 4759, 4760, 4761, 4762, 4763, 4764, 4765, 4801, 4802, 4803, 4804,
  3384. 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4813, 4814, 4815, 4816, 4817, 4818,
  3385. 4819, 4820, 4821, 4823, 4824, 4901, 4902, 4903, 4904, 4979 ]