PreferenceTool.py 13.6 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jerome Perrin <jerome@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

30 31 32
from AccessControl import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager,\
                          setSecurityManager, newSecurityManager
33
from AccessControl.PermissionRole import  PermissionRole
34
from MethodObject import Method
35
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
36
from zLOG import LOG, PROBLEM
37 38 39

from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Tool.BaseTool import BaseTool
40
from Products.ERP5Type import Permissions, PropertySheet
41 42
from Products.ERP5Type.Cache import CachingMethod
from Products.ERP5Type.Utils import convertToUpperCase
43
from Products.ERP5Type.Accessor.TypeDefinition import list_types
44 45
from Products.ERP5Form import _dtmldir

46
_marker = object()
47

48 49 50 51 52 53
class Priority:
  """ names for priorities """
  SITE  = 1
  GROUP = 2
  USER  = 3

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
def updatePreferenceClassPropertySheetList():
  # The Preference class should be imported from the common location
  # in ERP5Type since it could be overloaded in another product
  from Products.ERP5Type.Document.Preference import Preference
  # 'Static' property sheets defined on the class
  class_property_sheet_list = Preference.property_sheets
  # Time to lookup for preferences defined on other modules
  property_sheets = list(class_property_sheet_list)
  for id in dir(PropertySheet):
    if id.endswith('Preference'):
      ps = getattr(PropertySheet, id)
      if ps not in property_sheets:
        property_sheets.append(ps)
  class_property_sheet_list = tuple(property_sheets)
  Preference.property_sheets = class_property_sheet_list

70

71
def createPreferenceToolAccessorList(portal) :
72 73 74 75 76 77 78
  """
    Initialize all Preference methods on the preference tool.
    This method must be called on startup.

    This tool is capable of updating the list of Preference
    property sheets by looking at all registered property sheets
    and considering those which name ends with 'Preference'
79
  """
80
  property_list = []
81

82 83
  # 'Dynamic' property sheets added by portal_type
  pref_portal_type = portal.portal_types.getTypeInfo('Preference')
84
  if pref_portal_type is None:
85
    LOG('ERP5Form.PreferenceTool', PROBLEM,
86
        'Preference type information is not installed.')
87
  else:
88 89
    pref_portal_type.updatePropertySheetDefinitionDict(
      {'_properties': property_list})
90

91
  # 'Static' property sheets defined on the class
92 93 94
  # The Preference class should be imported from the common location
  # in ERP5Type since it could be overloaded in another product
  from Products.ERP5Type.Document.Preference import Preference
95 96 97 98 99 100
  for property_sheet in Preference.property_sheets:
    property_list += property_sheet._properties

  # Generate common method names
  for prop in property_list:
    if prop.get('preference'):
101 102
      # XXX read_permission and write_permissions defined at
      # property sheet are not respected by this.
103
      # only properties marked as preference are used
104 105
      attribute = prop['id']
      attr_list = [ 'get%s' % convertToUpperCase(attribute)]
106 107
      if prop['type'] == 'boolean':
        attr_list.append('is%s' % convertToUpperCase(attribute))
108
      if prop['type'] in list_types :
109
        attr_list.append('get%sList' % convertToUpperCase(attribute))
110
      for attribute_name in attr_list:
111
        method = PreferenceMethod(attribute_name, prop.get('default'))
112
        setattr(PreferenceTool, attribute_name, method)
113 114 115 116
      read_permission = prop.get('read_permission')
      if read_permission:
        setattr(PreferenceTool, attribute_name + '__roles__',
            PermissionRole(read_permission))
117 118 119 120


class func_code: pass

121
class PreferenceMethod(Method):
122 123 124 125 126 127 128
  """ A method object that lookup the attribute on preferences. """
  # This is required to call the method form the Web
  func_code = func_code()
  func_code.co_varnames = ('self', )
  func_code.co_argcount = 1
  func_defaults = ()

129
  def __init__(self, attribute, default):
130
    self.__name__ = self._preference_getter = attribute
131
    self._preference_default = default
132
    self._preference_cache_id = 'PreferenceTool.CachingMethod.%s' % attribute
133

134
  def __call__(self, instance, default=_marker, *args, **kw):
135
    def _getPreference(*args, **kw):
136 137 138 139 140
      # XXX: sql_catalog_id is passed when calling getPreferredArchive
      # This is inconsistent with regular accessor API, and indicates that
      # there is a design problem in current archive API.
      sql_catalog_id = kw.pop('sql_catalog_id', None)
      for pref in instance._getSortedPreferenceList(sql_catalog_id=sql_catalog_id):
141 142 143 144 145 146 147
        value = getattr(pref, self._preference_getter)(_marker, *args, **kw)
        # XXX Due to UI limitation, null value is treated as if the property
        #     was not defined. The drawback is that it is not possible for a
        #     user to mask a non-null global value with a null value.
        if value not in (_marker, None, '', (), []):
          return value
      return _marker
148
    _getPreference = CachingMethod(_getPreference,
149 150
            id='%s.%s' % (self._preference_cache_id,
                          getSecurityManager().getUser().getId()),
151
            cache_factory='erp5_ui_short')
152
    value = _getPreference(*args, **kw)
153 154 155 156 157
    if value is not _marker:
      return value
    elif default is _marker:
      return self._preference_default
    return default
Aurel's avatar
Aurel committed
158

159
class PreferenceTool(BaseTool):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
160 161 162 163 164 165
  """
    PreferenceTool manages User Preferences / User profiles.

    TODO:
      - make the preference tool an action provider (templates)
  """
166 167 168
  id            = 'portal_preferences'
  meta_type     = 'ERP5 Preference Tool'
  portal_type   = 'Preference Tool'
Jérome Perrin's avatar
Jérome Perrin committed
169
  title         = 'Preferences'
170 171 172
  allowed_types = ( 'ERP5 Preference',)
  security      = ClassSecurityInfo()

173 174
  aq_preference_generated = False

175 176 177
  security.declareProtected(
       Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainPreferenceTool', _dtmldir )
178

179 180 181 182 183
  security.declarePrivate('manage_afterAdd')
  def manage_afterAdd(self, item, container) :
    """ init the permissions right after creation """
    item.manage_permission(Permissions.AddPortalContent,
          ['Member', 'Author', 'Manager'])
184 185
    item.manage_permission(Permissions.AddPortalFolders,
          ['Member', 'Author', 'Manager'])
186 187
    item.manage_permission(Permissions.View,
          ['Member', 'Auditor', 'Manager'])
188 189 190 191
    item.manage_permission(Permissions.CopyOrMove,
          ['Member', 'Auditor', 'Manager'])
    item.manage_permission(Permissions.ManageProperties,
          ['Manager'], acquire=0)
Aurel's avatar
Aurel committed
192 193
    item.manage_permission(Permissions.SetOwnPassword,
          ['Member', 'Author', 'Manager'])
194
    BaseTool.inheritedAttribute('manage_afterAdd')(self, item, container)
195

196
  security.declarePublic('getPreference')
197
  def getPreference(self, pref_name, default=_marker) :
198
    """ get the preference on the most appopriate Preference object. """
199
    method = getattr(self, 'get%s' % convertToUpperCase(pref_name), None)
200
    if method is not None:
201
      return method(default)
202
    return default
203

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  def _aq_dynamic(self, id):
    base_value = PreferenceTool.inheritedAttribute('_aq_dynamic')(self, id)
    if not PreferenceTool.aq_preference_generated:
      updatePreferenceClassPropertySheetList()

      portal = self.getPortalObject()
      while portal.portal_type != 'ERP5 Site':
        portal = portal.aq_parent.aq_inner.getPortalObject()
      createPreferenceToolAccessorList(portal)

      PreferenceTool.aq_preference_generated = True
      if base_value is None:
        return getattr(self, id)
    return base_value

219 220 221 222
  security.declareProtected(Permissions.ModifyPortalContent, "setPreference")
  def setPreference(self, pref_name, value) :
    """ set the preference on the active Preference object"""
    self.getActivePreference()._edit(**{pref_name:value})
223

224
  def _getSortedPreferenceList(self, sql_catalog_id=None):
225
    """ return the most appropriate preferences objects,
226 227
        sorted so that the first in the list should be applied first
    """
228
    prefs = []
229 230 231
    # XXX will also cause problems with Manager (too long)
    # XXX For manager, create a manager specific preference
    #                  or better solution
232 233
    user = getToolByName(self, 'portal_membership').getAuthenticatedMember()
    user_is_manager = 'Manager' in user.getRolesInContext(self)
234
    for pref in self.searchFolder(portal_type='Preference', sql_catalog_id=sql_catalog_id):
235
      pref = pref.getObject()
236
      if pref is not None and pref.getProperty('preference_state',
237
                                'broken') in ('enabled', 'global'):
238 239 240
        # XXX quick workaround so that manager only see user preference
        # they actually own.
        if user_is_manager and pref.getPriority() == Priority.USER :
241
          if pref.getOwnerTuple()[1] == user.getId():
242 243 244
            prefs.append(pref)
        else :
          prefs.append(pref)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
245
    prefs.sort(key=lambda x: x.getPriority(), reverse=True)
246
    # add system preferences before user preferences
247
    sys_prefs = [x.getObject() for x in self.searchFolder(portal_type='System Preference', sql_catalog_id=sql_catalog_id) \
248
                 if x.getObject().getProperty('preference_state', 'broken') in ('enabled', 'global')]
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
249
    sys_prefs.sort(key=lambda x: x.getPriority(), reverse=True)
250
    return sys_prefs + prefs
Aurel's avatar
Aurel committed
251

252 253 254 255 256 257 258 259 260 261
  def _getActivePreferenceByPortalType(self, portal_type):
    enabled_prefs = self._getSortedPreferenceList()
    if len(enabled_prefs) > 0 :
      try:
        return [x for x in enabled_prefs
            if x.getPortalType() == portal_type][0]
      except IndexError:
        pass
    return None

262 263
  security.declareProtected(Permissions.View, 'getActivePreference')
  def getActivePreference(self) :
Aurel's avatar
Aurel committed
264
    """ returns the current preference for the user.
265
       Note that this preference may be read only. """
266 267 268 269 270 271 272
    return self._getActivePreferenceByPortalType('Preference')

  security.declareProtected(Permissions.View, 'getActiveSystemPreference')
  def getActiveSystemPreference(self) :
    """ returns the current system preference for the user.
       Note that this preference may be read only. """
    return self._getActivePreferenceByPortalType('System Preference')
273

274
  security.declareProtected(Permissions.View, 'getDocumentTemplateList')
275
  def getDocumentTemplateList(self, folder=None) :
276
    """ returns all document templates that are in acceptable Preferences
277 278
        based on different criteria such as folder, portal_type, etc.
    """
279 280
    if folder is None:
      # as the preference tool is also a Folder, this method is called by
Aurel's avatar
Aurel committed
281
      # page templates to get the list of document templates for self.
282 283
      folder = self

284
    # We must set the user_id as a parameter to make sure each
Jérome Perrin's avatar
Jérome Perrin committed
285
    # user can get a different cache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
286
    def _getDocumentTemplateList(user_id, portal_type=None):
287 288
      acceptable_templates = []
      for pref in self._getSortedPreferenceList() :
Jérome Perrin's avatar
Jérome Perrin committed
289
        for doc in pref.contentValues() :
290 291 292 293 294
          if doc.getPortalType() == portal_type:
            acceptable_templates.append(doc.getRelativeUrl())
      return acceptable_templates
    _getDocumentTemplateList = CachingMethod(_getDocumentTemplateList,
                          'portal_preferences.getDocumentTemplateList',
Aurel's avatar
Aurel committed
295
                                             cache_factory='erp5_ui_medium')
296 297 298 299 300 301

    allowed_content_types = map(lambda pti: pti.id,
                                folder.allowedContentTypes())
    user_id = getToolByName(self, 'portal_membership').getAuthenticatedMember().getId()
    template_list = []
    for portal_type in allowed_content_types:
Jérome Perrin's avatar
Jérome Perrin committed
302
      for template_url in _getDocumentTemplateList(user_id, portal_type=portal_type):
303 304 305
        template = self.restrictedTraverse(template_url, None)
        if template is not None:
          template_list.append(template)
306
    return template_list
307

308 309
  security.declareProtected(Permissions.ManagePortal,
                            'createPreferenceForUser')
310 311 312
  def createPreferenceForUser(self, username, enable=True):
    """Creates a preference for a given user, and optionnally enable the
    preference.
313 314 315 316 317 318
    """
    security_manager = getSecurityManager()
    try:
      user_folder = self.getPortalObject().acl_users
      user = user_folder.getUserById(username)
      if user is None:
319
        raise ValueError("User %r not found" % (username, ))
320
      newSecurityManager(None, user.__of__(user_folder))
321 322 323 324
      preference = self.newContent(portal_type='Preference')
      if enable:
        preference.enable()
      return preference
325 326 327
    finally:
      setSecurityManager(security_manager)

328 329
InitializeClass(PreferenceTool)