PageRenderTime 86ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/script.module.feedparser/lib/feedparser.py

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