sobjects/hooks.py
branchstable
changeset 4556 43c14e0e8972
parent 4555 8968c50818db
parent 4553 23201259ffeb
child 4560 23e0632df615
equal deleted inserted replaced
4555:8968c50818db 4556:43c14e0e8972
     1 """various library content hooks
       
     2 
       
     3 :organization: Logilab
       
     4 :copyright: 2001-2010 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                                   _cw_unsafe=True)
       
    31         except RepositoryError, ex:
       
    32             # usually occurs if entity is coming from a read-only source
       
    33             # (eg ldap user)
       
    34             self.warning('cant change modification date for %s: %s', entity, ex)
       
    35 
       
    36 
       
    37 class AddUpdateCWUserHook(Hook):
       
    38     """ensure user logins are stripped"""
       
    39     events = ('before_add_entity', 'before_update_entity',)
       
    40     accepts = ('CWUser',)
       
    41 
       
    42     def call(self, session, entity):
       
    43         if 'login' in entity and entity['login']:
       
    44             entity['login'] = entity['login'].strip()
       
    45 
       
    46 
       
    47 class AutoDeleteBookmark(PreCommitOperation):
       
    48     beid = None # make pylint happy
       
    49     def precommit_event(self):
       
    50         session = self.session
       
    51         if not self.beid in session.transaction_data.get('pendingeids', ()):
       
    52             if not session.unsafe_execute('Any X WHERE X bookmarked_by U, X eid %(x)s',
       
    53                                           {'x': self.beid}, 'x'):
       
    54                 session.unsafe_execute('DELETE Bookmark X WHERE X eid %(x)s',
       
    55                                        {'x': self.beid}, 'x')
       
    56 
       
    57 class DelBookmarkedByHook(Hook):
       
    58     """ensure user logins are stripped"""
       
    59     events = ('after_delete_relation',)
       
    60     accepts = ('bookmarked_by',)
       
    61 
       
    62     def call(self, session, subj, rtype, obj):
       
    63         AutoDeleteBookmark(session, beid=subj)
       
    64 
       
    65 
       
    66 class TidyHtmlFields(Hook):
       
    67     """tidy HTML in rich text strings"""
       
    68     events = ('before_add_entity', 'before_update_entity')
       
    69     accepts = ('Any',)
       
    70 
       
    71     def call(self, session, entity):
       
    72         if session.is_super_session:
       
    73             return
       
    74         metaattrs = entity.e_schema.meta_attributes()
       
    75         for metaattr, (metadata, attr) in metaattrs.iteritems():
       
    76             if metadata == 'format':
       
    77                 try:
       
    78                     value = entity[attr]
       
    79                 except KeyError:
       
    80                     continue # no text to tidy
       
    81                 if isinstance(value, unicode): # filter out None and Binary
       
    82                     if self.event == 'before_add_entity':
       
    83                         fmt = entity.get(metaattr)
       
    84                     else:
       
    85                         fmt = entity.get_value(metaattr)
       
    86                     if fmt == 'text/html':
       
    87                         entity[attr] = soup2xhtml(value, session.encoding)