PageRenderTime 75ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/yarss2/lib/feedparser/feedparser.py

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