[Commits] (pavlov) update zaobao to use feedparser 3.0 beta 21, use the new task manager, handle unicode better, handle exceptions better. Uses TEXT lobs for storage so that zaobao items are now searchable.

commits at osafoundation.org commits at osafoundation.org
Mon Apr 19 14:08:57 PDT 2004


Commit by: pavlov
Modified files:
osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/ZaoBaoTask.py None 1.1
osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py 1.12 1.13
osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py 1.19 1.20
osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py 1.2 1.3
osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml 1.15 1.16
osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/ZaoBaoAgent.py 1.18 None

Log message:
update zaobao to use feedparser 3.0 beta 21, use the new task manager, handle unicode better, handle exceptions better.  Uses TEXT lobs for storage so that zaobao items are now searchable.


ViewCVS links:
http://cvs.osafoundation.org/index.cgi/osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/ZaoBaoTask.py?rev=1.1&content-type=text/vnd.viewcvs-markup
http://cvs.osafoundation.org/index.cgi/osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py.diff?r1=text&tr1=1.12&r2=text&tr2=1.13
http://cvs.osafoundation.org/index.cgi/osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py.diff?r1=text&tr1=1.19&r2=text&tr2=1.20
http://cvs.osafoundation.org/index.cgi/osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py.diff?r1=text&tr1=1.2&r2=text&tr2=1.3
http://cvs.osafoundation.org/index.cgi/osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml.diff?r1=text&tr1=1.15&r2=text&tr2=1.16
http://cvs.osafoundation.org/index.cgi/osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/ZaoBaoAgent.py.diff?r1=text&tr1=1.18&r2=text&tr2=None

Index: osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml
diff -u osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml:1.15 osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml:1.16
--- osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml:1.15	Tue Feb 10 20:59:51 2004
+++ osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/parcel.xml	Mon Apr 19 14:07:56 2004
@@ -5,14 +5,13 @@
         itemClass="OSAF.examples.zaobao.RSSData.ZaoBaoParcel"
         xmlns="//Schema/Core"
         xmlns:zaobao="//parcels/OSAF/examples/zaobao"
-        xmlns:foo="//parcels/OSAF/framework"
-        xmlns:bar="//parcels/OSAF/framework/agents"
-        xmlns:agent="//parcels/OSAF/framework/agents/schema"
+        xmlns:fw="//parcels/OSAF/framework"
+        xmlns:task="//parcels/OSAF/framework/tasks"
         xmlns:content="//parcels/OSAF/contentmodel"
         xmlns:docSchema="//parcels/OSAF/framework/blocks">
 
   <displayName>ZaoBao RSS Schema</displayName>
-  <description>RSS schema for ZaoBao parcel for 0.2 release</description>
+  <description>RSS schema for ZaoBao parcel for 0.4 release</description>
   <version>0.1</version>
 
 
@@ -122,6 +121,12 @@
       <inverseAttribute itemref="zaobao:RSSChannel/items"/>
     </Attribute>
 
+    <Attribute itemName="content">
+      <cardinality>single</cardinality>
+      <type itemref="Text"/>
+    </Attribute>
+
+    <attributes itemref="zaobao:RSSItem/content"/>
     <attributes itemref="zaobao:link"/>
     <attributes itemref="zaobao:category"/>
     <attributes itemref="zaobao:creator"/>
@@ -133,36 +138,26 @@
   </Kind>
 
 
+  <!-- ZaoBao Task Definition -->
 
-  <!-- ZaoBao Agent Definition -->
-
-  <agent:AgentItem itemName="ZaoBaoAgent">
-    <displayName>The ZaoBao Agent</displayName>
-    <description>This agent does ZaoBao's work</description>
-
-    <agent:Schedule itemName="ZaoBaoSchedule">
-      <agent:startTime>2003-11-11 12:56:00+0800</agent:startTime>
-      <agent:repeatFlag>True</agent:repeatFlag>
-      <agent:repeatDelay>00:00:05:00</agent:repeatDelay>
-    </agent:Schedule>
-
-    <agent:Action itemName="GetFeeds" itemClass="OSAF.examples.zaobao.ZaoBaoAgent.UpdateAction">
-      <description>Gets and updates all the feeds</description>
-    </agent:Action>
-
-    <agent:Instruction itemName="UpdateFeeds">
-      <description>Update feeds every so often based on the ZaoBaoSchedule</description>
-      <agent:enabled>True</agent:enabled>
-      <agent:schedule itemref="zaobao:ZaoBaoAgent/ZaoBaoSchedule"/>
-      <agent:actions itemref="zaobao:ZaoBaoAgent/GetFeeds"/>
-    </agent:Instruction>
 
-    <agent:instructions itemref="zaobao:ZaoBaoAgent/UpdateFeeds"/>
-  </agent:AgentItem>
+  <task:Task itemName="ZaoBaoTask">
+    <displayName>ZaoBao Scheduled Task</displayName>
 
+    <task:Schedule itemName="ZaoBaoSchedule">
+      <task:startTime>2003-11-11 11:11:11+0800</task:startTime>
+      <task:repeatFlag>True</task:repeatFlag>
+      <task:repeatDelay>00:00:05:00</task:repeatDelay>
+    </task:Schedule>
 
+    <task:Action itemName="GetFeeds" itemClass="OSAF.examples.zaobao.ZaoBaoTask.UpdateAction">
+      <description>Gets and updates all the feeds</description>
+    </task:Action>
 
+    <task:schedule itemref="zaobao:ZaoBaoTask/ZaoBaoSchedule"/>
+    <task:actions itemref="zaobao:ZaoBaoTask/GetFeeds"/>
 
+  </task:Task>
 
 
   <!-- view related stuff -->
@@ -170,8 +165,6 @@
     <classes key="python">OSAF.examples.zaobao.blocks.ZaoBaoItemDetail</classes>
     <superKinds itemref="docSchema:ItemDetail"/>
   </Kind>  
-
-
 
 
 </Parcel>

Index: osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py
diff -u osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py:1.12 osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py:1.13
--- osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py:1.12	Tue Mar 23 21:07:18 2004
+++ osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/RSSData.py	Mon Apr 19 14:07:56 2004
@@ -1,5 +1,5 @@
-__revision__  = "$Revision: 1.12 $"
-__date__      = "$Date: 2004/03/24 05:07:18 $"
+__revision__  = "$Revision: 1.13 $"
+__date__      = "$Date: 2004/04/19 21:07:56 $"
 __copyright__ = "Copyright (c) 2003 Open Source Applications Foundation"
 __license__   = "http://osafoundation.org/Chandler_0.1_license_terms.htm"
 
@@ -12,7 +12,6 @@
 import types
 import feedparser
 
-
 ##
 # ZaoBaoParcel
 ##
@@ -79,22 +78,20 @@
     RSSItemKindID = None
 
 
-def SetAttribute(self, data, attr, nattr=None, encoding=None):
+def SetAttribute(self, data, attr, nattr=None):
     if not nattr:
         nattr = attr
     value = data.get(attr)
     if value:
-        if encoding:
-            value = unicode(value, encoding)
         self.setAttributeValue(nattr, value)
 
-def SetAttributes(self, data, attributes, encoding=None):
+def SetAttributes(self, data, attributes):
     if type(attributes) == types.DictType:
         for attr, nattr in attributes.items():
-            SetAttribute(self, data, attr, nattr=nattr, encoding=encoding)
+            SetAttribute(self, data, attr, nattr=nattr)
     elif type(attributes) == types.ListType:
         for attr in attributes:
-            SetAttribute(self, data, attr, encoding=encoding)
+            SetAttribute(self, data, attr)
 
 
 ##
@@ -135,10 +132,11 @@
             lastModified = lastModified.tuple()
 
         # fetch the data
-        data = feedparser.parse(self.url, etag, lastModified)
 
-        # get the encoding
-        encoding = data.get('encoding', 'latin_1')
+        # XXX because of a bug in feedparser 3.0 betas we don't do
+        # etags or lastmodified here (bug 1421)
+        #data = feedparser.parse(self.url, etag, lastModified)
+        data = feedparser.parse(self.url)
 
         # set etag
         SetAttribute(self, data, 'etag')
@@ -148,27 +146,40 @@
         if modified:
             self.lastModified = mx.DateTime.mktime(modified)
 
-        self._DoChannel(data['channel'], encoding)
-        self._DoItems(data['items'], encoding)
+        # if the feed is bad, raise the sax exception
+        if data['bozo'] == 1:
+            raise data['bozo_exception']
+
+        self._DoChannel(data['channel'])
+        self._DoItems(data['items'])
 
-    def _DoChannel(self, data, encoding):
+    def _DoChannel(self, data):
         # fill in the item
         attrs = {'title':'displayName'}
-        SetAttributes(self, data, attrs, encoding)
+        SetAttributes(self, data, attrs)
 
         attrs = ['link', 'description', 'copyright', 'creator', 'category', 'language']
-        SetAttributes(self, data, attrs, encoding)
+        SetAttributes(self, data, attrs)
 
         date = data.get('date')
         if date:
-            self.date = mx.DateTime.DateTimeFrom(date)
+            self.date = mx.DateTime.DateTimeFrom(str(date))
 
-    def _DoItems(self, items, encoding):
+    def _DoItems(self, items):
         # make children
+        #print 'len items:', len(items)
+
+        # XXX because feedparser is currently broken and gives us
+        # all new entries when a feed changes, we need to delete
+        # all the existing items
+        if len(items) > 0:
+            for item in self.items:
+                item.delete()
+
         for itemData in items:
             #print 'new item'
             item = RSSItem()
-            item.Update(itemData, encoding)
+            item.Update(itemData)
             self.addValue('items', item)
 
 
@@ -184,14 +195,18 @@
             kind = ZaoBaoParcel.getRSSItemKind()
         super(RSSItem, self).__init__(name, parent, kind)
 
-    def Update(self, data, encoding):
+    def Update(self, data):
         # fill in the item
         attrs = {'title':'displayName'}
-        SetAttributes(self, data, attrs, encoding)
+        SetAttributes(self, data, attrs)
+
+        attrs = ['creator', 'link', 'category']
+        SetAttributes(self, data, attrs)
 
-        attrs = ['description', 'creator', 'link', 'category']
-        SetAttributes(self, data, attrs, encoding)
+        description = data.get('description')
+        if description:
+            self.content = self.getAttributeAspect('content', 'type').makeValue(description, indexed=True)
 
         date = data.get('date')
         if date:
-            self.date = mx.DateTime.DateTimeFrom(date)
+            self.date = mx.DateTime.DateTimeFrom(str(date))

Index: osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py
diff -u osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py:1.19 osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py:1.20
--- osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py:1.19	Tue Mar 23 21:07:18 2004
+++ osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/blocks.py	Mon Apr 19 14:07:56 2004
@@ -1,8 +1,8 @@
 """ ZaoBao blocks
 """
 
-__version__ = "$Revision: 1.19 $"
-__date__ = "$Date: 2004/03/24 05:07:18 $"
+__version__ = "$Revision: 1.20 $"
+__date__ = "$Date: 2004/04/19 21:07:56 $"
 __copyright__ = "Copyright (c) 2003 Open Source Applications Foundation"
 __license__ = "http://osafoundation.org/Chandler_0.1_license_terms.htm"
 
@@ -118,9 +118,13 @@
             if link:
                 HTMLText = HTMLText + '</a>\n'
 
-            desc = item.getAttributeValue('description', default=displayName)
+            content = item.getAttributeValue('content', default=None)
+            if content:
+                content = content.getReader().read()
+            else:
+                content = displayName
             #desc = desc.replace("<", "&lt;").replace(">", "&gt;")
-            HTMLText = HTMLText + '<p>' + desc + '</p>\n\n'
+            HTMLText = HTMLText + '<p>' + content + '</p>\n\n'
 
             HTMLText = HTMLText + '</body></html>\n'
 

Index: osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py
diff -u osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py:1.2 osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py:1.3
--- osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py:1.2	Thu Jan 15 14:30:51 2004
+++ osaf/chandler/Chandler/parcels/OSAF/examples/zaobao/feedparser.py	Mon Apr 19 14:07:56 2004
@@ -1,126 +1,36 @@
-#!/usr/bin/python
-"""Ultra-liberal feed parser
+#!/usr/bin/env python
+"""Universal feed parser
 
 Visit http://diveintomark.org/projects/feed_parser/ for the latest version
 
-Handles RSS 0.9x, RSS 1.0, RSS 2.0, Atom feeds
+Handles RSS 0.9x, RSS 1.0, RSS 2.0, Hot RSS, Atom, CDF feeds
 
-Things it handles that choke other parsers:
-- bastard combinations of RSS 0.9x and RSS 1.0
-- illegal 8-bit XML characters
-- naked and/or invalid HTML in description
-- content:encoded, xhtml:body, fullitem
-- guid
-- elements in non-standard namespaces or non-default namespaces
-- multiple content items per entry (Atom)
-- multiple links per entry (Atom)
-
-Other features:
-- resolves relative URIs in some elements
-  - uses xml:base to define base URI
-  - uses URI of feed if no xml:base is given
-  - to control which elements are resolved, set FeedParser.can_be_relative_uri
-- resolves relative URIs within embedded markup
-  - to control which elements are resolved, set FeedParser.can_contain_relative_uris
-- sanitizes embedded markup in some elements
-  - to allow/disallow HTML elements, set HTMLSanitizer.acceptable_elements
-  - to allow/disallow HTML attributes, set HTMLSanitizer.acceptable_attributes
-  - to control which feed elements are sanitized, set FeedParser.can_contain_dangerous_markup
-  - to disable entirely (NOT RECOMMENDED), set FeedParser.can_contain_dangerous_markup = []
-- tidies embedded markup
-  - fixes malformed HTML
-  - converts to XHTML
-  - converts character entities to numeric entities
-  - requires tidylib <http://utidylib.sourceforge.net/> or mxTidy <http://www.lemburg.com/files/python/mxTidy.html>
-
-Requires Python 2.1; 2.3 or later recommended
+Required: Python 2.1 or later
+Recommended: Python 2.3 or later
+Recommended: libxml2 <http://xmlsoft.org/python.html>
 """
 
-__version__ = "2.7"
+__version__ = "3.0-beta-21"
 __author__ = "Mark Pilgrim <http://diveintomark.org/>"
 __copyright__ = "Copyright 2002-4, Mark Pilgrim"
 __contributors__ = ["Jason Diamond <http://injektilo.org/>",
                     "John Beimler <http://john.beimler.org/>",
                     "Fazal Majid <http://www.majid.info/mylos/weblog/>"]
 __license__ = "Python"
-__history__ = """
-1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements,
-  added Simon Fell's test suite
-1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections
-2.0 - 10/19/2002
-  JD - use inchannel to watch out for image and textinput elements which can
-  also contain title, link, and description elements
-  JD - check for isPermaLink="false" attribute on guid elements
-  JD - replaced openAnything with open_resource supporting ETag and
-  If-Modified-Since request headers
-  JD - parse now accepts etag, modified, agent, and referrer optional
-  arguments
-  JD - modified parse to return a dictionary instead of a tuple so that any
-  etag or modified information can be returned and cached by the caller
-2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything
-  because of etag/modified, return the old etag/modified to the caller to
-  indicate why nothing is being returned
-2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its
-  useless.  Fixes the problem JD was addressing by adding it.
-2.1 - 11/14/2002 - MAP - added gzip support
-2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent.
-  start_admingeneratoragent is an example of how to handle elements with
-  only attributes, no content.
-2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify);
-  also, make sure we send the User-Agent even if urllib2 isn't available.
-  Match any variation of backend.userland.com/rss namespace.
-2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is.
-2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's
-  snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed
-  project name
-2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree);
-  removed unnecessary urllib code -- urllib2 should always be available anyway;
-  return actual url, status, and full HTTP headers (as result['url'],
-  result['status'], and result['headers']) if parsing a remote feed over HTTP --
-  this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>;
-  added the latest namespace-of-the-week for RSS 2.0
-2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom
-  User-Agent (otherwise urllib2 sends two, which confuses some servers)
-2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for
-  inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds
-2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or
-  textInput, and also to return the character encoding (if specified)
-2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking
-  nested divs within content (JohnD); fixed missing sys import (JohanS);
-  fixed regular expression to capture XML character encoding (Andrei);
-  added support for Atom 0.3-style links; fixed bug with textInput tracking;
-  added support for cloud (MartijnP); added support for multiple
-  category/dc:subject (MartijnP); normalize content model: "description" gets
-  description (which can come from description, summary, or full content if no
-  description), "content" gets dict of base/language/type/value (which can come
-  from content:encoded, xhtml:body, content, or fullitem);
-  fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang
-  tracking; fixed bug tracking unknown tags; fixed bug tracking content when
-  <content> element is not in default namespace (like Pocketsoap feed);
-  resolve relative URLs in link, guid, docs, url, comments, wfw:comment,
-  wfw:commentRSS; resolve relative URLs within embedded HTML markup in
-  description, xhtml:body, content, content:encoded, title, subtitle,
-  summary, info, tagline, and copyright; added support for pingback and
-  trackback namespaces
-2.7 - 1/5/2004 - MAP - really added support for trackback and pingback
-  namespaces, as opposed to 2.6 when I said I did but didn't really;
-  sanitize HTML markup within some elements; added mxTidy support (if
-  installed) to tidy HTML markup within some elements; fixed indentation
-  bug in parse_date (FazalM); use socket.setdefaulttimeout if available
-  (FazalM); universal date parsing and normalization (FazalM): 'created', modified',
-  'issued' are parsed into 9-tuple date format and stored in 'created_parsed',
-  'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified'
-  and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa
-2.7.1 - 1/9/2004 - MAP - fixed bug handling &quot; and &apos;.  fixed memory
-  leak not closing url opener (JohnD); added dc:publisher support (MarekK);
-  added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK)
-"""
+_debug = 0
 
 # if you are embedding feedparser in a larger application, you should change this to your application name and URL
-USER_AGENT = "UltraLiberalFeedParser/%s +http://diveintomark.org/projects/feed_parser/" % __version__
+USER_AGENT = "UniversalFeedParser/%s%s +http://diveintomark.org/projects/feed_parser/" % (__version__, _debug and "-debug" or "")
 
 # ---------- required modules (should come with any Python distribution) ----------
-import cgi, re, sgmllib, string, StringIO, urllib2, sys, copy, urlparse, htmlentitydefs, time, rfc822
+#import cjkcodecs.aliases
+#import japanese
+
+import sgmllib, re, sys, copy, urlparse, time, rfc822
+try:
+    from cStringIO import StringIO as _StringIO
+except:
+    from StringIO import StringIO as _StringIO
 
 # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
 
@@ -132,148 +42,236 @@
     
 # timeoutsocket allows feedparser to time out rather than hang forever on ultra-slow servers.
 # Python 2.3 now has this functionality available in the standard socket library, so under
-# 2.3 you don't need to install anything.
-import socket
-if hasattr(socket, 'setdefaulttimeout'):
-    socket.setdefaulttimeout(10)
-else:
-    try:
-        import timeoutsocket # http://www.timo-tasi.org/python/timeoutsocket.py
-        timeoutsocket.setDefaultSocketTimeout(10)
-    except ImportError:
-        pass
+# 2.3 you don't need to install anything.  But you probably should anyway, because the socket
+# module is buggy and timeoutsocket is better.
+try:
+    import timeoutsocket # http://www.timo-tasi.org/python/timeoutsocket.py
+    timeoutsocket.setDefaultSocketTimeout(10)
+except ImportError:
+    import socket
+    if hasattr(socket, 'setdefaulttimeout'):
+        socket.setdefaulttimeout(10)
+import urllib2
 
 # mxtidy allows feedparser to tidy malformed embedded HTML markup in description, content, etc.
-# this does not affect HTML sanitizing, which is self-contained in the HTMLSanitizer class
+# this does not affect HTML sanitizing, which is self-contained in the _HTMLSanitizer class
+#try:
+#    from mx.Tidy import Tidy as _mxtidy # http://www.lemburg.com/files/python/mxTidy.html
+#except:
+#    _mxtidy = None
+
+# If a real XML parser is available, feedparser will attempt to use it.  feedparser works
+# with both the built-in SAX parser and PyXML SAX parser.  On platforms where the Python
+# distribution does not come with an XML parser (such as Mac OS X 10.2 and some versions of
+# FreeBSD), feedparser will just fall back on regex-based parsing.  If XML libraries are
+# available but the feed turns out not to be well-formed XML, feedparser will fall back
+# on regex-based parsing and set the "bozo" bit in the results to indicate that the feed
+# author is a bozo who can't generate well-formed XML.  The two advantages of using a real
+# XML parser are (1) Unicode support, and (2) to get people to stop yelling at me for not
+# using one.
 try:
-    from mx.Tidy import Tidy as mxtidy # http://www.lemburg.com/files/python/mxTidy.html
+    import xml.sax
+    from xml.sax.saxutils import escape as _xmlescape
+    _XML_AVAILABLE = 1
 except:
-    mxtidy = None
+    _XML_AVAILABLE = 0
+    def _xmlescape(data):
+        data = data.replace("&", "&amp;")
+        data = data.replace(">", "&gt;")
+        data = data.replace("<", "&lt;")
+        return data
 
-# ---------- don't touch this ----------
+# base64 support for Atom feeds that contain embedded binary data
+try:
+    import base64, binascii
+except:
+    base64 = binascii = None
+    
+# ---------- don't touch these ----------
 sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
+sgmllib.special = re.compile('<!')
 
-if not dict:
+SUPPORTED_VERSIONS = {'': 'unknown',
+                      'rss090': 'RSS 0.90',
+                      'rss091n': 'RSS 0.91 (Netscape)',
+                      'rss091u': 'RSS 0.91 (Userland)',
+                      'rss092': 'RSS 0.92',
+                      'rss093': 'RSS 0.93',
+                      'rss094': 'RSS 0.94',
+                      'rss20': 'RSS 2.0',
+                      'rss10': 'RSS 1.0',
+                      'rss': 'RSS (unknown version)',
+                      'atom01': 'Atom 0.1',
+                      'atom02': 'Atom 0.2',
+                      'atom03': 'Atom 0.3',
+                      'atom': 'Atom (unknown version)',
+                      'cdf': 'CDF',
+                      'hotrss': 'Hot RSS',
+                      }
+
+try:
+    dict
+except NameError:
+    # Python 2.1 does not have a built-in dict() function
     def dict(aList):
         rc = {}
         for k, v in aList:
             rc[k] = v
         return rc
 
-class FeedParser(sgmllib.SGMLParser):
-    namespaces = {"http://backend.userland.com/rss": "",
+class _FeedParserMixin:
+    namespaces = {"": "",
+                  "http://backend.userland.com/rss": "",
                   "http://blogs.law.harvard.edu/tech/rss": "",
                   "http://purl.org/rss/1.0/": "",
+                  "http://my.netscape.com/rdf/simple/0.9/": "",
                   "http://example.com/newformat#": "",
                   "http://example.com/necho": "",
                   "http://purl.org/echo/": "",
                   "uri/of/echo/namespace#": "",
                   "http://purl.org/pie/": "",
                   "http://purl.org/atom/ns#": "",
-                  "http://purl.org/rss/1.0/modules/textinput/": "ti",
-                  "http://purl.org/rss/1.0/modules/company/": "co",
-                  "http://purl.org/rss/1.0/modules/syndication/": "sy",
-                  "http://purl.org/dc/elements/1.1/": "dc",
-                  "http://purl.org/dc/terms/": "dcterms",
-                  "http://webns.net/mvcb/": "admin",
-                  "http://wellformedweb.org/CommentAPI/": "wfw",
-                  "http://madskills.com/public/xml/rss/module/trackback/": "trackback",
+                  "http://purl.org/rss/1.0/modules/rss091#": "",
+                  
+                  "http://webns.net/mvcb/":                               "admin",
+                  "http://purl.org/rss/1.0/modules/aggregation/":         "ag",
+                  "http://purl.org/rss/1.0/modules/annotate/":            "annotate",
+                  "http://media.tangent.org/rss/1.0/":                    "audio",
+                  "http://backend.userland.com/blogChannelModule":        "blogChannel",
+                  "http://web.resource.org/cc/":                          "cc",
+                  "http://backend.userland.com/creativeCommonsRssModule": "creativeCommons",
+                  "http://purl.org/rss/1.0/modules/company":              "co",
+                  "http://purl.org/rss/1.0/modules/content/":             "content",
+                  "http://my.theinfo.org/changed/1.0/rss/":               "cp",
+                  "http://purl.org/dc/elements/1.1/":                     "dc",
+                  "http://purl.org/dc/terms/":                            "dcterms",
+                  "http://purl.org/rss/1.0/modules/email/":               "email",
+                  "http://purl.org/rss/1.0/modules/event/":               "ev",
+                  "http://postneo.com/icbm/":                             "icbm",
+                  "http://purl.org/rss/1.0/modules/image/":               "image",
+                  "http://xmlns.com/foaf/0.1/":                           "foaf",
+                  "http://freshmeat.net/rss/fm/":                         "fm",
+                  "http://purl.org/rss/1.0/modules/link/":                "l",
                   "http://madskills.com/public/xml/rss/module/pingback/": "pingback",
-                  "http://www.w3.org/1999/xhtml": "xhtml"}
-
-    can_be_relative_uri = ['link', 'id', 'guid', 'wfw_comment', 'wfw_commentRSS', 'docs', 'url', 'comments']
-    can_contain_relative_uris = ['content', 'body', 'xhtml_body', 'content_encoded', 'fullitem', 'description', 'title', 'summary', 'subtitle', 'info', 'tagline', 'copyright']
-    can_contain_dangerous_markup = ['content', 'body', 'xhtml_body', 'content_encoded', 'fullitem', 'description', 'title', 'summary', 'subtitle', 'info', 'tagline', 'copyright']
-    explicitly_set_type = ['title', 'tagline', 'summary', 'info', 'copyright', 'content']
+                  "http://prismstandard.org/namespaces/1.2/basic/":       "prism",
+                  "http://www.w3.org/1999/02/22-rdf-syntax-ns#":          "rdf",
+                  "http://www.w3.org/2000/01/rdf-schema#":                "rdfs",
+                  "http://purl.org/rss/1.0/modules/reference/":           "ref",
+                  "http://purl.org/rss/1.0/modules/richequiv/":           "reqv",
+                  "http://purl.org/rss/1.0/modules/search/":              "search",
+                  "http://purl.org/rss/1.0/modules/slash/":               "slash",
+                  "http://purl.org/rss/1.0/modules/servicestatus/":       "ss",
+                  "http://hacks.benhammersley.com/rss/streaming/":        "str",
+                  "http://purl.org/rss/1.0/modules/subscription/":        "sub",
+                  "http://purl.org/rss/1.0/modules/syndication/":         "sy",
+                  "http://purl.org/rss/1.0/modules/taxonomy/":            "taxo",
+                  "http://purl.org/rss/1.0/modules/threading/":           "thr",
+                  "http://purl.org/rss/1.0/modules/textinput/":           "ti",
+                  "http://madskills.com/public/xml/rss/module/trackback/":"trackback",
+                  "http://wellformedweb.org/CommentAPI/":                 "wfw",
+                  "http://purl.org/rss/1.0/modules/wiki/":                "wiki",
+                  "http://schemas.xmlsoap.org/soap/envelope/":            "soap",
+                  "http://www.w3.org/1999/xhtml":                         "xhtml",
+                  "http://www.w3.org/XML/1998/namespace":                 "xml"
+}
+
+    can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'comments']
+    can_contain_relative_uris = ['content', 'description', 'title', 'summary', 'info', 'tagline', 'copyright']
+    can_contain_dangerous_markup = ['content', 'description', 'title', 'summary', 'info', 'tagline', 'copyright']
     html_types = ['text/html', 'application/xhtml+xml']
     
     def __init__(self, baseuri=None):
-        sgmllib.SGMLParser.__init__(self)
-        self.baseuri = baseuri or ''
-        
-    def reset(self):
-        self.channel = {}
-        self.items = []
-        self.elementstack = []
+        if _debug: sys.stderr.write("initializing FeedParser\n")
+        self.channel = {} # channel- or feed-level data
+        self.items = [] # list of item- or entry-level data
+        self.version = '' # feed type/version, see SUPPORTED_VERSIONS
+
+        # the following are used internally to track state;
+        # some of this is kind of out of control and should
+        # probably be refactored into a finite state machine
         self.inchannel = 0
         self.initem = 0
         self.incontent = 0
         self.intextinput = 0
         self.inimage = 0
+        self.inauthor = 0
+        self.incontributor = 0
         self.contentparams = {}
         self.namespacemap = {}
+        self.elementstack = []
         self.basestack = []
         self.langstack = []
-        self.baseuri = ''
+        self.baseuri = baseuri or ''
         self.lang = None
-        sgmllib.SGMLParser.reset(self)
 
     def unknown_starttag(self, tag, attrs):
+        if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs))
         # normalize attrs
-        attrs = [(k.lower(), sgmllib.charref.sub(lambda m: chr(int(m.groups()[0])), v).strip()) for k, v in attrs]
+        attrs = [(k.lower(), sgmllib.charref.sub(lambda m: unichr(int(m.groups()[0])), v).strip()) for k, v in attrs]
         attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
         
-        # track inline content
-        if self.incontent and self.contentparams.get('mode') == 'xml':
-            return self.handle_data("<%s%s>" % (tag, "".join([' %s="%s"' % t for t in attrs])))
-
         # track xml:base and xml:lang
         attrsD = dict(attrs)
-        baseuri = attrsD.get('xml:base')
+        baseuri = attrsD.get('xml:base', attrsD.get('base'))
         if baseuri:
+            if _debug: sys.stderr.write('self.baseuri=%s\n' % baseuri)
             self.baseuri = baseuri
-        lang = attrsD.get('xml:lang')
+        lang = attrsD.get('xml:lang', attrsD.get('lang'))
         if lang:
             self.lang = lang
         self.basestack.append(baseuri)
         self.langstack.append(lang)
         
         # track namespaces
-        for prefix, value in attrs:
-            if not prefix.startswith("xmlns:"): continue
-            prefix = prefix[6:]
-            if value.find('backend.userland.com/rss') <> -1:
-                # match any backend.userland.com namespace
-                value = 'http://backend.userland.com/rss'
-            if self.namespaces.has_key(value):
-                self.namespacemap[prefix] = self.namespaces[value]
+        for prefix, uri in attrs:
+            if prefix.startswith('xmlns:'):
+                self.trackNamespace(prefix[6:], uri)
+            elif prefix == 'xmlns':
+                self.trackNamespace(None, uri)
+
+        # track inline content
+        if self.incontent and self.contentparams.get('mode') == 'escaped':
+            # element declared itself as escaped markup, but it isn't really
+            self.contentparams['mode'] = 'xml'
+        if self.incontent and self.contentparams.get('mode') == 'xml':
+            # Note: probably shouldn't simply recreate localname here, but
+            # our namespace handling isn't actually 100% correct in cases where
+            # the feed redefines the default namespace (which is actually
+            # the usual case for inline content, thanks Sam), so here we
+            # cheat and just reconstruct the element based on localname
+            # because that compensates for the bugs in our namespace handling.
+            # This will horribly munge inline content with non-empty qnames,
+            # but nobody actually does that, so I'm not fixing it.
+            tag = tag.split(':')[-1]
+            return self.handle_data("<%s%s>" % (tag, "".join([' %s="%s"' % t for t in attrs])), escape=0)
 
         # match namespaces
-        colonpos = tag.find(':')
-        if colonpos <> -1:
-            prefix = tag[:colonpos]
-            suffix = tag[colonpos+1:]
-            prefix = self.namespacemap.get(prefix, prefix)
-            if prefix:
-                prefix = prefix + '_'
+        if tag.find(':') <> -1:
+            prefix, suffix = tag.split(':', 1)
         else:
-            prefix = ''
-            suffix = tag
+            prefix, suffix = '', tag
+        prefix = self.namespacemap.get(prefix, prefix)
+        if prefix:
+            prefix = prefix + '_'
 
         # call special handler (if defined) or default handler
         methodname = '_start_' + prefix + suffix
         try:
             method = getattr(self, methodname)
-            return method(attrs)
+            return method(attrsD)
         except AttributeError:
             return self.push(prefix + suffix, 1)
 
     def unknown_endtag(self, tag):
-        # track inline content
-        if self.incontent and self.contentparams.get('mode') == 'xml':
-            self.handle_data("</%s>" % tag)
-
+        if _debug: sys.stderr.write('end %s\n' % tag)
         # match namespaces
-        colonpos = tag.find(':')
-        if colonpos <> -1:
-            prefix = tag[:colonpos]
-            suffix = tag[colonpos+1:]
-            prefix = self.namespacemap.get(prefix, prefix)
-            if prefix:
-                prefix = prefix + '_'
+        if tag.find(':') <> -1:
+            prefix, suffix = tag.split(':', 1)
         else:
-            prefix = ''
-            suffix = tag
+            prefix, suffix = '', tag
+        prefix = self.namespacemap.get(prefix, prefix)
+        if prefix:
+            prefix = prefix + '_'
 
         # call special handler (if defined) or default handler
         methodname = '_end_' + prefix + suffix
@@ -283,10 +281,20 @@
         except AttributeError:
             self.pop(prefix + suffix)
 
+        # track inline content
+        if self.incontent and self.contentparams.get('mode') == 'escaped':
+            # element declared itself as escaped markup, but it isn't really
+            self.contentparams['mode'] = 'xml'
+        if self.incontent and self.contentparams.get('mode') == 'xml':
+            tag = tag.split(':')[-1]
+            self.handle_data("</%s>" % tag, escape=0)
+
         # track xml:base and xml:lang going out of scope
         if self.basestack:
-            baseuri = self.basestack.pop()
-            if baseuri:
+            self.basestack.pop()
+            if self.basestack and self.basestack[-1]:
+                baseuri = self.basestack[-1]
+                if _debug: sys.stderr.write('self.baseuri=%s\n' % baseuri)
                 self.baseuri = baseuri
         if self.langstack:
             lang = self.langstack.pop()
@@ -298,8 +306,6 @@
         # Reconstruct the original character reference.
         if not self.elementstack: return
         text = "&#%s;" % ref
-        if self.incontent and self.contentparams.get('mode') == 'xml':
-            text = cgi.escape(text)
         self.elementstack[-1][2].append(text)
 
     def handle_entityref(self, ref):
@@ -307,16 +313,15 @@
         # Reconstruct the original entity reference.
         if not self.elementstack: return
         text = "&%s;" % ref
-        if self.incontent and self.contentparams.get('mode') == 'xml':
-            text = cgi.escape(text)
         self.elementstack[-1][2].append(text)
 
-    def handle_data(self, text):
+    def handle_data(self, text, escape=1):
         # called for each block of plain text, i.e. outside of any tag and
         # not containing any character or entity references
         if not self.elementstack: return
-        if self.incontent and self.contentparams.get('mode') == 'xml':
-            text = cgi.escape(text)
+#        if _debug: sys.stderr.write(text)
+        if escape and self.contentparams.get('mode') == 'xml':
+            text = _xmlescape(text)
         self.elementstack[-1][2].append(text)
 
     def handle_comment(self, text):
@@ -328,10 +333,12 @@
         pass
 
     def handle_decl(self, text):
-        # called for the DOCTYPE, if present, e.g.
-        # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
-        #     "http://www.w3.org/TR/html4/loose.dtd">
         pass
+#        # called for the DOCTYPE, if present, e.g.
+#        # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+#        #     "http://www.w3.org/TR/html4/loose.dtd">
+#        if text.count('http://my.netscape.com/publish/formats/rss-0.91.dtd'):
+#            self.version = 'rss091n'
 
     _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
     def _scan_name(self, i, declstartpos):
@@ -345,81 +352,127 @@
             name = s.strip()
             if (i + len(s)) == n:
                 return None, -1  # end of buffer
-            return string.lower(name), m.end()
+            return name.lower(), m.end()
         else:
             self.updatepos(declstartpos, i)
             self.error("expected name token")
 
     def parse_declaration(self, i):
         # override internal declaration handler to handle CDATA blocks
+        if _debug: sys.stderr.write("entering parse_declaration\n")
+#        if re.search(r'^<!DOCTYPE\s+?rss\s+?PUBLIC\s+?"-//Netscape Communications//DTD RSS 0.91//EN"\s+?"http://my.netscape.com/publish/formats/rss-0.91.dtd">', self.rawdata[i:]):
+#            if _debug: sys.stderr.write("found Netscape DOCTYPE\n")
+#            self.version = 'rss091n'
         if self.rawdata[i:i+9] == '<![CDATA[':
             k = self.rawdata.find(']]>', i)
             if k == -1: k = len(self.rawdata)
-            self.handle_data(cgi.escape(self.rawdata[i+9:k]))
+            self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
             return k+3
-        return sgmllib.SGMLParser.parse_declaration(self, i)
+        else:
+            k = self.rawdata.find('>', i)
+            return k+1
+
+    def trackNamespace(self, prefix, uri):
+        if (prefix, uri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version:
+            self.version = 'rss090'
+        if (prefix, uri) == (None, 'http://purl.org/rss/1.0/') and not self.version:
+            self.version = 'rss10'
+        if not prefix: return
+        if uri.find('backend.userland.com/rss') <> -1:
+            # match any backend.userland.com namespace
+            uri = 'http://backend.userland.com/rss'
+        if self.namespaces.has_key(uri):
+            self.namespacemap[prefix] = self.namespaces[uri]
 
     def resolveURI(self, uri):
         return urlparse.urljoin(self.baseuri or '', uri)
     
+    def decodeEntities(self, element, data):
+        if self.contentparams.get('mode') == 'escaped':
+            data = data.replace('&lt;', '<')
+            data = data.replace('&gt;', '>')
+            data = data.replace('&amp;', '&')
+            data = data.replace('&quot;', '"')
+            data = data.replace('&apos;', "'")
+        return data
+        
     def push(self, element, expectingText):
+#        while self.elementstack and self.elementstack[-1][1]:
+#            self.pop(self.elementstack[-1][0])
         self.elementstack.append([element, expectingText, []])
 
     def pop(self, element):
         if not self.elementstack: return
+#        while self.elementstack[-1][0] != element: self.pop(self.elementstack[-1][0])
         if self.elementstack[-1][0] != element: return
 
         element, expectingText, pieces = self.elementstack.pop()
-        if not expectingText: return
-        
         output = "".join(pieces)
         output = output.strip()
+        if not expectingText: return output
         
+        # decode base64 content
+        if self.contentparams.get('mode') == 'base64' and base64:
+            try:
+                output = base64.decodestring(output)
+            except binascii.Error:
+                pass
+            except binascii.Incomplete:
+                pass
+                
         # resolve relative URIs
         if (element in self.can_be_relative_uri) and output:
             output = self.resolveURI(output)
         
         # decode entities within embedded markup
-        output = output or ''
-        if (element in self.explicitly_set_type and self.contentparams.get('type') in self.html_types) or \
-           (element not in self.explicitly_set_type):
-            output = output.replace('&lt;', '<')
-            output = output.replace('&gt;', '>')
-            output = output.replace('&amp;', '&')
-        output = output.replace('&quot;', '"')
-        output = output.replace('&apos;', "'")
-        
+        output = self.decodeEntities(element, output)
+
         # resolve relative URIs within embedded markup
         if element in self.can_contain_relative_uris:
-            output = resolveRelativeURIs(output, self.baseuri)
+            output = _resolveRelativeURIs(output, self.baseuri)
         
         # sanitize embedded markup
         if element in self.can_contain_dangerous_markup:
-            output = sanitizeHTML(output)
+            output = _sanitizeHTML(output)
             
         # store output in appropriate place(s)
-        if self.incontent and self.initem:
-            if not self.items[-1].has_key(element):
-                self.items[-1][element] = []
-            contentparams = copy.deepcopy(self.contentparams)
-            contentparams['value'] = output
-            self.items[-1][element].append(contentparams)
-        elif self.initem:
-            if element == 'category':
+        if self.initem:
+            if element == 'content':
+                self.items[-1].setdefault(element, [])
+                contentparams = copy.deepcopy(self.contentparams)
+                contentparams['value'] = output
+                self.items[-1][element].append(contentparams)
+            elif element == 'category':
+                self.items[-1][element] = output
                 domain = self.items[-1]['categories'][-1][0]
                 self.items[-1]['categories'][-1] = (domain, output)
+            elif element == 'source':
+                self.items[-1]['source']['value'] = output
             elif element == 'link':
+                self.items[-1][element] = output
                 if output:
                     self.items[-1]['links'][-1]['href'] = output
-            self.items[-1][element] = output
+            else:
+                self.items[-1][element] = output
+                if self.incontent:
+                    if element == 'description':
+                        element = 'summary'
+                    contentparams = copy.deepcopy(self.contentparams)
+                    contentparams['value'] = output
+                    self.items[-1][element + '_detail'] = contentparams
         elif self.inchannel and (not self.intextinput) and (not self.inimage):
+            self.channel[element] = output
             if element == 'category':
                 domain = self.channel['categories'][-1][0]
                 self.channel['categories'][-1] = (domain, output)
             elif element == 'link':
-                self.channel['links']['href'] = output
-            self.channel[element] = output
-
+                self.channel['links'][-1]['href'] = output
+            elif self.incontent:
+                if element == 'description':
+                    element = 'tagline'
+                contentparams = copy.deepcopy(self.contentparams)
+                contentparams['value'] = output
+                self.channel[element + '_detail'] = contentparams
         return output
 
     def _mapToStandardPrefix(self, name):
@@ -431,8 +484,8 @@
             name = prefix + ':' + suffix
         return name
         
-    def _getAttribute(self, attrs, name):
-        return dict(attrs).get(self._mapToStandardPrefix(name))
+    def _getAttribute(self, attrsD, name):
+        return attrsD.get(self._mapToStandardPrefix(name))
 
     def _save(self, key, value):
         if value:
@@ -440,109 +493,275 @@
                 self.items[-1].setdefault(key, value)
             elif self.channel:
                 self.channel.setdefault(key, value)
-        
-    def _start_channel(self, attrs):
+
+    def _start_rss(self, attrsD):
+        versionmap = {'0.91': 'rss091u',
+                      '0.92': 'rss092',
+                      '0.93': 'rss093',
+                      '0.94': 'rss094'}
+        if not self.version:
+            attr_version = attrsD.get('version', '')
+            version = versionmap.get(attr_version)
+            if version:
+                self.version = version
+            elif attr_version.startswith('2.'):
+                self.version = 'rss20'
+            else:
+                self.version = 'rss'
+    
+    def _start_dlhottitles(self, attrsD):
+        self.version = 'hotrss'
+
+    def _start_channel(self, attrsD):
+        self.inchannel = 1
+        self._cdf_common(attrsD)
+    _start_feedinfo = _start_channel
+
+    def _cdf_common(self, attrsD):
+        if attrsD.has_key('lastmod'):
+            if _debug: sys.stderr.write(attrsD['lastmod'] + '\n')
+            self._start_modified({})
+            self.elementstack[-1][-1] = attrsD['lastmod']
+            self._end_modified()
+        if attrsD.has_key('href'):
+            self._start_link({})
+            self.elementstack[-1][-1] = attrsD['href']
+            self._end_link()
+    
+    def _start_feed(self, attrsD):
         self.inchannel = 1
-    _start_feed = _start_channel
+        versionmap = {'0.1': 'atom01',
+                      '0.2': 'atom02',
+                      '0.3': 'atom03'}
+        if not self.version:
+            attr_version = attrsD.get('version')
+            version = versionmap.get(attr_version)
+            if version:
+                self.version = version
+            else:
+                self.version = 'atom'
 
     def _end_channel(self):
         self.inchannel = 0
     _end_feed = _end_channel
     
-    def _start_image(self, attrs):
+    def _start_image(self, attrsD):
         self.inimage = 1
             
     def _end_image(self):
         self.inimage = 0
                 
-    def _start_textinput(self, attrs):
+    def _start_textinput(self, attrsD):
         self.intextinput = 1
+        self.push('textinput', 0)
+        context = self._getContext()
+        context.setdefault('textinput', {})
     _start_textInput = _start_textinput
     
     def _end_textinput(self):
+        self.pop('textinput')
         self.intextinput = 0
     _end_textInput = _end_textinput
 
-    def _start_tagline(self, attrs):
+    def _start_author(self, attrsD):
+        self.inauthor = 1
+        self.push('author', 1)
+    _start_managingeditor = _start_author
+    _start_dc_author = _start_author
+    _start_dc_creator = _start_author
+
+    def _end_author(self):
+        self.pop('author')
+        self.inauthor = 0
+        self._sync_author_detail()
+    _end_managingeditor = _end_author
+    _end_dc_author = _end_author
+    _end_dc_creator = _end_author
+
+    def _start_contributor(self, attrsD):
+        self.incontributor = 1
+        context = self._getContext()
+        context.setdefault('contributors', [])
+        context['contributors'].append({})
+        self.push('contributor', 0)
+
+    def _end_contributor(self):
+        self.pop('contributor')
+        self.incontributor = 0
+        
+    def _start_name(self, attrsD):
+        self.push('name', 0)
+
+    def _end_name(self):
+        value = self.pop('name')
+        if self.inauthor:
+            self._save_author('name', value)
+        elif self.incontributor:
+            self._save_contributor('name', value)
+        elif self.intextinput:
+            context = self._getContext()
+            context['textinput']['name'] = value
+
+    def _start_url(self, attrsD):
+        self.push('url', 1)
+    _start_homepage = _start_url
+    _start_uri = _start_url
+
+    def _end_url(self):
+        value = self.pop('url')
+        if self.inauthor:
+            self._save_author('url', value)
+        elif self.incontributor:
+            self._save_contributor('url', value)
+        elif self.inimage:
+            # TODO
+            pass
+        elif self.intextinput:
+            # TODO (map to link)
+            pass
+    _end_homepage = _end_url
+    _end_uri = _end_url
+
+    def _start_email(self, attrsD):
+        self.push('email', 0)
+
+    def _end_email(self):
+        value = self.pop('email')
+        if self.inauthor:
+            self._save_author('email', value)
+        elif self.incontributor:
+            self._save_contributor('email', value)
+            pass
+
+    def _getContext(self):
+        if self.initem:
+            context = self.items[-1]
+        else:
+            context = self.channel
+        return context
+
+    def _save_author(self, key, value):
+        context = self._getContext()
+        context.setdefault('author_detail', {})
+        context['author_detail'][key] = value
+        self._sync_author_detail()
+
+    def _save_contributor(self, key, value):
+        context = self._getContext()
+        context.setdefault('contributors', [{}])
+        context['contributors'][-1][key] = value
+
+    def _sync_author_detail(self):
+        context = self._getContext()
+        detail = context.get('author_detail')
+        if detail:
+            name = detail.get('name')
+            email = detail.get('email')
+            if name and email:
+                context['author'] = "%s (%s)" % (name, email)
+            elif name:
+                context['author'] = name
+            elif email:
+                context['author'] = email
+        else:
+            author = context.get('author')
+            if not author: return
+            emailmatch = re.search(r"""(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))""", author)
+            if not emailmatch: return
+            email = emailmatch.group(0)
+            # probably a better way to do the following, but it passes all the tests
+            author = author.replace(email, '')
+            author = author.replace('()', '')
+            author = author.strip()
+            if author and (author[0] == '('):
+                author = author[1:]
+            if author and (author[-1] == ')'):
+                author = author[:-1]
+            author = author.strip()
+            context.setdefault('author_detail', {})
+            context['author_detail']['name'] = author
+            context['author_detail']['email'] = email
+            
+    def _start_tagline(self, attrsD):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'escaped'),
+                              'type': attrsD.get('type', 'text/plain'),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
         self.push('tagline', 1)
+    _start_subtitle = _start_tagline
 
     def _end_tagline(self):
         value = self.pop('tagline')
+        self.incontent -= 1
+        self.contentparams.clear()
         if self.inchannel:
             self.channel['description'] = value
+    _end_subtitle = _end_tagline
             
-    def _start_item(self, attrs):
+    def _start_copyright(self, attrsD):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'escaped'),
+                              'type': attrsD.get('type', 'text/plain'),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
+        self.push('copyright', 1)
+    _start_dc_rights = _start_copyright
+
+    def _end_copyright(self):
+        self.pop('copyright')
+        self.incontent -= 1
+        self.contentparams.clear()
+    _end_dc_rights = _end_copyright
+
+    def _start_item(self, attrsD):
         self.items.append({})
         self.push('item', 0)
         self.initem = 1
+        self._cdf_common(attrsD)
     _start_entry = _start_item
+    _start_product = _start_item
 
     def _end_item(self):
         self.pop('item')
         self.initem = 0
     _end_entry = _end_item
 
-    def _start_dc_language(self, attrs):
+    def _start_dc_language(self, attrsD):
         self.push('language', 1)
     _start_language = _start_dc_language
 
     def _end_dc_language(self):
-        self.pop('language')
+        self.lang = self.pop('language')
     _end_language = _end_dc_language
 
-    def _start_dc_creator(self, attrs):
-        self.push('creator', 1)
-    _start_managingeditor = _start_dc_creator
-    _start_webmaster = _start_dc_creator
-    _start_name = _start_dc_creator
-
-    def _end_dc_creator(self):
-        self.pop('creator')
-    _end_managingeditor = _end_dc_creator
-    _end_webmaster = _end_dc_creator
-    _end_name = _end_dc_creator
-
-    def _start_dc_author(self, attrs):
-        self.push('author', 1)
-    _start_author = _start_dc_author
-
-    def _end_dc_author(self):
-        self.pop('author')
-    _end_author = _end_dc_author
-
-    def _start_dc_publisher(self, attrs):
+    def _start_dc_publisher(self, attrsD):
         self.push('publisher', 1)
+    _start_webmaster = _start_dc_publisher
 
     def _end_dc_publisher(self):
         self.pop('publisher')
+    _end_webmaster = _end_dc_publisher
         
-    def _start_dc_rights(self, attrs):
-        self.push('rights', 1)
-    _start_copyright = _start_dc_rights
-
-    def _end_dc_rights(self):
-        self.pop('rights')
-    _end_copyright = _end_dc_rights
-
-    def _start_dcterms_issued(self, attrs):
+    def _start_dcterms_issued(self, attrsD):
         self.push('issued', 1)
     _start_issued = _start_dcterms_issued
 
     def _end_dcterms_issued(self):
         value = self.pop('issued')
-        self._save('issued_parsed', parse_date(value))
+        self._save('issued_parsed', _parse_date(value))
     _end_issued = _end_dcterms_issued
 
-    def _start_dcterms_created(self, attrs):
+    def _start_dcterms_created(self, attrsD):
         self.push('created', 1)
     _start_created = _start_dcterms_created
 
     def _end_dcterms_created(self):
         value = self.pop('created')
-        self._save('created_parsed', parse_date(value))
+        self._save('created_parsed', _parse_date(value))
     _end_created = _end_dcterms_created
 
-    def _start_dcterms_modified(self, attrs):
+    def _start_dcterms_modified(self, attrsD):
         self.push('modified', 1)
     _start_modified = _start_dcterms_modified
     _start_dc_date = _start_dcterms_modified
@@ -550,7 +769,8 @@
 
     def _end_dcterms_modified(self):
         value = self.pop('modified')
-        parsed_value = parse_date(value)
+        if _debug: sys.stderr.write('_end_dcterms_modified, value=' + value + '\n')
+        parsed_value = _parse_date(value)
         self._save('date', value)
         self._save('date_parsed', parsed_value)
         self._save('modified_parsed', parsed_value)
@@ -558,9 +778,28 @@
     _end_dc_date = _end_dcterms_modified
     _end_pubdate = _end_dcterms_modified
 
-    def _start_category(self, attrs):
+    def _start_expirationdate(self, attrsD):
+        self.push('expired', 1)
+
+    def _end_expirationdate(self):
+        self._save('expired_parsed', _parse_date(self.pop('expired')))
+
+    def _start_cc_license(self, attrsD):
+        self.push('license', 1)
+        value = self._getAttribute(attrsD, 'rdf:resource')
+        if value:
+            self.elementstack[-1][2].append(value)
+        self.pop('license')
+        
+    def _start_creativecommons_license(self, attrsD):
+        self.push('license', 1)
+
+    def _end_creativecommons_license(self):
+        self.pop('license')
+
+    def _start_category(self, attrsD):
         self.push('category', 1)
-        domain = self._getAttribute(attrs, 'domain')
+        domain = self._getAttribute(attrsD, 'domain')
         cats = []
         if self.initem:
             cats = self.items[-1].setdefault('categories', [])
@@ -568,13 +807,17 @@
             cats = self.channel.setdefault('categories', [])
         cats.append((domain, None))
     _start_dc_subject = _start_category
+    _start_keywords = _start_category
         
     def _end_category(self):
         self.pop('category')
     _end_dc_subject = _end_category
+    _end_keywords = _end_category
         
-    def _start_link(self, attrs):
-        attrsD = dict(attrs)
+    def _start_cloud(self, attrsD):
+        self.channel['cloud'] = attrsD
+        
+    def _start_link(self, attrsD):
         attrsD.setdefault('rel', 'alternate')
         attrsD.setdefault('type', 'text/html')
         if attrsD.has_key('href'):
@@ -584,7 +827,8 @@
             self.items[-1].setdefault('links', [])
             self.items[-1]['links'].append(attrsD)
         elif self.inchannel:
-            self.channel['links'] = attrsD
+            self.channel.setdefault('links', [])
+            self.channel['links'].append(attrsD)
         if attrsD.has_key('href'):
             expectingText = 0
             if attrsD.get('type', '') in self.html_types:
@@ -594,9 +838,17 @@
                     self.channel['link'] = attrsD['href']
         else:
             self.push('link', expectingText)
+    _start_producturl = _start_link
 
-    def _start_guid(self, attrs):
-        self.guidislink = ('ispermalink', 'false') not in attrs
+    def _end_link(self):
+        value = self.pop('link')
+        if self.intextinput:
+            context = self._getContext()
+            context['textinput']['link'] = value
+    _end_producturl = _end_link
+
+    def _start_guid(self, attrsD):
+        self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
         self.push('guid', 1)
 
     def _end_guid(self):
@@ -607,78 +859,152 @@
             # and only if the item doesn't already have a link element
             self._save('link', value)
 
-    def _start_id(self, attrs):
+    def _start_id(self, attrsD):
         self.push('id', 1)
 
     def _end_id(self):
         value = self.pop('id')
         self._save('guid', value)
             
-    def _start_title(self, attrs):
+    def _start_title(self, attrsD):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'escaped'),
+                              'type': attrsD.get('type', 'text/plain'),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
         self.push('title', self.inchannel or self.initem)
     _start_dc_title = _start_title
 
     def _end_title(self):
-        self.pop('title')
+        value = self.pop('title')
+        self.incontent -= 1
+        self.contentparams.clear()
+        if self.intextinput:
+            context = self._getContext()
+            context['textinput']['title'] = value
     _end_dc_title = _end_title
 
-    def _start_description(self, attrs):
+    def _start_description(self, attrsD, default_content_type='text/html'):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'escaped'),
+                              'type': attrsD.get('type', default_content_type),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
         self.push('description', self.inchannel or self.initem)
 
+    def _start_abstract(self, attrsD):
+        return self._start_description(attrsD, 'text/plain')
+
     def _end_description(self):
         value = self.pop('description')
-        if self.initem:
-            self.items[-1]['summary'] = value
+        self.incontent -= 1
+        self.contentparams.clear()
+        context = self._getContext()
+        if self.intextinput:
+            context['textinput']['description'] = value
+        elif self.initem:
+            context['summary'] = value
         elif self.inchannel:
-            self.channel['tagline'] = value
-        
-    def _start_admin_generatoragent(self, attrs):
+            context['tagline'] = value
+    _end_abstract = _end_description
+
+    def _start_info(self, attrsD):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'escaped'),
+                              'type': attrsD.get('type', 'text/plain'),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
+        self.push('info', 1)
+
+    def _end_info(self):
+        self.pop('info')
+        self.incontent -= 1
+        self.contentparams.clear()
+
+    def _start_generator(self, attrsD):
+        if attrsD:
+            if attrsD.has_key('url'):
+                attrsD['url'] = self.resolveURI(attrsD['url'])
+            self.channel['generator_detail'] = attrsD
+        self.push('generator', 1)
+
+    def _end_generator(self):
+        value = self.pop('generator')
+        if self.channel.has_key('generator_detail'):
+            self.channel['generator_detail']['name'] = value
+            
+    def _start_admin_generatoragent(self, attrsD):
         self.push('generator', 1)
-        value = self._getAttribute(attrs, 'rdf:resource')
+        value = self._getAttribute(attrsD, 'rdf:resource')
         if value:
             self.elementstack[-1][2].append(value)
         self.pop('generator')
 
-    def _start_admin_errorreportsto(self, attrs):
+    def _start_admin_errorreportsto(self, attrsD):
         self.push('errorreportsto', 1)
-        value = self._getAttribute(attrs, 'rdf:resource')
+        value = self._getAttribute(attrsD, 'rdf:resource')
         if value:
             self.elementstack[-1][2].append(value)
         self.pop('errorreportsto')
         
-    def _start_summary(self, attrs):
+    def _start_summary(self, attrsD):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'escaped'),
+                              'type': attrsD.get('type', 'text/plain'),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
         self.push('summary', 1)
 
     def _end_summary(self):
         value = self.pop('summary')
         if self.items:
             self.items[-1]['description'] = value
+        self.incontent -= 1
+        self.contentparams.clear()
         
-    def _start_content(self, attrs):
-        attrsD = dict(attrs)
+    def _start_enclosure(self, attrsD):
+        if self.initem:
+            self.items[-1].setdefault('enclosures', [])
+            self.items[-1]['enclosures'].append(attrsD)
+            
+    def _start_source(self, attrsD):
+        if self.initem:
+            self.items[-1]['source'] = attrsD
+        self.push('source', 1)
+
+    def _end_source(self):
+        self.pop('source')
+
+    def _start_content(self, attrsD):
         self.incontent += 1
         self.contentparams = {'mode': attrsD.get('mode', 'xml'),
                               'type': attrsD.get('type', 'text/plain'),
-                              'language': attrsD.get('xml:lang', None),
+                              'language': attrsD.get('xml:lang', self.lang),
                               'base': attrsD.get('xml:base', self.baseuri)}
         self.push('content', 1)
 
-    def _start_body(self, attrs):
-        attrsD = dict(attrs)
+    def _start_prodlink(self, attrsD):
+        self.incontent += 1
+        self.contentparams = {'mode': attrsD.get('mode', 'xml'),
+                              'type': attrsD.get('type', 'text/html'),
+                              'language': attrsD.get('xml:lang', self.lang),
+                              'base': attrsD.get('xml:base', self.baseuri)}
+        self.push('content', 1)
+
+    def _start_body(self, attrsD):
         self.incontent += 1
         self.contentparams = {'mode': 'xml',
                               'type': 'application/xhtml+xml',
-                              'language': attrsD.get('xml:lang', None),
+                              'language': attrsD.get('xml:lang', self.lang),
                               'base': attrsD.get('xml:base', self.baseuri)}
         self.push('content', 1)
     _start_xhtml_body = _start_body
 
-    def _start_content_encoded(self, attrs):
-        attrsD = dict(attrs)
+    def _start_content_encoded(self, attrsD):
         self.incontent += 1
         self.contentparams = {'mode': 'escaped',
                               'type': 'text/html',
-                              'language': attrsD.get('xml:lang', None),
+                              'language': attrsD.get('xml:lang', self.lang),
                               'base': attrsD.get('xml:base', self.baseuri)}
         self.push('content', 1)
     _start_fullitem = _start_content_encoded
@@ -693,19 +1019,90 @@
     _end_xhtml_body = _end_content
     _end_content_encoded = _end_content
     _end_fullitem = _end_content
+    _end_prodlink = _end_content
 
-class BaseHTMLProcessor(sgmllib.SGMLParser):
+if _XML_AVAILABLE:
+    class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler, xml.sax.handler.EntityResolver):#, xml.sax.handler.DTDHandler):
+        def __init__(self, baseuri):
+            if _debug: sys.stderr.write('trying StrictFeedParser\n')
+            xml.sax.handler.ContentHandler.__init__(self)
+            _FeedParserMixin.__init__(self, baseuri)
+            self.bozo = 0
+            self.exc = None
+        
+        def startPrefixMapping(self, prefix, uri):
+            self.trackNamespace(prefix, uri)
+        
+        def startElementNS(self, name, qname, attrs):
+            namespace, localname = name
+            namespace = str(namespace or '')
+            if namespace.find('backend.userland.com/rss') <> -1:
+                # match any backend.userland.com namespace
+                namespace = 'http://backend.userland.com/rss'
+            prefix = self.namespaces.get(namespace, 'unknown')
+            if prefix:
+                localname = prefix + ':' + localname
+            localname = str(localname).lower()
+
+            # qname implementation is horribly broken in Python 2.1 (it
+            # doesn't report any), and slightly broken in Python 2.2 (it
+            # doesn't report the xml: namespace). So we match up namespaces
+            # with a known list first, and then possibly override them with
+            # the qnames the SAX parser gives us (if indeed it gives us any
+            # at all).  Thanks to MatejC for helping me test this and
+            # tirelessly telling me that it didn't work yet.
+            attrsD = {}
+            for (namespace, attrlocalname), attrvalue in attrs._attrs.items():
+                prefix = self.namespaces.get(namespace, '')
+                if prefix:
+                    attrlocalname = prefix + ":" + attrlocalname
+                attrsD[str(attrlocalname).lower()] = attrvalue
+            for qname in attrs.getQNames():
+                attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
+            self.unknown_starttag(localname, attrsD.items())
+
+        def resolveEntity(self, publicId, systemId):
+            pass
+#            return _StringIO()
+
+        def characters(self, text):
+            self.handle_data(text)
+
+        def endElementNS(self, name, qname):
+            namespace, localname = name
+            namespace = str(namespace)
+            prefix = self.namespaces.get(namespace, '')
+            if prefix:
+                localname = prefix + ':' + localname
+            localname = str(localname).lower()
+            self.unknown_endtag(localname)
+
+        def error(self, exc):
+            self.bozo = 1
+            self.exc = exc
+        def fatalError(self, exc):
+            self.error(exc)
+            raise exc
+
+class _LooseFeedParser(_FeedParserMixin, sgmllib.SGMLParser):
+    def __init__(self, baseuri):
+        sgmllib.SGMLParser.__init__(self)
+        _FeedParserMixin.__init__(self, baseuri)
+
+class _BaseHTMLProcessor(sgmllib.SGMLParser):
+    elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
+      'img', 'input', 'isindex', 'link', 'meta', 'param']
+    
     def __init__(self):
         sgmllib.SGMLParser.__init__(self)
         
     def reset(self):
-        # extend (called by sgmllib.SGMLParser.__init__)
         self.pieces = []
         sgmllib.SGMLParser.reset(self)
 
     def normalize_attrs(self, attrs):
         # utility method to be called by descendants
-        attrs = [(k.lower(), sgmllib.charref.sub(lambda m: chr(int(m.groups()[0])), v).strip()) for k, v in attrs]
+        attrs = [(k.lower(), sgmllib.charref.sub(lambda m: unichr(int(m.groups()[0])), v).strip()) for k, v in attrs]
         attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
         return attrs
 
@@ -714,12 +1111,16 @@
         # attrs is a list of (attr, value) tuples
         # e.g. for <pre class="screen">, tag="pre", attrs=[("class", "screen")]
         strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs])
-        self.pieces.append("<%(tag)s%(strattrs)s>" % locals())
+        if tag in self.elements_no_end_tag:
+            self.pieces.append("<%(tag)s%(strattrs)s />" % locals())
+        else:
+            self.pieces.append("<%(tag)s%(strattrs)s>" % locals())
         
     def unknown_endtag(self, tag):
         # called for each end tag, e.g. for </pre>, tag will be "pre"
         # Reconstruct the original end tag.
-        self.pieces.append("</%(tag)s>" % locals())
+        if tag not in self.elements_no_end_tag:
+            self.pieces.append("</%(tag)s>" % locals())
 
     def handle_charref(self, ref):
         # called for each character reference, e.g. for "&#160;", ref will be "160"
@@ -729,10 +1130,7 @@
     def handle_entityref(self, ref):
         # called for each entity reference, e.g. for "&copy;", ref will be "copy"
         # Reconstruct the original entity reference.
-        self.pieces.append("&%(ref)s" % locals())
-        # standard HTML entities are closed with a semicolon; other entities are not
-        if htmlentitydefs.entitydefs.has_key(ref):
-            self.pieces.append(";")
+        self.pieces.append("&%(ref)s;" % locals())
 
     def handle_data(self, text):
         # called for each block of plain text, i.e. outside of any tag and
@@ -761,7 +1159,7 @@
         """Return processed HTML as a single string"""
         return "".join(self.pieces)
 
-class RelativeURIResolver(BaseHTMLProcessor):
+class _RelativeURIResolver(_BaseHTMLProcessor):
     relative_uris = [('a', 'href'),
                      ('applet', 'codebase'),
                      ('area', 'href'),
@@ -789,7 +1187,7 @@
                      ('script', 'src')]
 
     def __init__(self, baseuri):
-        BaseHTMLProcessor.__init__(self)
+        _BaseHTMLProcessor.__init__(self)
         self.baseuri = baseuri
 
     def resolveURI(self, uri):
@@ -798,15 +1196,14 @@
     def unknown_starttag(self, tag, attrs):
         attrs = self.normalize_attrs(attrs)
         attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
-        BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
+        _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
         
-def resolveRelativeURIs(htmlSource, baseURI):
-    p = RelativeURIResolver(baseURI)
+def _resolveRelativeURIs(htmlSource, baseURI):
+    p = _RelativeURIResolver(baseURI)
     p.feed(htmlSource)
-    data = p.output()
-    return data
+    return p.output()
 
-class HTMLSanitizer(BaseHTMLProcessor):
+class _HTMLSanitizer(_BaseHTMLProcessor):
     acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
       'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
       'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset',
@@ -815,7 +1212,7 @@
       'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike',
       'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th',
       'thead', 'tr', 'tt', 'u', 'ul', 'var']
-    
+
     acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
       'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
       'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols',
@@ -826,16 +1223,28 @@
       'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
       'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type',
       'usemap', 'valign', 'value', 'vspace', 'width']
-    
+
+    unacceptable_elements_with_end_tag = ['script', 'applet']
+
+    def reset(self):
+        _BaseHTMLProcessor.reset(self)
+        self.unacceptablestack = 0
+        
     def unknown_starttag(self, tag, attrs):
-        if not tag in self.acceptable_elements: return
+        if not tag in self.acceptable_elements:
+            if tag in self.unacceptable_elements_with_end_tag:
+                self.unacceptablestack += 1
+            return
         attrs = self.normalize_attrs(attrs)
         attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes]
-        BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
+        _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
         
     def unknown_endtag(self, tag):
-        if not tag in self.acceptable_elements: return
-        BaseHTMLProcessor.unknown_endtag(self, tag)
+        if not tag in self.acceptable_elements:
+            if tag in self.unacceptable_elements_with_end_tag:
+                self.unacceptablestack -= 1
+            return
+        _BaseHTMLProcessor.unknown_endtag(self, tag)
 
     def handle_pi(self, text):
         pass
@@ -843,22 +1252,26 @@
     def handle_decl(self, text):
         pass
 
-def sanitizeHTML(htmlSource):
-    p = HTMLSanitizer()
+    def handle_data(self, text):
+        if not self.unacceptablestack:
+            _BaseHTMLProcessor.handle_data(self, text)
+
+def _sanitizeHTML(htmlSource):
+    p = _HTMLSanitizer()
     p.feed(htmlSource)
     data = p.output()
-    if mxtidy:
-        nerrors, nwarnings, data, errordata = mxtidy.tidy(data, output_xhtml=1, numeric_entities=1, wrap=0)
-        if data.count('<body'):
-            data = data.split('<body', 1)[1]
-            if data.count('>'):
-                data = data.split('>', 1)[1]
-        if data.count('</body'):
-            data = data.split('</body', 1)[0]
-        data = data.strip()
+#    if _mxtidy:
+#        nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, output_xhtml=1, numeric_entities=1, wrap=0)
+#        if data.count('<body'):
+#            data = data.split('<body', 1)[1]
+#            if data.count('>'):
+#                data = data.split('>', 1)[1]
+#        if data.count('</body'):
+#            data = data.split('</body', 1)[0]
+    data = data.strip().replace('\r\n', '\n')
     return data
 
-class FeedURLHandler(urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
+class _FeedURLHandler(urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
     def http_error_default(self, req, fp, code, msg, headers):
         if ((code / 100) == 3) and (code != 304):
             return self.http_error_302(req, fp, code, msg, headers)
@@ -866,7 +1279,6 @@
         infourl = addinfourl(fp, headers, req.get_full_url())
         infourl.status = code
         return infourl
-#        raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
 
     def http_error_302(self, req, fp, code, msg, headers):
         infourl = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
@@ -881,9 +1293,8 @@
     http_error_300 = http_error_302
     http_error_307 = http_error_302
         
-def open_resource(source, etag=None, modified=None, agent=None, referrer=None):
-    """
-    URI, filename, or string --> stream
+def _open_resource(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None):
+    """URL, filename, or string --> stream
 
     This function lets you define parsers that take any input source
     (URL, pathname to local or network file, or actual data as a string)
@@ -906,111 +1317,174 @@
     Referer[sic] request header.
     """
 
-    if hasattr(source, "read"):
-        return source
+    if hasattr(url_file_stream_or_string, "read"):
+        return url_file_stream_or_string
 
-    if source == "-":
+    if url_file_stream_or_string == "-":
         return sys.stdin
 
-    if not agent:
-        agent = USER_AGENT
-        
-    # try to open with urllib2 (to use optional headers)
-    request = urllib2.Request(source)
-    if etag:
-        request.add_header("If-None-Match", etag)
-    if modified:
-        request.add_header("If-Modified-Since", format_http_date(modified))
-    request.add_header("User-Agent", agent)
-    if referrer:
-        request.add_header("Referer", referrer)
+    if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):
+        if not agent:
+            agent = USER_AGENT
+        
+        # try to open with urllib2 (to use optional headers)
+        request = urllib2.Request(url_file_stream_or_string)
+        request.add_header("User-Agent", agent)
+        if etag:
+            request.add_header("If-None-Match", etag)
+        if modified:
+            # format into an RFC 1123-compliant timestamp. We can't use
+            # time.strftime() since the %a and %b directives can be affected
+            # by the current locale, but RFC 2616 states that dates must be
+            # in English.
+            short_weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+            months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
+            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]))
+        if referrer:
+            request.add_header("Referer", referrer)
         if gzip:
             request.add_header("Accept-encoding", "gzip")
-    opener = urllib2.build_opener(FeedURLHandler())
-    opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
-    try:
+        opener = urllib2.build_opener(_FeedURLHandler())
+        opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
         try:
-            return opener.open(request)
-        except:
-            # source is not a valid URL, but it might be a valid filename
-            pass
-    finally:
-        opener.close() # JohnD
+            try:
+                return opener.open(request)
+#            except ValueError:
+#                # not a valid URL, but might be a valid filename
+#                pass
+#            except AssertionError:
+#                # under Python 2.1, non-URLs will fail with an AssertionError;
+#                # still might be a valid filename, so fall through
+#                pass
+            except:
+                return _StringIO('')
+        finally:
+            opener.close() # JohnD
     
-    # try to open with native open function (if source is a filename)
+    # try to open with native open function (if url_file_stream_or_string is a filename)
     try:
-        return open(source)
+        return open(url_file_stream_or_string)
     except:
         pass
 
-    # treat source as string
-    return StringIO.StringIO(str(source))
+    # treat url_file_stream_or_string as string
+    return _StringIO(str(url_file_stream_or_string))
 
-def get_etag(resource):
-    """
-    Get the ETag associated with a response returned from a call to 
-    open_resource().
-
-    If the resource was not returned from an HTTP server or the server did
-    not specify an ETag for the resource, this will return None.
-    """
-
-    if hasattr(resource, "info"):
-        return resource.info().getheader("ETag")
-    return None
-
-def get_modified(resource):
-    """
-    Get the Last-Modified timestamp for a response returned from a call to
-    open_resource().
-
-    If the resource was not returned from an HTTP server or the server did
-    not specify a Last-Modified timestamp, this function will return None.
-    Otherwise, it returns a tuple of 9 integers as returned by gmtime() in
-    the standard Python time module().
-    """
-
-    if hasattr(resource, "info"):
-        last_modified = resource.info().getheader("Last-Modified")
-        if last_modified:
-            return parse_date(last_modified)
-    return None
-
-short_weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
-long_weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
-months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
-
-def format_http_date(date):
-    """
-    Formats a tuple of 9 integers into an RFC 1123-compliant timestamp as
-    required in RFC 2616. We don't use time.strftime() since the %a and %b
-    directives can be affected by the current locale (HTTP dates have to be
-    in English). The date MUST be in GMT (Greenwich Mean Time).
-    """
+# W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by
+# Drake and licensed under the Python license.  Removed all range checking
+# for month, day, hour, minute, and second, since mktime will normalize
+# these later
+def _w3dtf_parse(s):
+    def __extract_date(m):
+        year = int(m.group("year"))
+        if year < 100:
+            year = 100 * int(time.gmtime()[0] / 100) + int(year)
+        if year < 1000:
+            return 0, 0, 0
+        julian = m.group("julian")
+        if julian:
+            julian = int(julian)
+            month = julian / 30 + 1
+            day = julian % 30 + 1
+            jday = None
+            while jday != julian:
+                t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0))
+                jday = time.gmtime(t)[-2]
+                diff = abs(jday - julian)
+                if jday > julian:
+                    if diff < day:
+                        day = day - diff
+                    else:
+                        month = month - 1
+                        day = 31
+                elif jday < julian:
+                    if day + diff < 28:
+                       day = day + diff
+                    else:
+                        month = month + 1
+            return year, month, day
+        month = m.group("month")
+        day = 1
+        if month is None:
+            month = 1
+        else:
+            month = int(month)
+            day = m.group("day")
+            if day:
+                day = int(day)
+            else:
+                day = 1
+        return year, month, day
 
-    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (short_weekdays[date[6]], date[2], months[date[1] - 1], date[0], date[3], date[4], date[5])
+    def __extract_time(m):
+        if not m:
+            return 0, 0, 0
+        hours = m.group("hours")
+        if not hours:
+            return 0, 0, 0
+        hours = int(hours)
+        minutes = int(m.group("minutes"))
+        seconds = m.group("seconds")
+        if seconds:
+            seconds = int(seconds)
+        else:
+            seconds = 0
+        return hours, minutes, seconds
 
-# if possible, use the PyXML module xml.utils.iso8601 to parse dates
-try:
-    from xml.utils.iso8601 import parse as iso8601_parse
-except ImportError:
-    iso8601_parse = None
+    def __extract_tzd(m):
+        """Return the Time Zone Designator as an offset in seconds from UTC."""
+        if not m:
+            return 0
+        tzd = m.group("tzd")
+        if not tzd:
+            return 0
+        if tzd == "Z":
+            return 0
+        hours = int(m.group("tzdhours"))
+        minutes = m.group("tzdminutes")
+        if minutes:
+            minutes = int(minutes)
+        else:
+            minutes = 0
+        offset = (hours*60 + minutes) * 60
+        if tzd[0] == "+":
+            return -offset
+        return offset
+
+    __date_re = ("(?P<year>\d\d\d\d)"
+                 "(?:(?P<dsep>-|)"
+                 "(?:(?P<julian>\d\d\d)"
+                 "|(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?))?")
+    __tzd_re = "(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)"
+    __tzd_rx = re.compile(__tzd_re)
+    __time_re = ("(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)"
+                 "(?:(?P=tsep)(?P<seconds>\d\d(?:[.,]\d+)?))?"
+                 + __tzd_re)
+    __datetime_re = "%s(?:T%s)?" % (__date_re, __time_re)
+    __datetime_rx = re.compile(__datetime_re)
+    m = __datetime_rx.match(s)
+    if m is None or m.group() != s:
+        return None
+    gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0)
+    if gmt[0] == 0: return
+    return time.mktime(gmt) + __extract_tzd(m) - time.timezone
 
-# the ISO 8601 standard is very convoluted and irregular - a full ISO 8601
+# Additional ISO-8601 date parsing routines written by Fazal Majid
+# The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
 # parser is beyond the scope of feedparser and would be a worthwhile addition
 # to the Python library
 # A single regular expression cannot parse ISO 8601 date formats into groups
 # as the standard is highly irregular (for instance is 030104 2003-01-04 or
 # 0301-04-01), so we use templates instead
-# Please note the order in templates is significant because we need  a
+# Please note the order in templates is significant because we need a
 # greedy match
-iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO',
+_iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO',
                 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', 
                 '-YY-?MM', '-OOO', '-YY',
                 '--MM-?DD', '--MM',
                 '---DD',
                 'CC', '']
-iso8601_re = [
+_iso8601_re = [
     tmpl.replace(
     'YYYY', r'(?P<year>\d{4})').replace(
     'YY', r'(?P<year>\d\d)').replace(
@@ -1021,49 +1495,41 @@
     + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
     + r'(:(?P<second>\d{2}))?'
     + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
-    for tmpl in iso8601_tmpl]
+    for tmpl in _iso8601_tmpl]
+del tmpl
 
-iso8601_matches = [re.compile(regex).match for regex in iso8601_re]
+_iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
+del regex
 
-def parse_date(date):
-    """
-    Parses a variety of date formats into a tuple of 9 integers as
-    returned by time.gmtime(). This should not use time.strptime() since
-    that function is not available on all platforms and could also be
-    affected by the current locale.
-    """
+# rfc822.py defines several time zones, but we define some extra ones.
+# "ET" is equivalent to "EST", etc.
+_additional_timezones = {'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800}
+rfc822._timezones.update(_additional_timezones)
 
+def _parse_date(date):
+    """Parses a variety of date formats into a tuple of 9 integers"""
     date = str(date)
-
     try:
-        # if at all possible, use the standard library's rfc822 module's
-        # (RFC2822, actually, which also encompasses RFC1123)
-        # parsedate function instead of rolling our own
-        # rfc822.parsedate is quite robust, and handles asctime-style dates
-        # as well
+        # try the standard rfc822 library, which handles
+        # RFC822, RFC1123, RFC2822, and asctime
         tm = rfc822.parsedate_tz(date)
         if tm:
             return time.gmtime(rfc822.mktime_tz(tm))
-        # not a RFC2822 date, try ISO 8601 format instead
+        # not a RFC2822 date, try W3DTF profile of ISO-8601
         try:
-            if iso8601_parse:
-                tm = iso8601_parse(date)
+            tm = _w3dtf_parse(date)
         except ValueError:
             tm = None
         if tm:
             return time.gmtime(tm)
-        # unfortunately, xml.utils.iso8601 does not recognize many valid
-        # ISO8601 formats like 20040105, so we try our home-made
-        # regular expressions instead
-        for iso8601_match in iso8601_matches:
-            m = iso8601_match(date)
-            if m:
-                break
-        if not m:
-            return None
+        # try various non-W3DTF ISO-8601-compatible formats like 20040105
+        m = None
+        for _iso8601_match in _iso8601_matches:
+            m = _iso8601_match(date)
+            if m: break
+        if not m: return
         # catch truly malformed strings
-        if m.span() == (0, 0):
-            return None
+        if m.span() == (0, 0): return
         params = m.groupdict()
         ordinal = params.get("ordinal", 0)
         if ordinal:
@@ -1075,7 +1541,7 @@
             year = time.gmtime()[0]
         elif len(year) == 2:
             # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
-            year = 100 * (time.gmtime()[0] // 100) + int(year)
+            year = 100 * int(time.gmtime()[0] / 100) + int(year)
         else:
             year = int(year)
         month = params.get("month", "-")
@@ -1101,7 +1567,7 @@
             day = int(day)
         # special case of the century - is the first year of the 21st century
         # 2000 or 2001 ? The debate goes on...
-        if "century" in params:
+        if "century" in params.keys():
             year = (int(params["century"]) - 1) * 100 + 1
         # in ISO 8601 most fields are optional
         for field in ["hour", "minute", "second", "tzhour", "tzmin"]:
@@ -1132,157 +1598,235 @@
                 return None
         # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
         # which is guaranteed to normalize d/m/y/h/m/s
-        # many implementations have bugs, however
+        # many implementations have bugs, but we'll pretend they don't
         return time.localtime(time.mktime(tm))
     except:
         return None
 
-def parse(uri, etag=None, modified=None, agent=None, referrer=None):
+def _getCharacterEncoding(http_headers, xml_data):
+    """Get the character encoding of the XML document
+
+    http_headers is a dictionary
+    xml_data is a raw string (not Unicode)
+    
+    This is so much trickier than it sounds,
+    it's not even funny.  According to RFC 3023 ("XML Media Types"), if
+    the HTTP Content-Type is application/xml, application/*+xml,
+    application/xml-external-parsed-entity, or application/xml-dtd,
+    the encoding given in the charset parameter of the HTTP Content-Type
+    takes precedence over the encoding given in the XML prefix within the
+    document, and defaults to "utf-8" if neither are specified.  But, if
+    the HTTP Content-Type is text/xml, text/*+xml, or
+    text/xml-external-parsed-entity, the encoding given in the XML prefix
+    within the document is ALWAYS IGNORED and only the encoding given in
+    the charset parameter of the HTTP Content-Type header should be
+    respected, and it defaults to "us-ascii" if not specified.  If
+    Content-Type is unspecified (input was local file or non-HTTP source)
+    or unrecognized (server just got it totally wrong), then go by the
+    encoding given in the XML prefix of the document and default to
+    "utf-8" as per the XML specification.
+    """
+
+    def _parseHTTPContentType(content_type):
+        """takes HTTP Content-Type header and returns (content type, charset)
+
+        If no charset is specified, returns (content type, '')
+        If no content type is specified, returns ('', '')
+        Both return parameters are guaranteed to be lowercase strings
+        """
+        if not content_type:
+            return '', ''
+        paramstr = content_type.split(';')[1:]
+        if not paramstr:
+            return content_type, ''
+        content_type = content_type.split(';', 1)[0].strip().lower()
+        import string
+        params = dict([map(string.lower, map(string.strip, p.strip().split('=', 1))) for p in paramstr])
+        charset = params.get('charset')
+        if not charset:
+            return content_type, ''
+        if charset[0] in ('"', "'"):
+            charset = charset[1:]
+        if charset and charset[-1] in ('"', "'"):
+            charset = charset[:-1]
+        charset = charset.strip()
+        return content_type, charset
+
+    true_encoding = None
+    http_content_type, http_encoding = _parseHTTPContentType(http_headers.get("content-type"))
+    xml_encoding_match = re.compile('<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
+    xml_encoding = xml_encoding_match and xml_encoding_match.groups()[0].lower() or ''
+    if (http_content_type == 'application/xml') or \
+       (http_content_type == 'application/xml-dtd') or \
+       (http_content_type == 'application/xml-external-parsed-entity') or \
+       (http_content_type.startswith('application/') and http_content_type.endswith('+xml')):
+        if http_encoding:
+            true_encoding = http_encoding
+        elif xml_encoding:
+            true_encoding = xml_encoding
+        else:
+            true_encoding = 'utf-8'
+    elif (http_content_type == 'text/xml') or \
+         (http_content_type == 'text/xml-external-parsed-entity') or \
+         (http_content_type.startswith('text/') and http_content_type.endswith('+xml')):
+        if http_encoding:
+            true_encoding = http_encoding
+        else:
+            true_encoding = 'us-ascii'
+    else:
+        true_encoding = xml_encoding or 'utf-8'
+    return true_encoding, http_encoding, xml_encoding
+    
+def _changeEncodingDeclaration(data, encoding):
+    """Changes an XML data stream on the fly to specify a new encoding
+
+    data is a raw string (not Unicode) that is presumed to be in %encoding already
+    encoding is a string recognized by encodings.aliases
+    """
+    if _debug: sys.stderr.write('entering _changeEncodingDeclaration\n')
+    if _debug: sys.stderr.write('proposed encoding: %s\n' % encoding)
+    data = unicode(data, encoding)
+    declmatch = re.compile(u'^<\?xml[^>]*?>')
+    newdecl = unicode("""<?xml version='1.0' encoding='%s'?>""" % encoding, encoding)
+    if declmatch.search(data):
+        data = declmatch.sub(newdecl, data)
+    else:
+        data = newdecl + u'\n' + data
+    return data.encode(encoding)
+
+def _stripDoctype(data):
+    """Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
+
+    rss_version may be "rss091n" or None
+    stripped_data is the same XML document, minus the DOCTYPE
+    """
+    doctype_pattern = re.compile(r'<!DOCTYPE([^>]*?)>', re.MULTILINE)
+    doctype_results = doctype_pattern.findall(data)
+    doctype = doctype_results and doctype_results[0] or ''
+    if doctype.lower().count('netscape'):
+        version = 'rss091n'
+    else:
+        version = None
+    data = doctype_pattern.sub('', data)
+    return version, data
+    
+def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None):
+    """Parse a feed from a URL, file, stream, or string"""
     result = {}
-    f = open_resource(uri, etag=etag, modified=modified, agent=agent, referrer=referrer)
+    f = _open_resource(url_file_stream_or_string, etag=etag, modified=modified, agent=agent, referrer=referrer)
     data = f.read()
     if hasattr(f, "headers"):
         if gzip and f.headers.get('content-encoding', '') == 'gzip':
             try:
-                data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read()
+                data = gzip.GzipFile(fileobj=_StringIO(data)).read()
             except:
                 # some feeds claim to be gzipped but they're not, so we get garbage
                 data = ''
-    newEtag = get_etag(f)
-    if newEtag: result["etag"] = newEtag
-    elif etag: result["etag"] = etag
-    newModified = get_modified(f)
-    if newModified: result["modified"] = newModified
-    elif modified: result["modified"] = modified
+    if hasattr(f, "info"):
+        info = f.info()
+        result["etag"] = info.getheader("ETag")
+        last_modified = info.getheader("Last-Modified")
+        if last_modified:
+            result["modified"] = _parse_date(last_modified)
     if hasattr(f, "url"):
         result["url"] = f.url
-    if hasattr(f, "headers"):
-        result["headers"] = f.headers.dict
+        result["status"] = 200 # default, may be overridden later
     if hasattr(f, "status"):
         result["status"] = f.status
-    elif hasattr(f, "url"):
-        result["status"] = 200
-    # get the xml encoding
-#    xmlheaderRe = re.compile('<\?.*encoding="(.*)".*\?>') # TvdV's version
-#    xmlheaderRe = re.compile('xml\s.*\sencoding=(".*"|\'.*\').*') # Blake's version
-    xmlheaderRe = re.compile('<\?.*encoding=[\'"](.*?)[\'"].*\?>') # Andrei's version
-    match = xmlheaderRe.match(data)
-    if match:
-        result['encoding'] = match.groups()[0].lower()
+    if hasattr(f, "headers"):
+        result["headers"] = f.headers.dict
     f.close()
+    result['channel'] = {}
+    result['items'] = {}
+    result['encoding'], http_encoding, xml_encoding = _getCharacterEncoding(result.get("headers", {}), data)
+    result['version'], data = _stripDoctype(data)
     baseuri = result.get('headers', {}).get('content-location', result.get('url'))
-    r = FeedParser(baseuri)
-    r.feed(data)
-    result['channel'] = r.channel
-    result['items'] = r.items
+    # try true XML parser first
+    if _XML_AVAILABLE:
+        if _debug: sys.stderr.write('using xml library\n')
+        result['bozo'] = 0
+        feedparser = _StrictFeedParser(baseuri)
+        saxparser = xml.sax.make_parser(["drv_libxml2"])
+        saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
+        saxparser.setContentHandler(feedparser)
+        saxparser.setErrorHandler(feedparser)
+        try:
+            saxparser.setDTDHandler(feedparser)
+        except xml.sax.SAXNotSupportedException:
+            # libxml2 driver does not support DTDHandler
+            if _debug: sys.stderr.write('using an xml library that does not support DTDHandler (not a big deal)\n')
+        try:
+            saxparser.setEntityResolver(feedparser)
+        except xml.sax.SAXNotSupportedException:
+            # libxml2 driver does not support EntityResolver
+            if _debug: sys.stderr.write('using an xml library that does not support EntityResolver (not a big deal)\n')
+        encoding_set = (result['encoding'] == xml_encoding)
+#        if not encoding_set:
+#            if hasattr(xml.sax.handler, "property_encoding"):
+#                try:
+#                    saxparser.setProperty(xml.sax.handler.property_encoding, result['encoding'])
+#                    encoding_set = 1
+#                except xml.sax.SAXNotSupportedException:
+#                    pass
+#                except xml.sax.SAXNotRecognizedException:
+#                    pass
+        bozo_exception = None
+        if not encoding_set:
+            try:
+                data = _changeEncodingDeclaration(data, result['encoding'])
+                encoding_set = 1
+            except Exception, bozo_exception:
+                pass
+        if encoding_set:
+            source = xml.sax.xmlreader.InputSource()
+            source.setByteStream(_StringIO(data))
+            if hasattr(saxparser, '_ns_stack'):
+                # work around bug in built-in SAX parser (doesn't recognize xml: namespace)
+                # PyXML doesn't have this problem, and it doesn't have _ns_stack either
+                saxparser._ns_stack.append({'http://www.w3.org/XML/1998/namespace':'xml'})
+            try:
+                saxparser.parse(source)
+            except Exception, e:
+                # SAX parser is supposed to catch all of these and call feedparser.fatal_error,
+                # which captures them.  For some reason, some Unicode-related errors go
+                # uncaught on some combination of platform, XML library, Python version,
+                # and phase of the moon.
+                feedparser.bozo = 1
+                feedparser.bozo_exception = e
+            if feedparser.bozo:
+                # feed is not well-formed XML, fall back on regex-based parser
+                if _debug: sys.stderr.write('xml parsing failed, using regexes.  now you have two problems...\n')
+                result['bozo'] = 1
+                result['bozo_exception'] = feedparser.exc
+                # munge short tags, e.g. <description/> becomes <description></description>
+                data = re.sub(r'<(\S+)/>', r'<\1></\1>', data)
+                feedparser = _LooseFeedParser(baseuri)
+                feedparser.feed(data)
+        else:
+            if _debug: sys.stderr.write('character encoding is wrong, using regexes\n')
+            result['bozo'] = 1
+            result['bozo_exception'] = bozo_exception
+            # munge short tags, e.g. <description/> becomes <description></description>
+            data = re.sub(r'<(\S+)/>', r'<\1></\1>', data)
+            feedparser = _LooseFeedParser(baseuri)
+            feedparser.feed(data)
+    else:
+        if _debug: sys.stderr.write('no xml libraries available, using regexes\n')
+        # munge short tags, e.g. <description/> becomes <description></description>
+        data = re.sub(r'<(\S+)/>', r'<\1></\1>', data)
+        feedparser = _LooseFeedParser(baseuri)
+        feedparser.feed(data)
+    result['channel'] = feedparser.channel
+    result['items'] = feedparser.items
+    result['version'] = result['version'] or feedparser.version
     return result
 
-TEST_SUITE = ('http://www.pocketsoap.com/rssTests/rss1.0withModules.xml',
-              'http://www.pocketsoap.com/rssTests/rss1.0withModulesNoDefNS.xml',
-              'http://www.pocketsoap.com/rssTests/rss1.0withModulesNoDefNSLocalNameClash.xml',
-              'http://www.pocketsoap.com/rssTests/rss2.0noNSwithModules.xml',
-              'http://www.pocketsoap.com/rssTests/rss2.0noNSwithModulesLocalNameClash.xml',
-              'http://www.pocketsoap.com/rssTests/rss2.0NSwithModules.xml',
-              'http://www.pocketsoap.com/rssTests/rss2.0NSwithModulesNoDefNS.xml',
-              'http://www.pocketsoap.com/rssTests/rss2.0NSwithModulesNoDefNSLocalNameClash.xml')
-
-last_day_year = time.localtime(time.mktime(
-    (time.gmtime()[0], 12, 31, 0, 0, 0, 0, 0, 0)))
-last_day_january = time.localtime(time.mktime(
-    (time.gmtime()[0], 1, 31, 0, 0, 0, 0, 0, 0)))
-first_day_month = time.localtime(time.mktime(
-    (time.gmtime()[0], time.gmtime()[1], 1, 0, 0, 0, 0, 0, 0)))
-first_day_december = time.localtime(time.mktime(
-    (time.gmtime()[0], 12, 1, 0, 0, 0, 0, 0, 0)))
-DATETIME_SUITE = (
-    ('asctime', 'Sun Jan  4 16:29:06 PST 2004',
-     (2004, 1, 5, 0, 29, 6, 0, 5, 0)),
-    ('RFC-2822', 'Sat, 03 Jan 2004 07:21:52 GMT',
-     (2004, 1, 3, 7, 21, 52, 5, 3, 0)),
-    # http://www.w3.org/TR/NOTE-datetime
-    ('W3C-datetime (Tokyo)', '2003-12-31T18:14:55+08:00',
-     (2003, 12, 31, 10, 14, 55, 2, 365, 0)),
-    ('W3C-datetime (San Francisco)', '2003-12-31T10:14:55-08:00',
-     (2003, 12, 31, 18, 14, 55, 2, 365, 0)),
-    ('W3C-datetime (zulu)', '2003-12-31T10:14:55Z',
-     (2003, 12, 31, 10, 14, 55, 2, 365, 0)),
-    # Complete ISO 8601 test cases for the sake of completeness
-    # See:
-    # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
-    # http://www.mcs.vuw.ac.nz/technical/software/SGML/doc/iso8601/ISO8601.html
-    ('ISO8601 date only', '2003-12-31',
-     (2003, 12, 31, 0, 0, 0, 2, 365, 0)),
-    ('ISO8601 date only (variant)', '20031231',
-     (2003, 12, 31, 0, 0, 0, 2, 365, 0)),
-    ('ISO8601 year/month only', '2003-12',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 year only', '2003',
-     (2003, 1, 1, 0, 0, 0, 2, 1, 0)),
-    ('ISO8601 century only', '21',
-     (2001, 1, 1, 0, 0, 0, 0, 1, 0)),
-    ('ISO8601 century omitted', '03-12-31',
-     (2003, 12, 31, 0, 0, 0, 2, 365, 0)),
-    ('ISO8601 century omitted (variant)', '031231',
-     (2003, 12, 31, 0, 0, 0, 2, 365, 0)),
-    ('ISO8601 year/month only (century omitted)', '-03-12',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 year/month only (century omitted variant)', '-0312',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 year only (century omitted)', '-03',
-     (2003, 1, 1, 0, 0, 0, 2, 1, 0)),
-    ('ISO8601 day/month only (year omitted)', '--12-31', last_day_year),
-    ('ISO8601 day/month only (year omitted variant)', '--1231', last_day_year),
-    ('ISO8601 month only', '--12', first_day_december),
-    ('ISO8601 day only', '---01', first_day_month),
-    ('ISO8601 year/ordinal', '2003-335',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 year/ordinal (variant)', '2003335',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 year/ordinal (century omitted)', '03-335',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 year/ordinal (century omitted variant)', '03335',
-     (2003, 12, 1, 0, 0, 0, 0, 335, 0)),
-    ('ISO8601 ordinal only', '-%03d' % last_day_year[-2], last_day_year),
-    ('ISO8601 ordinal only', '-031', last_day_january),
-    # XXX missing ISO 8601 week/day formats
-    # time formats
-    ('ISO8601 time only', '17:41:00',
-     time.gmtime()[0:3] + (17, 41 ,00) + time.gmtime()[-3:]),
-    ('ISO8601 time only (zulu)', '17:41:00Z',
-     time.gmtime()[0:3] + (17, 41 ,00) + time.gmtime()[-3:]),
-    ('ISO8601 time only (Tokyo)', '18:14:55+08:00',
-     time.gmtime()[0:3] + (10, 14, 55) + time.gmtime()[-3:]),
-    ('ISO8601 time only (Tokyo)', '18:14:55+08',
-     time.gmtime()[0:3] + (10, 14, 55) + time.gmtime()[-3:]),
-    # rollover, leap years, and so on
-    ('Rollover', '2004-02-28T18:14:55-08:00',
-     (2004, 2, 29, 2, 14, 55, 6, 60, 0)),
-    ('Rollover', '2003-02-28T18:14:55-08:00',
-     (2003, 3, 1, 2, 14, 55, 5, 60, 0)),
-    ('Rollover (Y2K)', '2000-02-28T18:14:55-08:00',
-     (2000, 2, 29, 2, 14, 55, 1, 60, 0)),
-    # this will overflow due to 32-bit time_t overflow
-    # years multiple of 100 but not of 400 are not leap years, e.g. 1900, 2100
-    ('Rollover (2100) (IGNORE)', '2100-02-28T18:14:55-08:00',
-     (2100, 3, 1, 2, 14, 55, 0, 60, 0)),
-    # miscellaneous non-conforming formats, seen in the wild
-    ('Bogus (from http://mindview.net/WebLog/RSS.xml)', '1-2-04', None),
-    ('US-style date only', '04-01-05',
-     (2004, 1, 5, 0, 0, 0, 0, 5, 0)))
-    
-
 if __name__ == '__main__':
-    if sys.argv[1:] == ['date']:
-        for test, date, gmtime in DATETIME_SUITE:
-            result = parse_date(date)
-            if result != gmtime:
-                print '### failed test for', test, '("%s")' % date
-                print 'got',  result, 'expected', gmtime
+    if not sys.argv[1:]:
+        print __doc__
         sys.exit(0)
-    if sys.argv[1:]:
-        urls = sys.argv[1:]
     else:
-        urls = TEST_SUITE
+        urls = sys.argv[1:]
     from pprint import pprint
     for url in urls:
         print url
@@ -1291,11 +1835,112 @@
         pprint(result)
         print
 
-"""
-TODO
-- image
-- author
-- contributor
-- comments
-- base64 content
-"""
+#TODO
+#- image
+#
+#REVISION HISTORY
+#1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements,
+#  added Simon Fell's test suite
+#1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections
+#2.0 - 10/19/2002
+#  JD - use inchannel to watch out for image and textinput elements which can
+#  also contain title, link, and description elements
+#  JD - check for isPermaLink="false" attribute on guid elements
+#  JD - replaced openAnything with open_resource supporting ETag and
+#  If-Modified-Since request headers
+#  JD - parse now accepts etag, modified, agent, and referrer optional
+#  arguments
+#  JD - modified parse to return a dictionary instead of a tuple so that any
+#  etag or modified information can be returned and cached by the caller
+#2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything
+#  because of etag/modified, return the old etag/modified to the caller to
+#  indicate why nothing is being returned
+#2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its
+#  useless.  Fixes the problem JD was addressing by adding it.
+#2.1 - 11/14/2002 - MAP - added gzip support
+#2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent.
+#  start_admingeneratoragent is an example of how to handle elements with
+#  only attributes, no content.
+#2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify);
+#  also, make sure we send the User-Agent even if urllib2 isn't available.
+#  Match any variation of backend.userland.com/rss namespace.
+#2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is.
+#2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's
+#  snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed
+#  project name
+#2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree);
+#  removed unnecessary urllib code -- urllib2 should always be available anyway;
+#  return actual url, status, and full HTTP headers (as result['url'],
+#  result['status'], and result['headers']) if parsing a remote feed over HTTP --
+#  this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>;
+#  added the latest namespace-of-the-week for RSS 2.0
+#2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom
+#  User-Agent (otherwise urllib2 sends two, which confuses some servers)
+#2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for
+#  inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds
+#2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or
+#  textInput, and also to return the character encoding (if specified)
+#2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking
+#  nested divs within content (JohnD); fixed missing sys import (JohanS);
+#  fixed regular expression to capture XML character encoding (Andrei);
+#  added support for Atom 0.3-style links; fixed bug with textInput tracking;
+#  added support for cloud (MartijnP); added support for multiple
+#  category/dc:subject (MartijnP); normalize content model: "description" gets
+#  description (which can come from description, summary, or full content if no
+#  description), "content" gets dict of base/language/type/value (which can come
+#  from content:encoded, xhtml:body, content, or fullitem);
+#  fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang
+#  tracking; fixed bug tracking unknown tags; fixed bug tracking content when
+#  <content> element is not in default namespace (like Pocketsoap feed);
+#  resolve relative URLs in link, guid, docs, url, comments, wfw:comment,
+#  wfw:commentRSS; resolve relative URLs within embedded HTML markup in
+#  description, xhtml:body, content, content:encoded, title, subtitle,
+#  summary, info, tagline, and copyright; added support for pingback and
+#  trackback namespaces
+#2.7 - 1/5/2004 - MAP - really added support for trackback and pingback
+#  namespaces, as opposed to 2.6 when I said I did but didn't really;
+#  sanitize HTML markup within some elements; added mxTidy support (if
+#  installed) to tidy HTML markup within some elements; fixed indentation
+#  bug in _parse_date (FazalM); use socket.setdefaulttimeout if available
+#  (FazalM); universal date parsing and normalization (FazalM): 'created', modified',
+#  'issued' are parsed into 9-tuple date format and stored in 'created_parsed',
+#  'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified'
+#  and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa
+#2.7.1 - 1/9/2004 - MAP - fixed bug handling &quot; and &apos;.  fixed memory
+#  leak not closing url opener (JohnD); added dc:publisher support (MarekK);
+#  added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK)
+#2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed <br/> tags in
+#  encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL);
+#  fixed relative URI processing for guid (skadz); added ICBM support; added
+#  base64 support
+#2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many
+#  blogspot.com sites); added _debug variable
+#2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing
+#3.0 - MAP - parse entire feed with real XML parser (if available); added several
+#  new supported namespaces; fixed bug tracking naked markup in description;
+#  added support for enclosure; added support for source; re-added support for
+#  cloud which got dropped somehow; added support for expirationDate; fixed
+#  xml:lang inheritance; fixed multiple bugs tracking xml:base URI, one for
+#  documents that don't define one explicitly and one for documents that define
+#  an outer and an inner xml:base that goes out of scope before the end of the
+#  document; fixed bug parsing multiple links at feed level; added feed type and
+#  version detection, result["version"] will be one of SUPPORTED_VERSIONS.keys()
+#  or empty string if unrecognized; added support for creativeCommons:license and
+#  cc:license; added support for full Atom content model in title, tagline, info,
+#  copyright, summary; fixed bug with gzip encoding (not always telling server
+#  we support it when we do); support Atom-style author element in author_detail
+#  (dictionary of "name", "url", "email"); map author to author_detail if author
+#  contains name + email address; better handling of empty HTML tags (br, hr, img,
+#  etc.) in embedded markup, in either HTML or XHTML form (<br>, <br/>, <br />);
+#  fixed CDATA handling in non-wellformed feeds under Python 2.1; fixed bug
+#  resolving relative links in wfw:commentRSS; fixed bug capturing author and
+#  contributor URL; fixed bug resolving relative links in author and contributor
+#  URL; fixed bug resolvin relative links in generator URL; added support for
+#  recognizing RSS 1.0; passed Simon Fell's namespace tests, and included them
+#  permanently in the test suite with his permission; determine character
+#  encoding as per RFC 3023; always map description to summary_detail (Andrei);
+#  use libxml2 (if available); fixed bug exploding author information when
+#  author name was in parentheses; removed ultra-problematic mxTidy support;
+#  patch to workaround crash in PyXML/expat when encountering invalid entities
+#  (MarkMoraes); support for textinput/textInput; added CDF support; added
+#  Hot RSS support



More information about the Commits mailing list