PageRenderTime 83ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/feedparser.py

https://bitbucket.org/jespern/cx
Python | 3687 lines | 3466 code | 83 blank | 138 comment | 204 complexity | 5a92a2cf4b2970a80bdb0ef15777ae7b 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.2-pre-" + "$Revision: 285 $"[11:14] + "-svn"
  11. __license__ = """Copyright (c) 2002-2008, 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. "Sam Ruby <http://intertwingly.net/>"]
  37. _debug = 0
  38. # HTTP "User-Agent" header to send to servers when downloading feeds.
  39. # If you are embedding feedparser in a larger application, you should
  40. # change this to your application name and URL.
  41. USER_AGENT = "UniversalFeedParser/%s +http://feedparser.org/" % __version__
  42. # HTTP "Accept" header to send to servers when downloading feeds. If you don't
  43. # want to send an Accept header, set this to None.
  44. 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"
  45. # List of preferred XML parsers, by SAX driver name. These will be tried first,
  46. # but if they're not installed, Python will keep searching through its own list
  47. # of pre-installed parsers until it finds one that supports everything we need.
  48. PREFERRED_XML_PARSERS = ["drv_libxml2"]
  49. # If you want feedparser to automatically run HTML markup through HTML Tidy, set
  50. # this to 1. Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html>
  51. # or utidylib <http://utidylib.berlios.de/>.
  52. TIDY_MARKUP = 0
  53. # List of Python interfaces for HTML Tidy, in order of preference. Only useful
  54. # if TIDY_MARKUP = 1
  55. PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"]
  56. # If you want feedparser to automatically resolve all relative URIs, set this
  57. # to 1.
  58. RESOLVE_RELATIVE_URIS = 1
  59. # If you want feedparser to automatically sanitize all potentially unsafe
  60. # HTML content, set this to 1.
  61. SANITIZE_HTML = 1
  62. # ---------- required modules (should come with any Python distribution) ----------
  63. import sgmllib, re, sys, copy, urlparse, time, rfc822, types, cgi, urllib, urllib2
  64. try:
  65. from cStringIO import StringIO as _StringIO
  66. except:
  67. from StringIO import StringIO as _StringIO
  68. # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
  69. # gzip is included with most Python distributions, but may not be available if you compiled your own
  70. try:
  71. import gzip
  72. except:
  73. gzip = None
  74. try:
  75. import zlib
  76. except:
  77. zlib = None
  78. # If a real XML parser is available, feedparser will attempt to use it. feedparser has
  79. # been tested with the built-in SAX parser, PyXML, and libxml2. On platforms where the
  80. # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
  81. # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
  82. try:
  83. import xml.sax
  84. xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
  85. from xml.sax.saxutils import escape as _xmlescape
  86. _XML_AVAILABLE = 1
  87. except:
  88. _XML_AVAILABLE = 0
  89. def _xmlescape(data,entities={}):
  90. data = data.replace('&', '&amp;')
  91. data = data.replace('>', '&gt;')
  92. data = data.replace('<', '&lt;')
  93. for char, entity in entities:
  94. data = data.replace(char, entity)
  95. return data
  96. # base64 support for Atom feeds that contain embedded binary data
  97. try:
  98. import base64, binascii
  99. except:
  100. base64 = binascii = None
  101. # cjkcodecs and iconv_codec provide support for more character encodings.
  102. # Both are available from http://cjkpython.i18n.org/
  103. try:
  104. import cjkcodecs.aliases
  105. except:
  106. pass
  107. try:
  108. import iconv_codec
  109. except:
  110. pass
  111. # chardet library auto-detects character encodings
  112. # Download from http://chardet.feedparser.org/
  113. try:
  114. import chardet
  115. if _debug:
  116. import chardet.constants
  117. chardet.constants._debug = 1
  118. except:
  119. chardet = None
  120. # reversable htmlentitydefs mappings for Python 2.2
  121. try:
  122. from htmlentitydefs import name2codepoint, codepoint2name
  123. except:
  124. import htmlentitydefs
  125. name2codepoint={}
  126. codepoint2name={}
  127. for (name,codepoint) in htmlentitydefs.entitydefs.iteritems():
  128. if codepoint.startswith('&#'): codepoint=unichr(int(codepoint[2:-1]))
  129. name2codepoint[name]=ord(codepoint)
  130. codepoint2name[ord(codepoint)]=name
  131. # BeautifulSoup parser used for parsing microformats from embedded HTML content
  132. # http://www.crummy.com/software/BeautifulSoup/
  133. # feedparser is tested with BeautifulSoup 3.0.x, but it might work with the
  134. # older 2.x series. If it doesn't, and you can figure out why, I'll accept a
  135. # patch and modify the compatibility statement accordingly.
  136. try:
  137. import BeautifulSoup
  138. except:
  139. BeautifulSoup = None
  140. # ---------- don't touch these ----------
  141. class ThingsNobodyCaresAboutButMe(Exception): pass
  142. class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
  143. class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
  144. class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
  145. class UndeclaredNamespace(Exception): pass
  146. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  147. sgmllib.special = re.compile('<!')
  148. sgmllib.charref = re.compile('&#(\d+|x[0-9a-fA-F]+);')
  149. if sgmllib.endbracket.search(' <').start(0):
  150. class EndBracketMatch:
  151. endbracket = re.compile('''([^'"<>]|"[^"]*"(?=>|/|\s|\w+=)|'[^']*'(?=>|/|\s|\w+=))*(?=[<>])|.*?(?=[<>])''')
  152. def search(self,string,index=0):
  153. self.match = self.endbracket.match(string,index)
  154. if self.match: return self
  155. def start(self,n):
  156. return self.match.end(n)
  157. sgmllib.endbracket = EndBracketMatch()
  158. SUPPORTED_VERSIONS = {'': 'unknown',
  159. 'rss090': 'RSS 0.90',
  160. 'rss091n': 'RSS 0.91 (Netscape)',
  161. 'rss091u': 'RSS 0.91 (Userland)',
  162. 'rss092': 'RSS 0.92',
  163. 'rss093': 'RSS 0.93',
  164. 'rss094': 'RSS 0.94',
  165. 'rss20': 'RSS 2.0',
  166. 'rss10': 'RSS 1.0',
  167. 'rss': 'RSS (unknown version)',
  168. 'atom01': 'Atom 0.1',
  169. 'atom02': 'Atom 0.2',
  170. 'atom03': 'Atom 0.3',
  171. 'atom10': 'Atom 1.0',
  172. 'atom': 'Atom (unknown version)',
  173. 'cdf': 'CDF',
  174. 'hotrss': 'Hot RSS'
  175. }
  176. try:
  177. UserDict = dict
  178. except NameError:
  179. # Python 2.1 does not have dict
  180. from UserDict import UserDict
  181. def dict(aList):
  182. rc = {}
  183. for k, v in aList:
  184. rc[k] = v
  185. return rc
  186. class FeedParserDict(UserDict):
  187. keymap = {'channel': 'feed',
  188. 'items': 'entries',
  189. 'guid': 'id',
  190. 'date': 'updated',
  191. 'date_parsed': 'updated_parsed',
  192. 'description': ['subtitle', 'summary'],
  193. 'url': ['href'],
  194. 'modified': 'updated',
  195. 'modified_parsed': 'updated_parsed',
  196. 'issued': 'published',
  197. 'issued_parsed': 'published_parsed',
  198. 'copyright': 'rights',
  199. 'copyright_detail': 'rights_detail',
  200. 'tagline': 'subtitle',
  201. 'tagline_detail': 'subtitle_detail'}
  202. def __getitem__(self, key):
  203. if key == 'category':
  204. return UserDict.__getitem__(self, 'tags')[0]['term']
  205. if key == 'enclosures':
  206. norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel'])
  207. return [norel(link) for link in UserDict.__getitem__(self, 'links') if link['rel']=='enclosure']
  208. if key == 'license':
  209. for link in UserDict.__getitem__(self, 'links'):
  210. if link['rel']=='license' and link.has_key('href'):
  211. return link['href']
  212. if key == 'categories':
  213. return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
  214. realkey = self.keymap.get(key, key)
  215. if type(realkey) == types.ListType:
  216. for k in realkey:
  217. if UserDict.has_key(self, k):
  218. return UserDict.__getitem__(self, k)
  219. if UserDict.has_key(self, key):
  220. return UserDict.__getitem__(self, key)
  221. return UserDict.__getitem__(self, realkey)
  222. def __setitem__(self, key, value):
  223. for k in self.keymap.keys():
  224. if key == k:
  225. key = self.keymap[k]
  226. if type(key) == types.ListType:
  227. key = key[0]
  228. return UserDict.__setitem__(self, key, value)
  229. def get(self, key, default=None):
  230. if self.has_key(key):
  231. return self[key]
  232. else:
  233. return default
  234. def setdefault(self, key, value):
  235. if not self.has_key(key):
  236. self[key] = value
  237. return self[key]
  238. def has_key(self, key):
  239. try:
  240. return hasattr(self, key) or UserDict.has_key(self, key)
  241. except AttributeError:
  242. return False
  243. def __getattr__(self, key):
  244. try:
  245. return self.__dict__[key]
  246. except KeyError:
  247. pass
  248. try:
  249. assert not key.startswith('_')
  250. return self.__getitem__(key)
  251. except:
  252. raise AttributeError, "object has no attribute '%s'" % key
  253. def __setattr__(self, key, value):
  254. if key.startswith('_') or key == 'data':
  255. self.__dict__[key] = value
  256. else:
  257. return self.__setitem__(key, value)
  258. def __contains__(self, key):
  259. return self.has_key(key)
  260. def zopeCompatibilityHack():
  261. global FeedParserDict
  262. del FeedParserDict
  263. def FeedParserDict(aDict=None):
  264. rc = {}
  265. if aDict:
  266. rc.update(aDict)
  267. return rc
  268. _ebcdic_to_ascii_map = None
  269. def _ebcdic_to_ascii(s):
  270. global _ebcdic_to_ascii_map
  271. if not _ebcdic_to_ascii_map:
  272. emap = (
  273. 0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  274. 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  275. 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  276. 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  277. 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  278. 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  279. 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  280. 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  281. 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,201,
  282. 202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
  283. 209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
  284. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
  285. 123,65,66,67,68,69,70,71,72,73,232,233,234,235,236,237,
  286. 125,74,75,76,77,78,79,80,81,82,238,239,240,241,242,243,
  287. 92,159,83,84,85,86,87,88,89,90,244,245,246,247,248,249,
  288. 48,49,50,51,52,53,54,55,56,57,250,251,252,253,254,255
  289. )
  290. import string
  291. _ebcdic_to_ascii_map = string.maketrans( \
  292. ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  293. return s.translate(_ebcdic_to_ascii_map)
  294. _cp1252 = {
  295. unichr(128): unichr(8364), # euro sign
  296. unichr(130): unichr(8218), # single low-9 quotation mark
  297. unichr(131): unichr( 402), # latin small letter f with hook
  298. unichr(132): unichr(8222), # double low-9 quotation mark
  299. unichr(133): unichr(8230), # horizontal ellipsis
  300. unichr(134): unichr(8224), # dagger
  301. unichr(135): unichr(8225), # double dagger
  302. unichr(136): unichr( 710), # modifier letter circumflex accent
  303. unichr(137): unichr(8240), # per mille sign
  304. unichr(138): unichr( 352), # latin capital letter s with caron
  305. unichr(139): unichr(8249), # single left-pointing angle quotation mark
  306. unichr(140): unichr( 338), # latin capital ligature oe
  307. unichr(142): unichr( 381), # latin capital letter z with caron
  308. unichr(145): unichr(8216), # left single quotation mark
  309. unichr(146): unichr(8217), # right single quotation mark
  310. unichr(147): unichr(8220), # left double quotation mark
  311. unichr(148): unichr(8221), # right double quotation mark
  312. unichr(149): unichr(8226), # bullet
  313. unichr(150): unichr(8211), # en dash
  314. unichr(151): unichr(8212), # em dash
  315. unichr(152): unichr( 732), # small tilde
  316. unichr(153): unichr(8482), # trade mark sign
  317. unichr(154): unichr( 353), # latin small letter s with caron
  318. unichr(155): unichr(8250), # single right-pointing angle quotation mark
  319. unichr(156): unichr( 339), # latin small ligature oe
  320. unichr(158): unichr( 382), # latin small letter z with caron
  321. unichr(159): unichr( 376)} # latin capital letter y with diaeresis
  322. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  323. def _urljoin(base, uri):
  324. uri = _urifixer.sub(r'\1\3', uri)
  325. try:
  326. return urlparse.urljoin(base, uri)
  327. except:
  328. uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)])
  329. return urlparse.urljoin(base, uri)
  330. class _FeedParserMixin:
  331. namespaces = {'': '',
  332. 'http://backend.userland.com/rss': '',
  333. 'http://blogs.law.harvard.edu/tech/rss': '',
  334. 'http://purl.org/rss/1.0/': '',
  335. 'http://my.netscape.com/rdf/simple/0.9/': '',
  336. 'http://example.com/newformat#': '',
  337. 'http://example.com/necho': '',
  338. 'http://purl.org/echo/': '',
  339. 'uri/of/echo/namespace#': '',
  340. 'http://purl.org/pie/': '',
  341. 'http://purl.org/atom/ns#': '',
  342. 'http://www.w3.org/2005/Atom': '',
  343. 'http://purl.org/rss/1.0/modules/rss091#': '',
  344. 'http://webns.net/mvcb/': 'admin',
  345. 'http://purl.org/rss/1.0/modules/aggregation/': 'ag',
  346. 'http://purl.org/rss/1.0/modules/annotate/': 'annotate',
  347. 'http://media.tangent.org/rss/1.0/': 'audio',
  348. 'http://backend.userland.com/blogChannelModule': 'blogChannel',
  349. 'http://web.resource.org/cc/': 'cc',
  350. 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  351. 'http://purl.org/rss/1.0/modules/company': 'co',
  352. 'http://purl.org/rss/1.0/modules/content/': 'content',
  353. 'http://my.theinfo.org/changed/1.0/rss/': 'cp',
  354. 'http://purl.org/dc/elements/1.1/': 'dc',
  355. 'http://purl.org/dc/terms/': 'dcterms',
  356. 'http://purl.org/rss/1.0/modules/email/': 'email',
  357. 'http://purl.org/rss/1.0/modules/event/': 'ev',
  358. 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner',
  359. 'http://freshmeat.net/rss/fm/': 'fm',
  360. 'http://xmlns.com/foaf/0.1/': 'foaf',
  361. 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo',
  362. 'http://postneo.com/icbm/': 'icbm',
  363. 'http://purl.org/rss/1.0/modules/image/': 'image',
  364. 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes',
  365. 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes',
  366. 'http://purl.org/rss/1.0/modules/link/': 'l',
  367. 'http://search.yahoo.com/mrss': 'media',
  368. 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  369. 'http://prismstandard.org/namespaces/1.2/basic/': 'prism',
  370. 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf',
  371. 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs',
  372. 'http://purl.org/rss/1.0/modules/reference/': 'ref',
  373. 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv',
  374. 'http://purl.org/rss/1.0/modules/search/': 'search',
  375. 'http://purl.org/rss/1.0/modules/slash/': 'slash',
  376. 'http://schemas.xmlsoap.org/soap/envelope/': 'soap',
  377. 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss',
  378. 'http://hacks.benhammersley.com/rss/streaming/': 'str',
  379. 'http://purl.org/rss/1.0/modules/subscription/': 'sub',
  380. 'http://purl.org/rss/1.0/modules/syndication/': 'sy',
  381. 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf',
  382. 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo',
  383. 'http://purl.org/rss/1.0/modules/threading/': 'thr',
  384. 'http://purl.org/rss/1.0/modules/textinput/': 'ti',
  385. 'http://madskills.com/public/xml/rss/module/trackback/':'trackback',
  386. 'http://wellformedweb.org/commentAPI/': 'wfw',
  387. 'http://purl.org/rss/1.0/modules/wiki/': 'wiki',
  388. 'http://www.w3.org/1999/xhtml': 'xhtml',
  389. 'http://www.w3.org/1999/xlink': 'xlink',
  390. 'http://www.w3.org/XML/1998/namespace': 'xml'
  391. }
  392. _matchnamespaces = {}
  393. can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'icon', 'logo']
  394. can_contain_relative_uris = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  395. can_contain_dangerous_markup = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  396. html_types = ['text/html', 'application/xhtml+xml']
  397. def __init__(self, baseuri=None, baselang=None, encoding='utf-8'):
  398. if _debug: sys.stderr.write('initializing FeedParser\n')
  399. if not self._matchnamespaces:
  400. for k, v in self.namespaces.items():
  401. self._matchnamespaces[k.lower()] = v
  402. self.feeddata = FeedParserDict() # feed-level data
  403. self.encoding = encoding # character encoding
  404. self.entries = [] # list of entry-level data
  405. self.version = '' # feed type/version, see SUPPORTED_VERSIONS
  406. self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  407. # the following are used internally to track state;
  408. # this is really out of control and should be refactored
  409. self.infeed = 0
  410. self.inentry = 0
  411. self.incontent = 0
  412. self.intextinput = 0
  413. self.inimage = 0
  414. self.inauthor = 0
  415. self.incontributor = 0
  416. self.inpublisher = 0
  417. self.insource = 0
  418. self.sourcedata = FeedParserDict()
  419. self.contentparams = FeedParserDict()
  420. self._summaryKey = None
  421. self.namespacemap = {}
  422. self.elementstack = []
  423. self.basestack = []
  424. self.langstack = []
  425. self.baseuri = baseuri or ''
  426. self.lang = baselang or None
  427. self.svgOK = 0
  428. self.hasTitle = 0
  429. if baselang:
  430. self.feeddata['language'] = baselang.replace('_','-')
  431. def unknown_starttag(self, tag, attrs):
  432. if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs))
  433. # normalize attrs
  434. attrs = [(k.lower(), v) for k, v in attrs]
  435. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  436. # track xml:base and xml:lang
  437. attrsD = dict(attrs)
  438. baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  439. if type(baseuri) != type(u''):
  440. try:
  441. baseuri = unicode(baseuri, self.encoding)
  442. except:
  443. baseuri = unicode(baseuri, 'iso-8859-1')
  444. self.baseuri = _urljoin(self.baseuri, baseuri)
  445. lang = attrsD.get('xml:lang', attrsD.get('lang'))
  446. if lang == '':
  447. # xml:lang could be explicitly set to '', we need to capture that
  448. lang = None
  449. elif lang is None:
  450. # if no xml:lang is specified, use parent lang
  451. lang = self.lang
  452. if lang:
  453. if tag in ('feed', 'rss', 'rdf:RDF'):
  454. self.feeddata['language'] = lang.replace('_','-')
  455. self.lang = lang
  456. self.basestack.append(self.baseuri)
  457. self.langstack.append(lang)
  458. # track namespaces
  459. for prefix, uri in attrs:
  460. if prefix.startswith('xmlns:'):
  461. self.trackNamespace(prefix[6:], uri)
  462. elif prefix == 'xmlns':
  463. self.trackNamespace(None, uri)
  464. # track inline content
  465. if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  466. if tag in ['xhtml:div', 'div']: return # typepad does this 10/2007
  467. # element declared itself as escaped markup, but it isn't really
  468. self.contentparams['type'] = 'application/xhtml+xml'
  469. if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  470. if tag.find(':') <> -1:
  471. prefix, tag = tag.split(':', 1)
  472. namespace = self.namespacesInUse.get(prefix, '')
  473. if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
  474. attrs.append(('xmlns',namespace))
  475. if tag=='svg' and namespace=='http://www.w3.org/2000/svg':
  476. attrs.append(('xmlns',namespace))
  477. if tag == 'svg': self.svgOK = 1
  478. return self.handle_data('<%s%s>' % (tag, self.strattrs(attrs)), escape=0)
  479. # match namespaces
  480. if tag.find(':') <> -1:
  481. prefix, suffix = tag.split(':', 1)
  482. else:
  483. prefix, suffix = '', tag
  484. prefix = self.namespacemap.get(prefix, prefix)
  485. if prefix:
  486. prefix = prefix + '_'
  487. # special hack for better tracking of empty textinput/image elements in illformed feeds
  488. if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  489. self.intextinput = 0
  490. if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  491. self.inimage = 0
  492. # call special handler (if defined) or default handler
  493. methodname = '_start_' + prefix + suffix
  494. try:
  495. method = getattr(self, methodname)
  496. return method(attrsD)
  497. except AttributeError:
  498. return self.push(prefix + suffix, 1)
  499. def unknown_endtag(self, tag):
  500. if _debug: sys.stderr.write('end %s\n' % tag)
  501. # match namespaces
  502. if tag.find(':') <> -1:
  503. prefix, suffix = tag.split(':', 1)
  504. else:
  505. prefix, suffix = '', tag
  506. prefix = self.namespacemap.get(prefix, prefix)
  507. if prefix:
  508. prefix = prefix + '_'
  509. if suffix == 'svg': self.svgOK = 0
  510. # call special handler (if defined) or default handler
  511. methodname = '_end_' + prefix + suffix
  512. try:
  513. if self.svgOK: raise AttributeError()
  514. method = getattr(self, methodname)
  515. method()
  516. except AttributeError:
  517. self.pop(prefix + suffix)
  518. # track inline content
  519. if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  520. # element declared itself as escaped markup, but it isn't really
  521. if tag in ['xhtml:div', 'div']: return # typepad does this 10/2007
  522. self.contentparams['type'] = 'application/xhtml+xml'
  523. if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  524. tag = tag.split(':')[-1]
  525. self.handle_data('</%s>' % tag, escape=0)
  526. # track xml:base and xml:lang going out of scope
  527. if self.basestack:
  528. self.basestack.pop()
  529. if self.basestack and self.basestack[-1]:
  530. self.baseuri = self.basestack[-1]
  531. if self.langstack:
  532. self.langstack.pop()
  533. if self.langstack: # and (self.langstack[-1] is not None):
  534. self.lang = self.langstack[-1]
  535. def handle_charref(self, ref):
  536. # called for each character reference, e.g. for '&#160;', ref will be '160'
  537. if not self.elementstack: return
  538. ref = ref.lower()
  539. if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  540. text = '&#%s;' % ref
  541. else:
  542. if ref[0] == 'x':
  543. c = int(ref[1:], 16)
  544. else:
  545. c = int(ref)
  546. text = unichr(c).encode('utf-8')
  547. self.elementstack[-1][2].append(text)
  548. def handle_entityref(self, ref):
  549. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  550. if not self.elementstack: return
  551. if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref)
  552. if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  553. text = '&%s;' % ref
  554. elif ref in self.entities.keys():
  555. text = self.entities[ref]
  556. if text.startswith('&#') and text.endswith(';'):
  557. return self.handle_entityref(text)
  558. else:
  559. try: name2codepoint[ref]
  560. except KeyError: text = '&%s;' % ref
  561. else: text = unichr(name2codepoint[ref]).encode('utf-8')
  562. self.elementstack[-1][2].append(text)
  563. def handle_data(self, text, escape=1):
  564. # called for each block of plain text, i.e. outside of any tag and
  565. # not containing any character or entity references
  566. if not self.elementstack: return
  567. if escape and self.contentparams.get('type') == 'application/xhtml+xml':
  568. text = _xmlescape(text)
  569. self.elementstack[-1][2].append(text)
  570. def handle_comment(self, text):
  571. # called for each comment, e.g. <!-- insert message here -->
  572. pass
  573. def handle_pi(self, text):
  574. # called for each processing instruction, e.g. <?instruction>
  575. pass
  576. def handle_decl(self, text):
  577. pass
  578. def parse_declaration(self, i):
  579. # override internal declaration handler to handle CDATA blocks
  580. if _debug: sys.stderr.write('entering parse_declaration\n')
  581. if self.rawdata[i:i+9] == '<![CDATA[':
  582. k = self.rawdata.find(']]>', i)
  583. if k == -1: k = len(self.rawdata)
  584. self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  585. return k+3
  586. else:
  587. k = self.rawdata.find('>', i)
  588. return k+1
  589. def mapContentType(self, contentType):
  590. contentType = contentType.lower()
  591. if contentType == 'text':
  592. contentType = 'text/plain'
  593. elif contentType == 'html':
  594. contentType = 'text/html'
  595. elif contentType == 'xhtml':
  596. contentType = 'application/xhtml+xml'
  597. return contentType
  598. def trackNamespace(self, prefix, uri):
  599. loweruri = uri.lower()
  600. if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version:
  601. self.version = 'rss090'
  602. if loweruri == 'http://purl.org/rss/1.0/' and not self.version:
  603. self.version = 'rss10'
  604. if loweruri == 'http://www.w3.org/2005/atom' and not self.version:
  605. self.version = 'atom10'
  606. if loweruri.find('backend.userland.com/rss') <> -1:
  607. # match any backend.userland.com namespace
  608. uri = 'http://backend.userland.com/rss'
  609. loweruri = uri
  610. if self._matchnamespaces.has_key(loweruri):
  611. self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  612. self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  613. else:
  614. self.namespacesInUse[prefix or ''] = uri
  615. def resolveURI(self, uri):
  616. return _urljoin(self.baseuri or '', uri)
  617. def decodeEntities(self, element, data):
  618. return data
  619. def strattrs(self, attrs):
  620. return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'&quot;'})) for t in attrs])
  621. def push(self, element, expectingText):
  622. self.elementstack.append([element, expectingText, []])
  623. def pop(self, element, stripWhitespace=1):
  624. if not self.elementstack: return
  625. if self.elementstack[-1][0] != element: return
  626. element, expectingText, pieces = self.elementstack.pop()
  627. if self.version == 'atom10' and self.contentparams.get('type','text') == 'application/xhtml+xml':
  628. # remove enclosing child element, but only if it is a <div> and
  629. # only if all the remaining content is nested underneath it.
  630. # This means that the divs would be retained in the following:
  631. # <div>foo</div><div>bar</div>
  632. while pieces and len(pieces)>1 and not pieces[-1].strip():
  633. del pieces[-1]
  634. while pieces and len(pieces)>1 and not pieces[0].strip():
  635. del pieces[0]
  636. if pieces and (pieces[0] == '<div>' or pieces[0].startswith('<div ')) and pieces[-1]=='</div>':
  637. depth = 0
  638. for piece in pieces[:-1]:
  639. if piece.startswith('</'):
  640. depth -= 1
  641. if depth == 0: break
  642. elif piece.startswith('<') and not piece.endswith('/>'):
  643. depth += 1
  644. else:
  645. pieces = pieces[1:-1]
  646. output = ''.join(pieces)
  647. if stripWhitespace:
  648. output = output.strip()
  649. if not expectingText: return output
  650. # decode base64 content
  651. if base64 and self.contentparams.get('base64', 0):
  652. try:
  653. output = base64.decodestring(output)
  654. except binascii.Error:
  655. pass
  656. except binascii.Incomplete:
  657. pass
  658. # resolve relative URIs
  659. if (element in self.can_be_relative_uri) and output:
  660. output = self.resolveURI(output)
  661. # decode entities within embedded markup
  662. if not self.contentparams.get('base64', 0):
  663. output = self.decodeEntities(element, output)
  664. if self.lookslikehtml(output):
  665. self.contentparams['type']='text/html'
  666. # remove temporary cruft from contentparams
  667. try:
  668. del self.contentparams['mode']
  669. except KeyError:
  670. pass
  671. try:
  672. del self.contentparams['base64']
  673. except KeyError:
  674. pass
  675. is_htmlish = self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types
  676. # resolve relative URIs within embedded markup
  677. if is_htmlish and RESOLVE_RELATIVE_URIS:
  678. if element in self.can_contain_relative_uris:
  679. output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', 'text/html'))
  680. # parse microformats
  681. # (must do this before sanitizing because some microformats
  682. # rely on elements that we sanitize)
  683. if is_htmlish and element in ['content', 'description', 'summary']:
  684. mfresults = _parseMicroformats(output, self.baseuri, self.encoding)
  685. if mfresults:
  686. for tag in mfresults.get('tags', []):
  687. self._addTag(tag['term'], tag['scheme'], tag['label'])
  688. for enclosure in mfresults.get('enclosures', []):
  689. self._start_enclosure(enclosure)
  690. for xfn in mfresults.get('xfn', []):
  691. self._addXFN(xfn['relationships'], xfn['href'], xfn['name'])
  692. vcard = mfresults.get('vcard')
  693. if vcard:
  694. self._getContext()['vcard'] = vcard
  695. # sanitize embedded markup
  696. if is_htmlish and SANITIZE_HTML:
  697. if element in self.can_contain_dangerous_markup:
  698. output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', 'text/html'))
  699. if self.encoding and type(output) != type(u''):
  700. try:
  701. output = unicode(output, self.encoding)
  702. except:
  703. pass
  704. # address common error where people take data that is already
  705. # utf-8, presume that it is iso-8859-1, and re-encode it.
  706. if self.encoding=='utf-8' and type(output) == type(u''):
  707. try:
  708. output = unicode(output.encode('iso-8859-1'), 'utf-8')
  709. except:
  710. pass
  711. # map win-1252 extensions to the proper code points
  712. if type(output) == type(u''):
  713. output = u''.join([c in _cp1252.keys() and _cp1252[c] or c for c in output])
  714. # categories/tags/keywords/whatever are handled in _end_category
  715. if element == 'category':
  716. return output
  717. if element == 'title' and self.hasTitle:
  718. return output
  719. # store output in appropriate place(s)
  720. if self.inentry and not self.insource:
  721. if element == 'content':
  722. self.entries[-1].setdefault(element, [])
  723. contentparams = copy.deepcopy(self.contentparams)
  724. contentparams['value'] = output
  725. self.entries[-1][element].append(contentparams)
  726. elif element == 'link':
  727. self.entries[-1][element] = output
  728. if output:
  729. self.entries[-1]['links'][-1]['href'] = output
  730. else:
  731. if element == 'description':
  732. element = 'summary'
  733. self.entries[-1][element] = output
  734. if self.incontent:
  735. contentparams = copy.deepcopy(self.contentparams)
  736. contentparams['value'] = output
  737. self.entries[-1][element + '_detail'] = contentparams
  738. elif (self.infeed or self.insource):# and (not self.intextinput) and (not self.inimage):
  739. context = self._getContext()
  740. if element == 'description':
  741. element = 'subtitle'
  742. context[element] = output
  743. if element == 'link':
  744. context['links'][-1]['href'] = output
  745. elif self.incontent:
  746. contentparams = copy.deepcopy(self.contentparams)
  747. contentparams['value'] = output
  748. context[element + '_detail'] = contentparams
  749. return output
  750. def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  751. self.incontent += 1
  752. if self.lang: self.lang=self.lang.replace('_','-')
  753. self.contentparams = FeedParserDict({
  754. 'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  755. 'language': self.lang,
  756. 'base': self.baseuri})
  757. self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  758. self.push(tag, expectingText)
  759. def popContent(self, tag):
  760. value = self.pop(tag)
  761. self.incontent -= 1
  762. self.contentparams.clear()
  763. return value
  764. # a number of elements in a number of RSS variants are nominally plain
  765. # text, but this is routinely ignored. This is an attempt to detect
  766. # the most common cases. As false positives often result in silent
  767. # data loss, this function errs on the conservative side.
  768. def lookslikehtml(self, str):
  769. if self.version.startswith('atom'): return
  770. if self.contentparams.get('type','text/html') != 'text/plain': return
  771. # must have a close tag or a entity reference to qualify
  772. if not (re.search(r'</(\w+)>',str) or re.search("&#?\w+;",str)): return
  773. # all tags must be in a restricted subset of valid HTML tags
  774. if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements,
  775. re.findall(r'</?(\w+)',str)): return
  776. # all entities must have been defined as valid HTML entities
  777. from htmlentitydefs import entitydefs
  778. if filter(lambda e: e not in entitydefs.keys(),
  779. re.findall(r'&(\w+);',str)): return
  780. return 1
  781. def _mapToStandardPrefix(self, name):
  782. colonpos = name.find(':')
  783. if colonpos <> -1:
  784. prefix = name[:colonpos]
  785. suffix = name[colonpos+1:]
  786. prefix = self.namespacemap.get(prefix, prefix)
  787. name = prefix + ':' + suffix
  788. return name
  789. def _getAttribute(self, attrsD, name):
  790. return attrsD.get(self._mapToStandardPrefix(name))
  791. def _isBase64(self, attrsD, contentparams):
  792. if attrsD.get('mode', '') == 'base64':
  793. return 1
  794. if self.contentparams['type'].startswith('text/'):
  795. return 0
  796. if self.contentparams['type'].endswith('+xml'):
  797. return 0
  798. if self.contentparams['type'].endswith('/xml'):
  799. return 0
  800. return 1
  801. def _itsAnHrefDamnIt(self, attrsD):
  802. href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  803. if href:
  804. try:
  805. del attrsD['url']
  806. except KeyError:
  807. pass
  808. try:
  809. del attrsD['uri']
  810. except KeyError:
  811. pass
  812. attrsD['href'] = href
  813. return attrsD
  814. def _save(self, key, value):
  815. context = self._getContext()
  816. context.setdefault(key, value)
  817. def _start_rss(self, attrsD):
  818. versionmap = {'0.91': 'rss091u',
  819. '0.92': 'rss092',
  820. '0.93': 'rss093',
  821. '0.94': 'rss094'}
  822. if not self.version:
  823. attr_version = attrsD.get('version', '')
  824. version = versionmap.get(attr_version)
  825. if version:
  826. self.version = version
  827. elif attr_version.startswith('2.'):
  828. self.version = 'rss20'
  829. else:
  830. self.version = 'rss'
  831. def _start_dlhottitles(self, attrsD):
  832. self.version = 'hotrss'
  833. def _start_channel(self, attrsD):
  834. self.infeed = 1
  835. self._cdf_common(attrsD)
  836. _start_feedinfo = _start_channel
  837. def _cdf_common(self, attrsD):
  838. if attrsD.has_key('lastmod'):
  839. self._start_modified({})
  840. self.elementstack[-1][-1] = attrsD['lastmod']
  841. self._end_modified()
  842. if attrsD.has_key('href'):
  843. self._start_link({})
  844. self.elementstack[-1][-1] = attrsD['href']
  845. self._end_link()
  846. def _start_feed(self, attrsD):
  847. self.infeed = 1
  848. versionmap = {'0.1': 'atom01',
  849. '0.2': 'atom02',
  850. '0.3': 'atom03'}
  851. if not self.version:
  852. attr_version = attrsD.get('version')
  853. version = versionmap.get(attr_version)
  854. if version:
  855. self.version = version
  856. else:
  857. self.version = 'atom'
  858. def _end_channel(self):
  859. self.infeed = 0
  860. _end_feed = _end_channel
  861. def _start_image(self, attrsD):
  862. context = self._getContext()
  863. context.setdefault('image', FeedParserDict())
  864. self.inimage = 1
  865. self.hasTitle = 0
  866. self.push('image', 0)
  867. def _end_image(self):
  868. self.pop('image')
  869. self.inimage = 0
  870. def _start_textinput(self, attrsD):
  871. context = self._getContext()
  872. context.setdefault('textinput', FeedParserDict())
  873. self.intextinput = 1
  874. self.hasTitle = 0
  875. self.push('textinput', 0)
  876. _start_textInput = _start_textinput
  877. def _end_textinput(self):
  878. self.pop('textinput')
  879. self.intextinput = 0
  880. _end_textInput = _end_textinput
  881. def _start_author(self, attrsD):
  882. self.inauthor = 1
  883. self.push('author', 1)
  884. _start_managingeditor = _start_author
  885. _start_dc_author = _start_author
  886. _start_dc_creator = _start_author
  887. _start_itunes_author = _start_author
  888. def _end_author(self):
  889. self.pop('author')
  890. self.inauthor = 0
  891. self._sync_author_detail()
  892. _end_managingeditor = _end_author
  893. _end_dc_author = _end_author
  894. _end_dc_creator = _end_author
  895. _end_itunes_author = _end_author
  896. def _start_itunes_owner(self, attrsD):
  897. self.inpublisher = 1
  898. self.push('publisher', 0)
  899. def _end_itunes_owner(self):
  900. self.pop('publisher')
  901. self.inpublisher = 0
  902. self._sync_author_detail('publisher')
  903. def _start_contributor(self, attrsD):
  904. self.incontributor = 1
  905. context = self._getContext()
  906. context.setdefault('contributors', [])
  907. context['contributors'].append(FeedParserDict())
  908. self.push('contributor', 0)
  909. def _end_contributor(self):
  910. self.pop('contributor')
  911. self.incontributor = 0
  912. def _start_dc_contributor(self, attrsD):
  913. self.incontributor = 1
  914. context = self._getContext()
  915. context.setdefault('contributors', [])
  916. context['contributors'].append(FeedParserDict())
  917. self.push('name', 0)
  918. def _end_dc_contributor(self):
  919. self._end_name()
  920. self.incontributor = 0
  921. def _start_name(self, attrsD):
  922. self.push('name', 0)
  923. _start_itunes_name = _start_name
  924. def _end_name(self):
  925. value = self.pop('name')
  926. if self.inpublisher:
  927. self._save_author('name', value, 'publisher')
  928. elif self.inauthor:
  929. self._save_author('name', value)
  930. elif self.incontributor:
  931. self._save_contributor('name', value)
  932. elif self.intextinput:
  933. context = self._getContext()
  934. context['name'] = value
  935. _end_itunes_name = _end_name
  936. def _start_width(self, attrsD):
  937. self.push('width', 0)
  938. def _end_width(self):
  939. value = self.pop('width')
  940. try:
  941. value = int(value)
  942. except:
  943. value = 0
  944. if self.inimage:
  945. context = self._getContext()
  946. context['width'] = value
  947. def _start_height(self, attrsD):
  948. self.push('height', 0)
  949. def _end_height(self):
  950. value = self.pop('height')
  951. try:
  952. value = int(value)
  953. except:
  954. value = 0
  955. if self.inimage:
  956. context = self._getContext()
  957. context['height'] = value
  958. def _start_url(self, attrsD):
  959. self.push('href', 1)
  960. _start_homepage = _start_url
  961. _start_uri = _start_url
  962. def _end_url(self):
  963. value = self.pop('href')
  964. if self.inauthor:
  965. self._save_author('href', value)
  966. elif self.incontributor:
  967. self._save_contributor('href', value)
  968. _end_homepage = _end_url
  969. _end_uri = _end_url
  970. def _start_email(self, attrsD):
  971. self.push('email', 0)
  972. _start_itunes_email = _start_email
  973. def _end_email(self):
  974. value = self.pop('email')
  975. if self.inpublisher:
  976. self._save_author('email', value, 'publisher')
  977. elif self.inauthor:
  978. self._save_author('email', value)
  979. elif self.incontributor:
  980. self._save_contributor('email', value)
  981. _end_itunes_email = _end_email
  982. def _getContext(self):
  983. if self.insource:
  984. context = self.sourcedata
  985. elif self.inimage:
  986. context = self.feeddata['image']
  987. elif self.intextinput:
  988. context = self.feeddata['textinput']
  989. elif self.inentry:
  990. context = self.entries[-1]
  991. else:
  992. context = self.feeddata
  993. return context
  994. def _save_author(self, key, value, prefix='author'):
  995. context = self._getContext()
  996. context.setdefault(prefix + '_detail', FeedParserDict())
  997. context[prefix + '_detail'][key] = value
  998. self._sync_author_detail()
  999. def _save_contributor(self, key, value):
  1000. context = self._getContext()
  1001. context.setdefault('contributors', [FeedParserDict()])
  1002. context['contributors'][-1][key] = value
  1003. def _sync_author_detail(self, key='author'):
  1004. context = self._getContext()
  1005. detail = context.get('%s_detail' % key)
  1006. if detail:
  1007. name = detail.get('name')
  1008. email = detail.get('email')
  1009. if name and email:
  1010. context[key] = '%s (%s)' % (name, email)
  1011. elif name:
  1012. context[key] = name
  1013. elif email:
  1014. context[key] = email
  1015. else:
  1016. author, email = context.get(key), None
  1017. if not author: return
  1018. 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})(\]?))(\?subject=\S+)?''', author)
  1019. if emailmatch:
  1020. email = emailmatch.group(0)
  1021. # probably a better way to do the following, but it passes all the tests
  1022. author = author.replace(email, '')
  1023. author = author.replace('()', '')
  1024. author = author.replace('<>', '')
  1025. author = author.replace('&lt;&gt;', '')
  1026. author = author.strip()
  1027. if author and (author[0] == '('):
  1028. author = author[1:]
  1029. if author and (author[-1] == ')'):
  1030. author = author[:-1]
  1031. author = author.strip()
  1032. if author or email:
  1033. context.setdefault('%s_detail' % key, FeedParserDict())
  1034. if author:
  1035. context['%s_detail' % key]['name'] = author
  1036. if email:
  1037. context['%s_detail' % key]['email'] = email
  1038. def _start_subtitle(self, attrsD):
  1039. self.pushContent('subtitle', attrsD, 'text/plain', 1)
  1040. _start_tagline = _start_subtitle
  1041. _start_itunes_subtitle = _start_subtitle
  1042. def _end_subtitle(self):
  1043. self.popContent('subtitle')
  1044. _end_tagline = _end_subtitle
  1045. _end_itunes_subtitle = _end_subtitle
  1046. def _start_rights(self, attrsD):
  1047. self.pushContent('rights', attrsD, 'text/plain', 1)
  1048. _start_dc_rights = _start_rights
  1049. _start_copyright = _start_rights
  1050. def _end_rights(self):
  1051. self.popContent('rights')
  1052. _end_dc_rights = _end_rights
  1053. _end_copyright = _end_rights
  1054. def _start_item(self, attrsD):
  1055. self.entries.append(FeedParserDict())
  1056. self.push('item', 0)
  1057. self.inentry = 1
  1058. self.guidislink = 0
  1059. self.hasTitle = 0
  1060. id = self._getAttribute(attrsD, 'rdf:about')
  1061. if id:
  1062. context = self._getContext()
  1063. context['id'] = id
  1064. self._cdf_common(attrsD)
  1065. _start_entry = _start_item
  1066. _start_product = _start_item
  1067. def _end_item(self):
  1068. self.pop('item')
  1069. self.inentry = 0
  1070. _end_entry = _end_item
  1071. def _start_dc_language(self, attrsD):
  1072. self.push('language', 1)
  1073. _start_language = _start_dc_language
  1074. def _end_dc_language(self):
  1075. self.lang = self.pop('language')
  1076. _end_language = _end_dc_language
  1077. def _start_dc_publisher(self, attrsD):
  1078. self.push('publisher', 1)
  1079. _start_webmaster = _start_dc_publisher
  1080. def _end_dc_publisher(self):
  1081. self.pop('publisher')
  1082. self._sync_author_detail('publisher')
  1083. _end_webmaster = _end_dc_publisher
  1084. def _start_published(self, attrsD):
  1085. self.push('published', 1)
  1086. _start_dcterms_issued = _start_published
  1087. _start_issued = _start_published
  1088. def _end_published(self):
  1089. value = self.pop('published')
  1090. self._save('published_parsed', _parse_date(value))
  1091. _end_dcterms_issued = _end_published
  1092. _end_issued = _end_published
  1093. def _start_updated(self, attrsD):
  1094. self.push('updated', 1)
  1095. _start_modified = _start_updated
  1096. _start_dcterms_modified = _start_updated
  1097. _start_pubdate = _start_updated
  1098. _start_dc_date = _start_updated
  1099. def _end_updated(self):
  1100. value = self.pop('updated')
  1101. parsed_value = _parse_date(value)
  1102. self._save('updated_parsed', parsed_value)
  1103. _end_modified = _end_updated
  1104. _end_dcterms_modified = _end_updated
  1105. _end_pubdate = _end_updated
  1106. _end_dc_date = _end_updated
  1107. def _start_created(self, attrsD):
  1108. self.push('created', 1)
  1109. _start_dcterms_created = _start_created
  1110. def _end_created(self):
  1111. value = self.pop('created')
  1112. self._save('created_parsed', _parse_date(value))
  1113. _end_dcterms_created = _end_created
  1114. def _start_expirationdate(self, attrsD):
  1115. self.push('expired', 1)
  1116. def _end_expirationdate(self):
  1117. self._save('expired_parsed', _parse_date(self.pop('expired')))
  1118. def _start_cc_license(self, attrsD):
  1119. context = self._getContext()
  1120. value = self._getAttribute(attrsD, 'rdf:resource')
  1121. attrsD = FeedParserDict()
  1122. attrsD['rel']='license'
  1123. if value: attrsD['href']=value
  1124. context.setdefault('links', []).append(attrsD)
  1125. def _start_creativecommons_license(self, attrsD):
  1126. self.push('license', 1)
  1127. _start_creativeCommons_license = _start_creativecommons_license
  1128. def _end_creativecommons_license(self):
  1129. value = self.pop('license')
  1130. context = self._getContext()
  1131. attrsD = FeedParserDict()
  1132. attrsD['rel']='license'
  1133. if value: attrsD['href']=value
  1134. context.setdefault('links', []).append(attrsD)
  1135. del context['license']
  1136. _end_creativeCommons_license = _end_creativecommons_license
  1137. def _addXFN(self, relationships, href, name):
  1138. context = self._getContext()
  1139. xfn = context.setdefault('xfn', [])
  1140. value = FeedParserDict({'relationships': relationships, 'href': href, 'name': name})
  1141. if value not in xfn:
  1142. xfn.append(value)
  1143. def _addTag(self, term, scheme, label):
  1144. context = self._getContext()
  1145. tags = context.setdefault('tags', [])
  1146. if (not term) and (not scheme) and (not label): return
  1147. value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
  1148. if value not in tags:
  1149. tags.append(value)
  1150. def _start_category(self, attrsD):
  1151. if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD))
  1152. term = attrsD.get('term')
  1153. scheme = attrsD.get('scheme', attrsD.get('domain'))
  1154. label = attrsD.get('label')
  1155. self._addTag(term, scheme, label)
  1156. self.push('category', 1)
  1157. _start_dc_subject = _start_category
  1158. _start_keywords = _start_category
  1159. def _end_itunes_keywords(self):
  1160. for term in self.pop('itunes_keywords').split():
  1161. self._addTag(term, 'http://www.itunes.com/', None)
  1162. def _start_itunes_category(self, attrsD):
  1163. self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
  1164. self.push('category', 1)
  1165. def _end_category(self):
  1166. value = self.pop('category')
  1167. if not value: return
  1168. context = self._getContext()
  1169. tags = context['tags']
  1170. if value and len(tags) and not tags[-1]['term']:
  1171. tags[-1]['term'] = value
  1172. else:
  1173. self._addTag(value, None, None)
  1174. _end_dc_subject = _end_category
  1175. _end_keywords = _end_category
  1176. _end_itunes_category = _end_category
  1177. def _start_cloud(self, attrsD):
  1178. self._getContext()['cloud'] = FeedParserDict(attrsD)
  1179. def _start_link(self, attrsD):
  1180. attrsD.setdefault('rel', 'alternate')
  1181. if attrsD['rel'] == 'self':
  1182. attrsD.setdefault('type', 'application/atom+xml')
  1183. else:
  1184. attrsD.setdefault('type', 'text/html')
  1185. context = self._getContext()
  1186. attrsD = self._itsAnHrefDamnIt(attrsD)
  1187. if attrsD.has_key('href'):
  1188. attrsD['href'] = self.resolveURI(attrsD['href'])
  1189. if attrsD.get('rel')=='enclosure' and not context.get('id'):
  1190. context['id'] = attrsD.get('href')
  1191. expectingText = self.infeed or self.inentry or self.insource
  1192. context.setdefault('links', [])
  1193. context['links'].append(FeedParserDict(attrsD))
  1194. if attrsD.has_key('href'):
  1195. expectingText = 0
  1196. if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
  1197. context['link'] = attrsD['href']
  1198. else:
  1199. self.push('link', expectingText)
  1200. _start_producturl = _start_link
  1201. def _end_link(self):
  1202. value = self.pop('link')
  1203. context = self._getContext()
  1204. _end_producturl = _end_link
  1205. def _start_guid(self, attrsD):
  1206. self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
  1207. self.push('id', 1)
  1208. def _end_guid(self):
  1209. value = self.pop('id')
  1210. self._save('guidislink', self.guidislink and not self._getContext().has_key('link'))
  1211. if self.guidislink:
  1212. # guid acts as link, but only if 'ispermalink' is not present or is 'true',
  1213. # and only if the item doesn't already have a link element
  1214. self._save('link', value)
  1215. def _start_title(self, attrsD):
  1216. if self.svgOK: return self.unknown_starttag('title', attrsD.items())
  1217. self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1218. _start_dc_title = _start_title
  1219. _start_media_title = _start_title
  1220. def _end_title(self):
  1221. if self.svgOK: return
  1222. value = self.popContent('title')
  1223. if not value: return
  1224. context = self._getContext()
  1225. self.hasTitle = 1
  1226. _end_dc_title = _end_title
  1227. def _end_media_title(self):
  1228. hasTitle = self.hasTitle
  1229. self._end_title()
  1230. self.hasTitle = hasTitle
  1231. def _start_description(self, attrsD):
  1232. context = self._getContext()
  1233. if context.has_key('summary'):
  1234. self._summaryKey = 'content'
  1235. self._start_content(attrsD)
  1236. else:
  1237. self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)
  1238. _start_dc_description = _start_description
  1239. def _start_abstract(self, attrsD):
  1240. self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1241. def _end_description(self):
  1242. if self._summaryKey == 'content':
  1243. self._end_content()
  1244. else:
  1245. value = self.popContent('description')
  1246. self._summaryKey = None
  1247. _end_abstract = _end_description
  1248. _end_dc_description = _end_description
  1249. def _start_info(self, attrsD):
  1250. self.pushContent('info', attrsD, 'text/plain', 1)
  1251. _start_feedburner_browserfriendly = _start_info
  1252. def _end_info(self):
  1253. self.popContent('info')
  1254. _end_feedburner_browserfriendly = _end_info
  1255. def _start_generator(self, attrsD):
  1256. if attrsD:
  1257. attrsD = self._itsAnHrefDamnIt(attrsD)
  1258. if attrsD.has_key('href'):
  1259. attrsD['href'] = self.resolveURI(attrsD['href'])
  1260. self._getContext()['generator_detail'] = FeedParserDict(attrsD)
  1261. self.push('generator', 1)
  1262. def _end_generator(self):
  1263. value = self.pop('generator')
  1264. context = self._getContext()
  1265. if context.has_key('generator_detail'):
  1266. context['generator_detail']['name'] = value
  1267. def _start_admin_generatoragent(self, attrsD):
  1268. self.push('generator', 1)
  1269. value = self._getAttribute(attrsD, 'rdf:resource')
  1270. if value:
  1271. self.elementstack[-1][2].append(value)
  1272. self.pop('generator')
  1273. self._getContext()['generator_detail'] = FeedParserDict({'href': value})
  1274. def _start_admin_errorreportsto(self, attrsD):
  1275. self.push('errorreportsto', 1)
  1276. value = self._getAttribute(attrsD, 'rdf:resource')
  1277. if value:
  1278. self.elementstack[-1][2].append(value)
  1279. self.pop('errorreportsto')
  1280. def _start_summary(self, attrsD):
  1281. context = self._getContext()
  1282. if context.has_key('summary'):
  1283. self._summaryKey = 'content'
  1284. self._start_content(attrsD)
  1285. else:
  1286. self._summaryKey = 'summary'
  1287. self.pushContent(self._summaryKey, attrsD, 'text/plain', 1)
  1288. _start_itunes_summary = _start_summary
  1289. def _end_summary(self):
  1290. if self._summaryKey == 'content':
  1291. self._end_content()
  1292. else:
  1293. self.popContent(self._summaryKey or 'summary')
  1294. self._summaryKey = None
  1295. _end_itunes_summary = _end_summary
  1296. def _start_enclosure(self, attrsD):
  1297. attrsD = self._itsAnHrefDamnIt(attrsD)
  1298. context = self._getContext()
  1299. attrsD['rel']='enclosure'
  1300. context.setdefault('links', []).append(FeedParserDict(attrsD))
  1301. href = attrsD.get('href')
  1302. if href and not context.get('id'):
  1303. context['id'] = href
  1304. def _start_source(self, attrsD):
  1305. self.insource = 1
  1306. self.hasTitle = 0
  1307. def _end_source(self):
  1308. self.insource = 0
  1309. self._getContext()['source'] = copy.deepcopy(self.sourcedata)
  1310. self.sourcedata.clear()
  1311. def _start_content(self, attrsD):
  1312. self.pushContent('content', attrsD, 'text/plain', 1)
  1313. src = attrsD.get('src')
  1314. if src:
  1315. self.contentparams['src'] = src
  1316. self.push('content', 1)
  1317. def _start_prodlink(self, attrsD):
  1318. self.pushContent('content', attrsD, 'text/html', 1)
  1319. def _start_body(self, attrsD):
  1320. self.pushContent('content', attrsD, 'application/xhtml+xml', 1)
  1321. _start_xhtml_body = _start_body
  1322. def _start_content_encoded(self, attrsD):
  1323. self.pushContent('content', attrsD, 'text/html', 1)
  1324. _start_fullitem = _start_content_encoded
  1325. def _end_content(self):
  1326. copyToDescription = self.mapContentType(self.contentparams.get('type')) in (['text/plain'] + self.html_types)
  1327. value = self.popContent('content')
  1328. if copyToDescription:
  1329. self._save('description', value)
  1330. _end_body = _end_content
  1331. _end_xhtml_body = _end_content
  1332. _end_content_encoded = _end_content
  1333. _end_fullitem = _end_content
  1334. _end_prodlink = _end_content
  1335. def _start_itunes_image(self, attrsD):
  1336. self.push('itunes_image', 0)
  1337. self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
  1338. _start_itunes_link = _start_itunes_image
  1339. def _end_itunes_block(self):
  1340. value = self.pop('itunes_block', 0)
  1341. self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
  1342. def _end_itunes_explicit(self):
  1343. value = self.pop('itunes_explicit', 0)
  1344. self._getContext()['itunes_explicit'] = (value == 'yes') and 1 or 0
  1345. if _XML_AVAILABLE:
  1346. class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler):
  1347. def __init__(self, baseuri, baselang, encoding):
  1348. if _debug: sys.stderr.write('trying StrictFeedParser\n')
  1349. xml.sax.handler.ContentHandler.__init__(self)
  1350. _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1351. self.bozo = 0
  1352. self.exc = None
  1353. def startPrefixMapping(self, prefix, uri):
  1354. self.trackNamespace(prefix, uri)
  1355. def startElementNS(self, name, qname, attrs):
  1356. namespace, localname = name
  1357. lowernamespace = str(namespace or '').lower()
  1358. if lowernamespace.find('backend.userland.com/rss') <> -1:
  1359. # match any backend.userland.com namespace
  1360. namespace = 'http://backend.userland.com/rss'
  1361. lowernamespace = namespace
  1362. if qname and qname.find(':') > 0:
  1363. givenprefix = qname.split(':')[0]
  1364. else:
  1365. givenprefix = None
  1366. prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1367. if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and not self.namespacesInUse.has_key(givenprefix):
  1368. raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix
  1369. localname = str(localname).lower()
  1370. # qname implementation is horribly broken in Python 2.1 (it
  1371. # doesn't report any), and slightly broken in Python 2.2 (it
  1372. # doesn't report the xml: namespace). So we match up namespaces
  1373. # with a known list first, and then possibly override them with
  1374. # the qnames the SAX parser gives us (if indeed it gives us any
  1375. # at all). Thanks to MatejC for helping me test this and
  1376. # tirelessly telling me that it didn't work yet.
  1377. attrsD = {}
  1378. if localname=='math' and namespace=='http://www.w3.org/1998/Math/MathML':
  1379. attrsD['xmlns']=namespace
  1380. if localname=='svg' and namespace=='http://www.w3.org/2000/svg':
  1381. attrsD['xmlns']=namespace
  1382. if prefix:
  1383. localname = prefix.lower() + ':' + localname
  1384. elif namespace and not qname: #Expat
  1385. for name,value in self.namespacesInUse.items():
  1386. if name and value == namespace:
  1387. localname = name + ':' + localname
  1388. break
  1389. 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))
  1390. for (namespace, attrlocalname), attrvalue in attrs._attrs.items():
  1391. lowernamespace = (namespace or '').lower()
  1392. prefix = self._matchnamespaces.get(lowernamespace, '')
  1393. if prefix:
  1394. attrlocalname = prefix + ':' + attrlocalname
  1395. attrsD[str(attrlocalname).lower()] = attrvalue
  1396. for qname in attrs.getQNames():
  1397. attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
  1398. self.unknown_starttag(localname, attrsD.items())
  1399. def characters(self, text):
  1400. self.handle_data(text)
  1401. def endElementNS(self, name, qname):
  1402. namespace, localname = name
  1403. lowernamespace = str(namespace or '').lower()
  1404. if qname and qname.find(':') > 0:
  1405. givenprefix = qname.split(':')[0]
  1406. else:
  1407. givenprefix = ''
  1408. prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1409. if prefix:
  1410. localname = prefix + ':' + localname
  1411. elif namespace and not qname: #Expat
  1412. for name,value in self.namespacesInUse.items():
  1413. if name and value == namespace:
  1414. localname = name + ':' + localname
  1415. break
  1416. localname = str(localname).lower()
  1417. self.unknown_endtag(localname)
  1418. def error(self, exc):
  1419. self.bozo = 1
  1420. self.exc = exc
  1421. def fatalError(self, exc):
  1422. self.error(exc)
  1423. raise exc
  1424. class _BaseHTMLProcessor(sgmllib.SGMLParser):
  1425. special = re.compile('''[<>'"]''')
  1426. bare_ampersand = re.compile("&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)")
  1427. elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
  1428. 'img', 'input', 'isindex', 'link', 'meta', 'param']
  1429. def __init__(self, encoding, type):
  1430. self.encoding = encoding
  1431. self.type = type
  1432. if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding)
  1433. sgmllib.SGMLParser.__init__(self)
  1434. def reset(self):
  1435. self.pieces = []
  1436. sgmllib.SGMLParser.reset(self)
  1437. def _shorttag_replace(self, match):
  1438. tag = match.group(1)
  1439. if tag in self.elements_no_end_tag:
  1440. return '<' + tag + ' />'
  1441. else:
  1442. return '<' + tag + '></' + tag + '>'
  1443. def parse_starttag(self,i):
  1444. j=sgmllib.SGMLParser.parse_starttag(self, i)
  1445. if self.type == 'application/xhtml+xml':
  1446. if j>2 and self.rawdata[j-2:j]=='/>':
  1447. self.unknown_endtag(self.lasttag)
  1448. return j
  1449. def feed(self, data):
  1450. data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data)
  1451. #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace
  1452. data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data)
  1453. data = data.replace('&#39;', "'")
  1454. data = data.replace('&#34;', '"')
  1455. if self.encoding and type(data) == type(u''):
  1456. data = data.encode(self.encoding)
  1457. sgmllib.SGMLParser.feed(self, data)
  1458. sgmllib.SGMLParser.close(self)
  1459. def normalize_attrs(self, attrs):
  1460. if not attrs: return attrs
  1461. # utility method to be called by descendants
  1462. attrs = dict([(k.lower(), v) for k, v in attrs]).items()
  1463. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  1464. attrs.sort()
  1465. return attrs
  1466. def unknown_starttag(self, tag, attrs):
  1467. # called for each start tag
  1468. # attrs is a list of (attr, value) tuples
  1469. # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
  1470. if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag)
  1471. uattrs = []
  1472. strattrs=''
  1473. if attrs:
  1474. for key, value in attrs:
  1475. value=value.replace('>','&gt;').replace('<','&lt;').replace('"','&quot;')
  1476. value = self.bare_ampersand.sub("&amp;", value)
  1477. # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
  1478. if type(value) != type(u''):
  1479. try:
  1480. value = unicode(value, self.encoding)
  1481. except:
  1482. value = unicode(value, 'iso-8859-1')
  1483. uattrs.append((unicode(key, self.encoding), value))
  1484. strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs])
  1485. if self.encoding:
  1486. try:
  1487. strattrs=strattrs.encode(self.encoding)
  1488. except:
  1489. pass
  1490. if tag in self.elements_no_end_tag:
  1491. self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
  1492. else:
  1493. self.pieces.append('<%(tag)s%(strattrs)s>' % locals())
  1494. def unknown_endtag(self, tag):
  1495. # called for each end tag, e.g. for </pre>, tag will be 'pre'
  1496. # Reconstruct the original end tag.
  1497. if tag not in self.elements_no_end_tag:
  1498. self.pieces.append("</%(tag)s>" % locals())
  1499. def handle_charref(self, ref):
  1500. # called for each character reference, e.g. for '&#160;', ref will be '160'
  1501. # Reconstruct the original character reference.
  1502. if ref.startswith('x'):
  1503. value = unichr(int(ref[1:],16))
  1504. else:
  1505. value = unichr(int(ref))
  1506. if value in _cp1252.keys():
  1507. self.pieces.append('&#%s;' % hex(ord(_cp1252[value]))[1:])
  1508. else:
  1509. self.pieces.append('&#%(ref)s;' % locals())
  1510. def handle_entityref(self, ref):
  1511. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  1512. # Reconstruct the original entity reference.
  1513. if name2codepoint.has_key(ref):
  1514. self.pieces.append('&%(ref)s;' % locals())
  1515. else:
  1516. self.pieces.append('&amp;%(ref)s' % locals())
  1517. def handle_data(self, text):
  1518. # called for each block of plain text, i.e. outside of any tag and
  1519. # not containing any character or entity references
  1520. # Store the original text verbatim.
  1521. if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text)
  1522. self.pieces.append(text)
  1523. def handle_comment(self, text):
  1524. # called for each HTML comment, e.g. <!-- insert Javascript code here -->
  1525. # Reconstruct the original comment.
  1526. self.pieces.append('<!--%(text)s-->' % locals())
  1527. def handle_pi(self, text):
  1528. # called for each processing instruction, e.g. <?instruction>
  1529. # Reconstruct original processing instruction.
  1530. self.pieces.append('<?%(text)s>' % locals())
  1531. def handle_decl(self, text):
  1532. # called for the DOCTYPE, if present, e.g.
  1533. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  1534. # "http://www.w3.org/TR/html4/loose.dtd">
  1535. # Reconstruct original DOCTYPE
  1536. self.pieces.append('<!%(text)s>' % locals())
  1537. _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
  1538. def _scan_name(self, i, declstartpos):
  1539. rawdata = self.rawdata
  1540. n = len(rawdata)
  1541. if i == n:
  1542. return None, -1
  1543. m = self._new_declname_match(rawdata, i)
  1544. if m:
  1545. s = m.group()
  1546. name = s.strip()
  1547. if (i + len(s)) == n:
  1548. return None, -1 # end of buffer
  1549. return name.lower(), m.end()
  1550. else:
  1551. self.handle_data(rawdata)
  1552. # self.updatepos(declstartpos, i)
  1553. return None, -1
  1554. def convert_charref(self, name):
  1555. return '&#%s;' % name
  1556. def convert_entityref(self, name):
  1557. return '&%s;' % name
  1558. def output(self):
  1559. '''Return processed HTML as a single string'''
  1560. return ''.join([str(p) for p in self.pieces])
  1561. class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor):
  1562. def __init__(self, baseuri, baselang, encoding, entities):
  1563. sgmllib.SGMLParser.__init__(self)
  1564. _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1565. _BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml')
  1566. self.entities=entities
  1567. def decodeEntities(self, element, data):
  1568. data = data.replace('&#60;', '&lt;')
  1569. data = data.replace('&#x3c;', '&lt;')
  1570. data = data.replace('&#x3C;', '&lt;')
  1571. data = data.replace('&#62;', '&gt;')
  1572. data = data.replace('&#x3e;', '&gt;')
  1573. data = data.replace('&#x3E;', '&gt;')
  1574. data = data.replace('&#38;', '&amp;')
  1575. data = data.replace('&#x26;', '&amp;')
  1576. data = data.replace('&#34;', '&quot;')
  1577. data = data.replace('&#x22;', '&quot;')
  1578. data = data.replace('&#39;', '&apos;')
  1579. data = data.replace('&#x27;', '&apos;')
  1580. if self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  1581. data = data.replace('&lt;', '<')
  1582. data = data.replace('&gt;', '>')
  1583. data = data.replace('&amp;', '&')
  1584. data = data.replace('&quot;', '"')
  1585. data = data.replace('&apos;', "'")
  1586. return data
  1587. def strattrs(self, attrs):
  1588. return ''.join([' %s="%s"' % (n,v.replace('"','&quot;')) for n,v in attrs])
  1589. class _MicroformatsParser:
  1590. STRING = 1
  1591. DATE = 2
  1592. URI = 3
  1593. NODE = 4
  1594. EMAIL = 5
  1595. known_xfn_relationships = ['contact', 'acquaintance', 'friend', 'met', 'co-worker', 'coworker', 'colleague', 'co-resident', 'coresident', 'neighbor', 'child', 'parent', 'sibling', 'brother', 'sister', 'spouse', 'wife', 'husband', 'kin', 'relative', 'muse', 'crush', 'date', 'sweetheart', 'me']
  1596. known_binary_extensions = ['zip','rar','exe','gz','tar','tgz','tbz2','bz2','z','7z','dmg','img','sit','sitx','hqx','deb','rpm','bz2','jar','rar','iso','bin','msi','mp2','mp3','ogg','ogm','mp4','m4v','m4a','avi','wma','wmv']
  1597. def __init__(self, data, baseuri, encoding):
  1598. self.document = BeautifulSoup.BeautifulSoup(data)
  1599. self.baseuri = baseuri
  1600. self.encoding = encoding
  1601. if type(data) == type(u''):
  1602. data = data.encode(encoding)
  1603. self.tags = []
  1604. self.enclosures = []
  1605. self.xfn = []
  1606. self.vcard = None
  1607. def vcardEscape(self, s):
  1608. if type(s) in (type(''), type(u'')):
  1609. s = s.replace(',', '\\,').replace(';', '\\;').replace('\n', '\\n')
  1610. return s
  1611. def vcardFold(self, s):
  1612. s = re.sub(';+$', '', s)
  1613. sFolded = ''
  1614. iMax = 75
  1615. sPrefix = ''
  1616. while len(s) > iMax:
  1617. sFolded += sPrefix + s[:iMax] + '\n'
  1618. s = s[iMax:]
  1619. sPrefix = ' '
  1620. iMax = 74
  1621. sFolded += sPrefix + s
  1622. return sFolded
  1623. def normalize(self, s):
  1624. return re.sub(r'\s+', ' ', s).strip()
  1625. def unique(self, aList):
  1626. results = []
  1627. for element in aList:
  1628. if element not in results:
  1629. results.append(element)
  1630. return results
  1631. def toISO8601(self, dt):
  1632. return time.strftime('%Y-%m-%dT%H:%M:%SZ', dt)
  1633. def getPropertyValue(self, elmRoot, sProperty, iPropertyType=4, bAllowMultiple=0, bAutoEscape=0):
  1634. all = lambda x: 1
  1635. sProperty = sProperty.lower()
  1636. bFound = 0
  1637. bNormalize = 1
  1638. propertyMatch = {'class': re.compile(r'\b%s\b' % sProperty)}
  1639. if bAllowMultiple and (iPropertyType != self.NODE):
  1640. snapResults = []
  1641. containers = elmRoot(['ul', 'ol'], propertyMatch)
  1642. for container in containers:
  1643. snapResults.extend(container('li'))
  1644. bFound = (len(snapResults) != 0)
  1645. if not bFound:
  1646. snapResults = elmRoot(all, propertyMatch)
  1647. bFound = (len(snapResults) != 0)
  1648. if (not bFound) and (sProperty == 'value'):
  1649. snapResults = elmRoot('pre')
  1650. bFound = (len(snapResults) != 0)
  1651. bNormalize = not bFound
  1652. if not bFound:
  1653. snapResults = [elmRoot]
  1654. bFound = (len(snapResults) != 0)
  1655. arFilter = []
  1656. if sProperty == 'vcard':
  1657. snapFilter = elmRoot(all, propertyMatch)
  1658. for node in snapFilter:
  1659. if node.findParent(all, propertyMatch):
  1660. arFilter.append(node)
  1661. arResults = []
  1662. for node in snapResults:
  1663. if node not in arFilter:
  1664. arResults.append(node)
  1665. bFound = (len(arResults) != 0)
  1666. if not bFound:
  1667. if bAllowMultiple: return []
  1668. elif iPropertyType == self.STRING: return ''
  1669. elif iPropertyType == self.DATE: return None
  1670. elif iPropertyType == self.URI: return ''
  1671. elif iPropertyType == self.NODE: return None
  1672. else: return None
  1673. arValues = []
  1674. for elmResult in arResults:
  1675. sValue = None
  1676. if iPropertyType == self.NODE:
  1677. if bAllowMultiple:
  1678. arValues.append(elmResult)
  1679. continue
  1680. else:
  1681. return elmResult
  1682. sNodeName = elmResult.name.lower()
  1683. if (iPropertyType == self.EMAIL) and (sNodeName == 'a'):
  1684. sValue = (elmResult.get('href') or '').split('mailto:').pop().split('?')[0]
  1685. if sValue:
  1686. sValue = bNormalize and self.normalize(sValue) or sValue.strip()
  1687. if (not sValue) and (sNodeName == 'abbr'):
  1688. sValue = elmResult.get('title')
  1689. if sValue:
  1690. sValue = bNormalize and self.normalize(sValue) or sValue.strip()
  1691. if (not sValue) and (iPropertyType == self.URI):
  1692. if sNodeName == 'a': sValue = elmResult.get('href')
  1693. elif sNodeName == 'img': sValue = elmResult.get('src')
  1694. elif sNodeName == 'object': sValue = elmResult.get('data')
  1695. if sValue:
  1696. sValue = bNormalize and self.normalize(sValue) or sValue.strip()
  1697. if (not sValue) and (sNodeName == 'img'):
  1698. sValue = elmResult.get('alt')
  1699. if sValue:
  1700. sValue = bNormalize and self.normalize(sValue) or sValue.strip()
  1701. if not sValue:
  1702. sValue = elmResult.renderContents()
  1703. sValue = re.sub(r'<\S[^>]*>', '', sValue)
  1704. sValue = sValue.replace('\r\n', '\n')
  1705. sValue = sValue.replace('\r', '\n')
  1706. if sValue:
  1707. sValue = bNormalize and self.normalize(sValue) or sValue.strip()
  1708. if not sValue: continue
  1709. if iPropertyType == self.DATE:
  1710. sValue = _parse_date_iso8601(sValue)
  1711. if bAllowMultiple:
  1712. arValues.append(bAutoEscape and self.vcardEscape(sValue) or sValue)
  1713. else:
  1714. return bAutoEscape and self.vcardEscape(sValue) or sValue
  1715. return arValues
  1716. def findVCards(self, elmRoot, bAgentParsing=0):
  1717. sVCards = ''
  1718. if not bAgentParsing:
  1719. arCards = self.getPropertyValue(elmRoot, 'vcard', bAllowMultiple=1)
  1720. else:
  1721. arCards = [elmRoot]
  1722. for elmCard in arCards:
  1723. arLines = []
  1724. def processSingleString(sProperty):
  1725. sValue = self.getPropertyValue(elmCard, sProperty, self.STRING, bAutoEscape=1)
  1726. if sValue:
  1727. arLines.append(self.vcardFold(sProperty.upper() + ':' + sValue))
  1728. return sValue or ''
  1729. def processSingleURI(sProperty):
  1730. sValue = self.getPropertyValue(elmCard, sProperty, self.URI)
  1731. if sValue:
  1732. sContentType = ''
  1733. sEncoding = ''
  1734. sValueKey = ''
  1735. if sValue.startswith('data:'):
  1736. sEncoding = ';ENCODING=b'
  1737. sContentType = sValue.split(';')[0].split('/').pop()
  1738. sValue = sValue.split(',', 1).pop()
  1739. else:
  1740. elmValue = self.getPropertyValue(elmCard, sProperty)
  1741. if elmValue:
  1742. if sProperty != 'url':
  1743. sValueKey = ';VALUE=uri'
  1744. sContentType = elmValue.get('type', '').strip().split('/').pop().strip()
  1745. sContentType = sContentType.upper()
  1746. if sContentType == 'OCTET-STREAM':
  1747. sContentType = ''
  1748. if sContentType:
  1749. sContentType = ';TYPE=' + sContentType.upper()
  1750. arLines.append(self.vcardFold(sProperty.upper() + sEncoding + sContentType + sValueKey + ':' + sValue))
  1751. def processTypeValue(sProperty, arDefaultType, arForceType=None):
  1752. arResults = self.getPropertyValue(elmCard, sProperty, bAllowMultiple=1)
  1753. for elmResult in arResults:
  1754. arType = self.getPropertyValue(elmResult, 'type', self.STRING, 1, 1)
  1755. if arForceType:
  1756. arType = self.unique(arForceType + arType)
  1757. if not arType:
  1758. arType = arDefaultType
  1759. sValue = self.getPropertyValue(elmResult, 'value', self.EMAIL, 0)
  1760. if sValue:
  1761. arLines.append(self.vcardFold(sProperty.upper() + ';TYPE=' + ','.join(arType) + ':' + sValue))
  1762. # AGENT
  1763. # must do this before all other properties because it is destructive
  1764. # (removes nested class="vcard" nodes so they don't interfere with
  1765. # this vcard's other properties)
  1766. arAgent = self.getPropertyValue(elmCard, 'agent', bAllowMultiple=1)
  1767. for elmAgent in arAgent:
  1768. if re.compile(r'\bvcard\b').search(elmAgent.get('class')):
  1769. sAgentValue = self.findVCards(elmAgent, 1) + '\n'
  1770. sAgentValue = sAgentValue.replace('\n', '\\n')
  1771. sAgentValue = sAgentValue.replace(';', '\\;')
  1772. if sAgentValue:
  1773. arLines.append(self.vcardFold('AGENT:' + sAgentValue))
  1774. elmAgent['class'] = ''
  1775. elmAgent.contents = []
  1776. else:
  1777. sAgentValue = self.getPropertyValue(elmAgent, 'value', self.URI, bAutoEscape=1);
  1778. if sAgentValue:
  1779. arLines.append(self.vcardFold('AGENT;VALUE=uri:' + sAgentValue))
  1780. # FN (full name)
  1781. sFN = processSingleString('fn')
  1782. # N (name)
  1783. elmName = self.getPropertyValue(elmCard, 'n')
  1784. if elmName:
  1785. sFamilyName = self.getPropertyValue(elmName, 'family-name', self.STRING, bAutoEscape=1)
  1786. sGivenName = self.getPropertyValue(elmName, 'given-name', self.STRING, bAutoEscape=1)
  1787. arAdditionalNames = self.getPropertyValue(elmName, 'additional-name', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'additional-names', self.STRING, 1, 1)
  1788. arHonorificPrefixes = self.getPropertyValue(elmName, 'honorific-prefix', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'honorific-prefixes', self.STRING, 1, 1)
  1789. arHonorificSuffixes = self.getPropertyValue(elmName, 'honorific-suffix', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'honorific-suffixes', self.STRING, 1, 1)
  1790. arLines.append(self.vcardFold('N:' + sFamilyName + ';' +
  1791. sGivenName + ';' +
  1792. ','.join(arAdditionalNames) + ';' +
  1793. ','.join(arHonorificPrefixes) + ';' +
  1794. ','.join(arHonorificSuffixes)))
  1795. elif sFN:
  1796. # implied "N" optimization
  1797. # http://microformats.org/wiki/hcard#Implied_.22N.22_Optimization
  1798. arNames = self.normalize(sFN).split()
  1799. if len(arNames) == 2:
  1800. bFamilyNameFirst = (arNames[0].endswith(',') or
  1801. len(arNames[1]) == 1 or
  1802. ((len(arNames[1]) == 2) and (arNames[1].endswith('.'))))
  1803. if bFamilyNameFirst:
  1804. arLines.append(self.vcardFold('N:' + arNames[0] + ';' + arNames[1]))
  1805. else:
  1806. arLines.append(self.vcardFold('N:' + arNames[1] + ';' + arNames[0]))
  1807. # SORT-STRING
  1808. sSortString = self.getPropertyValue(elmCard, 'sort-string', self.STRING, bAutoEscape=1)
  1809. if sSortString:
  1810. arLines.append(self.vcardFold('SORT-STRING:' + sSortString))
  1811. # NICKNAME
  1812. arNickname = self.getPropertyValue(elmCard, 'nickname', self.STRING, 1, 1)
  1813. if arNickname:
  1814. arLines.append(self.vcardFold('NICKNAME:' + ','.join(arNickname)))
  1815. # PHOTO
  1816. processSingleURI('photo')
  1817. # BDAY
  1818. dtBday = self.getPropertyValue(elmCard, 'bday', self.DATE)
  1819. if dtBday:
  1820. arLines.append(self.vcardFold('BDAY:' + self.toISO8601(dtBday)))
  1821. # ADR (address)
  1822. arAdr = self.getPropertyValue(elmCard, 'adr', bAllowMultiple=1)
  1823. for elmAdr in arAdr:
  1824. arType = self.getPropertyValue(elmAdr, 'type', self.STRING, 1, 1)
  1825. if not arType:
  1826. arType = ['intl','postal','parcel','work'] # default adr types, see RFC 2426 section 3.2.1
  1827. sPostOfficeBox = self.getPropertyValue(elmAdr, 'post-office-box', self.STRING, 0, 1)
  1828. sExtendedAddress = self.getPropertyValue(elmAdr, 'extended-address', self.STRING, 0, 1)
  1829. sStreetAddress = self.getPropertyValue(elmAdr, 'street-address', self.STRING, 0, 1)
  1830. sLocality = self.getPropertyValue(elmAdr, 'locality', self.STRING, 0, 1)
  1831. sRegion = self.getPropertyValue(elmAdr, 'region', self.STRING, 0, 1)
  1832. sPostalCode = self.getPropertyValue(elmAdr, 'postal-code', self.STRING, 0, 1)
  1833. sCountryName = self.getPropertyValue(elmAdr, 'country-name', self.STRING, 0, 1)
  1834. arLines.append(self.vcardFold('ADR;TYPE=' + ','.join(arType) + ':' +
  1835. sPostOfficeBox + ';' +
  1836. sExtendedAddress + ';' +
  1837. sStreetAddress + ';' +
  1838. sLocality + ';' +
  1839. sRegion + ';' +
  1840. sPostalCode + ';' +
  1841. sCountryName))
  1842. # LABEL
  1843. processTypeValue('label', ['intl','postal','parcel','work'])
  1844. # TEL (phone number)
  1845. processTypeValue('tel', ['voice'])
  1846. # EMAIL
  1847. processTypeValue('email', ['internet'], ['internet'])
  1848. # MAILER
  1849. processSingleString('mailer')
  1850. # TZ (timezone)
  1851. processSingleString('tz')
  1852. # GEO (geographical information)
  1853. elmGeo = self.getPropertyValue(elmCard, 'geo')
  1854. if elmGeo:
  1855. sLatitude = self.getPropertyValue(elmGeo, 'latitude', self.STRING, 0, 1)
  1856. sLongitude = self.getPropertyValue(elmGeo, 'longitude', self.STRING, 0, 1)
  1857. arLines.append(self.vcardFold('GEO:' + sLatitude + ';' + sLongitude))
  1858. # TITLE
  1859. processSingleString('title')
  1860. # ROLE
  1861. processSingleString('role')
  1862. # LOGO
  1863. processSingleURI('logo')
  1864. # ORG (organization)
  1865. elmOrg = self.getPropertyValue(elmCard, 'org')
  1866. if elmOrg:
  1867. sOrganizationName = self.getPropertyValue(elmOrg, 'organization-name', self.STRING, 0, 1)
  1868. if not sOrganizationName:
  1869. # implied "organization-name" optimization
  1870. # http://microformats.org/wiki/hcard#Implied_.22organization-name.22_Optimization
  1871. sOrganizationName = self.getPropertyValue(elmCard, 'org', self.STRING, 0, 1)
  1872. if sOrganizationName:
  1873. arLines.append(self.vcardFold('ORG:' + sOrganizationName))
  1874. else:
  1875. arOrganizationUnit = self.getPropertyValue(elmOrg, 'organization-unit', self.STRING, 1, 1)
  1876. arLines.append(self.vcardFold('ORG:' + sOrganizationName + ';' + ';'.join(arOrganizationUnit)))
  1877. # CATEGORY
  1878. arCategory = self.getPropertyValue(elmCard, 'category', self.STRING, 1, 1) + self.getPropertyValue(elmCard, 'categories', self.STRING, 1, 1)
  1879. if arCategory:
  1880. arLines.append(self.vcardFold('CATEGORIES:' + ','.join(arCategory)))
  1881. # NOTE
  1882. processSingleString('note')
  1883. # REV
  1884. processSingleString('rev')
  1885. # SOUND
  1886. processSingleURI('sound')
  1887. # UID
  1888. processSingleString('uid')
  1889. # URL
  1890. processSingleURI('url')
  1891. # CLASS
  1892. processSingleString('class')
  1893. # KEY
  1894. processSingleURI('key')
  1895. if arLines:
  1896. arLines = ['BEGIN:vCard','VERSION:3.0'] + arLines + ['END:vCard']
  1897. sVCards += '\n'.join(arLines) + '\n'
  1898. return sVCards.strip()
  1899. def isProbablyDownloadable(self, elm):
  1900. attrsD = elm.attrMap
  1901. if not attrsD.has_key('href'): return 0
  1902. linktype = attrsD.get('type', '').strip()
  1903. if linktype.startswith('audio/') or \
  1904. linktype.startswith('video/') or \
  1905. (linktype.startswith('application/') and not linktype.endswith('xml')):
  1906. return 1
  1907. path = urlparse.urlparse(attrsD['href'])[2]
  1908. if path.find('.') == -1: return 0
  1909. fileext = path.split('.').pop().lower()
  1910. return fileext in self.known_binary_extensions
  1911. def findTags(self):
  1912. all = lambda x: 1
  1913. for elm in self.document(all, {'rel': re.compile(r'\btag\b')}):
  1914. href = elm.get('href')
  1915. if not href: continue
  1916. urlscheme, domain, path, params, query, fragment = \
  1917. urlparse.urlparse(_urljoin(self.baseuri, href))
  1918. segments = path.split('/')
  1919. tag = segments.pop()
  1920. if not tag:
  1921. tag = segments.pop()
  1922. tagscheme = urlparse.urlunparse((urlscheme, domain, '/'.join(segments), '', '', ''))
  1923. if not tagscheme.endswith('/'):
  1924. tagscheme += '/'
  1925. self.tags.append(FeedParserDict({"term": tag, "scheme": tagscheme, "label": elm.string or ''}))
  1926. def findEnclosures(self):
  1927. all = lambda x: 1
  1928. enclosure_match = re.compile(r'\benclosure\b')
  1929. for elm in self.document(all, {'href': re.compile(r'.+')}):
  1930. if not enclosure_match.search(elm.get('rel', '')) and not self.isProbablyDownloadable(elm): continue
  1931. if elm.attrMap not in self.enclosures:
  1932. self.enclosures.append(elm.attrMap)
  1933. if elm.string and not elm.get('title'):
  1934. self.enclosures[-1]['title'] = elm.string
  1935. def findXFN(self):
  1936. all = lambda x: 1
  1937. for elm in self.document(all, {'rel': re.compile('.+'), 'href': re.compile('.+')}):
  1938. rels = elm.get('rel', '').split()
  1939. xfn_rels = []
  1940. for rel in rels:
  1941. if rel in self.known_xfn_relationships:
  1942. xfn_rels.append(rel)
  1943. if xfn_rels:
  1944. self.xfn.append({"relationships": xfn_rels, "href": elm.get('href', ''), "name": elm.string})
  1945. def _parseMicroformats(htmlSource, baseURI, encoding):
  1946. if not BeautifulSoup: return
  1947. if _debug: sys.stderr.write('entering _parseMicroformats\n')
  1948. p = _MicroformatsParser(htmlSource, baseURI, encoding)
  1949. p.vcard = p.findVCards(p.document)
  1950. p.findTags()
  1951. p.findEnclosures()
  1952. p.findXFN()
  1953. return {"tags": p.tags, "enclosures": p.enclosures, "xfn": p.xfn, "vcard": p.vcard}
  1954. class _RelativeURIResolver(_BaseHTMLProcessor):
  1955. relative_uris = [('a', 'href'),
  1956. ('applet', 'codebase'),
  1957. ('area', 'href'),
  1958. ('blockquote', 'cite'),
  1959. ('body', 'background'),
  1960. ('del', 'cite'),
  1961. ('form', 'action'),
  1962. ('frame', 'longdesc'),
  1963. ('frame', 'src'),
  1964. ('iframe', 'longdesc'),
  1965. ('iframe', 'src'),
  1966. ('head', 'profile'),
  1967. ('img', 'longdesc'),
  1968. ('img', 'src'),
  1969. ('img', 'usemap'),
  1970. ('input', 'src'),
  1971. ('input', 'usemap'),
  1972. ('ins', 'cite'),
  1973. ('link', 'href'),
  1974. ('object', 'classid'),
  1975. ('object', 'codebase'),
  1976. ('object', 'data'),
  1977. ('object', 'usemap'),
  1978. ('q', 'cite'),
  1979. ('script', 'src')]
  1980. def __init__(self, baseuri, encoding, type):
  1981. _BaseHTMLProcessor.__init__(self, encoding, type)
  1982. self.baseuri = baseuri
  1983. def resolveURI(self, uri):
  1984. return _urljoin(self.baseuri, uri.strip())
  1985. def unknown_starttag(self, tag, attrs):
  1986. attrs = self.normalize_attrs(attrs)
  1987. attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
  1988. _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1989. def _resolveRelativeURIs(htmlSource, baseURI, encoding, type):
  1990. if _debug: sys.stderr.write('entering _resolveRelativeURIs\n')
  1991. p = _RelativeURIResolver(baseURI, encoding, type)
  1992. p.feed(htmlSource)
  1993. return p.output()
  1994. class _HTMLSanitizer(_BaseHTMLProcessor):
  1995. acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article',
  1996. 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', 'canvas',
  1997. 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command',
  1998. 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir',
  1999. 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset', 'figure', 'footer',
  2000. 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i',
  2001. 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map',
  2002. 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup',
  2003. 'option', 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
  2004. 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'sub',
  2005. 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot', 'th', 'thead',
  2006. 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript']
  2007. acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  2008. 'action', 'align', 'alt', 'autoplay', 'autocomplete', 'autofocus', 'axis',
  2009. 'background', 'balance', 'bgcolor', 'bgproperties', 'border',
  2010. 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
  2011. 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
  2012. 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols',
  2013. 'colspan', 'compact', 'contenteditable', 'coords', 'data', 'datafld',
  2014. 'datapagesize', 'datasrc', 'datetime', 'default', 'delay', 'dir',
  2015. 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for',
  2016. 'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus',
  2017. 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode',
  2018. 'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc',
  2019. 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max',
  2020. 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref',
  2021. 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size',
  2022. 'prompt', 'pqg', 'radiogroup', 'readonly', 'rel', 'repeat-max',
  2023. 'repeat-min', 'replace', 'required', 'rev', 'rightspacing', 'rows',
  2024. 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src',
  2025. 'start', 'step', 'summary', 'suppress', 'tabindex', 'target', 'template',
  2026. 'title', 'toppadding', 'type', 'unselectable', 'usemap', 'urn', 'valign',
  2027. 'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap',
  2028. 'xml:lang']
  2029. unacceptable_elements_with_end_tag = ['script', 'applet', 'style']
  2030. acceptable_css_properties = ['azimuth', 'background-color',
  2031. 'border-bottom-color', 'border-collapse', 'border-color',
  2032. 'border-left-color', 'border-right-color', 'border-top-color', 'clear',
  2033. 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
  2034. 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
  2035. 'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
  2036. 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
  2037. 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
  2038. 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
  2039. 'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
  2040. 'white-space', 'width']
  2041. # survey of common keywords found in feeds
  2042. acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue',
  2043. 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
  2044. 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
  2045. 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
  2046. 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
  2047. 'transparent', 'underline', 'white', 'yellow']
  2048. valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' +
  2049. '\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$')
  2050. mathml_elements = ['annotation', 'annotation-xml', 'maction', 'math',
  2051. 'merror', 'mfenced', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
  2052. 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle',
  2053. 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
  2054. 'munderover', 'none', 'semantics']
  2055. mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign',
  2056. 'columnalign', 'close', 'columnlines', 'columnspacing', 'columnspan', 'depth',
  2057. 'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows',
  2058. 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness',
  2059. 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant',
  2060. 'maxsize', 'minsize', 'open', 'other', 'rowalign', 'rowalign', 'rowalign',
  2061. 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
  2062. 'separator', 'separators', 'stretchy', 'width', 'width', 'xlink:href',
  2063. 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink']
  2064. # svgtiny - foreignObject + linearGradient + radialGradient + stop
  2065. svg_elements = ['a', 'animate', 'animateColor', 'animateMotion',
  2066. 'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'foreignObject',
  2067. 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
  2068. 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath',
  2069. 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop',
  2070. 'svg', 'switch', 'text', 'title', 'tspan', 'use']
  2071. # svgtiny + class + opacity + offset + xmlns + xmlns:xlink
  2072. svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic',
  2073. 'arabic-form', 'ascent', 'attributeName', 'attributeType',
  2074. 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
  2075. 'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx',
  2076. 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity',
  2077. 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style',
  2078. 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2',
  2079. 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x',
  2080. 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines',
  2081. 'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid',
  2082. 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max',
  2083. 'min', 'name', 'offset', 'opacity', 'orient', 'origin',
  2084. 'overline-position', 'overline-thickness', 'panose-1', 'path',
  2085. 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY',
  2086. 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures',
  2087. 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv',
  2088. 'stop-color', 'stop-opacity', 'strikethrough-position',
  2089. 'strikethrough-thickness', 'stroke', 'stroke-dasharray',
  2090. 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
  2091. 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage',
  2092. 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2',
  2093. 'underline-position', 'underline-thickness', 'unicode', 'unicode-range',
  2094. 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width',
  2095. 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
  2096. 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
  2097. 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1',
  2098. 'y2', 'zoomAndPan']
  2099. svg_attr_map = None
  2100. svg_elem_map = None
  2101. acceptable_svg_properties = [ 'fill', 'fill-opacity', 'fill-rule',
  2102. 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
  2103. 'stroke-opacity']
  2104. def reset(self):
  2105. _BaseHTMLProcessor.reset(self)
  2106. self.unacceptablestack = 0
  2107. self.mathmlOK = 0
  2108. self.svgOK = 0
  2109. def unknown_starttag(self, tag, attrs):
  2110. acceptable_attributes = self.acceptable_attributes
  2111. keymap = {}
  2112. if not tag in self.acceptable_elements or self.svgOK:
  2113. if tag in self.unacceptable_elements_with_end_tag:
  2114. self.unacceptablestack += 1
  2115. # not otherwise acceptable, perhaps it is MathML or SVG?
  2116. if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs:
  2117. self.mathmlOK = 1
  2118. if tag=='svg' and ('xmlns','http://www.w3.org/2000/svg') in attrs:
  2119. self.svgOK = 1
  2120. # chose acceptable attributes based on tag class, else bail
  2121. if self.mathmlOK and tag in self.mathml_elements:
  2122. acceptable_attributes = self.mathml_attributes
  2123. elif self.svgOK and tag in self.svg_elements:
  2124. # for most vocabularies, lowercasing is a good idea. Many
  2125. # svg elements, however, are camel case
  2126. if not self.svg_attr_map:
  2127. lower=[attr.lower() for attr in self.svg_attributes]
  2128. mix=[a for a in self.svg_attributes if a not in lower]
  2129. self.svg_attributes = lower
  2130. self.svg_attr_map = dict([(a.lower(),a) for a in mix])
  2131. lower=[attr.lower() for attr in self.svg_elements]
  2132. mix=[a for a in self.svg_elements if a not in lower]
  2133. self.svg_elements = lower
  2134. self.svg_elem_map = dict([(a.lower(),a) for a in mix])
  2135. acceptable_attributes = self.svg_attributes
  2136. tag = self.svg_elem_map.get(tag,tag)
  2137. keymap = self.svg_attr_map
  2138. elif not tag in self.acceptable_elements:
  2139. return
  2140. # declare xlink namespace, if needed
  2141. if self.mathmlOK or self.svgOK:
  2142. if filter(lambda (n,v): n.startswith('xlink:'),attrs):
  2143. if not ('xmlns:xlink','http://www.w3.org/1999/xlink') in attrs:
  2144. attrs.append(('xmlns:xlink','http://www.w3.org/1999/xlink'))
  2145. clean_attrs = []
  2146. for key, value in self.normalize_attrs(attrs):
  2147. if key in acceptable_attributes:
  2148. key=keymap.get(key,key)
  2149. clean_attrs.append((key,value))
  2150. elif key=='style':
  2151. clean_value = self.sanitize_style(value)
  2152. if clean_value: clean_attrs.append((key,clean_value))
  2153. _BaseHTMLProcessor.unknown_starttag(self, tag, clean_attrs)
  2154. def unknown_endtag(self, tag):
  2155. if not tag in self.acceptable_elements:
  2156. if tag in self.unacceptable_elements_with_end_tag:
  2157. self.unacceptablestack -= 1
  2158. if self.mathmlOK and tag in self.mathml_elements:
  2159. if tag == 'math': self.mathmlOK = 0
  2160. elif self.svgOK and tag in self.svg_elements:
  2161. tag = self.svg_elem_map.get(tag,tag)
  2162. if tag == 'svg': self.svgOK = 0
  2163. else:
  2164. return
  2165. _BaseHTMLProcessor.unknown_endtag(self, tag)
  2166. def handle_pi(self, text):
  2167. pass
  2168. def handle_decl(self, text):
  2169. pass
  2170. def handle_data(self, text):
  2171. if not self.unacceptablestack:
  2172. _BaseHTMLProcessor.handle_data(self, text)
  2173. def sanitize_style(self, style):
  2174. # disallow urls
  2175. style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style)
  2176. # gauntlet
  2177. if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return ''
  2178. if not re.match("^(\s*[-\w]+\s*:\s*[^:;]*(;|$))*$", style): return ''
  2179. clean = []
  2180. for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style):
  2181. if not value: continue
  2182. if prop.lower() in self.acceptable_css_properties:
  2183. clean.append(prop + ': ' + value + ';')
  2184. elif prop.split('-')[0].lower() in ['background','border','margin','padding']:
  2185. for keyword in value.split():
  2186. if not keyword in self.acceptable_css_keywords and \
  2187. not self.valid_css_values.match(keyword):
  2188. break
  2189. else:
  2190. clean.append(prop + ': ' + value + ';')
  2191. elif self.svgOK and prop.lower() in self.acceptable_svg_properties:
  2192. clean.append(prop + ': ' + value + ';')
  2193. return ' '.join(clean)
  2194. def _sanitizeHTML(htmlSource, encoding, type):
  2195. p = _HTMLSanitizer(encoding, type)
  2196. p.feed(htmlSource)
  2197. data = p.output()
  2198. if TIDY_MARKUP:
  2199. # loop through list of preferred Tidy interfaces looking for one that's installed,
  2200. # then set up a common _tidy function to wrap the interface-specific API.
  2201. _tidy = None
  2202. for tidy_interface in PREFERRED_TIDY_INTERFACES:
  2203. try:
  2204. if tidy_interface == "uTidy":
  2205. from tidy import parseString as _utidy
  2206. def _tidy(data, **kwargs):
  2207. return str(_utidy(data, **kwargs))
  2208. break
  2209. elif tidy_interface == "mxTidy":
  2210. from mx.Tidy import Tidy as _mxtidy
  2211. def _tidy(data, **kwargs):
  2212. nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs)
  2213. return data
  2214. break
  2215. except:
  2216. pass
  2217. if _tidy:
  2218. utf8 = type(data) == type(u'')
  2219. if utf8:
  2220. data = data.encode('utf-8')
  2221. data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8")
  2222. if utf8:
  2223. data = unicode(data, 'utf-8')
  2224. if data.count('<body'):
  2225. data = data.split('<body', 1)[1]
  2226. if data.count('>'):
  2227. data = data.split('>', 1)[1]
  2228. if data.count('</body'):
  2229. data = data.split('</body', 1)[0]
  2230. data = data.strip().replace('\r\n', '\n')
  2231. return data
  2232. class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
  2233. def http_error_default(self, req, fp, code, msg, headers):
  2234. if ((code / 100) == 3) and (code != 304):
  2235. return self.http_error_302(req, fp, code, msg, headers)
  2236. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  2237. infourl.status = code
  2238. return infourl
  2239. def http_error_302(self, req, fp, code, msg, headers):
  2240. if headers.dict.has_key('location'):
  2241. infourl = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
  2242. else:
  2243. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  2244. if not hasattr(infourl, 'status'):
  2245. infourl.status = code
  2246. return infourl
  2247. def http_error_301(self, req, fp, code, msg, headers):
  2248. if headers.dict.has_key('location'):
  2249. infourl = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
  2250. else:
  2251. infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  2252. if not hasattr(infourl, 'status'):
  2253. infourl.status = code
  2254. return infourl
  2255. http_error_300 = http_error_302
  2256. http_error_303 = http_error_302
  2257. http_error_307 = http_error_302
  2258. def http_error_401(self, req, fp, code, msg, headers):
  2259. # Check if
  2260. # - server requires digest auth, AND
  2261. # - we tried (unsuccessfully) with basic auth, AND
  2262. # - we're using Python 2.3.3 or later (digest auth is irreparably broken in earlier versions)
  2263. # If all conditions hold, parse authentication information
  2264. # out of the Authorization header we sent the first time
  2265. # (for the username and password) and the WWW-Authenticate
  2266. # header the server sent back (for the realm) and retry
  2267. # the request with the appropriate digest auth headers instead.
  2268. # This evil genius hack has been brought to you by Aaron Swartz.
  2269. host = urlparse.urlparse(req.get_full_url())[1]
  2270. try:
  2271. assert sys.version.split()[0] >= '2.3.3'
  2272. assert base64 != None
  2273. user, passw = base64.decodestring(req.headers['Authorization'].split(' ')[1]).split(':')
  2274. realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0]
  2275. self.add_password(realm, host, user, passw)
  2276. retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  2277. self.reset_retry_count()
  2278. return retry
  2279. except:
  2280. return self.http_error_default(req, fp, code, msg, headers)
  2281. def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers):
  2282. """URL, filename, or string --> stream
  2283. This function lets you define parsers that take any input source
  2284. (URL, pathname to local or network file, or actual data as a string)
  2285. and deal with it in a uniform manner. Returned object is guaranteed
  2286. to have all the basic stdio read methods (read, readline, readlines).
  2287. Just .close() the object when you're done with it.
  2288. If the etag argument is supplied, it will be used as the value of an
  2289. If-None-Match request header.
  2290. If the modified argument is supplied, it can be a tuple of 9 integers
  2291. (as returned by gmtime() in the standard Python time module) or a date
  2292. string in any format supported by feedparser. Regardless, it MUST
  2293. be in GMT (Greenwich Mean Time). It will be reformatted into an
  2294. RFC 1123-compliant date and used as the value of an If-Modified-Since
  2295. request header.
  2296. If the agent argument is supplied, it will be used as the value of a
  2297. User-Agent request header.
  2298. If the referrer argument is supplied, it will be used as the value of a
  2299. Referer[sic] request header.
  2300. If handlers is supplied, it is a list of handlers used to build a
  2301. urllib2 opener.
  2302. """
  2303. if hasattr(url_file_stream_or_string, 'read'):
  2304. return url_file_stream_or_string
  2305. if url_file_stream_or_string == '-':
  2306. return sys.stdin
  2307. if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):
  2308. if not agent:
  2309. agent = USER_AGENT
  2310. # test for inline user:password for basic auth
  2311. auth = None
  2312. if base64:
  2313. urltype, rest = urllib.splittype(url_file_stream_or_string)
  2314. realhost, rest = urllib.splithost(rest)
  2315. if realhost:
  2316. user_passwd, realhost = urllib.splituser(realhost)
  2317. if user_passwd:
  2318. url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest)
  2319. auth = base64.encodestring(user_passwd).strip()
  2320. # iri support
  2321. try:
  2322. if isinstance(url_file_stream_or_string,unicode):
  2323. url_file_stream_or_string = url_file_stream_or_string.encode('idna')
  2324. else:
  2325. url_file_stream_or_string = url_file_stream_or_string.decode('utf-8').encode('idna')
  2326. except:
  2327. pass
  2328. # try to open with urllib2 (to use optional headers)
  2329. request = urllib2.Request(url_file_stream_or_string)
  2330. request.add_header('User-Agent', agent)
  2331. if etag:
  2332. request.add_header('If-None-Match', etag)
  2333. if type(modified) == type(''):
  2334. modified = _parse_date(modified)
  2335. if modified:
  2336. # format into an RFC 1123-compliant timestamp. We can't use
  2337. # time.strftime() since the %a and %b directives can be affected
  2338. # by the current locale, but RFC 2616 states that dates must be
  2339. # in English.
  2340. short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  2341. months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  2342. 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]))
  2343. if referrer:
  2344. request.add_header('Referer', referrer)
  2345. if gzip and zlib:
  2346. request.add_header('Accept-encoding', 'gzip, deflate')
  2347. elif gzip:
  2348. request.add_header('Accept-encoding', 'gzip')
  2349. elif zlib:
  2350. request.add_header('Accept-encoding', 'deflate')
  2351. else:
  2352. request.add_header('Accept-encoding', '')
  2353. if auth:
  2354. request.add_header('Authorization', 'Basic %s' % auth)
  2355. if ACCEPT_HEADER:
  2356. request.add_header('Accept', ACCEPT_HEADER)
  2357. request.add_header('A-IM', 'feed') # RFC 3229 support
  2358. opener = apply(urllib2.build_opener, tuple([_FeedURLHandler()] + handlers))
  2359. opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
  2360. try:
  2361. return opener.open(request)
  2362. finally:
  2363. opener.close() # JohnD
  2364. # try to open with native open function (if url_file_stream_or_string is a filename)
  2365. try:
  2366. return open(url_file_stream_or_string)
  2367. except:
  2368. pass
  2369. # treat url_file_stream_or_string as string
  2370. return _StringIO(str(url_file_stream_or_string))
  2371. _date_handlers = []
  2372. def registerDateHandler(func):
  2373. '''Register a date handler function (takes string, returns 9-tuple date in GMT)'''
  2374. _date_handlers.insert(0, func)
  2375. # ISO-8601 date parsing routines written by Fazal Majid.
  2376. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
  2377. # parser is beyond the scope of feedparser and would be a worthwhile addition
  2378. # to the Python library.
  2379. # A single regular expression cannot parse ISO 8601 date formats into groups
  2380. # as the standard is highly irregular (for instance is 030104 2003-01-04 or
  2381. # 0301-04-01), so we use templates instead.
  2382. # Please note the order in templates is significant because we need a
  2383. # greedy match.
  2384. _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-0MM?-?DD', 'YYYY-MM', 'YYYY-?OOO',
  2385. 'YY-?MM-?DD', 'YY-?OOO', 'YYYY',
  2386. '-YY-?MM', '-OOO', '-YY',
  2387. '--MM-?DD', '--MM',
  2388. '---DD',
  2389. 'CC', '']
  2390. _iso8601_re = [
  2391. tmpl.replace(
  2392. 'YYYY', r'(?P<year>\d{4})').replace(
  2393. 'YY', r'(?P<year>\d\d)').replace(
  2394. 'MM', r'(?P<month>[01]\d)').replace(
  2395. 'DD', r'(?P<day>[0123]\d)').replace(
  2396. 'OOO', r'(?P<ordinal>[0123]\d\d)').replace(
  2397. 'CC', r'(?P<century>\d\d$)')
  2398. + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
  2399. + r'(:(?P<second>\d{2}(\.\d*)?))?'
  2400. + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
  2401. for tmpl in _iso8601_tmpl]
  2402. del tmpl
  2403. _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
  2404. del regex
  2405. def _parse_date_iso8601(dateString):
  2406. '''Parse a variety of ISO-8601-compatible formats like 20040105'''
  2407. m = None
  2408. for _iso8601_match in _iso8601_matches:
  2409. m = _iso8601_match(dateString)
  2410. if m: break
  2411. if not m: return
  2412. if m.span() == (0, 0): return
  2413. params = m.groupdict()
  2414. ordinal = params.get('ordinal', 0)
  2415. if ordinal:
  2416. ordinal = int(ordinal)
  2417. else:
  2418. ordinal = 0
  2419. year = params.get('year', '--')
  2420. if not year or year == '--':
  2421. year = time.gmtime()[0]
  2422. elif len(year) == 2:
  2423. # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
  2424. year = 100 * int(time.gmtime()[0] / 100) + int(year)
  2425. else:
  2426. year = int(year)
  2427. month = params.get('month', '-')
  2428. if not month or month == '-':
  2429. # ordinals are NOT normalized by mktime, we simulate them
  2430. # by setting month=1, day=ordinal
  2431. if ordinal:
  2432. month = 1
  2433. else:
  2434. month = time.gmtime()[1]
  2435. month = int(month)
  2436. day = params.get('day', 0)
  2437. if not day:
  2438. # see above
  2439. if ordinal:
  2440. day = ordinal
  2441. elif params.get('century', 0) or \
  2442. params.get('year', 0) or params.get('month', 0):
  2443. day = 1
  2444. else:
  2445. day = time.gmtime()[2]
  2446. else:
  2447. day = int(day)
  2448. # special case of the century - is the first year of the 21st century
  2449. # 2000 or 2001 ? The debate goes on...
  2450. if 'century' in params.keys():
  2451. year = (int(params['century']) - 1) * 100 + 1
  2452. # in ISO 8601 most fields are optional
  2453. for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
  2454. if not params.get(field, None):
  2455. params[field] = 0
  2456. hour = int(params.get('hour', 0))
  2457. minute = int(params.get('minute', 0))
  2458. second = int(float(params.get('second', 0)))
  2459. # weekday is normalized by mktime(), we can ignore it
  2460. weekday = 0
  2461. daylight_savings_flag = -1
  2462. tm = [year, month, day, hour, minute, second, weekday,
  2463. ordinal, daylight_savings_flag]
  2464. # ISO 8601 time zone adjustments
  2465. tz = params.get('tz')
  2466. if tz and tz != 'Z':
  2467. if tz[0] == '-':
  2468. tm[3] += int(params.get('tzhour', 0))
  2469. tm[4] += int(params.get('tzmin', 0))
  2470. elif tz[0] == '+':
  2471. tm[3] -= int(params.get('tzhour', 0))
  2472. tm[4] -= int(params.get('tzmin', 0))
  2473. else:
  2474. return None
  2475. # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
  2476. # which is guaranteed to normalize d/m/y/h/m/s.
  2477. # Many implementations have bugs, but we'll pretend they don't.
  2478. return time.localtime(time.mktime(tm))
  2479. registerDateHandler(_parse_date_iso8601)
  2480. # 8-bit date handling routines written by ytrewq1.
  2481. _korean_year = u'\ub144' # b3e2 in euc-kr
  2482. _korean_month = u'\uc6d4' # bff9 in euc-kr
  2483. _korean_day = u'\uc77c' # c0cf in euc-kr
  2484. _korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr
  2485. _korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr
  2486. _korean_onblog_date_re = \
  2487. re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \
  2488. (_korean_year, _korean_month, _korean_day))
  2489. _korean_nate_date_re = \
  2490. re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \
  2491. (_korean_am, _korean_pm))
  2492. def _parse_date_onblog(dateString):
  2493. '''Parse a string according to the OnBlog 8-bit date format'''
  2494. m = _korean_onblog_date_re.match(dateString)
  2495. if not m: return
  2496. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2497. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2498. 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  2499. 'zonediff': '+09:00'}
  2500. if _debug: sys.stderr.write('OnBlog date parsed as: %s\n' % w3dtfdate)
  2501. return _parse_date_w3dtf(w3dtfdate)
  2502. registerDateHandler(_parse_date_onblog)
  2503. def _parse_date_nate(dateString):
  2504. '''Parse a string according to the Nate 8-bit date format'''
  2505. m = _korean_nate_date_re.match(dateString)
  2506. if not m: return
  2507. hour = int(m.group(5))
  2508. ampm = m.group(4)
  2509. if (ampm == _korean_pm):
  2510. hour += 12
  2511. hour = str(hour)
  2512. if len(hour) == 1:
  2513. hour = '0' + hour
  2514. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2515. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2516. 'hour': hour, 'minute': m.group(6), 'second': m.group(7),\
  2517. 'zonediff': '+09:00'}
  2518. if _debug: sys.stderr.write('Nate date parsed as: %s\n' % w3dtfdate)
  2519. return _parse_date_w3dtf(w3dtfdate)
  2520. registerDateHandler(_parse_date_nate)
  2521. _mssql_date_re = \
  2522. re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?')
  2523. def _parse_date_mssql(dateString):
  2524. '''Parse a string according to the MS SQL date format'''
  2525. m = _mssql_date_re.match(dateString)
  2526. if not m: return
  2527. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2528. {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2529. 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  2530. 'zonediff': '+09:00'}
  2531. if _debug: sys.stderr.write('MS SQL date parsed as: %s\n' % w3dtfdate)
  2532. return _parse_date_w3dtf(w3dtfdate)
  2533. registerDateHandler(_parse_date_mssql)
  2534. # Unicode strings for Greek date strings
  2535. _greek_months = \
  2536. { \
  2537. u'\u0399\u03b1\u03bd': u'Jan', # c9e1ed in iso-8859-7
  2538. u'\u03a6\u03b5\u03b2': u'Feb', # d6e5e2 in iso-8859-7
  2539. u'\u039c\u03ac\u03ce': u'Mar', # ccdcfe in iso-8859-7
  2540. u'\u039c\u03b1\u03ce': u'Mar', # cce1fe in iso-8859-7
  2541. u'\u0391\u03c0\u03c1': u'Apr', # c1f0f1 in iso-8859-7
  2542. u'\u039c\u03ac\u03b9': u'May', # ccdce9 in iso-8859-7
  2543. u'\u039c\u03b1\u03ca': u'May', # cce1fa in iso-8859-7
  2544. u'\u039c\u03b1\u03b9': u'May', # cce1e9 in iso-8859-7
  2545. u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7
  2546. u'\u0399\u03bf\u03bd': u'Jun', # c9efed in iso-8859-7
  2547. u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7
  2548. u'\u0399\u03bf\u03bb': u'Jul', # c9f9eb in iso-8859-7
  2549. u'\u0391\u03cd\u03b3': u'Aug', # c1fde3 in iso-8859-7
  2550. u'\u0391\u03c5\u03b3': u'Aug', # c1f5e3 in iso-8859-7
  2551. u'\u03a3\u03b5\u03c0': u'Sep', # d3e5f0 in iso-8859-7
  2552. u'\u039f\u03ba\u03c4': u'Oct', # cfeaf4 in iso-8859-7
  2553. u'\u039d\u03bf\u03ad': u'Nov', # cdefdd in iso-8859-7
  2554. u'\u039d\u03bf\u03b5': u'Nov', # cdefe5 in iso-8859-7
  2555. u'\u0394\u03b5\u03ba': u'Dec', # c4e5ea in iso-8859-7
  2556. }
  2557. _greek_wdays = \
  2558. { \
  2559. u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7
  2560. u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7
  2561. u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7
  2562. u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7
  2563. u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7
  2564. u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7
  2565. u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7
  2566. }
  2567. _greek_date_format_re = \
  2568. re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)')
  2569. def _parse_date_greek(dateString):
  2570. '''Parse a string according to a Greek 8-bit date format.'''
  2571. m = _greek_date_format_re.match(dateString)
  2572. if not m: return
  2573. try:
  2574. wday = _greek_wdays[m.group(1)]
  2575. month = _greek_months[m.group(3)]
  2576. except:
  2577. return
  2578. rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
  2579. {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\
  2580. 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\
  2581. 'zonediff': m.group(8)}
  2582. if _debug: sys.stderr.write('Greek date parsed as: %s\n' % rfc822date)
  2583. return _parse_date_rfc822(rfc822date)
  2584. registerDateHandler(_parse_date_greek)
  2585. # Unicode strings for Hungarian date strings
  2586. _hungarian_months = \
  2587. { \
  2588. u'janu\u00e1r': u'01', # e1 in iso-8859-2
  2589. u'febru\u00e1ri': u'02', # e1 in iso-8859-2
  2590. u'm\u00e1rcius': u'03', # e1 in iso-8859-2
  2591. u'\u00e1prilis': u'04', # e1 in iso-8859-2
  2592. u'm\u00e1ujus': u'05', # e1 in iso-8859-2
  2593. u'j\u00fanius': u'06', # fa in iso-8859-2
  2594. u'j\u00falius': u'07', # fa in iso-8859-2
  2595. u'augusztus': u'08',
  2596. u'szeptember': u'09',
  2597. u'okt\u00f3ber': u'10', # f3 in iso-8859-2
  2598. u'november': u'11',
  2599. u'december': u'12',
  2600. }
  2601. _hungarian_date_format_re = \
  2602. re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))')
  2603. def _parse_date_hungarian(dateString):
  2604. '''Parse a string according to a Hungarian 8-bit date format.'''
  2605. m = _hungarian_date_format_re.match(dateString)
  2606. if not m: return
  2607. try:
  2608. month = _hungarian_months[m.group(2)]
  2609. day = m.group(3)
  2610. if len(day) == 1:
  2611. day = '0' + day
  2612. hour = m.group(4)
  2613. if len(hour) == 1:
  2614. hour = '0' + hour
  2615. except:
  2616. return
  2617. w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \
  2618. {'year': m.group(1), 'month': month, 'day': day,\
  2619. 'hour': hour, 'minute': m.group(5),\
  2620. 'zonediff': m.group(6)}
  2621. if _debug: sys.stderr.write('Hungarian date parsed as: %s\n' % w3dtfdate)
  2622. return _parse_date_w3dtf(w3dtfdate)
  2623. registerDateHandler(_parse_date_hungarian)
  2624. # W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by
  2625. # Drake and licensed under the Python license. Removed all range checking
  2626. # for month, day, hour, minute, and second, since mktime will normalize
  2627. # these later
  2628. def _parse_date_w3dtf(dateString):
  2629. def __extract_date(m):
  2630. year = int(m.group('year'))
  2631. if year < 100:
  2632. year = 100 * int(time.gmtime()[0] / 100) + int(year)
  2633. if year < 1000:
  2634. return 0, 0, 0
  2635. julian = m.group('julian')
  2636. if julian:
  2637. julian = int(julian)
  2638. month = julian / 30 + 1
  2639. day = julian % 30 + 1
  2640. jday = None
  2641. while jday != julian:
  2642. t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0))
  2643. jday = time.gmtime(t)[-2]
  2644. diff = abs(jday - julian)
  2645. if jday > julian:
  2646. if diff < day:
  2647. day = day - diff
  2648. else:
  2649. month = month - 1
  2650. day = 31
  2651. elif jday < julian:
  2652. if day + diff < 28:
  2653. day = day + diff
  2654. else:
  2655. month = month + 1
  2656. return year, month, day
  2657. month = m.group('month')
  2658. day = 1
  2659. if month is None:
  2660. month = 1
  2661. else:
  2662. month = int(month)
  2663. day = m.group('day')
  2664. if day:
  2665. day = int(day)
  2666. else:
  2667. day = 1
  2668. return year, month, day
  2669. def __extract_time(m):
  2670. if not m:
  2671. return 0, 0, 0
  2672. hours = m.group('hours')
  2673. if not hours:
  2674. return 0, 0, 0
  2675. hours = int(hours)
  2676. minutes = int(m.group('minutes'))
  2677. seconds = m.group('seconds')
  2678. if seconds:
  2679. seconds = int(seconds)
  2680. else:
  2681. seconds = 0
  2682. return hours, minutes, seconds
  2683. def __extract_tzd(m):
  2684. '''Return the Time Zone Designator as an offset in seconds from UTC.'''
  2685. if not m:
  2686. return 0
  2687. tzd = m.group('tzd')
  2688. if not tzd:
  2689. return 0
  2690. if tzd == 'Z':
  2691. return 0
  2692. hours = int(m.group('tzdhours'))
  2693. minutes = m.group('tzdminutes')
  2694. if minutes:
  2695. minutes = int(minutes)
  2696. else:
  2697. minutes = 0
  2698. offset = (hours*60 + minutes) * 60
  2699. if tzd[0] == '+':
  2700. return -offset
  2701. return offset
  2702. __date_re = ('(?P<year>\d\d\d\d)'
  2703. '(?:(?P<dsep>-|)'
  2704. '(?:(?P<julian>\d\d\d)'
  2705. '|(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?))?')
  2706. __tzd_re = '(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)'
  2707. __tzd_rx = re.compile(__tzd_re)
  2708. __time_re = ('(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)'
  2709. '(?:(?P=tsep)(?P<seconds>\d\d(?:[.,]\d+)?))?'
  2710. + __tzd_re)
  2711. __datetime_re = '%s(?:T%s)?' % (__date_re, __time_re)
  2712. __datetime_rx = re.compile(__datetime_re)
  2713. m = __datetime_rx.match(dateString)
  2714. if (m is None) or (m.group() != dateString): return
  2715. gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0)
  2716. if gmt[0] == 0: return
  2717. return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone)
  2718. registerDateHandler(_parse_date_w3dtf)
  2719. def _parse_date_rfc822(dateString):
  2720. '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date'''
  2721. data = dateString.split()
  2722. if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames:
  2723. del data[0]
  2724. if len(data) == 4:
  2725. s = data[3]
  2726. i = s.find('+')
  2727. if i > 0:
  2728. data[3:] = [s[:i], s[i+1:]]
  2729. else:
  2730. data.append('')
  2731. dateString = " ".join(data)
  2732. if len(data) < 5:
  2733. dateString += ' 00:00:00 GMT'
  2734. tm = rfc822.parsedate_tz(dateString)
  2735. if tm:
  2736. return time.gmtime(rfc822.mktime_tz(tm))
  2737. # rfc822.py defines several time zones, but we define some extra ones.
  2738. # 'ET' is equivalent to 'EST', etc.
  2739. _additional_timezones = {'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800}
  2740. rfc822._timezones.update(_additional_timezones)
  2741. registerDateHandler(_parse_date_rfc822)
  2742. def _parse_date_perforce(aDateString):
  2743. """parse a date in yyyy/mm/dd hh:mm:ss TTT format"""
  2744. # Fri, 2006/09/15 08:19:53 EDT
  2745. _my_date_pattern = re.compile( \
  2746. r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})')
  2747. dow, year, month, day, hour, minute, second, tz = \
  2748. _my_date_pattern.search(aDateString).groups()
  2749. months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  2750. dateString = "%s, %s %s %s %s:%s:%s %s" % (dow, day, months[int(month) - 1], year, hour, minute, second, tz)
  2751. tm = rfc822.parsedate_tz(dateString)
  2752. if tm:
  2753. return time.gmtime(rfc822.mktime_tz(tm))
  2754. registerDateHandler(_parse_date_perforce)
  2755. def _parse_date(dateString):
  2756. '''Parses a variety of date formats into a 9-tuple in GMT'''
  2757. for handler in _date_handlers:
  2758. try:
  2759. date9tuple = handler(dateString)
  2760. if not date9tuple: continue
  2761. if len(date9tuple) != 9:
  2762. if _debug: sys.stderr.write('date handler function must return 9-tuple\n')
  2763. raise ValueError
  2764. map(int, date9tuple)
  2765. return date9tuple
  2766. except Exception, e:
  2767. if _debug: sys.stderr.write('%s raised %s\n' % (handler.__name__, repr(e)))
  2768. pass
  2769. return None
  2770. def _getCharacterEncoding(http_headers, xml_data):
  2771. '''Get the character encoding of the XML document
  2772. http_headers is a dictionary
  2773. xml_data is a raw string (not Unicode)
  2774. This is so much trickier than it sounds, it's not even funny.
  2775. According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type
  2776. is application/xml, application/*+xml,
  2777. application/xml-external-parsed-entity, or application/xml-dtd,
  2778. the encoding given in the charset parameter of the HTTP Content-Type
  2779. takes precedence over the encoding given in the XML prefix within the
  2780. document, and defaults to 'utf-8' if neither are specified. But, if
  2781. the HTTP Content-Type is text/xml, text/*+xml, or
  2782. text/xml-external-parsed-entity, the encoding given in the XML prefix
  2783. within the document is ALWAYS IGNORED and only the encoding given in
  2784. the charset parameter of the HTTP Content-Type header should be
  2785. respected, and it defaults to 'us-ascii' if not specified.
  2786. Furthermore, discussion on the atom-syntax mailing list with the
  2787. author of RFC 3023 leads me to the conclusion that any document
  2788. served with a Content-Type of text/* and no charset parameter
  2789. must be treated as us-ascii. (We now do this.) And also that it
  2790. must always be flagged as non-well-formed. (We now do this too.)
  2791. If Content-Type is unspecified (input was local file or non-HTTP source)
  2792. or unrecognized (server just got it totally wrong), then go by the
  2793. encoding given in the XML prefix of the document and default to
  2794. 'iso-8859-1' as per the HTTP specification (RFC 2616).
  2795. Then, assuming we didn't find a character encoding in the HTTP headers
  2796. (and the HTTP Content-type allowed us to look in the body), we need
  2797. to sniff the first few bytes of the XML data and try to determine
  2798. whether the encoding is ASCII-compatible. Section F of the XML
  2799. specification shows the way here:
  2800. http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2801. If the sniffed encoding is not ASCII-compatible, we need to make it
  2802. ASCII compatible so that we can sniff further into the XML declaration
  2803. to find the encoding attribute, which will tell us the true encoding.
  2804. Of course, none of this guarantees that we will be able to parse the
  2805. feed in the declared character encoding (assuming it was declared
  2806. correctly, which many are not). CJKCodecs and iconv_codec help a lot;
  2807. you should definitely install them if you can.
  2808. http://cjkpython.i18n.org/
  2809. '''
  2810. def _parseHTTPContentType(content_type):
  2811. '''takes HTTP Content-Type header and returns (content type, charset)
  2812. If no charset is specified, returns (content type, '')
  2813. If no content type is specified, returns ('', '')
  2814. Both return parameters are guaranteed to be lowercase strings
  2815. '''
  2816. content_type = content_type or ''
  2817. content_type, params = cgi.parse_header(content_type)
  2818. return content_type, params.get('charset', '').replace("'", '')
  2819. sniffed_xml_encoding = ''
  2820. xml_encoding = ''
  2821. true_encoding = ''
  2822. http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type'))
  2823. # Must sniff for non-ASCII-compatible character encodings before
  2824. # searching for XML declaration. This heuristic is defined in
  2825. # section F of the XML specification:
  2826. # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2827. try:
  2828. if xml_data[:4] == '\x4c\x6f\xa7\x94':
  2829. # EBCDIC
  2830. xml_data = _ebcdic_to_ascii(xml_data)
  2831. elif xml_data[:4] == '\x00\x3c\x00\x3f':
  2832. # UTF-16BE
  2833. sniffed_xml_encoding = 'utf-16be'
  2834. xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
  2835. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') and (xml_data[2:4] != '\x00\x00'):
  2836. # UTF-16BE with BOM
  2837. sniffed_xml_encoding = 'utf-16be'
  2838. xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
  2839. elif xml_data[:4] == '\x3c\x00\x3f\x00':
  2840. # UTF-16LE
  2841. sniffed_xml_encoding = 'utf-16le'
  2842. xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
  2843. elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and (xml_data[2:4] != '\x00\x00'):
  2844. # UTF-16LE with BOM
  2845. sniffed_xml_encoding = 'utf-16le'
  2846. xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
  2847. elif xml_data[:4] == '\x00\x00\x00\x3c':
  2848. # UTF-32BE
  2849. sniffed_xml_encoding = 'utf-32be'
  2850. xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
  2851. elif xml_data[:4] == '\x3c\x00\x00\x00':
  2852. # UTF-32LE
  2853. sniffed_xml_encoding = 'utf-32le'
  2854. xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
  2855. elif xml_data[:4] == '\x00\x00\xfe\xff':
  2856. # UTF-32BE with BOM
  2857. sniffed_xml_encoding = 'utf-32be'
  2858. xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
  2859. elif xml_data[:4] == '\xff\xfe\x00\x00':
  2860. # UTF-32LE with BOM
  2861. sniffed_xml_encoding = 'utf-32le'
  2862. xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
  2863. elif xml_data[:3] == '\xef\xbb\xbf':
  2864. # UTF-8 with BOM
  2865. sniffed_xml_encoding = 'utf-8'
  2866. xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
  2867. else:
  2868. # ASCII-compatible
  2869. pass
  2870. xml_encoding_match = re.compile('^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
  2871. except:
  2872. xml_encoding_match = None
  2873. if xml_encoding_match:
  2874. xml_encoding = xml_encoding_match.groups()[0].lower()
  2875. 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')):
  2876. xml_encoding = sniffed_xml_encoding
  2877. acceptable_content_type = 0
  2878. application_content_types = ('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity')
  2879. text_content_types = ('text/xml', 'text/xml-external-parsed-entity')
  2880. if (http_content_type in application_content_types) or \
  2881. (http_content_type.startswith('application/') and http_content_type.endswith('+xml')):
  2882. acceptable_content_type = 1
  2883. true_encoding = http_encoding or xml_encoding or 'utf-8'
  2884. elif (http_content_type in text_content_types) or \
  2885. (http_content_type.startswith('text/')) and http_content_type.endswith('+xml'):
  2886. acceptable_content_type = 1
  2887. true_encoding = http_encoding or 'us-ascii'
  2888. elif http_content_type.startswith('text/'):
  2889. true_encoding = http_encoding or 'us-ascii'
  2890. elif http_headers and (not http_headers.has_key('content-type')):
  2891. true_encoding = xml_encoding or 'iso-8859-1'
  2892. else:
  2893. true_encoding = xml_encoding or 'utf-8'
  2894. return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type
  2895. def _toUTF8(data, encoding):
  2896. '''Changes an XML data stream on the fly to specify a new encoding
  2897. data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already
  2898. encoding is a string recognized by encodings.aliases
  2899. '''
  2900. if _debug: sys.stderr.write('entering _toUTF8, trying encoding %s\n' % encoding)
  2901. # strip Byte Order Mark (if present)
  2902. if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
  2903. if _debug:
  2904. sys.stderr.write('stripping BOM\n')
  2905. if encoding != 'utf-16be':
  2906. sys.stderr.write('trying utf-16be instead\n')
  2907. encoding = 'utf-16be'
  2908. data = data[2:]
  2909. elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
  2910. if _debug:
  2911. sys.stderr.write('stripping BOM\n')
  2912. if encoding != 'utf-16le':
  2913. sys.stderr.write('trying utf-16le instead\n')
  2914. encoding = 'utf-16le'
  2915. data = data[2:]
  2916. elif data[:3] == '\xef\xbb\xbf':
  2917. if _debug:
  2918. sys.stderr.write('stripping BOM\n')
  2919. if encoding != 'utf-8':
  2920. sys.stderr.write('trying utf-8 instead\n')
  2921. encoding = 'utf-8'
  2922. data = data[3:]
  2923. elif data[:4] == '\x00\x00\xfe\xff':
  2924. if _debug:
  2925. sys.stderr.write('stripping BOM\n')
  2926. if encoding != 'utf-32be':
  2927. sys.stderr.write('trying utf-32be instead\n')
  2928. encoding = 'utf-32be'
  2929. data = data[4:]
  2930. elif data[:4] == '\xff\xfe\x00\x00':
  2931. if _debug:
  2932. sys.stderr.write('stripping BOM\n')
  2933. if encoding != 'utf-32le':
  2934. sys.stderr.write('trying utf-32le instead\n')
  2935. encoding = 'utf-32le'
  2936. data = data[4:]
  2937. newdata = unicode(data, encoding)
  2938. if _debug: sys.stderr.write('successfully converted %s data to unicode\n' % encoding)
  2939. declmatch = re.compile('^<\?xml[^>]*?>')
  2940. newdecl = '''<?xml version='1.0' encoding='utf-8'?>'''
  2941. if declmatch.search(newdata):
  2942. newdata = declmatch.sub(newdecl, newdata)
  2943. else:
  2944. newdata = newdecl + u'\n' + newdata
  2945. return newdata.encode('utf-8')
  2946. def _stripDoctype(data):
  2947. '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
  2948. rss_version may be 'rss091n' or None
  2949. stripped_data is the same XML document, minus the DOCTYPE
  2950. '''
  2951. start = re.search('<\w',data)
  2952. start = start and start.start() or -1
  2953. head,data = data[:start+1], data[start+1:]
  2954. entity_pattern = re.compile(r'^\s*<!ENTITY([^>]*?)>', re.MULTILINE)
  2955. entity_results=entity_pattern.findall(head)
  2956. head = entity_pattern.sub('', head)
  2957. doctype_pattern = re.compile(r'^\s*<!DOCTYPE([^>]*?)>', re.MULTILINE)
  2958. doctype_results = doctype_pattern.findall(head)
  2959. doctype = doctype_results and doctype_results[0] or ''
  2960. if doctype.lower().count('netscape'):
  2961. version = 'rss091n'
  2962. else:
  2963. version = None
  2964. # only allow in 'safe' inline entity definitions
  2965. replacement=''
  2966. if len(doctype_results)==1 and entity_results:
  2967. safe_pattern=re.compile('\s+(\w+)\s+"(&#\w+;|[^&"]*)"')
  2968. safe_entities=filter(lambda e: safe_pattern.match(e),entity_results)
  2969. if safe_entities:
  2970. replacement='<!DOCTYPE feed [\n <!ENTITY %s>\n]>' % '>\n <!ENTITY '.join(safe_entities)
  2971. data = doctype_pattern.sub(replacement, head) + data
  2972. return version, data, dict(replacement and safe_pattern.findall(replacement))
  2973. def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]):
  2974. '''Parse a feed from a URL, file, stream, or string'''
  2975. result = FeedParserDict()
  2976. result['feed'] = FeedParserDict()
  2977. result['entries'] = []
  2978. if _XML_AVAILABLE:
  2979. result['bozo'] = 0
  2980. if type(handlers) == types.InstanceType:
  2981. handlers = [handlers]
  2982. try:
  2983. f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers)
  2984. data = f.read()
  2985. except Exception, e:
  2986. result['bozo'] = 1
  2987. result['bozo_exception'] = e
  2988. data = ''
  2989. f = None
  2990. # if feed is gzip-compressed, decompress it
  2991. if f and data and hasattr(f, 'headers'):
  2992. if gzip and f.headers.get('content-encoding', '') == 'gzip':
  2993. try:
  2994. data = gzip.GzipFile(fileobj=_StringIO(data)).read()
  2995. except Exception, e:
  2996. # Some feeds claim to be gzipped but they're not, so
  2997. # we get garbage. Ideally, we should re-request the
  2998. # feed without the 'Accept-encoding: gzip' header,
  2999. # but we don't.
  3000. result['bozo'] = 1
  3001. result['bozo_exception'] = e
  3002. data = ''
  3003. elif zlib and f.headers.get('content-encoding', '') == 'deflate':
  3004. try:
  3005. data = zlib.decompress(data, -zlib.MAX_WBITS)
  3006. except Exception, e:
  3007. result['bozo'] = 1
  3008. result['bozo_exception'] = e
  3009. data = ''
  3010. # save HTTP headers
  3011. if hasattr(f, 'info'):
  3012. info = f.info()
  3013. result['etag'] = info.getheader('ETag')
  3014. last_modified = info.getheader('Last-Modified')
  3015. if last_modified:
  3016. result['modified'] = _parse_date(last_modified)
  3017. if hasattr(f, 'url'):
  3018. result['href'] = f.url
  3019. result['status'] = 200
  3020. if hasattr(f, 'status'):
  3021. result['status'] = f.status
  3022. if hasattr(f, 'headers'):
  3023. result['headers'] = f.headers.dict
  3024. if hasattr(f, 'close'):
  3025. f.close()
  3026. # there are four encodings to keep track of:
  3027. # - http_encoding is the encoding declared in the Content-Type HTTP header
  3028. # - xml_encoding is the encoding declared in the <?xml declaration
  3029. # - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data
  3030. # - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications
  3031. http_headers = result.get('headers', {})
  3032. result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type = \
  3033. _getCharacterEncoding(http_headers, data)
  3034. if http_headers and (not acceptable_content_type):
  3035. if http_headers.has_key('content-type'):
  3036. bozo_message = '%s is not an XML media type' % http_headers['content-type']
  3037. else:
  3038. bozo_message = 'no Content-type specified'
  3039. result['bozo'] = 1
  3040. result['bozo_exception'] = NonXMLContentType(bozo_message)
  3041. result['version'], data, entities = _stripDoctype(data)
  3042. baseuri = http_headers.get('content-location', result.get('href'))
  3043. baselang = http_headers.get('content-language', None)
  3044. # if server sent 304, we're done
  3045. if result.get('status', 0) == 304:
  3046. result['version'] = ''
  3047. result['debug_message'] = 'The feed has not changed since you last checked, ' + \
  3048. 'so the server sent no data. This is a feature, not a bug!'
  3049. return result
  3050. # if there was a problem downloading, we're done
  3051. if not data:
  3052. return result
  3053. # determine character encoding
  3054. use_strict_parser = 0
  3055. known_encoding = 0
  3056. tried_encodings = []
  3057. # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM
  3058. for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding):
  3059. if not proposed_encoding: continue
  3060. if proposed_encoding in tried_encodings: continue
  3061. tried_encodings.append(proposed_encoding)
  3062. try:
  3063. data = _toUTF8(data, proposed_encoding)
  3064. known_encoding = use_strict_parser = 1
  3065. break
  3066. except:
  3067. pass
  3068. # if no luck and we have auto-detection library, try that
  3069. if (not known_encoding) and chardet:
  3070. try:
  3071. proposed_encoding = chardet.detect(data)['encoding']
  3072. if proposed_encoding and (proposed_encoding not in tried_encodings):
  3073. tried_encodings.append(proposed_encoding)
  3074. data = _toUTF8(data, proposed_encoding)
  3075. known_encoding = use_strict_parser = 1
  3076. except:
  3077. pass
  3078. # if still no luck and we haven't tried utf-8 yet, try that
  3079. if (not known_encoding) and ('utf-8' not in tried_encodings):
  3080. try:
  3081. proposed_encoding = 'utf-8'
  3082. tried_encodings.append(proposed_encoding)
  3083. data = _toUTF8(data, proposed_encoding)
  3084. known_encoding = use_strict_parser = 1
  3085. except:
  3086. pass
  3087. # if still no luck and we haven't tried windows-1252 yet, try that
  3088. if (not known_encoding) and ('windows-1252' not in tried_encodings):
  3089. try:
  3090. proposed_encoding = 'windows-1252'
  3091. tried_encodings.append(proposed_encoding)
  3092. data = _toUTF8(data, proposed_encoding)
  3093. known_encoding = use_strict_parser = 1
  3094. except:
  3095. pass
  3096. # if still no luck and we haven't tried iso-8859-2 yet, try that.
  3097. if (not known_encoding) and ('iso-8859-2' not in tried_encodings):
  3098. try:
  3099. proposed_encoding = 'iso-8859-2'
  3100. tried_encodings.append(proposed_encoding)
  3101. data = _toUTF8(data, proposed_encoding)
  3102. known_encoding = use_strict_parser = 1
  3103. except:
  3104. pass
  3105. # if still no luck, give up
  3106. if not known_encoding:
  3107. result['bozo'] = 1
  3108. result['bozo_exception'] = CharacterEncodingUnknown( \
  3109. 'document encoding unknown, I tried ' + \
  3110. '%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' % \
  3111. (result['encoding'], xml_encoding))
  3112. result['encoding'] = ''
  3113. elif proposed_encoding != result['encoding']:
  3114. result['bozo'] = 1
  3115. result['bozo_exception'] = CharacterEncodingOverride( \
  3116. 'documented declared as %s, but parsed as %s' % \
  3117. (result['encoding'], proposed_encoding))
  3118. result['encoding'] = proposed_encoding
  3119. if not _XML_AVAILABLE:
  3120. use_strict_parser = 0
  3121. if use_strict_parser:
  3122. # initialize the SAX parser
  3123. feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8')
  3124. saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
  3125. saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
  3126. saxparser.setContentHandler(feedparser)
  3127. saxparser.setErrorHandler(feedparser)
  3128. source = xml.sax.xmlreader.InputSource()
  3129. source.setByteStream(_StringIO(data))
  3130. if hasattr(saxparser, '_ns_stack'):
  3131. # work around bug in built-in SAX parser (doesn't recognize xml: namespace)
  3132. # PyXML doesn't have this problem, and it doesn't have _ns_stack either
  3133. saxparser._ns_stack.append({'http://www.w3.org/XML/1998/namespace':'xml'})
  3134. try:
  3135. saxparser.parse(source)
  3136. except Exception, e:
  3137. if _debug:
  3138. import traceback
  3139. traceback.print_stack()
  3140. traceback.print_exc()
  3141. sys.stderr.write('xml parsing failed\n')
  3142. result['bozo'] = 1
  3143. result['bozo_exception'] = feedparser.exc or e
  3144. use_strict_parser = 0
  3145. if not use_strict_parser:
  3146. feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '', entities)
  3147. feedparser.feed(data)
  3148. result['feed'] = feedparser.feeddata
  3149. result['entries'] = feedparser.entries
  3150. result['version'] = result['version'] or feedparser.version
  3151. result['namespaces'] = feedparser.namespacesInUse
  3152. return result
  3153. class Serializer:
  3154. def __init__(self, results):
  3155. self.results = results
  3156. class TextSerializer(Serializer):
  3157. def write(self, stream=sys.stdout):
  3158. self._writer(stream, self.results, '')
  3159. def _writer(self, stream, node, prefix):
  3160. if not node: return
  3161. if hasattr(node, 'keys'):
  3162. keys = node.keys()
  3163. keys.sort()
  3164. for k in keys:
  3165. if k in ('description', 'link'): continue
  3166. if node.has_key(k + '_detail'): continue
  3167. if node.has_key(k + '_parsed'): continue
  3168. self._writer(stream, node[k], prefix + k + '.')
  3169. elif type(node) == types.ListType:
  3170. index = 0
  3171. for n in node:
  3172. self._writer(stream, n, prefix[:-1] + '[' + str(index) + '].')
  3173. index += 1
  3174. else:
  3175. try:
  3176. s = str(node).encode('utf-8')
  3177. s = s.replace('\\', '\\\\')
  3178. s = s.replace('\r', '')
  3179. s = s.replace('\n', r'\n')
  3180. stream.write(prefix[:-1])
  3181. stream.write('=')
  3182. stream.write(s)
  3183. stream.write('\n')
  3184. except:
  3185. pass
  3186. class PprintSerializer(Serializer):
  3187. def write(self, stream=sys.stdout):
  3188. if self.results.has_key('href'):
  3189. stream.write(self.results['href'] + '\n\n')
  3190. from pprint import pprint
  3191. pprint(self.results, stream)
  3192. stream.write('\n')
  3193. if __name__ == '__main__':
  3194. try:
  3195. from optparse import OptionParser
  3196. except:
  3197. OptionParser = None
  3198. if OptionParser:
  3199. optionParser = OptionParser(version=__version__, usage="%prog [options] url_or_filename_or_-")
  3200. optionParser.set_defaults(format="pprint")
  3201. optionParser.add_option("-A", "--user-agent", dest="agent", metavar="AGENT", help="User-Agent for HTTP URLs")
  3202. optionParser.add_option("-e", "--referer", "--referrer", dest="referrer", metavar="URL", help="Referrer for HTTP URLs")
  3203. optionParser.add_option("-t", "--etag", dest="etag", metavar="TAG", help="ETag/If-None-Match for HTTP URLs")
  3204. optionParser.add_option("-m", "--last-modified", dest="modified", metavar="DATE", help="Last-modified/If-Modified-Since for HTTP URLs (any supported date format)")
  3205. optionParser.add_option("-f", "--format", dest="format", metavar="FORMAT", help="output results in FORMAT (text, pprint)")
  3206. optionParser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="write debugging information to stderr")
  3207. (options, urls) = optionParser.parse_args()
  3208. if options.verbose:
  3209. _debug = 1
  3210. if not urls:
  3211. optionParser.print_help()
  3212. sys.exit(0)
  3213. else:
  3214. if not sys.argv[1:]:
  3215. print __doc__
  3216. sys.exit(0)
  3217. class _Options:
  3218. etag = modified = agent = referrer = None
  3219. format = 'pprint'
  3220. options = _Options()
  3221. urls = sys.argv[1:]
  3222. zopeCompatibilityHack()
  3223. serializer = globals().get(options.format.capitalize() + 'Serializer', Serializer)
  3224. for url in urls:
  3225. results = parse(url, etag=options.etag, modified=options.modified, agent=options.agent, referrer=options.referrer)
  3226. serializer(results).write(sys.stdout)
  3227. #REVISION HISTORY
  3228. #1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements,
  3229. # added Simon Fell's test suite
  3230. #1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections
  3231. #2.0 - 10/19/2002
  3232. # JD - use inchannel to watch out for image and textinput elements which can
  3233. # also contain title, link, and description elements
  3234. # JD - check for isPermaLink='false' attribute on guid elements
  3235. # JD - replaced openAnything with open_resource supporting ETag and
  3236. # If-Modified-Since request headers
  3237. # JD - parse now accepts etag, modified, agent, and referrer optional
  3238. # arguments
  3239. # JD - modified parse to return a dictionary instead of a tuple so that any
  3240. # etag or modified information can be returned and cached by the caller
  3241. #2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything
  3242. # because of etag/modified, return the old etag/modified to the caller to
  3243. # indicate why nothing is being returned
  3244. #2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its
  3245. # useless. Fixes the problem JD was addressing by adding it.
  3246. #2.1 - 11/14/2002 - MAP - added gzip support
  3247. #2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent.
  3248. # start_admingeneratoragent is an example of how to handle elements with
  3249. # only attributes, no content.
  3250. #2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify);
  3251. # also, make sure we send the User-Agent even if urllib2 isn't available.
  3252. # Match any variation of backend.userland.com/rss namespace.
  3253. #2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is.
  3254. #2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's
  3255. # snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed
  3256. # project name
  3257. #2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree);
  3258. # removed unnecessary urllib code -- urllib2 should always be available anyway;
  3259. # return actual url, status, and full HTTP headers (as result['url'],
  3260. # result['status'], and result['headers']) if parsing a remote feed over HTTP --
  3261. # this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>;
  3262. # added the latest namespace-of-the-week for RSS 2.0
  3263. #2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom
  3264. # User-Agent (otherwise urllib2 sends two, which confuses some servers)
  3265. #2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for
  3266. # inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds
  3267. #2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or
  3268. # textInput, and also to return the character encoding (if specified)
  3269. #2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking
  3270. # nested divs within content (JohnD); fixed missing sys import (JohanS);
  3271. # fixed regular expression to capture XML character encoding (Andrei);
  3272. # added support for Atom 0.3-style links; fixed bug with textInput tracking;
  3273. # added support for cloud (MartijnP); added support for multiple
  3274. # category/dc:subject (MartijnP); normalize content model: 'description' gets
  3275. # description (which can come from description, summary, or full content if no
  3276. # description), 'content' gets dict of base/language/type/value (which can come
  3277. # from content:encoded, xhtml:body, content, or fullitem);
  3278. # fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang
  3279. # tracking; fixed bug tracking unknown tags; fixed bug tracking content when
  3280. # <content> element is not in default namespace (like Pocketsoap feed);
  3281. # resolve relative URLs in link, guid, docs, url, comments, wfw:comment,
  3282. # wfw:commentRSS; resolve relative URLs within embedded HTML markup in
  3283. # description, xhtml:body, content, content:encoded, title, subtitle,
  3284. # summary, info, tagline, and copyright; added support for pingback and
  3285. # trackback namespaces
  3286. #2.7 - 1/5/2004 - MAP - really added support for trackback and pingback
  3287. # namespaces, as opposed to 2.6 when I said I did but didn't really;
  3288. # sanitize HTML markup within some elements; added mxTidy support (if
  3289. # installed) to tidy HTML markup within some elements; fixed indentation
  3290. # bug in _parse_date (FazalM); use socket.setdefaulttimeout if available
  3291. # (FazalM); universal date parsing and normalization (FazalM): 'created', modified',
  3292. # 'issued' are parsed into 9-tuple date format and stored in 'created_parsed',
  3293. # 'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified'
  3294. # and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa
  3295. #2.7.1 - 1/9/2004 - MAP - fixed bug handling &quot; and &apos;. fixed memory
  3296. # leak not closing url opener (JohnD); added dc:publisher support (MarekK);
  3297. # added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK)
  3298. #2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed <br/> tags in
  3299. # encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL);
  3300. # fixed relative URI processing for guid (skadz); added ICBM support; added
  3301. # base64 support
  3302. #2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many
  3303. # blogspot.com sites); added _debug variable
  3304. #2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing
  3305. #
  3306. #rest of revision history is in HTML docs now