PageRenderTime 36ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/wiki/web/widgets/rss/feedparser.py

https://bitbucket.org/nagyv/openerp-addons
Python | 2860 lines | 2744 code | 48 blank | 68 comment | 102 complexity | cd573160f063f3ab691efaa196a575ff MD5 | raw file
  1. #!/usr/bin/env python
  2. """Universal feed parser
  3. Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds
  4. Visit http://feedparser.org/ for the latest version
  5. Visit http://feedparser.org/docs/ for the latest documentation
  6. Required: Python 2.1 or later
  7. Recommended: Python 2.3 or later
  8. Recommended: CJKCodecs and iconv_codec <http://cjkpython.i18n.org/>
  9. """
  10. __version__ = "4.1"# + "$Revision: 1.92 $"[11:15] + "-cvs"
  11. __license__ = """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved.
  12. Redistribution and use in source and binary forms, with or without modification,
  13. are permitted provided that the following conditions are met:
  14. * Redistributions of source code must retain the above copyright notice,
  15. this list of conditions and the following disclaimer.
  16. * Redistributions in binary form must reproduce the above copyright notice,
  17. this list of conditions and the following disclaimer in the documentation
  18. and/or other materials provided with the distribution.
  19. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
  20. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  23. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. POSSIBILITY OF SUCH DAMAGE."""
  30. __author__ = "Mark Pilgrim <http://diveintomark.org/>"
  31. __contributors__ = ["Jason Diamond <http://injektilo.org/>",
  32. "John Beimler <http://john.beimler.org/>",
  33. "Fazal Majid <http://www.majid.info/mylos/weblog/>",
  34. "Aaron Swartz <http://aaronsw.com/>",
  35. "Kevin Marks <http://epeus.blogspot.com/>"]
  36. _debug = 0
  37. # HTTP "User-Agent" header to send to servers when downloading feeds.
  38. # If you are embedding feedparser in a larger application, you should
  39. # change this to your application name and URL.
  40. USER_AGENT = "UniversalFeedParser/%s +http://feedparser.org/" % __version__
  41. # HTTP "Accept" header to send to servers when downloading feeds. If you don't
  42. # want to send an Accept header, set this to None.
  43. 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"
  44. # List of preferred XML parsers, by SAX driver name. These will be tried first,
  45. # but if they're not installed, Python will keep searching through its own list
  46. # of pre-installed parsers until it finds one that supports everything we need.
  47. PREFERRED_XML_PARSERS = ["drv_libxml2"]
  48. # If you want feedparser to automatically run HTML markup through HTML Tidy, set
  49. # this to 1. Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html>
  50. # or utidylib <http://utidylib.berlios.de/>.
  51. TIDY_MARKUP = 0
  52. # List of Python interfaces for HTML Tidy, in order of preference. Only useful
  53. # if TIDY_MARKUP = 1
  54. PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"]
  55. # ---------- required modules (should come with any Python distribution) ----------
  56. import sgmllib, re, sys, copy, urlparse, time, rfc822, types, cgi, urllib, urllib2
  57. try:
  58. from cStringIO import StringIO as _StringIO
  59. except:
  60. from StringIO import StringIO as _StringIO
  61. # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
  62. # gzip is included with most Python distributions, but may not be available if you compiled your own
  63. try:
  64. import gzip
  65. except:
  66. gzip = None
  67. try:
  68. import zlib
  69. except:
  70. zlib = None
  71. # If a real XML parser is available, feedparser will attempt to use it. feedparser has
  72. # been tested with the built-in SAX parser, PyXML, and libxml2. On platforms where the
  73. # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
  74. # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
  75. try:
  76. import xml.sax
  77. xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
  78. from xml.sax.saxutils import escape as _xmlescape
  79. _XML_AVAILABLE = 1
  80. except:
  81. _XML_AVAILABLE = 0
  82. def _xmlescape(data):
  83. data = data.replace('&', '&amp;')
  84. data = data.replace('>', '&gt;')
  85. data = data.replace('<', '&lt;')
  86. return data
  87. # base64 support for Atom feeds that contain embedded binary data
  88. try:
  89. import base64, binascii
  90. except:
  91. base64 = binascii = None
  92. # cjkcodecs and iconv_codec provide support for more character encodings.
  93. # Both are available from http://cjkpython.i18n.org/
  94. try:
  95. import cjkcodecs.aliases
  96. except:
  97. pass
  98. try:
  99. import iconv_codec
  100. except:
  101. pass
  102. # chardet library auto-detects character encodings
  103. # Download from http://chardet.feedparser.org/
  104. try:
  105. import chardet
  106. if _debug:
  107. import chardet.constants
  108. chardet.constants._debug = 1
  109. except:
  110. chardet = None
  111. # ---------- don't touch these ----------
  112. class ThingsNobodyCaresAboutButMe(Exception): pass
  113. class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
  114. class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
  115. class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
  116. class UndeclaredNamespace(Exception): pass
  117. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  118. sgmllib.special = re.compile('<!')
  119. sgmllib.charref = re.compile('&#(x?[0-9A-Fa-f]+)[^0-9A-Fa-f]')
  120. SUPPORTED_VERSIONS = {'': 'unknown',
  121. 'rss090': 'RSS 0.90',
  122. 'rss091n': 'RSS 0.91 (Netscape)',
  123. 'rss091u': 'RSS 0.91 (Userland)',
  124. 'rss092': 'RSS 0.92',
  125. 'rss093': 'RSS 0.93',
  126. 'rss094': 'RSS 0.94',
  127. 'rss20': 'RSS 2.0',
  128. 'rss10': 'RSS 1.0',
  129. 'rss': 'RSS (unknown version)',
  130. 'atom01': 'Atom 0.1',
  131. 'atom02': 'Atom 0.2',
  132. 'atom03': 'Atom 0.3',
  133. 'atom10': 'Atom 1.0',
  134. 'atom': 'Atom (unknown version)',
  135. 'cdf': 'CDF',
  136. 'hotrss': 'Hot RSS'
  137. }
  138. try:
  139. UserDict = dict
  140. except NameError:
  141. # Python 2.1 does not have dict
  142. from UserDict import UserDict
  143. def dict(aList):
  144. rc = {}
  145. for k, v in aList:
  146. rc[k] = v
  147. return rc
  148. class FeedParserDict(UserDict):
  149. keymap = {'channel': 'feed',
  150. 'items': 'entries',
  151. 'guid': 'id',
  152. 'date': 'updated',
  153. 'date_parsed': 'updated_parsed',
  154. 'description': ['subtitle', 'summary'],
  155. 'url': ['href'],
  156. 'modified': 'updated',
  157. 'modified_parsed': 'updated_parsed',
  158. 'issued': 'published',
  159. 'issued_parsed': 'published_parsed',
  160. 'copyright': 'rights',
  161. 'copyright_detail': 'rights_detail',
  162. 'tagline': 'subtitle',
  163. 'tagline_detail': 'subtitle_detail'}
  164. def __getitem__(self, key):
  165. if key == 'category':
  166. return UserDict.__getitem__(self, 'tags')[0]['term']
  167. if key == 'categories':
  168. return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
  169. realkey = self.keymap.get(key, key)
  170. if type(realkey) == types.ListType:
  171. for k in realkey:
  172. if UserDict.has_key(self, k):
  173. return UserDict.__getitem__(self, k)
  174. if UserDict.has_key(self, key):
  175. return UserDict.__getitem__(self, key)
  176. return UserDict.__getitem__(self, realkey)
  177. def __setitem__(self, key, value):
  178. for k in self.keymap.keys():
  179. if key == k:
  180. key = self.keymap[k]
  181. if type(key) == types.ListType:
  182. key = key[0]
  183. return UserDict.__setitem__(self, key, value)
  184. def get(self, key, default=None):
  185. if self.has_key(key):
  186. return self[key]
  187. else:
  188. return default
  189. def setdefault(self, key, value):
  190. if not self.has_key(key):
  191. self[key] = value
  192. return self[key]
  193. def has_key(self, key):
  194. try:
  195. return hasattr(self, key) or UserDict.has_key(self, key)
  196. except AttributeError:
  197. return False
  198. def __getattr__(self, key):
  199. try:
  200. return self.__dict__[key]
  201. except KeyError:
  202. pass
  203. try:
  204. assert not key.startswith('_')
  205. return self.__getitem__(key)
  206. except:
  207. raise AttributeError, "object has no attribute '%s'" % key
  208. def __setattr__(self, key, value):
  209. if key.startswith('_') or key == 'data':
  210. self.__dict__[key] = value
  211. else:
  212. return self.__setitem__(key, value)
  213. def __contains__(self, key):
  214. return self.has_key(key)
  215. def zopeCompatibilityHack():
  216. global FeedParserDict
  217. del FeedParserDict
  218. def FeedParserDict(aDict=None):
  219. rc = {}
  220. if aDict:
  221. rc.update(aDict)
  222. return rc
  223. _ebcdic_to_ascii_map = None
  224. def _ebcdic_to_ascii(s):
  225. global _ebcdic_to_ascii_map
  226. if not _ebcdic_to_ascii_map:
  227. emap = (
  228. 0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  229. 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  230. 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  231. 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  232. 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  233. 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  234. 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  235. 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  236. 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,201,
  237. 202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
  238. 209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
  239. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
  240. 123,65,66,67,68,69,70,71,72,73,232,233,234,235,236,237,
  241. 125,74,75,76,77,78,79,80,81,82,238,239,240,241,242,243,
  242. 92,159,83,84,85,86,87,88,89,90,244,245,246,247,248,249,
  243. 48,49,50,51,52,53,54,55,56,57,250,251,252,253,254,255
  244. )
  245. import string
  246. _ebcdic_to_ascii_map = string.maketrans( \
  247. ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  248. return s.translate(_ebcdic_to_ascii_map)
  249. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  250. def _urljoin(base, uri):
  251. uri = _urifixer.sub(r'\1\3', uri)
  252. return urlparse.urljoin(base, uri)
  253. class _FeedParserMixin:
  254. namespaces = {'': '',
  255. 'http://backend.userland.com/rss': '',
  256. 'http://blogs.law.harvard.edu/tech/rss': '',
  257. 'http://purl.org/rss/1.0/': '',
  258. 'http://my.netscape.com/rdf/simple/0.9/': '',
  259. 'http://example.com/newformat#': '',
  260. 'http://example.com/necho': '',
  261. 'http://purl.org/echo/': '',
  262. 'uri/of/echo/namespace#': '',
  263. 'http://purl.org/pie/': '',
  264. 'http://purl.org/atom/ns#': '',
  265. 'http://www.w3.org/2005/Atom': '',
  266. 'http://purl.org/rss/1.0/modules/rss091#': '',
  267. 'http://webns.net/mvcb/': 'admin',
  268. 'http://purl.org/rss/1.0/modules/aggregation/': 'ag',
  269. 'http://purl.org/rss/1.0/modules/annotate/': 'annotate',
  270. 'http://media.tangent.org/rss/1.0/': 'audio',
  271. 'http://backend.userland.com/blogChannelModule': 'blogChannel',
  272. 'http://web.resource.org/cc/': 'cc',
  273. 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  274. 'http://purl.org/rss/1.0/modules/company': 'co',
  275. 'http://purl.org/rss/1.0/modules/content/': 'content',
  276. 'http://my.theinfo.org/changed/1.0/rss/': 'cp',
  277. 'http://purl.org/dc/elements/1.1/': 'dc',
  278. 'http://purl.org/dc/terms/': 'dcterms',
  279. 'http://purl.org/rss/1.0/modules/email/': 'email',
  280. 'http://purl.org/rss/1.0/modules/event/': 'ev',
  281. 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner',
  282. 'http://freshmeat.net/rss/fm/': 'fm',
  283. 'http://xmlns.com/foaf/0.1/': 'foaf',
  284. 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo',
  285. 'http://postneo.com/icbm/': 'icbm',
  286. 'http://purl.org/rss/1.0/modules/image/': 'image',
  287. 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
  288. 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
  289. 'http://purl.org/rss/1.0/modules/link/': 'l',
  290. 'http://search.yahoo.com/mrss': 'media',
  291. 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  292. 'http://prismstandard.org/namespaces/1.2/basic/': 'prism',
  293. 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
  294. 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs',
  295. 'http://purl.org/rss/1.0/modules/reference/': 'ref',
  296. 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv',
  297. 'http://purl.org/rss/1.0/modules/search/': 'search',
  298. 'http://purl.org/rss/1.0/modules/slash/': 'slash',
  299. 'http://schemas.xmlsoap.org/soap/envelope/': 'soap',
  300. 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss',
  301. 'http://hacks.benhammersley.com/rss/streaming/': 'str',
  302. 'http://purl.org/rss/1.0/modules/subscription/': 'sub',
  303. 'http://purl.org/rss/1.0/modules/syndication/': 'sy',
  304. 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo',
  305. 'http://purl.org/rss/1.0/modules/threading/': 'thr',
  306. 'http://purl.org/rss/1.0/modules/textinput/': 'ti',
  307. 'http://madskills.com/public/xml/rss/module/trackback/':'trackback',
  308. 'http://wellformedweb.org/commentAPI/': 'wfw',
  309. 'http://purl.org/rss/1.0/modules/wiki/': 'wiki',
  310. 'http://www.w3.org/1999/xhtml': 'xhtml',
  311. 'http://www.w3.org/XML/1998/namespace': 'xml',
  312. 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf'
  313. }
  314. _matchnamespaces = {}
  315. can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'license', 'icon', 'logo']
  316. can_contain_relative_uris = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  317. can_contain_dangerous_markup = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  318. html_types = ['text/html', 'application/xhtml+xml']
  319. def __init__(self, baseuri=None, baselang=None, encoding='utf-8'):
  320. if _debug: sys.stderr.write('initializing FeedParser\n')
  321. if not self._matchnamespaces:
  322. for k, v in self.namespaces.items():
  323. self._matchnamespaces[k.lower()] = v
  324. self.feeddata = FeedParserDict() # feed-level data
  325. self.encoding = encoding # character encoding
  326. self.entries = [] # list of entry-level data
  327. self.version = '' # feed type/version, see SUPPORTED_VERSIONS
  328. self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  329. # the following are used internally to track state;
  330. # this is really out of control and should be refactored
  331. self.infeed = 0
  332. self.inentry = 0
  333. self.incontent = 0
  334. self.intextinput = 0
  335. self.inimage = 0
  336. self.inauthor = 0
  337. self.incontributor = 0
  338. self.inpublisher = 0
  339. self.insource = 0
  340. self.sourcedata = FeedParserDict()
  341. self.contentparams = FeedParserDict()
  342. self._summaryKey = None
  343. self.namespacemap = {}
  344. self.elementstack = []
  345. self.basestack = []
  346. self.langstack = []
  347. self.baseuri = baseuri or ''
  348. self.lang = baselang or None
  349. if baselang:
  350. self.feeddata['language'] = baselang
  351. def unknown_starttag(self, tag, attrs):
  352. if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs))
  353. # normalize attrs
  354. attrs = [(k.lower(), v) for k, v in attrs]
  355. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  356. # track xml:base and xml:lang
  357. attrsD = dict(attrs)
  358. baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  359. self.baseuri = _urljoin(self.baseuri, baseuri)
  360. lang = attrsD.get('xml:lang', attrsD.get('lang'))
  361. if lang == '':
  362. # xml:lang could be explicitly set to '', we need to capture that
  363. lang = None
  364. elif lang is None:
  365. # if no xml:lang is specified, use parent lang
  366. lang = self.lang
  367. if lang:
  368. if tag in ('feed', 'rss', 'rdf:RDF'):
  369. self.feeddata['language'] = lang
  370. self.lang = lang
  371. self.basestack.append(self.baseuri)
  372. self.langstack.append(lang)
  373. # track namespaces
  374. for prefix, uri in attrs:
  375. if prefix.startswith('xmlns:'):
  376. self.trackNamespace(prefix[6:], uri)
  377. elif prefix == 'xmlns':
  378. self.trackNamespace(None, uri)
  379. # track inline content
  380. if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  381. # element declared itself as escaped markup, but it isn't really
  382. self.contentparams['type'] = 'application/xhtml+xml'
  383. if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  384. # Note: probably shouldn't simply recreate localname here, but
  385. # our namespace handling isn't actually 100% correct in cases where
  386. # the feed redefines the default namespace (which is actually
  387. # the usual case for inline content, thanks Sam), so here we
  388. # cheat and just reconstruct the element based on localname
  389. # because that compensates for the bugs in our namespace handling.
  390. # This will horribly munge inline content with non-empty qnames,
  391. # but nobody actually does that, so I'm not fixing it.
  392. tag = tag.split(':')[-1]
  393. return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0)
  394. # match namespaces
  395. if tag.find(':') <> -1:
  396. prefix, suffix = tag.split(':', 1)
  397. else:
  398. prefix, suffix = '', tag
  399. prefix = self.namespacemap.get(prefix, prefix)
  400. if prefix:
  401. prefix = prefix + '_'
  402. # special hack for better tracking of empty textinput/image elements in illformed feeds
  403. if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  404. self.intextinput = 0
  405. if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  406. self.inimage = 0
  407. # call special handler (if defined) or default handler
  408. methodname = '_start_' + prefix + suffix
  409. try:
  410. method = getattr(self, methodname)
  411. return method(attrsD)
  412. except AttributeError:
  413. return self.push(prefix + suffix, 1)
  414. def unknown_endtag(self, tag):
  415. if _debug: sys.stderr.write('end %s\n' % tag)
  416. # match namespaces
  417. if tag.find(':') <> -1:
  418. prefix, suffix = tag.split(':', 1)
  419. else:
  420. prefix, suffix = '', tag
  421. prefix = self.namespacemap.get(prefix, prefix)
  422. if prefix:
  423. prefix = prefix + '_'
  424. # call special handler (if defined) or default handler
  425. methodname = '_end_' + prefix + suffix
  426. try:
  427. method = getattr(self, methodname)
  428. method()
  429. except AttributeError:
  430. self.pop(prefix + suffix)
  431. # track inline content
  432. if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  433. # element declared itself as escaped markup, but it isn't really
  434. self.contentparams['type'] = 'application/xhtml+xml'
  435. if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  436. tag = tag.split(':')[-1]
  437. self.handle_data('</%s>' % tag, escape=0)
  438. # track xml:base and xml:lang going out of scope
  439. if self.basestack:
  440. self.basestack.pop()
  441. if self.basestack and self.basestack[-1]:
  442. self.baseuri = self.basestack[-1]
  443. if self.langstack:
  444. self.langstack.pop()
  445. if self.langstack: # and (self.langstack[-1] is not None):
  446. self.lang = self.langstack[-1]
  447. def handle_charref(self, ref):
  448. # called for each character reference, e.g. for '&#160;', ref will be '160'
  449. if not self.elementstack: return
  450. ref = ref.lower()
  451. if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  452. text = '&#%s;' % ref
  453. else:
  454. if ref[0] == 'x':
  455. c = int(ref[1:], 16)
  456. else:
  457. c = int(ref)
  458. text = unichr(c).encode('utf-8')
  459. self.elementstack[-1][2].append(text)
  460. def handle_entityref(self, ref):
  461. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  462. if not self.elementstack: return
  463. if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref)
  464. if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  465. text = '&%s;' % ref
  466. else:
  467. # entity resolution graciously donated by Aaron Swartz
  468. def name2cp(k):
  469. import htmlentitydefs
  470. if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3
  471. return htmlentitydefs.name2codepoint[k]
  472. k = htmlentitydefs.entitydefs[k]
  473. if k.startswith('&#') and k.endswith(';'):
  474. return int(k[2:-1]) # not in latin-1
  475. return ord(k)
  476. try: name2cp(ref)
  477. except KeyError: text = '&%s;' % ref
  478. else: text = unichr(name2cp(ref)).encode('utf-8')
  479. self.elementstack[-1][2].append(text)
  480. def handle_data(self, text, escape=1):
  481. # called for each block of plain text, i.e. outside of any tag and
  482. # not containing any character or entity references
  483. if not self.elementstack: return
  484. if escape and self.contentparams.get('type') == 'application/xhtml+xml':
  485. text = _xmlescape(text)
  486. self.elementstack[-1][2].append(text)
  487. def handle_comment(self, text):
  488. # called for each comment, e.g. <!-- insert message here -->
  489. pass
  490. def handle_pi(self, text):
  491. # called for each processing instruction, e.g. <?instruction>
  492. pass
  493. def handle_decl(self, text):
  494. pass
  495. def parse_declaration(self, i):
  496. # override internal declaration handler to handle CDATA blocks
  497. if _debug: sys.stderr.write('entering parse_declaration\n')
  498. if self.rawdata[i:i+9] == '<![CDATA[':
  499. k = self.rawdata.find(']]>', i)
  500. if k == -1: k = len(self.rawdata)
  501. self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  502. return k+3
  503. else:
  504. k = self.rawdata.find('>', i)
  505. return k+1
  506. def mapContentType(self, contentType):
  507. contentType = contentType.lower()
  508. if contentType == 'text':
  509. contentType = 'text/plain'
  510. elif contentType == 'html':
  511. contentType = 'text/html'
  512. elif contentType == 'xhtml':
  513. contentType = 'application/xhtml+xml'
  514. return contentType
  515. def trackNamespace(self, prefix, uri):
  516. loweruri = uri.lower()
  517. if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version:
  518. self.version = 'rss090'
  519. if loweruri == 'http://purl.org/rss/1.0/' and not self.version:
  520. self.version = 'rss10'
  521. if loweruri == 'http://www.w3.org/2005/atom' and not self.version:
  522. self.version = 'atom10'
  523. if loweruri.find('backend.userland.com/rss') <> -1:
  524. # match any backend.userland.com namespace
  525. uri = 'http://backend.userland.com/rss'
  526. loweruri = uri
  527. if self._matchnamespaces.has_key(loweruri):
  528. self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  529. self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  530. else:
  531. self.namespacesInUse[prefix or ''] = uri
  532. def resolveURI(self, uri):
  533. return _urljoin(self.baseuri or '', uri)
  534. def decodeEntities(self, element, data):
  535. return data
  536. def push(self, element, expectingText):
  537. self.elementstack.append([element, expectingText, []])
  538. def pop(self, element, stripWhitespace=1):
  539. if not self.elementstack: return
  540. if self.elementstack[-1][0] != element: return
  541. element, expectingText, pieces = self.elementstack.pop()
  542. output = ''.join(pieces)
  543. if stripWhitespace:
  544. output = output.strip()
  545. if not expectingText: return output
  546. # decode base64 content
  547. if base64 and self.contentparams.get('base64', 0):
  548. try:
  549. output = base64.decodestring(output)
  550. except binascii.Error:
  551. pass
  552. except binascii.Incomplete:
  553. pass
  554. # resolve relative URIs
  555. if (element in self.can_be_relative_uri) and output:
  556. output = self.resolveURI(output)
  557. # decode entities within embedded markup
  558. if not self.contentparams.get('base64', 0):
  559. output = self.decodeEntities(element, output)
  560. # remove temporary cruft from contentparams
  561. try:
  562. del self.contentparams['mode']
  563. except KeyError:
  564. pass
  565. try:
  566. del self.contentparams['base64']
  567. except KeyError:
  568. pass
  569. # resolve relative URIs within embedded markup
  570. if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  571. if element in self.can_contain_relative_uris:
  572. output = _resolveRelativeURIs(output, self.baseuri, self.encoding)
  573. # sanitize embedded markup
  574. if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  575. if element in self.can_contain_dangerous_markup:
  576. output = _sanitizeHTML(output, self.encoding)
  577. if self.encoding and type(output) != type(u''):
  578. try:
  579. output = unicode(output, self.encoding)
  580. except:
  581. pass
  582. # categories/tags/keywords/whatever are handled in _end_category
  583. if element == 'category':
  584. return output
  585. # store output in appropriate place(s)
  586. if self.inentry and not self.insource:
  587. if element == 'content':
  588. self.entries[-1].setdefault(element, [])
  589. contentparams = copy.deepcopy(self.contentparams)
  590. contentparams['value'] = output
  591. self.entries[-1][element].append(contentparams)
  592. elif element == 'link':
  593. self.entries[-1][element] = output
  594. if output:
  595. self.entries[-1]['links'][-1]['href'] = output
  596. else:
  597. if element == 'description':
  598. element = 'summary'
  599. self.entries[-1][element] = output
  600. if self.incontent:
  601. contentparams = copy.deepcopy(self.contentparams)
  602. contentparams['value'] = output
  603. self.entries[-1][element + '_detail'] = contentparams
  604. elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage):
  605. context = self._getContext()
  606. if element == 'description':
  607. element = 'subtitle'
  608. context[element] = output
  609. if element == 'link':
  610. context['links'][-1]['href'] = output
  611. elif self.incontent:
  612. contentparams = copy.deepcopy(self.contentparams)
  613. contentparams['value'] = output
  614. context[element + '_detail'] = contentparams
  615. return output
  616. def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  617. self.incontent += 1
  618. self.contentparams = FeedParserDict({
  619. 'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  620. 'language': self.lang,
  621. 'base': self.baseuri})
  622. self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  623. self.push(tag, expectingText)
  624. def popContent(self, tag):
  625. value = self.pop(tag)
  626. self.incontent -= 1
  627. self.contentparams.clear()
  628. return value
  629. def _mapToStandardPrefix(self, name):
  630. colonpos = name.find(':')
  631. if colonpos <> -1:
  632. prefix = name[:colonpos]
  633. suffix = name[colonpos+1:]
  634. prefix = self.namespacemap.get(prefix, prefix)
  635. name = prefix + ':' + suffix
  636. return name
  637. def _getAttribute(self, attrsD, name):
  638. return attrsD.get(self._mapToStandardPrefix(name))
  639. def _isBase64(self, attrsD, contentparams):
  640. if attrsD.get('mode', '') == 'base64':
  641. return 1
  642. if self.contentparams['type'].startswith('text/'):
  643. return 0
  644. if self.contentparams['type'].endswith('+xml'):
  645. return 0
  646. if self.contentparams['type'].endswith('/xml'):
  647. return 0
  648. return 1
  649. def _itsAnHrefDamnIt(self, attrsD):
  650. href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  651. if href:
  652. try:
  653. del attrsD['url']
  654. except KeyError:
  655. pass
  656. try:
  657. del attrsD['uri']
  658. except KeyError:
  659. pass
  660. attrsD['href'] = href
  661. return attrsD
  662. def _save(self, key, value):
  663. context = self._getContext()
  664. context.setdefault(key, value)
  665. def _start_rss(self, attrsD):
  666. versionmap = {'0.91': 'rss091u',
  667. '0.92': 'rss092',
  668. '0.93': 'rss093',
  669. '0.94': 'rss094'}
  670. if not self.version:
  671. attr_version = attrsD.get('version', '')
  672. version = versionmap.get(attr_version)
  673. if version:
  674. self.version = version
  675. elif attr_version.startswith('2.'):
  676. self.version = 'rss20'
  677. else:
  678. self.version = 'rss'
  679. def _start_dlhottitles(self, attrsD):
  680. self.version = 'hotrss'
  681. def _start_channel(self, attrsD):
  682. self.infeed = 1
  683. self._cdf_common(attrsD)
  684. _start_feedinfo = _start_channel
  685. def _cdf_common(self, attrsD):
  686. if attrsD.has_key('lastmod'):
  687. self._start_modified({})
  688. self.elementstack[-1][-1] = attrsD['lastmod']
  689. self._end_modified()
  690. if attrsD.has_key('href'):
  691. self._start_link({})
  692. self.elementstack[-1][-1] = attrsD['href']
  693. self._end_link()
  694. def _start_feed(self, attrsD):
  695. self.infeed = 1
  696. versionmap = {'0.1': 'atom01',
  697. '0.2': 'atom02',
  698. '0.3': 'atom03'}
  699. if not self.version:
  700. attr_version = attrsD.get('version')
  701. version = versionmap.get(attr_version)
  702. if version:
  703. self.version = version
  704. else:
  705. self.version = 'atom'
  706. def _end_channel(self):
  707. self.infeed = 0
  708. _end_feed = _end_channel
  709. def _start_image(self, attrsD):
  710. self.inimage = 1
  711. self.push('image', 0)
  712. context = self._getContext()
  713. context.setdefault('image', FeedParserDict())
  714. def _end_image(self):
  715. self.pop('image')
  716. self.inimage = 0
  717. def _start_textinput(self, attrsD):
  718. self.intextinput = 1
  719. self.push('textinput', 0)
  720. context = self._getContext()
  721. context.setdefault('textinput', FeedParserDict())
  722. _start_textInput = _start_textinput
  723. def _end_textinput(self):
  724. self.pop('textinput')
  725. self.intextinput = 0
  726. _end_textInput = _end_textinput
  727. def _start_author(self, attrsD):
  728. self.inauthor = 1
  729. self.push('author', 1)
  730. _start_managingeditor = _start_author
  731. _start_dc_author = _start_author
  732. _start_dc_creator = _start_author
  733. _start_itunes_author = _start_author
  734. def _end_author(self):
  735. self.pop('author')
  736. self.inauthor = 0
  737. self._sync_author_detail()
  738. _end_managingeditor = _end_author
  739. _end_dc_author = _end_author
  740. _end_dc_creator = _end_author
  741. _end_itunes_author = _end_author
  742. def _start_itunes_owner(self, attrsD):
  743. self.inpublisher = 1
  744. self.push('publisher', 0)
  745. def _end_itunes_owner(self):
  746. self.pop('publisher')
  747. self.inpublisher = 0
  748. self._sync_author_detail('publisher')
  749. def _start_contributor(self, attrsD):
  750. self.incontributor = 1
  751. context = self._getContext()
  752. context.setdefault('contributors', [])
  753. context['contributors'].append(FeedParserDict())
  754. self.push('contributor', 0)
  755. def _end_contributor(self):
  756. self.pop('contributor')
  757. self.incontributor = 0
  758. def _start_dc_contributor(self, attrsD):
  759. self.incontributor = 1
  760. context = self._getContext()
  761. context.setdefault('contributors', [])
  762. context['contributors'].append(FeedParserDict())
  763. self.push('name', 0)
  764. def _end_dc_contributor(self):
  765. self._end_name()
  766. self.incontributor = 0
  767. def _start_name(self, attrsD):
  768. self.push('name', 0)
  769. _start_itunes_name = _start_name
  770. def _end_name(self):
  771. value = self.pop('name')
  772. if self.inpublisher:
  773. self._save_author('name', value, 'publisher')
  774. elif self.inauthor:
  775. self._save_author('name', value)
  776. elif self.incontributor:
  777. self._save_contributor('name', value)
  778. elif self.intextinput:
  779. context = self._getContext()
  780. context['textinput']['name'] = value
  781. _end_itunes_name = _end_name
  782. def _start_width(self, attrsD):
  783. self.push('width', 0)
  784. def _end_width(self):
  785. value = self.pop('width')
  786. try:
  787. value = int(value)
  788. except:
  789. value = 0
  790. if self.inimage:
  791. context = self._getContext()
  792. context['image']['width'] = value
  793. def _start_height(self, attrsD):
  794. self.push('height', 0)
  795. def _end_height(self):
  796. value = self.pop('height')
  797. try:
  798. value = int(value)
  799. except:
  800. value = 0
  801. if self.inimage:
  802. context = self._getContext()
  803. context['image']['height'] = value
  804. def _start_url(self, attrsD):
  805. self.push('href', 1)
  806. _start_homepage = _start_url
  807. _start_uri = _start_url
  808. def _end_url(self):
  809. value = self.pop('href')
  810. if self.inauthor:
  811. self._save_author('href', value)
  812. elif self.incontributor:
  813. self._save_contributor('href', value)
  814. elif self.inimage:
  815. context = self._getContext()
  816. context['image']['href'] = value
  817. elif self.intextinput:
  818. context = self._getContext()
  819. context['textinput']['link'] = value
  820. _end_homepage = _end_url
  821. _end_uri = _end_url
  822. def _start_email(self, attrsD):
  823. self.push('email', 0)
  824. _start_itunes_email = _start_email
  825. def _end_email(self):
  826. value = self.pop('email')
  827. if self.inpublisher:
  828. self._save_author('email', value, 'publisher')
  829. elif self.inauthor:
  830. self._save_author('email', value)
  831. elif self.incontributor:
  832. self._save_contributor('email', value)
  833. _end_itunes_email = _end_email
  834. def _getContext(self):
  835. if self.insource:
  836. context = self.sourcedata
  837. elif self.inentry:
  838. context = self.entries[-1]
  839. else:
  840. context = self.feeddata
  841. return context
  842. def _save_author(self, key, value, prefix='author'):
  843. context = self._getContext()
  844. context.setdefault(prefix + '_detail', FeedParserDict())
  845. context[prefix + '_detail'][key] = value
  846. self._sync_author_detail()
  847. def _save_contributor(self, key, value):
  848. context = self._getContext()
  849. context.setdefault('contributors', [FeedParserDict()])
  850. context['contributors'][-1][key] = value
  851. def _sync_author_detail(self, key='author'):
  852. context = self._getContext()
  853. detail = context.get('%s_detail' % key)
  854. if detail:
  855. name = detail.get('name')
  856. email = detail.get('email')
  857. if name and email:
  858. context[key] = '%s (%s)' % (name, email)
  859. elif name:
  860. context[key] = name
  861. elif email:
  862. context[key] = email
  863. else:
  864. author = context.get(key)
  865. if not author: return
  866. emailmatch = re.search(r'''(([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})(\]?))''', author)
  867. if not emailmatch: return
  868. email = emailmatch.group(0)
  869. # probably a better way to do the following, but it passes all the tests
  870. author = author.replace(email, '')
  871. author = author.replace('()', '')
  872. author = author.strip()
  873. if author and (author[0] == '('):
  874. author = author[1:]
  875. if author and (author[-1] == ')'):
  876. author = author[:-1]
  877. author = author.strip()
  878. context.setdefault('%s_detail' % key, FeedParserDict())
  879. context['%s_detail' % key]['name'] = author
  880. context['%s_detail' % key]['email'] = email
  881. def _start_subtitle(self, attrsD):
  882. self.pushContent('subtitle', attrsD, 'text/plain', 1)
  883. _start_tagline = _start_subtitle
  884. _start_itunes_subtitle = _start_subtitle
  885. def _end_subtitle(self):
  886. self.popContent('subtitle')
  887. _end_tagline = _end_subtitle
  888. _end_itunes_subtitle = _end_subtitle
  889. def _start_rights(self, attrsD):
  890. self.pushContent('rights', attrsD, 'text/plain', 1)
  891. _start_dc_rights = _start_rights
  892. _start_copyright = _start_rights
  893. def _end_rights(self):
  894. self.popContent('rights')
  895. _end_dc_rights = _end_rights
  896. _end_copyright = _end_rights
  897. def _start_item(self, attrsD):
  898. self.entries.append(FeedParserDict())
  899. self.push('item', 0)
  900. self.inentry = 1
  901. self.guidislink = 0
  902. id = self._getAttribute(attrsD, 'rdf:about')
  903. if id:
  904. context = self._getContext()
  905. context['id'] = id
  906. self._cdf_common(attrsD)
  907. _start_entry = _start_item
  908. _start_product = _start_item
  909. def _end_item(self):
  910. self.pop('item')
  911. self.inentry = 0
  912. _end_entry = _end_item
  913. def _start_dc_language(self, attrsD):
  914. self.push('language', 1)
  915. _start_language = _start_dc_language
  916. def _end_dc_language(self):
  917. self.lang = self.pop('language')
  918. _end_language = _end_dc_language
  919. def _start_dc_publisher(self, attrsD):
  920. self.push('publisher', 1)
  921. _start_webmaster = _start_dc_publisher
  922. def _end_dc_publisher(self):
  923. self.pop('publisher')
  924. self._sync_author_detail('publisher')
  925. _end_webmaster = _end_dc_publisher
  926. def _start_published(self, attrsD):
  927. self.push('published', 1)
  928. _start_dcterms_issued = _start_published
  929. _start_issued = _start_published
  930. def _end_published(self):
  931. value = self.pop('published')
  932. self._save('published_parsed', _parse_date(value))
  933. _end_dcterms_issued = _end_published
  934. _end_issued = _end_published
  935. def _start_updated(self, attrsD):
  936. self.push('updated', 1)
  937. _start_modified = _start_updated
  938. _start_dcterms_modified = _start_updated
  939. _start_pubdate = _start_updated
  940. _start_dc_date = _start_updated
  941. def _end_updated(self):
  942. value = self.pop('updated')
  943. parsed_value = _parse_date(value)
  944. self._save('updated_parsed', parsed_value)
  945. _end_modified = _end_updated
  946. _end_dcterms_modified = _end_updated
  947. _end_pubdate = _end_updated
  948. _end_dc_date = _end_updated
  949. def _start_created(self, attrsD):
  950. self.push('created', 1)
  951. _start_dcterms_created = _start_created
  952. def _end_created(self):
  953. value = self.pop('created')
  954. self._save('created_parsed', _parse_date(value))
  955. _end_dcterms_created = _end_created
  956. def _start_expirationdate(self, attrsD):
  957. self.push('expired', 1)
  958. def _end_expirationdate(self):
  959. self._save('expired_parsed', _parse_date(self.pop('expired')))
  960. def _start_cc_license(self, attrsD):
  961. self.push('license', 1)
  962. value = self._getAttribute(attrsD, 'rdf:resource')
  963. if value:
  964. self.elementstack[-1][2].append(value)
  965. self.pop('license')
  966. def _start_creativecommons_license(self, attrsD):
  967. self.push('license', 1)
  968. def _end_creativecommons_license(self):
  969. self.pop('license')
  970. def _addTag(self, term, scheme, label):
  971. context = self._getContext()
  972. tags = context.setdefault('tags', [])
  973. if (not term) and (not scheme) and (not label): return
  974. value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
  975. if value not in tags:
  976. tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label}))
  977. def _start_category(self, attrsD):
  978. if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD))
  979. term = attrsD.get('term')
  980. scheme = attrsD.get('scheme', attrsD.get('domain'))
  981. label = attrsD.get('label')
  982. self._addTag(term, scheme, label)
  983. self.push('category', 1)
  984. _start_dc_subject = _start_category
  985. _start_keywords = _start_category
  986. def _end_itunes_keywords(self):
  987. for term in self.pop('itunes_keywords').split():
  988. self._addTag(term, 'http://www.itunes.com/', None)
  989. def _start_itunes_category(self, attrsD):
  990. self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
  991. self.push('category', 1)
  992. def _end_category(self):
  993. value = self.pop('category')
  994. if not value: return
  995. context = self._getContext()
  996. tags = context['tags']
  997. if value and len(tags) and not tags[-1]['term']:
  998. tags[-1]['term'] = value
  999. else:
  1000. self._addTag(value, None, None)
  1001. _end_dc_subject = _end_category
  1002. _end_keywords = _end_category
  1003. _end_itunes_category = _end_category
  1004. def _start_cloud(self, attrsD):
  1005. self._getContext()['cloud'] = FeedParserDict(attrsD)
  1006. def _start_link(self, attrsD):
  1007. attrsD.setdefault('rel', 'alternate')
  1008. attrsD.setdefault('type', 'text/html')
  1009. attrsD = self._itsAnHrefDamnIt(attrsD)
  1010. if attrsD.has_key('href'):
  1011. attrsD['href'] = self.resolveURI(attrsD['href'])
  1012. expectingText = self.infeed or self.inentry or self.insource
  1013. context = self._getContext()
  1014. context.setdefault('links', [])
  1015. context['links'].append(FeedParserDict(attrsD))
  1016. if attrsD['rel'] == 'enclosure':
  1017. self._start_enclosure(attrsD)
  1018. if attrsD.has_key('href'):
  1019. expectingText = 0
  1020. if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
  1021. context['link'] = attrsD['href']
  1022. else:
  1023. self.push('link', expectingText)
  1024. _start_producturl = _start_link
  1025. def _end_link(self):
  1026. value = self.pop('link')
  1027. context = self._getContext()
  1028. if self.intextinput:
  1029. context['textinput']['link'] = value
  1030. if self.inimage:
  1031. context['image']['link'] = value
  1032. _end_producturl = _end_link
  1033. def _start_guid(self, attrsD):
  1034. self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
  1035. self.push('id', 1)
  1036. def _end_guid(self):
  1037. value = self.pop('id')
  1038. self._save('guidislink', self.guidislink and not self._getContext().has_key('link'))
  1039. if self.guidislink:
  1040. # guid acts as link, but only if 'ispermalink' is not present or is 'true',
  1041. # and only if the item doesn't already have a link element
  1042. self._save('link', value)
  1043. def _start_title(self, attrsD):
  1044. self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1045. _start_dc_title = _start_title
  1046. _start_media_title = _start_title
  1047. def _end_title(self):
  1048. value = self.popContent('title')
  1049. context = self._getContext()
  1050. if self.intextinput:
  1051. context['textinput']['title'] = value
  1052. elif self.inimage:
  1053. context['image']['title'] = value
  1054. _end_dc_title = _end_title
  1055. _end_media_title = _end_title
  1056. def _start_description(self, attrsD):
  1057. context = self._getContext()
  1058. if context.has_key('summary'):
  1059. self._summaryKey = 'content'
  1060. self._start_content(attrsD)
  1061. else:
  1062. self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)
  1063. def _start_abstract(self, attrsD):
  1064. self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1065. def _end_description(self):
  1066. if self._summaryKey == 'content':
  1067. self._end_content()
  1068. else:
  1069. value = self.popContent('description')
  1070. context = self._getContext()
  1071. if self.intextinput:
  1072. context['textinput']['description'] = value
  1073. elif self.inimage:
  1074. context['image']['description'] = value
  1075. self._summaryKey = None
  1076. _end_abstract = _end_description
  1077. def _start_info(self, attrsD):
  1078. self.pushContent('info', attrsD, 'text/plain', 1)
  1079. _start_feedburner_browserfriendly = _start_info
  1080. def _end_info(self):
  1081. self.popContent('info')
  1082. _end_feedburner_browserfriendly = _end_info
  1083. def _start_generator(self, attrsD):
  1084. if attrsD:
  1085. attrsD = self._itsAnHrefDamnIt(attrsD)
  1086. if attrsD.has_key('href'):
  1087. attrsD['href'] = self.resolveURI(attrsD['href'])
  1088. self._getContext()['generator_detail'] = FeedParserDict(attrsD)
  1089. self.push('generator', 1)
  1090. def _end_generator(self):
  1091. value = self.pop('generator')
  1092. context = self._getContext()
  1093. if context.has_key('generator_detail'):
  1094. context['generator_detail']['name'] = value
  1095. def _start_admin_generatoragent(self, attrsD):
  1096. self.push('generator', 1)
  1097. value = self._getAttribute(attrsD, 'rdf:resource')
  1098. if value:
  1099. self.elementstack[-1][2].append(value)
  1100. self.pop('generator')
  1101. self._getContext()['generator_detail'] = FeedParserDict({'href': value})
  1102. def _start_admin_errorreportsto(self, attrsD):
  1103. self.push('errorreportsto', 1)
  1104. value = self._getAttribute(attrsD, 'rdf:resource')
  1105. if value:
  1106. self.elementstack[-1][2].append(value)
  1107. self.pop('errorreportsto')
  1108. def _start_summary(self, attrsD):
  1109. context = self._getContext()
  1110. if context.has_key('summary'):
  1111. self._summaryKey = 'content'
  1112. self._start_content(attrsD)
  1113. else:
  1114. self._summaryKey = 'summary'
  1115. self.pushContent(self._summaryKey, attrsD, 'text/plain', 1)
  1116. _start_itunes_summary = _start_summary
  1117. def _end_summary(self):
  1118. if self._summaryKey == 'content':
  1119. self._end_content()
  1120. else:
  1121. self.popContent(self._summaryKey or 'summary')
  1122. self._summaryKey = None
  1123. _end_itunes_summary = _end_summary
  1124. def _start_enclosure(self, attrsD):
  1125. attrsD = self._itsAnHrefDamnIt(attrsD)
  1126. self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD))
  1127. href = attrsD.get('href')
  1128. if href:
  1129. context = self._getContext()
  1130. if not context.get('id'):
  1131. context['id'] = href
  1132. def _start_source(self, attrsD):
  1133. self.insource = 1
  1134. def _end_source(self):
  1135. self.insource = 0
  1136. self._getContext()['source'] = copy.deepcopy(self.sourcedata)
  1137. self.sourcedata.clear()
  1138. def _start_content(self, attrsD):
  1139. self.pushContent('content', attrsD, 'text/plain', 1)
  1140. src = attrsD.get('src')
  1141. if src:
  1142. self.contentparams['src'] = src
  1143. self.push('content', 1)
  1144. def _start_prodlink(self, attrsD):
  1145. self.pushContent('content', attrsD, 'text/html', 1)
  1146. def _start_body(self, attrsD):
  1147. self.pushContent('content', attrsD, 'application/xhtml+xml', 1)
  1148. _start_xhtml_body = _start_body
  1149. def _start_content_encoded(self, attrsD):
  1150. self.pushContent('content', attrsD, 'text/html', 1)
  1151. _start_fullitem = _start_content_encoded
  1152. def _end_content(self):
  1153. copyToDescription = self.mapContentType(self.contentparams.get('type')) in (['text/plain'] + self.html_types)
  1154. value = self.popContent('content')
  1155. if copyToDescription:
  1156. self._save('description', value)
  1157. _end_body = _end_content
  1158. _end_xhtml_body = _end_content
  1159. _end_content_encoded = _end_content
  1160. _end_fullitem = _end_content
  1161. _end_prodlink = _end_content
  1162. def _start_itunes_image(self, attrsD):
  1163. self.push('itunes_image', 0)
  1164. self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
  1165. _start_itunes_link = _start_itunes_image
  1166. def _end_itunes_block(self):
  1167. value = self.pop('itunes_block', 0)
  1168. self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
  1169. def _end_itunes_explicit(self):
  1170. value = self.pop('itunes_explicit', 0)
  1171. self._getContext()['itunes_explicit'] = (value == 'yes') and 1 or 0
  1172. if _XML_AVAILABLE:
  1173. class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler):
  1174. def __init__(self, baseuri, baselang, encoding):
  1175. if _debug: sys.stderr.write('trying StrictFeedParser\n')
  1176. xml.sax.handler.ContentHandler.__init__(self)
  1177. _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1178. self.bozo = 0
  1179. self.exc = None
  1180. def startPrefixMapping(self, prefix, uri):
  1181. self.trackNamespace(prefix, uri)
  1182. def startElementNS(self, name, qname, attrs):
  1183. namespace, localname = name
  1184. lowernamespace = str(namespace or '').lower()
  1185. if lowernamespace.find('backend.userland.com/rss') <> -1:
  1186. # match any backend.userland.com namespace
  1187. namespace = 'http://backend.userland.com/rss'
  1188. lowernamespace = namespace
  1189. if qname and qname.find(':') > 0:
  1190. givenprefix = qname.split(':')[0]
  1191. else:
  1192. givenprefix = None
  1193. prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1194. if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and not self.namespacesInUse.has_key(givenprefix):
  1195. raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix
  1196. if prefix:
  1197. localname = prefix + ':' + localname
  1198. localname = str(localname).lower()
  1199. if _debug: sys.stderr.write('startElementNS: qname = %s, namespace = %s, givenprefix = %s, prefix = %s, attrs = %s, localname = %s\n' % (qname, namespace, givenprefix, prefix, attrs.items(), localname))
  1200. # qname implementation is horribly broken in Python 2.1 (it
  1201. # doesn't report any), and slightly broken in Python 2.2 (it
  1202. # doesn't report the xml: namespace). So we match up namespaces
  1203. # with a known list first, and then possibly override them with
  1204. # the qnames the SAX parser gives us (if indeed it gives us any
  1205. # at all). Thanks to MatejC for helping me test this and
  1206. # tirelessly telling me that it didn't work yet.
  1207. attrsD = {}
  1208. for (namespace, attrlocalname), attrvalue in attrs._attrs.items():
  1209. lowernamespace = (namespace or '').lower()
  1210. prefix = self._matchnamespaces.get(lowernamespace, '')
  1211. if prefix:
  1212. attrlocalname = prefix + ':' + attrlocalname
  1213. attrsD[str(attrlocalname).lower()] = attrvalue
  1214. for qname in attrs.getQNames():
  1215. attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
  1216. self.unknown_starttag(localname, attrsD.items())
  1217. def characters(self, text):
  1218. self.handle_data(text)
  1219. def endElementNS(self, name, qname):
  1220. namespace, localname = name
  1221. lowernamespace = str(namespace or '').lower()
  1222. if qname and qname.find(':') > 0:
  1223. givenprefix = qname.split(':')[0]
  1224. else:
  1225. givenprefix = ''
  1226. prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1227. if prefix:
  1228. localname = prefix + ':' + localname
  1229. localname = str(localname).lower()
  1230. self.unknown_endtag(localname)
  1231. def error(self, exc):
  1232. self.bozo = 1
  1233. self.exc = exc
  1234. def fatalError(self, exc):
  1235. self.error(exc)
  1236. raise exc
  1237. class _BaseHTMLProcessor(sgmllib.SGMLParser):
  1238. elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
  1239. 'img', 'input', 'isindex', 'link', 'meta', 'param']
  1240. def __init__(self, encoding):
  1241. self.encoding = encoding
  1242. if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding)
  1243. sgmllib.SGMLParser.__init__(self)
  1244. def reset(self):
  1245. self.pieces = []
  1246. sgmllib.SGMLParser.reset(self)
  1247. def _shorttag_replace(self, match):
  1248. tag = match.group(1)
  1249. if tag in self.elements_no_end_tag:
  1250. return '<' + tag + ' />'
  1251. else:
  1252. return '<' + tag + '></' + tag + '>'
  1253. def feed(self, data):
  1254. data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data)
  1255. #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace
  1256. data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data)
  1257. data = data.replace('&#39;', "'")
  1258. data = data.replace('&#34;', '"')
  1259. if self.encoding and type(data) == type(u''):
  1260. data = data.encode(self.encoding)
  1261. sgmllib.SGMLParser.feed(self, data)
  1262. def normalize_attrs(self, attrs):
  1263. # utility method to be called by descendants
  1264. attrs = [(k.lower(), v) for k, v in attrs]
  1265. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  1266. return attrs
  1267. def unknown_starttag(self, tag, attrs):
  1268. # called for each start tag
  1269. # attrs is a list of (attr, value) tuples
  1270. # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
  1271. if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag)
  1272. uattrs = []
  1273. # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
  1274. for key, value in attrs:
  1275. if type(value) != type(u''):
  1276. value = unicode(value, self.encoding)
  1277. uattrs.append((unicode(key, self.encoding), value))
  1278. strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding)
  1279. if tag in self.elements_no_end_tag:
  1280. self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
  1281. else:
  1282. self.pieces.append('<%(tag)s%(strattrs)s>' % locals())
  1283. def unknown_endtag(self, tag):
  1284. # called for each end tag, e.g. for </pre>, tag will be 'pre'
  1285. # Reconstruct the original end tag.
  1286. if tag not in self.elements_no_end_tag:
  1287. self.pieces.append("</%(tag)s>" % locals())
  1288. def handle_charref(self, ref):
  1289. # called for each character reference, e.g. for '&#160;', ref will be '160'
  1290. # Reconstruct the original character reference.
  1291. self.pieces.append('&#%(ref)s;' % locals())
  1292. def handle_entityref(self, ref):
  1293. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  1294. # Reconstruct the original entity reference.
  1295. self.pieces.append('&%(ref)s;' % locals())
  1296. def handle_data(self, text):
  1297. # called for each block of plain text, i.e. outside of any tag and
  1298. # not containing any character or entity references
  1299. # Store the original text verbatim.
  1300. if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text)
  1301. self.pieces.append(text)
  1302. def handle_comment(self, text):
  1303. # called for each HTML comment, e.g. <!-- insert Javascript code here -->
  1304. # Reconstruct the original comment.
  1305. self.pieces.append('<!--%(text)s-->' % locals())
  1306. def handle_pi(self, text):
  1307. # called for each processing instruction, e.g. <?instruction>
  1308. # Reconstruct original processing instruction.
  1309. self.pieces.append('<?%(text)s>' % locals())
  1310. def handle_decl(self, text):
  1311. # called for the DOCTYPE, if present, e.g.
  1312. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  1313. # "http://www.w3.org/TR/html4/loose.dtd">
  1314. # Reconstruct original DOCTYPE
  1315. self.pieces.append('<!%(text)s>' % locals())
  1316. _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
  1317. def _scan_name(self, i, declstartpos):
  1318. rawdata = self.rawdata
  1319. n = len(rawdata)
  1320. if i == n:
  1321. return None, -1
  1322. m = self._new_declname_match(rawdata, i)
  1323. if m:
  1324. s = m.group()
  1325. name = s.strip()
  1326. if (i + len(s)) == n:
  1327. return None, -1 # end of buffer
  1328. return name.lower(), m.end()
  1329. else:
  1330. self.handle_data(rawdata)
  1331. # self.updatepos(declstartpos, i)
  1332. return None, -1
  1333. def output(self):
  1334. '''Return processed HTML as a single string'''
  1335. return ''.join([str(p) for p in self.pieces])
  1336. class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor):
  1337. def __init__(self, baseuri, baselang, encoding):
  1338. sgmllib.SGMLParser.__init__(self)
  1339. _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1340. def decodeEntities(self, element, data):
  1341. data = data.replace('&#60;', '&lt;')
  1342. data = data.replace('&#x3c;', '&lt;')
  1343. data = data.replace('&#62;', '&gt;')
  1344. data = data.replace('&#x3e;', '&gt;')
  1345. data = data.replace('&#38;', '&amp;')
  1346. data = data.replace('&#x26;', '&amp;')
  1347. data = data.replace('&#34;', '&quot;')
  1348. data = data.replace('&#x22;', '&quot;')
  1349. data = data.replace('&#39;', '&apos;')
  1350. data = data.replace('&#x27;', '&apos;')
  1351. if self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  1352. data = data.replace('&lt;', '<')
  1353. data = data.replace('&gt;', '>')
  1354. data = data.replace('&amp;', '&')
  1355. data = data.replace('&quot;', '"')
  1356. data = data.replace('&apos;', "'")
  1357. return data
  1358. class _RelativeURIResolver(_BaseHTMLProcessor):
  1359. relative_uris = [('a', 'href'),
  1360. ('applet', 'codebase'),
  1361. ('area', 'href'),
  1362. ('blockquote', 'cite'),
  1363. ('body', 'background'),
  1364. ('del', 'cite'),
  1365. ('form', 'action'),
  1366. ('frame', 'longdesc'),
  1367. ('frame', 'src'),
  1368. ('iframe', 'longdesc'),
  1369. ('iframe', 'src'),
  1370. ('head', 'profile'),
  1371. ('img', 'longdesc'),
  1372. ('img', 'src'),
  1373. ('img', 'usemap'),
  1374. ('input', 'src'),
  1375. ('input', 'usemap'),
  1376. ('ins', 'cite'),
  1377. ('link', 'href'),
  1378. ('object', 'classid'),
  1379. ('object', 'codebase'),
  1380. ('object', 'data'),
  1381. ('object', 'usemap'),
  1382. ('q', 'cite'),
  1383. ('script', 'src')]
  1384. def __init__(self, baseuri, encoding):
  1385. _BaseHTMLProcessor.__init__(self, encoding)
  1386. self.baseuri = baseuri
  1387. def resolveURI(self, uri):
  1388. return _urljoin(self.baseuri, uri)
  1389. def unknown_starttag(self, tag, attrs):
  1390. attrs = self.normalize_attrs(attrs)
  1391. attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
  1392. _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1393. def _resolveRelativeURIs(htmlSource, baseURI, encoding):
  1394. if _debug: sys.stderr.write('entering _resolveRelativeURIs\n')
  1395. p = _RelativeURIResolver(baseURI, encoding)
  1396. p.feed(htmlSource)
  1397. return p.output()
  1398. class _HTMLSanitizer(_BaseHTMLProcessor):
  1399. acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
  1400. 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
  1401. 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset',
  1402. 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input',
  1403. 'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup',
  1404. 'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike',
  1405. 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th',
  1406. 'thead', 'tr', 'tt', 'u', 'ul', 'var']
  1407. acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  1408. 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
  1409. 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols',
  1410. 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled',
  1411. 'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace',
  1412. 'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method',
  1413. 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly',
  1414. 'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
  1415. 'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type',
  1416. 'usemap', 'valign', 'value', 'vspace', 'width']
  1417. unacceptable_elements_with_end_tag = ['script', 'applet']
  1418. def reset(self):
  1419. _BaseHTMLProcessor.reset(self)
  1420. self.unacceptablestack = 0
  1421. def unknown_starttag(self, tag, attrs):
  1422. if not tag in self.acceptable_elements:
  1423. if tag in self.unacceptable_elements_with_end_tag:
  1424. self.unacceptablestack += 1
  1425. return
  1426. attrs = self.normalize_attrs(attrs)
  1427. attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes]
  1428. _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1429. def unknown_endtag(self, tag):
  1430. if not tag in self.acceptable_elements:
  1431. if tag in self.unacceptable_elements_with_end_tag:
  1432. self.unacceptablestack -= 1
  1433. return
  1434. _BaseHTMLProcessor.unknown_endtag(self, tag)
  1435. def handle_pi(self, text):
  1436. pass
  1437. def handle_decl(self, text):
  1438. pass
  1439. def handle_data(self, text):
  1440. if not self.unacceptablestack:
  1441. _BaseHTMLProcessor.handle_data(self, text)
  1442. def _sanitizeHTML(htmlSource, encoding):
  1443. p = _HTMLSanitizer(encoding)
  1444. p.feed(htmlSource)
  1445. data = p.output()
  1446. if TIDY_MARKUP:
  1447. # loop through list of preferred Tidy interfaces looking for one that's installed,
  1448. # then set up a common _tidy function to wrap the interface-specific API.
  1449. _tidy = None
  1450. for tidy_interface in PREFERRED_TIDY_INTERFACES:
  1451. try:
  1452. if tidy_interface == "uTidy":
  1453. from tidy import parseString as _utidy
  1454. def _tidy(data, **kwargs):
  1455. return str(_utidy(data, **kwargs))
  1456. break
  1457. elif tidy_interface == "mxTidy":
  1458. from mx.Tidy import Tidy as _mxtidy
  1459. def _tidy(data, **kwargs):
  1460. nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs)
  1461. return data
  1462. break
  1463. except:
  1464. pass
  1465. if _tidy:
  1466. utf8 = type(data) == type(u'')
  1467. if utf8:
  1468. data = data.encode('utf-8')
  1469. data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8")
  1470. if utf8:
  1471. data = unicode(data, 'utf-8')
  1472. if data.count('<body'):
  1473. data = data.split('<body', 1)[1]
  1474. if data.count('>'):
  1475. data = data.split('>', 1)[1]
  1476. if data.count('</body'):
  1477. data = data.split('</body', 1)[0]
  1478. data = data.strip().replace('\r\n', '\n')
  1479. return data
  1480. class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
  1481. def http_error_default(self, req, fp, code, msg, headers):
  1482. if ((code / 100) == 3) and (code != 304):
  1483. return self.http_error_302(req, fp, code, msg, headers)
  1484. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1485. infourl.status = code
  1486. return infourl
  1487. def http_error_302(self, req, fp, code, msg, headers):
  1488. if headers.dict.has_key('location'):
  1489. infourl = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
  1490. else:
  1491. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1492. if not hasattr(infourl, 'status'):
  1493. infourl.status = code
  1494. return infourl
  1495. def http_error_301(self, req, fp, code, msg, headers):
  1496. if headers.dict.has_key('location'):
  1497. infourl = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
  1498. else:
  1499. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1500. if not hasattr(infourl, 'status'):
  1501. infourl.status = code
  1502. return infourl
  1503. http_error_300 = http_error_302
  1504. http_error_303 = http_error_302
  1505. http_error_307 = http_error_302
  1506. def http_error_401(self, req, fp, code, msg, headers):
  1507. # Check if
  1508. # - server requires digest auth, AND
  1509. # - we tried (unsuccessfully) with basic auth, AND
  1510. # - we're using Python 2.3.3 or later (digest auth is irreparably broken in earlier versions)
  1511. # If all conditions hold, parse authentication information
  1512. # out of the Authorization header we sent the first time
  1513. # (for the username and password) and the WWW-Authenticate
  1514. # header the server sent back (for the realm) and retry
  1515. # the request with the appropriate digest auth headers instead.
  1516. # This evil genius hack has been brought to you by Aaron Swartz.
  1517. host = urlparse.urlparse(req.get_full_url())[1]
  1518. try:
  1519. assert sys.version.split()[0] >= '2.3.3'
  1520. assert base64 != None
  1521. user, passw = base64.decodestring(req.headers['Authorization'].split(' ')[1]).split(':')
  1522. realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0]
  1523. self.add_password(realm, host, user, passw)
  1524. retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  1525. self.reset_retry_count()
  1526. return retry
  1527. except:
  1528. return self.http_error_default(req, fp, code, msg, headers)
  1529. def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers):
  1530. """URL, filename, or string --> stream
  1531. This function lets you define parsers that take any input source
  1532. (URL, pathname to local or network file, or actual data as a string)
  1533. and deal with it in a uniform manner. Returned object is guaranteed
  1534. to have all the basic stdio read methods (read, readline, readlines).
  1535. Just .close() the object when you're done with it.
  1536. If the etag argument is supplied, it will be used as the value of an
  1537. If-None-Match request header.
  1538. If the modified argument is supplied, it must be a tuple of 9 integers
  1539. as returned by gmtime() in the standard Python time module. This MUST
  1540. be in GMT (Greenwich Mean Time). The formatted date/time will be used
  1541. as the value of an If-Modified-Since request header.
  1542. If the agent argument is supplied, it will be used as the value of a
  1543. User-Agent request header.
  1544. If the referrer argument is supplied, it will be used as the value of a
  1545. Referer[sic] request header.
  1546. If handlers is supplied, it is a list of handlers used to build a
  1547. urllib2 opener.
  1548. """
  1549. if hasattr(url_file_stream_or_string, 'read'):
  1550. return url_file_stream_or_string
  1551. if url_file_stream_or_string == '-':
  1552. return sys.stdin
  1553. if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):
  1554. if not agent:
  1555. agent = USER_AGENT
  1556. # test for inline user:password for basic auth
  1557. auth = None
  1558. if base64:
  1559. urltype, rest = urllib.splittype(url_file_stream_or_string)
  1560. realhost, rest = urllib.splithost(rest)
  1561. if realhost:
  1562. user_passwd, realhost = urllib.splituser(realhost)
  1563. if user_passwd:
  1564. url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest)
  1565. auth = base64.encodestring(user_passwd).strip()
  1566. # try to open with urllib2 (to use optional headers)
  1567. request = urllib2.Request(url_file_stream_or_string)
  1568. request.add_header('User-Agent', agent)
  1569. if etag:
  1570. request.add_header('If-None-Match', etag)
  1571. if modified:
  1572. # format into an RFC 1123-compliant timestamp. We can't use
  1573. # time.strftime() since the %a and %b directives can be affected
  1574. # by the current locale, but RFC 2616 states that dates must be
  1575. # in English.
  1576. short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  1577. months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  1578. 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]))
  1579. if referrer:
  1580. request.add_header('Referer', referrer)
  1581. if gzip and zlib:
  1582. request.add_header('Accept-encoding', 'gzip, deflate')
  1583. elif gzip:
  1584. request.add_header('Accept-encoding', 'gzip')
  1585. elif zlib:
  1586. request.add_header('Accept-encoding', 'deflate')
  1587. else:
  1588. request.add_header('Accept-encoding', '')
  1589. if auth:
  1590. request.add_header('Authorization', 'Basic %s' % auth)
  1591. if ACCEPT_HEADER:
  1592. request.add_header('Accept', ACCEPT_HEADER)
  1593. request.add_header('A-IM', 'feed') # RFC 3229 support
  1594. opener = apply(urllib2.build_opener, tuple([_FeedURLHandler()] + handlers))
  1595. opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
  1596. try:
  1597. return opener.open(request)
  1598. finally:
  1599. opener.close() # JohnD
  1600. # try to open with native open function (if url_file_stream_or_string is a filename)
  1601. try:
  1602. return open(url_file_stream_or_string)
  1603. except:
  1604. pass
  1605. # treat url_file_stream_or_string as string
  1606. return _StringIO(str(url_file_stream_or_string))
  1607. _date_handlers = []
  1608. def registerDateHandler(func):
  1609. '''Register a date handler function (takes string, returns 9-tuple date in GMT)'''
  1610. _date_handlers.insert(0, func)
  1611. # ISO-8601 date parsing routines written by Fazal Majid.
  1612. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
  1613. # parser is beyond the scope of feedparser and would be a worthwhile addition
  1614. # to the Python library.
  1615. # A single regular expression cannot parse ISO 8601 date formats into groups
  1616. # as the standard is highly irregular (for instance is 030104 2003-01-04 or
  1617. # 0301-04-01), so we use templates instead.
  1618. # Please note the order in templates is significant because we need a
  1619. # greedy match.
  1620. _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO',
  1621. 'YY-?MM-?DD', 'YY-?OOO', 'YYYY',
  1622. '-YY-?MM', '-OOO', '-YY',
  1623. '--MM-?DD', '--MM',
  1624. '---DD',
  1625. 'CC', '']
  1626. _iso8601_re = [
  1627. tmpl.replace(
  1628. 'YYYY', r'(?P<year>\d{4})').replace(
  1629. 'YY', r'(?P<year>\d\d)').replace(
  1630. 'MM', r'(?P<month>[01]\d)').replace(
  1631. 'DD', r'(?P<day>[0123]\d)').replace(
  1632. 'OOO', r'(?P<ordinal>[0123]\d\d)').replace(
  1633. 'CC', r'(?P<century>\d\d$)')
  1634. + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
  1635. + r'(:(?P<second>\d{2}))?'
  1636. + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
  1637. for tmpl in _iso8601_tmpl]
  1638. del tmpl
  1639. _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
  1640. del regex
  1641. def _parse_date_iso8601(dateString):
  1642. '''Parse a variety of ISO-8601-compatible formats like 20040105'''
  1643. m = None
  1644. for _iso8601_match in _iso8601_matches:
  1645. m = _iso8601_match(dateString)
  1646. if m: break
  1647. if not m: return
  1648. if m.span() == (0, 0): return
  1649. params = m.groupdict()
  1650. ordinal = params.get('ordinal', 0)
  1651. if ordinal:
  1652. ordinal = int(ordinal)
  1653. else:
  1654. ordinal = 0
  1655. year = params.get('year', '--')
  1656. if not year or year == '--':
  1657. year = time.gmtime()[0]
  1658. elif len(year) == 2:
  1659. # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
  1660. year = 100 * int(time.gmtime()[0] / 100) + int(year)
  1661. else:
  1662. year = int(year)
  1663. month = params.get('month', '-')
  1664. if not month or month == '-':
  1665. # ordinals are NOT normalized by mktime, we simulate them
  1666. # by setting month=1, day=ordinal
  1667. if ordinal:
  1668. month = 1
  1669. else:
  1670. month = time.gmtime()[1]
  1671. month = int(month)
  1672. day = params.get('day', 0)
  1673. if not day:
  1674. # see above
  1675. if ordinal:
  1676. day = ordinal
  1677. elif params.get('century', 0) or \
  1678. params.get('year', 0) or params.get('month', 0):
  1679. day = 1
  1680. else:
  1681. day = time.gmtime()[2]
  1682. else:
  1683. day = int(day)
  1684. # special case of the century - is the first year of the 21st century
  1685. # 2000 or 2001 ? The debate goes on...
  1686. if 'century' in params.keys():
  1687. year = (int(params['century']) - 1) * 100 + 1
  1688. # in ISO 8601 most fields are optional
  1689. for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
  1690. if not params.get(field, None):
  1691. params[field] = 0
  1692. hour = int(params.get('hour', 0))
  1693. minute = int(params.get('minute', 0))
  1694. second = int(params.get('second', 0))
  1695. # weekday is normalized by mktime(), we can ignore it
  1696. weekday = 0
  1697. # daylight savings is complex, but not needed for feedparser's purposes
  1698. # as time zones, if specified, include mention of whether it is active
  1699. # (e.g. PST vs. PDT, CET). Using -1 is implementation-dependent and
  1700. # and most implementations have DST bugs
  1701. daylight_savings_flag = 0
  1702. tm = [year, month, day, hour, minute, second, weekday,
  1703. ordinal, daylight_savings_flag]
  1704. # ISO 8601 time zone adjustments
  1705. tz = params.get('tz')
  1706. if tz and tz != 'Z':
  1707. if tz[0] == '-':
  1708. tm[3] += int(params.get('tzhour', 0))
  1709. tm[4] += int(params.get('tzmin', 0))
  1710. elif tz[0] == '+':
  1711. tm[3] -= int(params.get('tzhour', 0))
  1712. tm[4] -= int(params.get('tzmin', 0))
  1713. else:
  1714. return None
  1715. # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
  1716. # which is guaranteed to normalize d/m/y/h/m/s.
  1717. # Many implementations have bugs, but we'll pretend they don't.
  1718. return time.localtime(time.mktime(tm))
  1719. registerDateHandler(_parse_date_iso8601)
  1720. # 8-bit date handling routines written by ytrewq1.
  1721. _korean_year = u'\ub144' # b3e2 in euc-kr
  1722. _korean_month = u'\uc6d4' # bff9 in euc-kr
  1723. _korean_day = u'\uc77c' # c0cf in euc-kr
  1724. _korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr
  1725. _korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr
  1726. _korean_onblog_date_re = \
  1727. re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \
  1728. (_korean_year, _korean_month, _korean_day))
  1729. _korean_nate_date_re = \
  1730. re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \
  1731. (_korean_am, _korean_pm))
  1732. def _parse_date_onblog(dateString):
  1733. '''Parse a string according to the OnBlog 8-bit date format'''
  1734. m = _korean_onblog_date_re.match(dateString)
  1735. if not m: return
  1736. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  1737. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  1738. 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  1739. 'zonediff': '+09:00'}
  1740. if _debug: sys.stderr.write('OnBlog date parsed as: %s\n' % w3dtfdate)
  1741. return _parse_date_w3dtf(w3dtfdate)
  1742. registerDateHandler(_parse_date_onblog)
  1743. def _parse_date_nate(dateString):
  1744. '''Parse a string according to the Nate 8-bit date format'''
  1745. m = _korean_nate_date_re.match(dateString)
  1746. if not m: return
  1747. hour = int(m.group(5))
  1748. ampm = m.group(4)
  1749. if (ampm == _korean_pm):
  1750. hour += 12
  1751. hour = str(hour)
  1752. if len(hour) == 1:
  1753. hour = '0' + hour
  1754. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  1755. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  1756. 'hour': hour, 'minute': m.group(6), 'second': m.group(7),\
  1757. 'zonediff': '+09:00'}
  1758. if _debug: sys.stderr.write('Nate date parsed as: %s\n' % w3dtfdate)
  1759. return _parse_date_w3dtf(w3dtfdate)
  1760. registerDateHandler(_parse_date_nate)
  1761. _mssql_date_re = \
  1762. re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?')
  1763. def _parse_date_mssql(dateString):
  1764. '''Parse a string according to the MS SQL date format'''
  1765. m = _mssql_date_re.match(dateString)
  1766. if not m: return
  1767. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  1768. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  1769. 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  1770. 'zonediff': '+09:00'}
  1771. if _debug: sys.stderr.write('MS SQL date parsed as: %s\n' % w3dtfdate)
  1772. return _parse_date_w3dtf(w3dtfdate)
  1773. registerDateHandler(_parse_date_mssql)
  1774. # Unicode strings for Greek date strings
  1775. _greek_months = \
  1776. { \
  1777. u'\u0399\u03b1\u03bd': u'Jan', # c9e1ed in iso-8859-7
  1778. u'\u03a6\u03b5\u03b2': u'Feb', # d6e5e2 in iso-8859-7
  1779. u'\u039c\u03ac\u03ce': u'Mar', # ccdcfe in iso-8859-7
  1780. u'\u039c\u03b1\u03ce': u'Mar', # cce1fe in iso-8859-7
  1781. u'\u0391\u03c0\u03c1': u'Apr', # c1f0f1 in iso-8859-7
  1782. u'\u039c\u03ac\u03b9': u'May', # ccdce9 in iso-8859-7
  1783. u'\u039c\u03b1\u03ca': u'May', # cce1fa in iso-8859-7
  1784. u'\u039c\u03b1\u03b9': u'May', # cce1e9 in iso-8859-7
  1785. u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7
  1786. u'\u0399\u03bf\u03bd': u'Jun', # c9efed in iso-8859-7
  1787. u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7
  1788. u'\u0399\u03bf\u03bb': u'Jul', # c9f9eb in iso-8859-7
  1789. u'\u0391\u03cd\u03b3': u'Aug', # c1fde3 in iso-8859-7
  1790. u'\u0391\u03c5\u03b3': u'Aug', # c1f5e3 in iso-8859-7
  1791. u'\u03a3\u03b5\u03c0': u'Sep', # d3e5f0 in iso-8859-7
  1792. u'\u039f\u03ba\u03c4': u'Oct', # cfeaf4 in iso-8859-7
  1793. u'\u039d\u03bf\u03ad': u'Nov', # cdefdd in iso-8859-7
  1794. u'\u039d\u03bf\u03b5': u'Nov', # cdefe5 in iso-8859-7
  1795. u'\u0394\u03b5\u03ba': u'Dec', # c4e5ea in iso-8859-7
  1796. }
  1797. _greek_wdays = \
  1798. { \
  1799. u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7
  1800. u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7
  1801. u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7
  1802. u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7
  1803. u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7
  1804. u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7
  1805. u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7
  1806. }
  1807. _greek_date_format_re = \
  1808. re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)')
  1809. def _parse_date_greek(dateString):
  1810. '''Parse a string according to a Greek 8-bit date format.'''
  1811. m = _greek_date_format_re.match(dateString)
  1812. if not m: return
  1813. try:
  1814. wday = _greek_wdays[m.group(1)]
  1815. month = _greek_months[m.group(3)]
  1816. except:
  1817. return
  1818. rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
  1819. {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\
  1820. 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\
  1821. 'zonediff': m.group(8)}
  1822. if _debug: sys.stderr.write('Greek date parsed as: %s\n' % rfc822date)
  1823. return _parse_date_rfc822(rfc822date)
  1824. registerDateHandler(_parse_date_greek)
  1825. # Unicode strings for Hungarian date strings
  1826. _hungarian_months = \
  1827. { \
  1828. u'janu\u00e1r': u'01', # e1 in iso-8859-2
  1829. u'febru\u00e1ri': u'02', # e1 in iso-8859-2
  1830. u'm\u00e1rcius': u'03', # e1 in iso-8859-2
  1831. u'\u00e1prilis': u'04', # e1 in iso-8859-2
  1832. u'm\u00e1ujus': u'05', # e1 in iso-8859-2
  1833. u'j\u00fanius': u'06', # fa in iso-8859-2
  1834. u'j\u00falius': u'07', # fa in iso-8859-2
  1835. u'augusztus': u'08',
  1836. u'szeptember': u'09',
  1837. u'okt\u00f3ber': u'10', # f3 in iso-8859-2
  1838. u'november': u'11',
  1839. u'december': u'12',
  1840. }
  1841. _hungarian_date_format_re = \
  1842. re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))')
  1843. def _parse_date_hungarian(dateString):
  1844. '''Parse a string according to a Hungarian 8-bit date format.'''
  1845. m = _hungarian_date_format_re.match(dateString)
  1846. if not m: return
  1847. try:
  1848. month = _hungarian_months[m.group(2)]
  1849. day = m.group(3)
  1850. if len(day) == 1:
  1851. day = '0' + day
  1852. hour = m.group(4)
  1853. if len(hour) == 1:
  1854. hour = '0' + hour
  1855. except:
  1856. return
  1857. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \
  1858. {'year': m.group(1), 'month': month, 'day': day,\
  1859. 'hour': hour, 'minute': m.group(5),\
  1860. 'zonediff': m.group(6)}
  1861. if _debug: sys.stderr.write('Hungarian date parsed as: %s\n' % w3dtfdate)
  1862. return _parse_date_w3dtf(w3dtfdate)
  1863. registerDateHandler(_parse_date_hungarian)
  1864. # W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by
  1865. # Drake and licensed under the Python license. Removed all range checking
  1866. # for month, day, hour, minute, and second, since mktime will normalize
  1867. # these later
  1868. def _parse_date_w3dtf(dateString):
  1869. def __extract_date(m):
  1870. year = int(m.group('year'))
  1871. if year < 100:
  1872. year = 100 * int(time.gmtime()[0] / 100) + int(year)
  1873. if year < 1000:
  1874. return 0, 0, 0
  1875. julian = m.group('julian')
  1876. if julian:
  1877. julian = int(julian)
  1878. month = julian / 30 + 1
  1879. day = julian % 30 + 1
  1880. jday = None
  1881. while jday != julian:
  1882. t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0))
  1883. jday = time.gmtime(t)[-2]
  1884. diff = abs(jday - julian)
  1885. if jday > julian:
  1886. if diff < day:
  1887. day = day - diff
  1888. else:
  1889. month = month - 1
  1890. day = 31
  1891. elif jday < julian:
  1892. if day + diff < 28:
  1893. day = day + diff
  1894. else:
  1895. month = month + 1
  1896. return year, month, day
  1897. month = m.group('month')
  1898. day = 1
  1899. if month is None:
  1900. month = 1
  1901. else:
  1902. month = int(month)
  1903. day = m.group('day')
  1904. if day:
  1905. day = int(day)
  1906. else:
  1907. day = 1
  1908. return year, month, day
  1909. def __extract_time(m):
  1910. if not m:
  1911. return 0, 0, 0
  1912. hours = m.group('hours')
  1913. if not hours:
  1914. return 0, 0, 0
  1915. hours = int(hours)
  1916. minutes = int(m.group('minutes'))
  1917. seconds = m.group('seconds')
  1918. if seconds:
  1919. seconds = int(seconds)
  1920. else:
  1921. seconds = 0
  1922. return hours, minutes, seconds
  1923. def __extract_tzd(m):
  1924. '''Return the Time Zone Designator as an offset in seconds from UTC.'''
  1925. if not m:
  1926. return 0
  1927. tzd = m.group('tzd')
  1928. if not tzd:
  1929. return 0
  1930. if tzd == 'Z':
  1931. return 0
  1932. hours = int(m.group('tzdhours'))
  1933. minutes = m.group('tzdminutes')
  1934. if minutes:
  1935. minutes = int(minutes)
  1936. else:
  1937. minutes = 0
  1938. offset = (hours*60 + minutes) * 60
  1939. if tzd[0] == '+':
  1940. return -offset
  1941. return offset
  1942. __date_re = ('(?P<year>\d\d\d\d)'
  1943. '(?:(?P<dsep>-|)'
  1944. '(?:(?P<julian>\d\d\d)'
  1945. '|(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?))?')
  1946. __tzd_re = '(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)'
  1947. __tzd_rx = re.compile(__tzd_re)
  1948. __time_re = ('(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)'
  1949. '(?:(?P=tsep)(?P<seconds>\d\d(?:[.,]\d+)?))?'
  1950. + __tzd_re)
  1951. __datetime_re = '%s(?:T%s)?' % (__date_re, __time_re)
  1952. __datetime_rx = re.compile(__datetime_re)
  1953. m = __datetime_rx.match(dateString)
  1954. if (m is None) or (m.group() != dateString): return
  1955. gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0)
  1956. if gmt[0] == 0: return
  1957. return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone)
  1958. registerDateHandler(_parse_date_w3dtf)
  1959. def _parse_date_rfc822(dateString):
  1960. '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date'''
  1961. data = dateString.split()
  1962. if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames:
  1963. del data[0]
  1964. if len(data) == 4:
  1965. s = data[3]
  1966. i = s.find('+')
  1967. if i > 0:
  1968. data[3:] = [s[:i], s[i+1:]]
  1969. else:
  1970. data.append('')
  1971. dateString = " ".join(data)
  1972. if len(data) < 5:
  1973. dateString += ' 00:00:00 GMT'
  1974. tm = rfc822.parsedate_tz(dateString)
  1975. if tm:
  1976. return time.gmtime(rfc822.mktime_tz(tm))
  1977. # rfc822.py defines several time zones, but we define some extra ones.
  1978. # 'ET' is equivalent to 'EST', etc.
  1979. _additional_timezones = {'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800}
  1980. rfc822._timezones.update(_additional_timezones)
  1981. registerDateHandler(_parse_date_rfc822)
  1982. def _parse_date(dateString):
  1983. '''Parses a variety of date formats into a 9-tuple in GMT'''
  1984. for handler in _date_handlers:
  1985. try:
  1986. date9tuple = handler(dateString)
  1987. if not date9tuple: continue
  1988. if len(date9tuple) != 9:
  1989. if _debug: sys.stderr.write('date handler function must return 9-tuple\n')
  1990. raise ValueError
  1991. map(int, date9tuple)
  1992. return date9tuple
  1993. except Exception, e:
  1994. if _debug: sys.stderr.write('%s raised %s\n' % (handler.__name__, repr(e)))
  1995. pass
  1996. return None
  1997. def _getCharacterEncoding(http_headers, xml_data):
  1998. '''Get the character encoding of the XML document
  1999. http_headers is a dictionary
  2000. xml_data is a raw string (not Unicode)
  2001. This is so much trickier than it sounds, it's not even funny.
  2002. According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type
  2003. is application/xml, application/*+xml,
  2004. application/xml-external-parsed-entity, or application/xml-dtd,
  2005. the encoding given in the charset parameter of the HTTP Content-Type
  2006. takes precedence over the encoding given in the XML prefix within the
  2007. document, and defaults to 'utf-8' if neither are specified. But, if
  2008. the HTTP Content-Type is text/xml, text/*+xml, or
  2009. text/xml-external-parsed-entity, the encoding given in the XML prefix
  2010. within the document is ALWAYS IGNORED and only the encoding given in
  2011. the charset parameter of the HTTP Content-Type header should be
  2012. respected, and it defaults to 'us-ascii' if not specified.
  2013. Furthermore, discussion on the atom-syntax mailing list with the
  2014. author of RFC 3023 leads me to the conclusion that any document
  2015. served with a Content-Type of text/* and no charset parameter
  2016. must be treated as us-ascii. (We now do this.) And also that it
  2017. must always be flagged as non-well-formed. (We now do this too.)
  2018. If Content-Type is unspecified (input was local file or non-HTTP source)
  2019. or unrecognized (server just got it totally wrong), then go by the
  2020. encoding given in the XML prefix of the document and default to
  2021. 'iso-8859-1' as per the HTTP specification (RFC 2616).
  2022. Then, assuming we didn't find a character encoding in the HTTP headers
  2023. (and the HTTP Content-type allowed us to look in the body), we need
  2024. to sniff the first few bytes of the XML data and try to determine
  2025. whether the encoding is ASCII-compatible. Section F of the XML
  2026. specification shows the way here:
  2027. http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2028. If the sniffed encoding is not ASCII-compatible, we need to make it
  2029. ASCII compatible so that we can sniff further into the XML declaration
  2030. to find the encoding attribute, which will tell us the true encoding.
  2031. Of course, none of this guarantees that we will be able to parse the
  2032. feed in the declared character encoding (assuming it was declared
  2033. correctly, which many are not). CJKCodecs and iconv_codec help a lot;
  2034. you should definitely install them if you can.
  2035. http://cjkpython.i18n.org/
  2036. '''
  2037. def _parseHTTPContentType(content_type):
  2038. '''takes HTTP Content-Type header and returns (content type, charset)
  2039. If no charset is specified, returns (content type, '')
  2040. If no content type is specified, returns ('', '')
  2041. Both return parameters are guaranteed to be lowercase strings
  2042. '''
  2043. content_type = content_type or ''
  2044. content_type, params = cgi.parse_header(content_type)
  2045. return content_type, params.get('charset', '').replace("'", '')
  2046. sniffed_xml_encoding = ''
  2047. xml_encoding = ''
  2048. true_encoding = ''
  2049. http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type'))
  2050. # Must sniff for non-ASCII-compatible character encodings before
  2051. # searching for XML declaration. This heuristic is defined in
  2052. # section F of the XML specification:
  2053. # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2054. try:
  2055. if xml_data[:4] == '\x4c\x6f\xa7\x94':
  2056. # EBCDIC
  2057. xml_data = _ebcdic_to_ascii(xml_data)
  2058. elif xml_data[:4] == '\x00\x3c\x00\x3f':
  2059. # UTF-16BE
  2060. sniffed_xml_encoding = 'utf-16be'
  2061. xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
  2062. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') and (xml_data[2:4] != '\x00\x00'):
  2063. # UTF-16BE with BOM
  2064. sniffed_xml_encoding = 'utf-16be'
  2065. xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
  2066. elif xml_data[:4] == '\x3c\x00\x3f\x00':
  2067. # UTF-16LE
  2068. sniffed_xml_encoding = 'utf-16le'
  2069. xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
  2070. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and (xml_data[2:4] != '\x00\x00'):
  2071. # UTF-16LE with BOM
  2072. sniffed_xml_encoding = 'utf-16le'
  2073. xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
  2074. elif xml_data[:4] == '\x00\x00\x00\x3c':
  2075. # UTF-32BE
  2076. sniffed_xml_encoding = 'utf-32be'
  2077. xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
  2078. elif xml_data[:4] == '\x3c\x00\x00\x00':
  2079. # UTF-32LE
  2080. sniffed_xml_encoding = 'utf-32le'
  2081. xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
  2082. elif xml_data[:4] == '\x00\x00\xfe\xff':
  2083. # UTF-32BE with BOM
  2084. sniffed_xml_encoding = 'utf-32be'
  2085. xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
  2086. elif xml_data[:4] == '\xff\xfe\x00\x00':
  2087. # UTF-32LE with BOM
  2088. sniffed_xml_encoding = 'utf-32le'
  2089. xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
  2090. elif xml_data[:3] == '\xef\xbb\xbf':
  2091. # UTF-8 with BOM
  2092. sniffed_xml_encoding = 'utf-8'
  2093. xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
  2094. else:
  2095. # ASCII-compatible
  2096. pass
  2097. xml_encoding_match = re.compile('^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
  2098. except:
  2099. xml_encoding_match = None
  2100. if xml_encoding_match:
  2101. xml_encoding = xml_encoding_match.groups()[0].lower()
  2102. if sniffed_xml_encoding and (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')):
  2103. xml_encoding = sniffed_xml_encoding
  2104. acceptable_content_type = 0
  2105. application_content_types = ('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity')
  2106. text_content_types = ('text/xml', 'text/xml-external-parsed-entity')
  2107. if (http_content_type in application_content_types) or \
  2108. (http_content_type.startswith('application/') and http_content_type.endswith('+xml')):
  2109. acceptable_content_type = 1
  2110. true_encoding = http_encoding or xml_encoding or 'utf-8'
  2111. elif (http_content_type in text_content_types) or \
  2112. (http_content_type.startswith('text/')) and http_content_type.endswith('+xml'):
  2113. acceptable_content_type = 1
  2114. true_encoding = http_encoding or 'us-ascii'
  2115. elif http_content_type.startswith('text/'):
  2116. true_encoding = http_encoding or 'us-ascii'
  2117. elif http_headers and (not http_headers.has_key('content-type')):
  2118. true_encoding = xml_encoding or 'iso-8859-1'
  2119. else:
  2120. true_encoding = xml_encoding or 'utf-8'
  2121. return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type
  2122. def _toUTF8(data, encoding):
  2123. '''Changes an XML data stream on the fly to specify a new encoding
  2124. data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already
  2125. encoding is a string recognized by encodings.aliases
  2126. '''
  2127. if _debug: sys.stderr.write('entering _toUTF8, trying encoding %s\n' % encoding)
  2128. # strip Byte Order Mark (if present)
  2129. if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
  2130. if _debug:
  2131. sys.stderr.write('stripping BOM\n')
  2132. if encoding != 'utf-16be':
  2133. sys.stderr.write('trying utf-16be instead\n')
  2134. encoding = 'utf-16be'
  2135. data = data[2:]
  2136. elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
  2137. if _debug:
  2138. sys.stderr.write('stripping BOM\n')
  2139. if encoding != 'utf-16le':
  2140. sys.stderr.write('trying utf-16le instead\n')
  2141. encoding = 'utf-16le'
  2142. data = data[2:]
  2143. elif data[:3] == '\xef\xbb\xbf':
  2144. if _debug:
  2145. sys.stderr.write('stripping BOM\n')
  2146. if encoding != 'utf-8':
  2147. sys.stderr.write('trying utf-8 instead\n')
  2148. encoding = 'utf-8'
  2149. data = data[3:]
  2150. elif data[:4] == '\x00\x00\xfe\xff':
  2151. if _debug:
  2152. sys.stderr.write('stripping BOM\n')
  2153. if encoding != 'utf-32be':
  2154. sys.stderr.write('trying utf-32be instead\n')
  2155. encoding = 'utf-32be'
  2156. data = data[4:]
  2157. elif data[:4] == '\xff\xfe\x00\x00':
  2158. if _debug:
  2159. sys.stderr.write('stripping BOM\n')
  2160. if encoding != 'utf-32le':
  2161. sys.stderr.write('trying utf-32le instead\n')
  2162. encoding = 'utf-32le'
  2163. data = data[4:]
  2164. newdata = unicode(data, encoding)
  2165. if _debug: sys.stderr.write('successfully converted %s data to unicode\n' % encoding)
  2166. declmatch = re.compile('^<\?xml[^>]*?>')
  2167. newdecl = '''<?xml version='1.0' encoding='utf-8'?>'''
  2168. if declmatch.search(newdata):
  2169. newdata = declmatch.sub(newdecl, newdata)
  2170. else:
  2171. newdata = newdecl + u'\n' + newdata
  2172. return newdata.encode('utf-8')
  2173. def _stripDoctype(data):
  2174. '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
  2175. rss_version may be 'rss091n' or None
  2176. stripped_data is the same XML document, minus the DOCTYPE
  2177. '''
  2178. entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE)
  2179. data = entity_pattern.sub('', data)
  2180. doctype_pattern = re.compile(r'<!DOCTYPE([^>]*?)>', re.MULTILINE)
  2181. doctype_results = doctype_pattern.findall(data)
  2182. doctype = doctype_results and doctype_results[0] or ''
  2183. if doctype.lower().count('netscape'):
  2184. version = 'rss091n'
  2185. else:
  2186. version = None
  2187. data = doctype_pattern.sub('', data)
  2188. return version, data
  2189. def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]):
  2190. '''Parse a feed from a URL, file, stream, or string'''
  2191. result = FeedParserDict()
  2192. result['feed'] = FeedParserDict()
  2193. result['entries'] = []
  2194. if _XML_AVAILABLE:
  2195. result['bozo'] = 0
  2196. if type(handlers) == types.InstanceType:
  2197. handlers = [handlers]
  2198. try:
  2199. f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers)
  2200. data = f.read()
  2201. except Exception, e:
  2202. result['bozo'] = 1
  2203. result['bozo_exception'] = e
  2204. data = ''
  2205. f = None
  2206. # if feed is gzip-compressed, decompress it
  2207. if f and data and hasattr(f, 'headers'):
  2208. if gzip and f.headers.get('content-encoding', '') == 'gzip':
  2209. try:
  2210. data = gzip.GzipFile(fileobj=_StringIO(data)).read()
  2211. except Exception, e:
  2212. # Some feeds claim to be gzipped but they're not, so
  2213. # we get garbage. Ideally, we should re-request the
  2214. # feed without the 'Accept-encoding: gzip' header,
  2215. # but we don't.
  2216. result['bozo'] = 1
  2217. result['bozo_exception'] = e
  2218. data = ''
  2219. elif zlib and f.headers.get('content-encoding', '') == 'deflate':
  2220. try:
  2221. data = zlib.decompress(data, -zlib.MAX_WBITS)
  2222. except Exception, e:
  2223. result['bozo'] = 1
  2224. result['bozo_exception'] = e
  2225. data = ''
  2226. # save HTTP headers
  2227. if hasattr(f, 'info'):
  2228. info = f.info()
  2229. result['etag'] = info.getheader('ETag')
  2230. last_modified = info.getheader('Last-Modified')
  2231. if last_modified:
  2232. result['modified'] = _parse_date(last_modified)
  2233. if hasattr(f, 'url'):
  2234. result['href'] = f.url
  2235. result['status'] = 200
  2236. if hasattr(f, 'status'):
  2237. result['status'] = f.status
  2238. if hasattr(f, 'headers'):
  2239. result['headers'] = f.headers.dict
  2240. if hasattr(f, 'close'):
  2241. f.close()
  2242. # there are four encodings to keep track of:
  2243. # - http_encoding is the encoding declared in the Content-Type HTTP header
  2244. # - xml_encoding is the encoding declared in the <?xml declaration
  2245. # - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data
  2246. # - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications
  2247. http_headers = result.get('headers', {})
  2248. result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type = \
  2249. _getCharacterEncoding(http_headers, data)
  2250. if http_headers and (not acceptable_content_type):
  2251. if http_headers.has_key('content-type'):
  2252. bozo_message = '%s is not an XML media type' % http_headers['content-type']
  2253. else:
  2254. bozo_message = 'no Content-type specified'
  2255. result['bozo'] = 1
  2256. result['bozo_exception'] = NonXMLContentType(bozo_message)
  2257. result['version'], data = _stripDoctype(data)
  2258. baseuri = http_headers.get('content-location', result.get('href'))
  2259. baselang = http_headers.get('content-language', None)
  2260. # if server sent 304, we're done
  2261. if result.get('status', 0) == 304:
  2262. result['version'] = ''
  2263. result['debug_message'] = 'The feed has not changed since you last checked, ' + \
  2264. 'so the server sent no data. This is a feature, not a bug!'
  2265. return result
  2266. # if there was a problem downloading, we're done
  2267. if not data:
  2268. return result
  2269. # determine character encoding
  2270. use_strict_parser = 0
  2271. known_encoding = 0
  2272. tried_encodings = []
  2273. # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM
  2274. for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding):
  2275. if not proposed_encoding: continue
  2276. if proposed_encoding in tried_encodings: continue
  2277. tried_encodings.append(proposed_encoding)
  2278. try:
  2279. data = _toUTF8(data, proposed_encoding)
  2280. known_encoding = use_strict_parser = 1
  2281. break
  2282. except:
  2283. pass
  2284. # if no luck and we have auto-detection library, try that
  2285. if (not known_encoding) and chardet:
  2286. try:
  2287. proposed_encoding = chardet.detect(data)['encoding']
  2288. if proposed_encoding and (proposed_encoding not in tried_encodings):
  2289. tried_encodings.append(proposed_encoding)
  2290. data = _toUTF8(data, proposed_encoding)
  2291. known_encoding = use_strict_parser = 1
  2292. except:
  2293. pass
  2294. # if still no luck and we haven't tried utf-8 yet, try that
  2295. if (not known_encoding) and ('utf-8' not in tried_encodings):
  2296. try:
  2297. proposed_encoding = 'utf-8'
  2298. tried_encodings.append(proposed_encoding)
  2299. data = _toUTF8(data, proposed_encoding)
  2300. known_encoding = use_strict_parser = 1
  2301. except:
  2302. pass
  2303. # if still no luck and we haven't tried windows-1252 yet, try that
  2304. if (not known_encoding) and ('windows-1252' not in tried_encodings):
  2305. try:
  2306. proposed_encoding = 'windows-1252'
  2307. tried_encodings.append(proposed_encoding)
  2308. data = _toUTF8(data, proposed_encoding)
  2309. known_encoding = use_strict_parser = 1
  2310. except:
  2311. pass
  2312. # if still no luck, give up
  2313. if not known_encoding:
  2314. result['bozo'] = 1
  2315. result['bozo_exception'] = CharacterEncodingUnknown( \
  2316. 'document encoding unknown, I tried ' + \
  2317. '%s, %s, utf-8, and windows-1252 but nothing worked' % \
  2318. (result['encoding'], xml_encoding))
  2319. result['encoding'] = ''
  2320. elif proposed_encoding != result['encoding']:
  2321. result['bozo'] = 1
  2322. result['bozo_exception'] = CharacterEncodingOverride( \
  2323. 'documented declared as %s, but parsed as %s' % \
  2324. (result['encoding'], proposed_encoding))
  2325. result['encoding'] = proposed_encoding
  2326. if not _XML_AVAILABLE:
  2327. use_strict_parser = 0
  2328. if use_strict_parser:
  2329. # initialize the SAX parser
  2330. feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8')
  2331. saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
  2332. saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
  2333. saxparser.setContentHandler(feedparser)
  2334. saxparser.setErrorHandler(feedparser)
  2335. source = xml.sax.xmlreader.InputSource()
  2336. source.setByteStream(_StringIO(data))
  2337. if hasattr(saxparser, '_ns_stack'):
  2338. # work around bug in built-in SAX parser (doesn't recognize xml: namespace)
  2339. # PyXML doesn't have this problem, and it doesn't have _ns_stack either
  2340. saxparser._ns_stack.append({'http://www.w3.org/XML/1998/namespace':'xml'})
  2341. try:
  2342. saxparser.parse(source)
  2343. except Exception, e:
  2344. if _debug:
  2345. import traceback
  2346. traceback.print_stack()
  2347. traceback.print_exc()
  2348. sys.stderr.write('xml parsing failed\n')
  2349. result['bozo'] = 1
  2350. result['bozo_exception'] = feedparser.exc or e
  2351. use_strict_parser = 0
  2352. if not use_strict_parser:
  2353. feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '')
  2354. feedparser.feed(data)
  2355. result['feed'] = feedparser.feeddata
  2356. result['entries'] = feedparser.entries
  2357. result['version'] = result['version'] or feedparser.version
  2358. result['namespaces'] = feedparser.namespacesInUse
  2359. return result
  2360. if __name__ == '__main__':
  2361. if not sys.argv[1:]:
  2362. print __doc__
  2363. sys.exit(0)
  2364. else:
  2365. urls = sys.argv[1:]
  2366. zopeCompatibilityHack()
  2367. from pprint import pprint
  2368. for url in urls:
  2369. print url
  2370. print
  2371. result = parse(url)
  2372. pprint(result)
  2373. print
  2374. #REVISION HISTORY
  2375. #1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements,
  2376. # added Simon Fell's test suite
  2377. #1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections
  2378. #2.0 - 10/19/2002
  2379. # JD - use inchannel to watch out for image and textinput elements which can
  2380. # also contain title, link, and description elements
  2381. # JD - check for isPermaLink='false' attribute on guid elements
  2382. # JD - replaced openAnything with open_resource supporting ETag and
  2383. # If-Modified-Since request headers
  2384. # JD - parse now accepts etag, modified, agent, and referrer optional
  2385. # arguments
  2386. # JD - modified parse to return a dictionary instead of a tuple so that any
  2387. # etag or modified information can be returned and cached by the caller
  2388. #2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything
  2389. # because of etag/modified, return the old etag/modified to the caller to
  2390. # indicate why nothing is being returned
  2391. #2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its
  2392. # useless. Fixes the problem JD was addressing by adding it.
  2393. #2.1 - 11/14/2002 - MAP - added gzip support
  2394. #2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent.
  2395. # start_admingeneratoragent is an example of how to handle elements with
  2396. # only attributes, no content.
  2397. #2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify);
  2398. # also, make sure we send the User-Agent even if urllib2 isn't available.
  2399. # Match any variation of backend.userland.com/rss namespace.
  2400. #2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is.
  2401. #2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's
  2402. # snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed
  2403. # project name
  2404. #2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree);
  2405. # removed unnecessary urllib code -- urllib2 should always be available anyway;
  2406. # return actual url, status, and full HTTP headers (as result['url'],
  2407. # result['status'], and result['headers']) if parsing a remote feed over HTTP --
  2408. # this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>;
  2409. # added the latest namespace-of-the-week for RSS 2.0
  2410. #2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom
  2411. # User-Agent (otherwise urllib2 sends two, which confuses some servers)
  2412. #2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for
  2413. # inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds
  2414. #2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or
  2415. # textInput, and also to return the character encoding (if specified)
  2416. #2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking
  2417. # nested divs within content (JohnD); fixed missing sys import (JohanS);
  2418. # fixed regular expression to capture XML character encoding (Andrei);
  2419. # added support for Atom 0.3-style links; fixed bug with textInput tracking;
  2420. # added support for cloud (MartijnP); added support for multiple
  2421. # category/dc:subject (MartijnP); normalize content model: 'description' gets
  2422. # description (which can come from description, summary, or full content if no
  2423. # description), 'content' gets dict of base/language/type/value (which can come
  2424. # from content:encoded, xhtml:body, content, or fullitem);
  2425. # fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang
  2426. # tracking; fixed bug tracking unknown tags; fixed bug tracking content when
  2427. # <content> element is not in default namespace (like Pocketsoap feed);
  2428. # resolve relative URLs in link, guid, docs, url, comments, wfw:comment,
  2429. # wfw:commentRSS; resolve relative URLs within embedded HTML markup in
  2430. # description, xhtml:body, content, content:encoded, title, subtitle,
  2431. # summary, info, tagline, and copyright; added support for pingback and
  2432. # trackback namespaces
  2433. #2.7 - 1/5/2004 - MAP - really added support for trackback and pingback
  2434. # namespaces, as opposed to 2.6 when I said I did but didn't really;
  2435. # sanitize HTML markup within some elements; added mxTidy support (if
  2436. # installed) to tidy HTML markup within some elements; fixed indentation
  2437. # bug in _parse_date (FazalM); use socket.setdefaulttimeout if available
  2438. # (FazalM); universal date parsing and normalization (FazalM): 'created', modified',
  2439. # 'issued' are parsed into 9-tuple date format and stored in 'created_parsed',
  2440. # 'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified'
  2441. # and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa
  2442. #2.7.1 - 1/9/2004 - MAP - fixed bug handling &quot; and &apos;. fixed memory
  2443. # leak not closing url opener (JohnD); added dc:publisher support (MarekK);
  2444. # added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK)
  2445. #2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed <br/> tags in
  2446. # encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL);
  2447. # fixed relative URI processing for guid (skadz); added ICBM support; added
  2448. # base64 support
  2449. #2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many
  2450. # blogspot.com sites); added _debug variable
  2451. #2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing
  2452. #3.0b3 - 1/23/2004 - MAP - parse entire feed with real XML parser (if available);
  2453. # added several new supported namespaces; fixed bug tracking naked markup in
  2454. # description; added support for enclosure; added support for source; re-added
  2455. # support for cloud which got dropped somehow; added support for expirationDate
  2456. #3.0b4 - 1/26/2004 - MAP - fixed xml:lang inheritance; fixed multiple bugs tracking
  2457. # xml:base URI, one for documents that don't define one explicitly and one for
  2458. # documents that define an outer and an inner xml:base that goes out of scope
  2459. # before the end of the document
  2460. #3.0b5 - 1/26/2004 - MAP - fixed bug parsing multiple links at feed level
  2461. #3.0b6 - 1/27/2004 - MAP - added feed type and version detection, result['version']
  2462. # will be one of SUPPORTED_VERSIONS.keys() or empty string if unrecognized;
  2463. # added support for creativeCommons:license and cc:license; added support for
  2464. # full Atom content model in title, tagline, info, copyright, summary; fixed bug
  2465. # with gzip encoding (not always telling server we support it when we do)
  2466. #3.0b7 - 1/28/2004 - MAP - support Atom-style author element in author_detail
  2467. # (dictionary of 'name', 'url', 'email'); map author to author_detail if author
  2468. # contains name + email address
  2469. #3.0b8 - 1/28/2004 - MAP - added support for contributor
  2470. #3.0b9 - 1/29/2004 - MAP - fixed check for presence of dict function; added
  2471. # support for summary
  2472. #3.0b10 - 1/31/2004 - MAP - incorporated ISO-8601 date parsing routines from
  2473. # xml.util.iso8601
  2474. #3.0b11 - 2/2/2004 - MAP - added 'rights' to list of elements that can contain
  2475. # dangerous markup; fiddled with decodeEntities (not right); liberalized
  2476. # date parsing even further
  2477. #3.0b12 - 2/6/2004 - MAP - fiddled with decodeEntities (still not right);
  2478. # added support to Atom 0.2 subtitle; added support for Atom content model
  2479. # in copyright; better sanitizing of dangerous HTML elements with end tags
  2480. # (script, frameset)
  2481. #3.0b13 - 2/8/2004 - MAP - better handling of empty HTML tags (br, hr, img,
  2482. # etc.) in embedded markup, in either HTML or XHTML form (<br>, <br/>, <br />)
  2483. #3.0b14 - 2/8/2004 - MAP - fixed CDATA handling in non-wellformed feeds under
  2484. # Python 2.1
  2485. #3.0b15 - 2/11/2004 - MAP - fixed bug resolving relative links in wfw:commentRSS;
  2486. # fixed bug capturing author and contributor URL; fixed bug resolving relative
  2487. # links in author and contributor URL; fixed bug resolvin relative links in
  2488. # generator URL; added support for recognizing RSS 1.0; passed Simon Fell's
  2489. # namespace tests, and included them permanently in the test suite with his
  2490. # permission; fixed namespace handling under Python 2.1
  2491. #3.0b16 - 2/12/2004 - MAP - fixed support for RSS 0.90 (broken in b15)
  2492. #3.0b17 - 2/13/2004 - MAP - determine character encoding as per RFC 3023
  2493. #3.0b18 - 2/17/2004 - MAP - always map description to summary_detail (Andrei);
  2494. # use libxml2 (if available)
  2495. #3.0b19 - 3/15/2004 - MAP - fixed bug exploding author information when author
  2496. # name was in parentheses; removed ultra-problematic mxTidy support; patch to
  2497. # workaround crash in PyXML/expat when encountering invalid entities
  2498. # (MarkMoraes); support for textinput/textInput
  2499. #3.0b20 - 4/7/2004 - MAP - added CDF support
  2500. #3.0b21 - 4/14/2004 - MAP - added Hot RSS support
  2501. #3.0b22 - 4/19/2004 - MAP - changed 'channel' to 'feed', 'item' to 'entries' in
  2502. # results dict; changed results dict to allow getting values with results.key
  2503. # as well as results[key]; work around embedded illformed HTML with half
  2504. # a DOCTYPE; work around malformed Content-Type header; if character encoding
  2505. # is wrong, try several common ones before falling back to regexes (if this
  2506. # works, bozo_exception is set to CharacterEncodingOverride); fixed character
  2507. # encoding issues in BaseHTMLProcessor by tracking encoding and converting
  2508. # from Unicode to raw strings before feeding data to sgmllib.SGMLParser;
  2509. # convert each value in results to Unicode (if possible), even if using
  2510. # regex-based parsing
  2511. #3.0b23 - 4/21/2004 - MAP - fixed UnicodeDecodeError for feeds that contain
  2512. # high-bit characters in attributes in embedded HTML in description (thanks
  2513. # Thijs van de Vossen); moved guid, date, and date_parsed to mapped keys in
  2514. # FeedParserDict; tweaked FeedParserDict.has_key to return True if asking
  2515. # about a mapped key
  2516. #3.0fc1 - 4/23/2004 - MAP - made results.entries[0].links[0] and
  2517. # results.entries[0].enclosures[0] into FeedParserDict; fixed typo that could
  2518. # cause the same encoding to be tried twice (even if it failed the first time);
  2519. # fixed DOCTYPE stripping when DOCTYPE contained entity declarations;
  2520. # better textinput and image tracking in illformed RSS 1.0 feeds
  2521. #3.0fc2 - 5/10/2004 - MAP - added and passed Sam's amp tests; added and passed
  2522. # my blink tag tests
  2523. #3.0fc3 - 6/18/2004 - MAP - fixed bug in _changeEncodingDeclaration that
  2524. # failed to parse utf-16 encoded feeds; made source into a FeedParserDict;
  2525. # duplicate admin:generatorAgent/@rdf:resource in generator_detail.url;
  2526. # added support for image; refactored parse() fallback logic to try other
  2527. # encodings if SAX parsing fails (previously it would only try other encodings
  2528. # if re-encoding failed); remove unichr madness in normalize_attrs now that
  2529. # we're properly tracking encoding in and out of BaseHTMLProcessor; set
  2530. # feed.language from root-level xml:lang; set entry.id from rdf:about;
  2531. # send Accept header
  2532. #3.0 - 6/21/2004 - MAP - don't try iso-8859-1 (can't distinguish between
  2533. # iso-8859-1 and windows-1252 anyway, and most incorrectly marked feeds are
  2534. # windows-1252); fixed regression that could cause the same encoding to be
  2535. # tried twice (even if it failed the first time)
  2536. #3.0.1 - 6/22/2004 - MAP - default to us-ascii for all text/* content types;
  2537. # recover from malformed content-type header parameter with no equals sign
  2538. # ('text/xml; charset:iso-8859-1')
  2539. #3.1 - 6/28/2004 - MAP - added and passed tests for converting HTML entities
  2540. # to Unicode equivalents in illformed feeds (aaronsw); added and
  2541. # passed tests for converting character entities to Unicode equivalents
  2542. # in illformed feeds (aaronsw); test for valid parsers when setting
  2543. # XML_AVAILABLE; make version and encoding available when server returns
  2544. # a 304; add handlers parameter to pass arbitrary urllib2 handlers (like
  2545. # digest auth or proxy support); add code to parse username/password
  2546. # out of url and send as basic authentication; expose downloading-related
  2547. # exceptions in bozo_exception (aaronsw); added __contains__ method to
  2548. # FeedParserDict (aaronsw); added publisher_detail (aaronsw)
  2549. #3.2 - 7/3/2004 - MAP - use cjkcodecs and iconv_codec if available; always
  2550. # convert feed to UTF-8 before passing to XML parser; completely revamped
  2551. # logic for determining character encoding and attempting XML parsing
  2552. # (much faster); increased default timeout to 20 seconds; test for presence
  2553. # of Location header on redirects; added tests for many alternate character
  2554. # encodings; support various EBCDIC encodings; support UTF-16BE and
  2555. # UTF16-LE with or without a BOM; support UTF-8 with a BOM; support
  2556. # UTF-32BE and UTF-32LE with or without a BOM; fixed crashing bug if no
  2557. # XML parsers are available; added support for 'Content-encoding: deflate';
  2558. # send blank 'Accept-encoding: ' header if neither gzip nor zlib modules
  2559. # are available
  2560. #3.3 - 7/15/2004 - MAP - optimize EBCDIC to ASCII conversion; fix obscure
  2561. # problem tracking xml:base and xml:lang if element declares it, child
  2562. # doesn't, first grandchild redeclares it, and second grandchild doesn't;
  2563. # refactored date parsing; defined public registerDateHandler so callers
  2564. # can add support for additional date formats at runtime; added support
  2565. # for OnBlog, Nate, MSSQL, Greek, and Hungarian dates (ytrewq1); added
  2566. # zopeCompatibilityHack() which turns FeedParserDict into a regular
  2567. # dictionary, required for Zope compatibility, and also makes command-
  2568. # line debugging easier because pprint module formats real dictionaries
  2569. # better than dictionary-like objects; added NonXMLContentType exception,
  2570. # which is stored in bozo_exception when a feed is served with a non-XML
  2571. # media type such as 'text/plain'; respect Content-Language as default
  2572. # language if not xml:lang is present; cloud dict is now FeedParserDict;
  2573. # generator dict is now FeedParserDict; better tracking of xml:lang,
  2574. # including support for xml:lang='' to unset the current language;
  2575. # recognize RSS 1.0 feeds even when RSS 1.0 namespace is not the default
  2576. # namespace; don't overwrite final status on redirects (scenarios:
  2577. # redirecting to a URL that returns 304, redirecting to a URL that
  2578. # redirects to another URL with a different type of redirect); add
  2579. # support for HTTP 303 redirects
  2580. #4.0 - MAP - support for relative URIs in xml:base attribute; fixed
  2581. # encoding issue with mxTidy (phopkins); preliminary support for RFC 3229;
  2582. # support for Atom 1.0; support for iTunes extensions; new 'tags' for
  2583. # categories/keywords/etc. as array of dict
  2584. # {'term': term, 'scheme': scheme, 'label': label} to match Atom 1.0
  2585. # terminology; parse RFC 822-style dates with no time; lots of other
  2586. # bug fixes
  2587. #4.1 - MAP - removed socket timeout; added support for chardet library
  2588. # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: