/lib/galaxy/util/sanitize_html.py

https://bitbucket.org/cistrome/cistrome-harvard/ · Python · 441 lines · 345 code · 52 blank · 44 comment · 90 complexity · d4ded7b5e467eff2b15d0a26066f5bac MD5 · raw file

  1. """
  2. HTML Sanitizer (ripped from feedparser)
  3. """
  4. import re, sgmllib
  5. # reversable htmlentitydefs mappings for Python 2.2
  6. try:
  7. from htmlentitydefs import name2codepoint, codepoint2name
  8. except:
  9. import htmlentitydefs
  10. name2codepoint={}
  11. codepoint2name={}
  12. for (name,codepoint) in htmlentitydefs.entitydefs.iteritems():
  13. if codepoint.startswith('&#'): codepoint=unichr(int(codepoint[2:-1]))
  14. name2codepoint[name]=ord(codepoint)
  15. codepoint2name[ord(codepoint)]=name
  16. _cp1252 = {
  17. unichr(128): unichr(8364), # euro sign
  18. unichr(130): unichr(8218), # single low-9 quotation mark
  19. unichr(131): unichr( 402), # latin small letter f with hook
  20. unichr(132): unichr(8222), # double low-9 quotation mark
  21. unichr(133): unichr(8230), # horizontal ellipsis
  22. unichr(134): unichr(8224), # dagger
  23. unichr(135): unichr(8225), # double dagger
  24. unichr(136): unichr( 710), # modifier letter circumflex accent
  25. unichr(137): unichr(8240), # per mille sign
  26. unichr(138): unichr( 352), # latin capital letter s with caron
  27. unichr(139): unichr(8249), # single left-pointing angle quotation mark
  28. unichr(140): unichr( 338), # latin capital ligature oe
  29. unichr(142): unichr( 381), # latin capital letter z with caron
  30. unichr(145): unichr(8216), # left single quotation mark
  31. unichr(146): unichr(8217), # right single quotation mark
  32. unichr(147): unichr(8220), # left double quotation mark
  33. unichr(148): unichr(8221), # right double quotation mark
  34. unichr(149): unichr(8226), # bullet
  35. unichr(150): unichr(8211), # en dash
  36. unichr(151): unichr(8212), # em dash
  37. unichr(152): unichr( 732), # small tilde
  38. unichr(153): unichr(8482), # trade mark sign
  39. unichr(154): unichr( 353), # latin small letter s with caron
  40. unichr(155): unichr(8250), # single right-pointing angle quotation mark
  41. unichr(156): unichr( 339), # latin small ligature oe
  42. unichr(158): unichr( 382), # latin small letter z with caron
  43. unichr(159): unichr( 376)} # latin capital letter y with diaeresis
  44. class _BaseHTMLProcessor(sgmllib.SGMLParser):
  45. special = re.compile('''[<>'"]''')
  46. bare_ampersand = re.compile("&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)")
  47. elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
  48. 'img', 'input', 'isindex', 'link', 'meta', 'param']
  49. def __init__(self, encoding, type):
  50. self.encoding = encoding
  51. self.type = type
  52. ## if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding)
  53. sgmllib.SGMLParser.__init__(self)
  54. def reset(self):
  55. self.pieces = []
  56. sgmllib.SGMLParser.reset(self)
  57. def _shorttag_replace(self, match):
  58. tag = match.group(1)
  59. if tag in self.elements_no_end_tag:
  60. return '<' + tag + ' />'
  61. else:
  62. return '<' + tag + '></' + tag + '>'
  63. def parse_starttag(self,i):
  64. j=sgmllib.SGMLParser.parse_starttag(self, i)
  65. if self.type == 'application/xhtml+xml':
  66. if j>2 and self.rawdata[j-2:j]=='/>':
  67. self.unknown_endtag(self.lasttag)
  68. return j
  69. def feed(self, data):
  70. data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data)
  71. #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace
  72. data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data)
  73. data = data.replace('&#39;', "'")
  74. data = data.replace('&#34;', '"')
  75. if self.encoding and type(data) == type(u''):
  76. data = data.encode(self.encoding)
  77. sgmllib.SGMLParser.feed(self, data)
  78. sgmllib.SGMLParser.close(self)
  79. def normalize_attrs(self, attrs):
  80. if not attrs: return attrs
  81. # utility method to be called by descendants
  82. attrs = dict([(k.lower(), v) for k, v in attrs]).items()
  83. attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  84. attrs.sort()
  85. return attrs
  86. def unknown_starttag(self, tag, attrs):
  87. # called for each start tag
  88. # attrs is a list of (attr, value) tuples
  89. # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
  90. ## if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag)
  91. uattrs = []
  92. strattrs=''
  93. if attrs:
  94. for key, value in attrs:
  95. value=value.replace('>','&gt;').replace('<','&lt;').replace('"','&quot;')
  96. value = self.bare_ampersand.sub("&amp;", value)
  97. # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
  98. if type(value) != type(u''):
  99. try:
  100. value = unicode(value, self.encoding)
  101. except:
  102. value = unicode(value, 'iso-8859-1')
  103. uattrs.append((unicode(key, self.encoding), value))
  104. strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs])
  105. if self.encoding:
  106. try:
  107. strattrs=strattrs.encode(self.encoding)
  108. except:
  109. pass
  110. if tag in self.elements_no_end_tag:
  111. self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
  112. else:
  113. self.pieces.append('<%(tag)s%(strattrs)s>' % locals())
  114. def unknown_endtag(self, tag):
  115. # called for each end tag, e.g. for </pre>, tag will be 'pre'
  116. # Reconstruct the original end tag.
  117. if tag not in self.elements_no_end_tag:
  118. self.pieces.append("</%(tag)s>" % locals())
  119. def handle_charref(self, ref):
  120. # called for each character reference, e.g. for '&#160;', ref will be '160'
  121. # Reconstruct the original character reference.
  122. if ref.startswith('x'):
  123. value = unichr(int(ref[1:],16))
  124. else:
  125. value = unichr(int(ref))
  126. if value in _cp1252.keys():
  127. self.pieces.append('&#%s;' % hex(ord(_cp1252[value]))[1:])
  128. else:
  129. self.pieces.append('&#%(ref)s;' % locals())
  130. def handle_entityref(self, ref):
  131. # called for each entity reference, e.g. for '&copy;', ref will be 'copy'
  132. # Reconstruct the original entity reference.
  133. if name2codepoint.has_key(ref):
  134. self.pieces.append('&%(ref)s;' % locals())
  135. else:
  136. self.pieces.append('&amp;%(ref)s' % locals())
  137. def handle_data(self, text):
  138. # called for each block of plain text, i.e. outside of any tag and
  139. # not containing any character or entity references
  140. # Store the original text verbatim.
  141. ## if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text)
  142. self.pieces.append(text)
  143. def handle_comment(self, text):
  144. # called for each HTML comment, e.g. <!-- insert Javascript code here -->
  145. # Reconstruct the original comment.
  146. self.pieces.append('<!--%(text)s-->' % locals())
  147. def handle_pi(self, text):
  148. # called for each processing instruction, e.g. <?instruction>
  149. # Reconstruct original processing instruction.
  150. self.pieces.append('<?%(text)s>' % locals())
  151. def handle_decl(self, text):
  152. # called for the DOCTYPE, if present, e.g.
  153. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  154. # "http://www.w3.org/TR/html4/loose.dtd">
  155. # Reconstruct original DOCTYPE
  156. self.pieces.append('<!%(text)s>' % locals())
  157. _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
  158. def _scan_name(self, i, declstartpos):
  159. rawdata = self.rawdata
  160. n = len(rawdata)
  161. if i == n:
  162. return None, -1
  163. m = self._new_declname_match(rawdata, i)
  164. if m:
  165. s = m.group()
  166. name = s.strip()
  167. if (i + len(s)) == n:
  168. return None, -1 # end of buffer
  169. return name.lower(), m.end()
  170. else:
  171. self.handle_data(rawdata)
  172. # self.updatepos(declstartpos, i)
  173. return None, -1
  174. def convert_charref(self, name):
  175. return '&#%s;' % name
  176. def convert_entityref(self, name):
  177. return '&%s;' % name
  178. def output(self):
  179. '''Return processed HTML as a single string'''
  180. return ''.join([str(p) for p in self.pieces])
  181. class _HTMLSanitizer(_BaseHTMLProcessor):
  182. acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article',
  183. 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', 'canvas',
  184. 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command',
  185. 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir',
  186. 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset', 'figure', 'footer',
  187. 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i',
  188. 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map',
  189. 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup',
  190. 'option', 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
  191. 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'sub',
  192. 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot', 'th', 'thead',
  193. 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript']
  194. acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  195. 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',
  196. 'background', 'balance', 'bgcolor', 'bgproperties', 'border',
  197. 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
  198. 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
  199. 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols',
  200. 'colspan', 'compact', 'contenteditable', 'controls', 'coords', 'data',
  201. 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', 'delay',
  202. 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for',
  203. 'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus',
  204. 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode',
  205. 'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc',
  206. 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max',
  207. 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref',
  208. 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size',
  209. 'prompt', 'pqg', 'radiogroup', 'readonly', 'rel', 'repeat-max',
  210. 'repeat-min', 'replace', 'required', 'rev', 'rightspacing', 'rows',
  211. 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src',
  212. 'start', 'step', 'summary', 'suppress', 'tabindex', 'target', 'template',
  213. 'title', 'toppadding', 'type', 'unselectable', 'usemap', 'urn', 'valign',
  214. 'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap',
  215. 'xml:lang']
  216. unacceptable_elements_with_end_tag = ['script', 'applet', 'style']
  217. acceptable_css_properties = ['azimuth', 'background-color',
  218. 'border-bottom-color', 'border-collapse', 'border-color',
  219. 'border-left-color', 'border-right-color', 'border-top-color', 'clear',
  220. 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
  221. 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
  222. 'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
  223. 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
  224. 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
  225. 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
  226. 'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
  227. 'white-space', 'width']
  228. # survey of common keywords found in feeds
  229. acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue',
  230. 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
  231. 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
  232. 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
  233. 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
  234. 'transparent', 'underline', 'white', 'yellow']
  235. valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' +
  236. '\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$')
  237. mathml_elements = ['annotation', 'annotation-xml', 'maction', 'math',
  238. 'merror', 'mfenced', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
  239. 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle',
  240. 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
  241. 'munderover', 'none', 'semantics']
  242. mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign',
  243. 'columnalign', 'close', 'columnlines', 'columnspacing', 'columnspan', 'depth',
  244. 'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows',
  245. 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness',
  246. 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant',
  247. 'maxsize', 'minsize', 'open', 'other', 'rowalign', 'rowalign', 'rowalign',
  248. 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
  249. 'separator', 'separators', 'stretchy', 'width', 'width', 'xlink:href',
  250. 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink']
  251. # svgtiny - foreignObject + linearGradient + radialGradient + stop
  252. svg_elements = ['a', 'animate', 'animateColor', 'animateMotion',
  253. 'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'foreignObject',
  254. 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
  255. 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath',
  256. 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop',
  257. 'svg', 'switch', 'text', 'title', 'tspan', 'use']
  258. # svgtiny + class + opacity + offset + xmlns + xmlns:xlink
  259. svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic',
  260. 'arabic-form', 'ascent', 'attributeName', 'attributeType',
  261. 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
  262. 'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx',
  263. 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity',
  264. 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style',
  265. 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2',
  266. 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x',
  267. 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines',
  268. 'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid',
  269. 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max',
  270. 'min', 'name', 'offset', 'opacity', 'orient', 'origin',
  271. 'overline-position', 'overline-thickness', 'panose-1', 'path',
  272. 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY',
  273. 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures',
  274. 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv',
  275. 'stop-color', 'stop-opacity', 'strikethrough-position',
  276. 'strikethrough-thickness', 'stroke', 'stroke-dasharray',
  277. 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
  278. 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage',
  279. 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2',
  280. 'underline-position', 'underline-thickness', 'unicode', 'unicode-range',
  281. 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width',
  282. 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
  283. 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
  284. 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1',
  285. 'y2', 'zoomAndPan']
  286. svg_attr_map = None
  287. svg_elem_map = None
  288. acceptable_svg_properties = [ 'fill', 'fill-opacity', 'fill-rule',
  289. 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
  290. 'stroke-opacity']
  291. def reset(self):
  292. _BaseHTMLProcessor.reset(self)
  293. self.unacceptablestack = 0
  294. self.mathmlOK = 0
  295. self.svgOK = 0
  296. def unknown_starttag(self, tag, attrs):
  297. acceptable_attributes = self.acceptable_attributes
  298. keymap = {}
  299. if not tag in self.acceptable_elements or self.svgOK:
  300. if tag in self.unacceptable_elements_with_end_tag:
  301. self.unacceptablestack += 1
  302. # not otherwise acceptable, perhaps it is MathML or SVG?
  303. if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs:
  304. self.mathmlOK += 1
  305. if tag=='svg' and ('xmlns','http://www.w3.org/2000/svg') in attrs:
  306. self.svgOK += 1
  307. # chose acceptable attributes based on tag class, else bail
  308. if self.mathmlOK and tag in self.mathml_elements:
  309. acceptable_attributes = self.mathml_attributes
  310. elif self.svgOK and tag in self.svg_elements:
  311. # for most vocabularies, lowercasing is a good idea. Many
  312. # svg elements, however, are camel case
  313. if not self.svg_attr_map:
  314. lower=[attr.lower() for attr in self.svg_attributes]
  315. mix=[a for a in self.svg_attributes if a not in lower]
  316. self.svg_attributes = lower
  317. self.svg_attr_map = dict([(a.lower(),a) for a in mix])
  318. lower=[attr.lower() for attr in self.svg_elements]
  319. mix=[a for a in self.svg_elements if a not in lower]
  320. self.svg_elements = lower
  321. self.svg_elem_map = dict([(a.lower(),a) for a in mix])
  322. acceptable_attributes = self.svg_attributes
  323. tag = self.svg_elem_map.get(tag,tag)
  324. keymap = self.svg_attr_map
  325. elif not tag in self.acceptable_elements:
  326. return
  327. # declare xlink namespace, if needed
  328. if self.mathmlOK or self.svgOK:
  329. if filter(lambda (n,v): n.startswith('xlink:'),attrs):
  330. if not ('xmlns:xlink','http://www.w3.org/1999/xlink') in attrs:
  331. attrs.append(('xmlns:xlink','http://www.w3.org/1999/xlink'))
  332. clean_attrs = []
  333. for key, value in self.normalize_attrs(attrs):
  334. if key=="href" and value.strip().startswith("javascript"):
  335. pass
  336. elif key in acceptable_attributes:
  337. key=keymap.get(key,key)
  338. clean_attrs.append((key,value))
  339. elif key=='style':
  340. pass
  341. ## clean_value = self.sanitize_style(value)
  342. ## if clean_value: clean_attrs.append((key,clean_value))
  343. _BaseHTMLProcessor.unknown_starttag(self, tag, clean_attrs)
  344. def unknown_endtag(self, tag):
  345. if not tag in self.acceptable_elements:
  346. if tag in self.unacceptable_elements_with_end_tag:
  347. self.unacceptablestack -= 1
  348. if self.mathmlOK and tag in self.mathml_elements:
  349. if tag == 'math' and self.mathmlOK: self.mathmlOK -= 1
  350. elif self.svgOK and tag in self.svg_elements:
  351. tag = self.svg_elem_map.get(tag,tag)
  352. if tag == 'svg' and self.svgOK: self.svgOK -= 1
  353. else:
  354. return
  355. _BaseHTMLProcessor.unknown_endtag(self, tag)
  356. def handle_pi(self, text):
  357. pass
  358. def handle_decl(self, text):
  359. pass
  360. def handle_data(self, text):
  361. if not self.unacceptablestack:
  362. _BaseHTMLProcessor.handle_data(self, text)
  363. def sanitize_style(self, style):
  364. # disallow urls
  365. style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style)
  366. # gauntlet
  367. if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return ''
  368. if not re.match("^(\s*[-\w]+\s*:\s*[^:;]*(;|$))*$", style): return ''
  369. clean = []
  370. for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style):
  371. if not value: continue
  372. if prop.lower() in self.acceptable_css_properties:
  373. clean.append(prop + ': ' + value + ';')
  374. elif prop.split('-')[0].lower() in ['background','border','margin','padding']:
  375. for keyword in value.split():
  376. if not keyword in self.acceptable_css_keywords and \
  377. not self.valid_css_values.match(keyword):
  378. break
  379. else:
  380. clean.append(prop + ': ' + value + ';')
  381. elif self.svgOK and prop.lower() in self.acceptable_svg_properties:
  382. clean.append(prop + ': ' + value + ';')
  383. return ' '.join(clean)
  384. def sanitize_html(htmlSource, encoding="utf-8", type="text/html"):
  385. p = _HTMLSanitizer(encoding, type)
  386. p.feed(htmlSource)
  387. data = p.output()
  388. data = data.strip().replace('\r\n', '\n')
  389. return data