sobjects/hooks.py
changeset 2841 107ba1c45227
parent 2840 06daf13195d4
child 2842 0477fff5f897
equal deleted inserted replaced
2840:06daf13195d4 2841:107ba1c45227
     1 """various library content hooks
       
     2 
       
     3 :organization: Logilab
       
     4 :copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.
       
     5 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
       
     6 :license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
       
     7 """
       
     8 __docformat__ = "restructuredtext en"
       
     9 
       
    10 from datetime import datetime
       
    11 
       
    12 from cubicweb import RepositoryError
       
    13 from cubicweb.common.uilib import soup2xhtml
       
    14 from cubicweb.server.hooksmanager import Hook
       
    15 from cubicweb.server.pool import PreCommitOperation
       
    16 
       
    17 
       
    18 class SetModificationDateOnStateChange(Hook):
       
    19     """update entity's modification date after changing its state"""
       
    20     events = ('after_add_relation',)
       
    21     accepts = ('in_state',)
       
    22 
       
    23     def call(self, session, fromeid, rtype, toeid):
       
    24         if fromeid in session.transaction_data.get('neweids', ()):
       
    25             # new entity, not needed
       
    26             return
       
    27         entity = session.entity_from_eid(fromeid)
       
    28         try:
       
    29             entity.set_attributes(modification_date=datetime.now())
       
    30         except RepositoryError, ex:
       
    31             # usually occurs if entity is coming from a read-only source
       
    32             # (eg ldap user)
       
    33             self.warning('cant change modification date for %s: %s', entity, ex)
       
    34 
       
    35 
       
    36 class AddUpdateCWUserHook(Hook):
       
    37     """ensure user logins are stripped"""
       
    38     events = ('before_add_entity', 'before_update_entity',)
       
    39     accepts = ('CWUser',)
       
    40 
       
    41     def call(self, session, entity):
       
    42         if 'login' in entity and entity['login']:
       
    43             entity['login'] = entity['login'].strip()
       
    44 
       
    45 
       
    46 class AutoDeleteBookmark(PreCommitOperation):
       
    47     beid = None # make pylint happy
       
    48     def precommit_event(self):
       
    49         session = self.session
       
    50         if not self.beid in session.transaction_data.get('pendingeids', ()):
       
    51             if not session.unsafe_execute('Any X WHERE X bookmarked_by U, X eid %(x)s',
       
    52                                           {'x': self.beid}, 'x'):
       
    53                 session.unsafe_execute('DELETE Bookmark X WHERE X eid %(x)s',
       
    54                                        {'x': self.beid}, 'x')
       
    55 
       
    56 class DelBookmarkedByHook(Hook):
       
    57     """ensure user logins are stripped"""
       
    58     events = ('after_delete_relation',)
       
    59     accepts = ('bookmarked_by',)
       
    60 
       
    61     def call(self, session, subj, rtype, obj):
       
    62         AutoDeleteBookmark(session, beid=subj)
       
    63 
       
    64 
       
    65 class TidyHtmlFields(Hook):
       
    66     """tidy HTML in rich text strings"""
       
    67     events = ('before_add_entity', 'before_update_entity')
       
    68     accepts = ('Any',)
       
    69 
       
    70     def call(self, session, entity):
       
    71         metaattrs = entity.e_schema.meta_attributes()
       
    72         for metaattr, (metadata, attr) in metaattrs.iteritems():
       
    73             if metadata == 'format':
       
    74                 try:
       
    75                     value = entity[attr]
       
    76                 except KeyError:
       
    77                     continue # no text to tidy
       
    78                 if isinstance(value, unicode): # filter out None and Binary
       
    79                     if self.event == 'before_add_entity':
       
    80                         fmt = entity.get(metaattr)
       
    81                     else:
       
    82                         fmt = entity.get_value(metaattr)
       
    83                     if fmt == 'text/html':
       
    84                         entity[attr] = soup2xhtml(value, session.encoding)