[FIX] tools: prevent html_translate crash with malformed HTML

If an user stores malformed HTML code in a *translatable HTML field*,
the ORM won't prevent it (this could be a fix for master as it breaks
existing behaviours) and it could be rendered anyway by browsers.

When reading/prefetching the record, the translation function was
crashing because malformed HTML is obviously malformed XML (the
translation function uses XML internals).

This fix will return the source value as a fallback if the HTML field is
malformed (and thus not translatable) + log the error.
This commit is contained in:
Richard Mathot
2016-09-22 16:01:03 +02:00
parent 343170a695
commit 419f4ac5db
+10 -6
View File
@@ -305,12 +305,16 @@ def html_translate(callback, value):
if not value:
return value
parser = etree.HTMLParser(encoding='utf-8')
trans = XMLTranslator(callback, 'html', parser)
wrapped = "<div>%s</div>" % encode(value)
root = etree.fromstring(wrapped, parser)
trans.process(root[0][0]) # html > body > div
return trans.get_done()[5:-6] # remove tags <div> and </div>
try:
parser = etree.HTMLParser(encoding='utf-8')
trans = XMLTranslator(callback, 'html', parser)
wrapped = "<div>%s</div>" % encode(value)
root = etree.fromstring(wrapped, parser)
trans.process(root[0][0]) # html > body > div
value = trans.get_done()[5:-6] # remove tags <div> and </div>
except ValueError:
_logger.exception("Cannot translate malformed HTML, using source value instead")
return value
#