sobjects/hooks.py
branchtls-sprint
changeset 1098 739d4dce9b19
parent 0 b97547f5f1fa
child 1101 0c067de38e46
--- a/sobjects/hooks.py	Thu Mar 12 16:34:13 2009 +0100
+++ b/sobjects/hooks.py	Thu Mar 12 18:40:24 2009 +0100
@@ -1,14 +1,16 @@
 """various library content hooks
 
 :organization: Logilab
-:copyright: 2001-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 """
 __docformat__ = "restructuredtext en"
 
+from cubicweb.common.uilib import soup2xhtml
 from cubicweb.server.hooksmanager import Hook
 from cubicweb.server.pool import PreCommitOperation
 
+
 class AddUpdateEUserHook(Hook):
     """ensure user logins are stripped"""
     events = ('before_add_entity', 'before_update_entity',)
@@ -35,3 +37,24 @@
     
     def call(self, session, subj, rtype, obj):
         AutoDeleteBookmark(session, beid=subj)
+
+
+class TidyHtmlFields(Hook):
+    """tidy HTML in rich text strings"""
+    events = ('before_add_entity', 'before_update_entity')
+    accepts = ('Any',)
+
+    def call(self, session, entity):
+        for formatattr, attr in entity.e_schema.format_fields.iteritems():
+            try:
+                value = entity[attr]
+            except KeyError:
+                continue # no text to tidy
+            if isinstance(value, unicode): # filter out None and Binary
+                if self.event == 'before_add_entity':
+                    fmt = entity.get(formatattr)
+                else:
+                    fmt = entity.get_value(formatattr)
+                if fmt == 'text/html':
+                    entity[attr] = soup2xhtml(value, session.encoding)
+