PreferenceTool.py 13.3 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 MethodObject import Method
34
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
35
from zLOG import LOG, PROBLEM
36 37 38

from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Tool.BaseTool import BaseTool
39
from Products.ERP5Type import Permissions
40 41
from Products.ERP5Type.Cache import CachingMethod
from Products.ERP5Type.Utils import convertToUpperCase
42
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
43 44
from Products.ERP5Form import _dtmldir

45
_marker = object()
46

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

53 54
class func_code: pass

55
class PreferenceMethod(Method):
56 57 58 59 60 61 62
  """ 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 = ()

63
  def __init__(self, attribute, default):
64
    self.__name__ = self._preference_getter = attribute
65
    self._preference_default = default
66
    self._preference_cache_id = 'PreferenceTool.CachingMethod.%s' % attribute
67

68
  def __call__(self, instance, default=_marker, *args, **kw):
69
    def _getPreference(default, *args, **kw):
70 71 72 73 74
      # 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):
75 76 77 78 79 80
        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
81 82 83
      if default is _marker:
        return self._preference_default
      return default
84
    _getPreference = CachingMethod(_getPreference,
85 86
            id='%s.%s' % (self._preference_cache_id,
                          getSecurityManager().getUser().getId()),
87
            cache_factory='erp5_ui_short')
88
    return _getPreference(default, *args, **kw)
Aurel's avatar
Aurel committed
89

90
class PreferenceTool(BaseTool):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
91 92 93 94 95 96
  """
    PreferenceTool manages User Preferences / User profiles.

    TODO:
      - make the preference tool an action provider (templates)
  """
97 98 99
  id            = 'portal_preferences'
  meta_type     = 'ERP5 Preference Tool'
  portal_type   = 'Preference Tool'
Jérome Perrin's avatar
Jérome Perrin committed
100
  title         = 'Preferences'
101 102 103
  allowed_types = ( 'ERP5 Preference',)
  security      = ClassSecurityInfo()

104 105
  aq_preference_generated = False

106 107 108
  security.declareProtected(
       Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainPreferenceTool', _dtmldir )
109

110 111 112 113 114
  security.declarePrivate('manage_afterAdd')
  def manage_afterAdd(self, item, container) :
    """ init the permissions right after creation """
    item.manage_permission(Permissions.AddPortalContent,
          ['Member', 'Author', 'Manager'])
115 116
    item.manage_permission(Permissions.AddPortalFolders,
          ['Member', 'Author', 'Manager'])
117 118
    item.manage_permission(Permissions.View,
          ['Member', 'Auditor', 'Manager'])
119 120 121 122
    item.manage_permission(Permissions.CopyOrMove,
          ['Member', 'Auditor', 'Manager'])
    item.manage_permission(Permissions.ManageProperties,
          ['Manager'], acquire=0)
Aurel's avatar
Aurel committed
123 124
    item.manage_permission(Permissions.SetOwnPassword,
          ['Member', 'Author', 'Manager'])
125
    BaseTool.inheritedAttribute('manage_afterAdd')(self, item, container)
126

127
  security.declarePublic('getPreference')
128
  def getPreference(self, pref_name, default=_marker) :
129
    """ get the preference on the most appopriate Preference object. """
130
    method = getattr(self, 'get%s' % convertToUpperCase(pref_name), None)
131
    if method is not None:
132
      return method(default)
133 134
    if default is _marker:
      return None
135
    return default
136

137 138 139 140
  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})
141

142
  def _getSortedPreferenceList(self, sql_catalog_id=None):
143
    """ return the most appropriate preferences objects,
144 145
        sorted so that the first in the list should be applied first
    """
146
    tv = getTransactionalVariable()
147 148 149 150 151 152 153
    security_manager = getSecurityManager()
    user = security_manager.getUser()
    acl_users = self.getPortalObject().acl_users
    try:
      # reset a security manager without any proxy role or unrestricted method,
      # wich affects the catalog search that we do to find applicable
      # preferences.
154
      actual_user = acl_users.getUserById(user.getId())
155
      if actual_user is not None:
156
        newSecurityManager(None, actual_user.__of__(acl_users))
157
      tv_key = 'PreferenceTool._getSortedPreferenceList/%s/%s' % (user.getId(),
158 159 160 161 162 163 164 165 166
                                                                  sql_catalog_id)
      if tv.get(tv_key, None) is None:
        prefs = []
        # XXX will also cause problems with Manager (too long)
        # XXX For manager, create a manager specific preference
        #                  or better solution
        user_is_manager = 'Manager' in user.getRolesInContext(self)
        for pref in self.searchFolder(portal_type='Preference', sql_catalog_id=sql_catalog_id):
          pref = pref.getObject()
167 168 169 170 171 172 173
            # XXX quick workaround so that managers only see user preference
            #     they actually own.
          if pref is not None and (not user_is_manager or
                                   pref.getPriority() != Priority.USER or
                                   pref.getOwnerTuple()[1] == user.getId()):
            if pref.getProperty('preference_state',
                                'broken') in ('enabled', 'global'):
174 175 176 177 178 179 180 181 182 183 184
                prefs.append(pref)
        prefs.sort(key=lambda x: x.getPriority(), reverse=True)
        # add system preferences before user preferences
        sys_prefs = [x.getObject() for x in self.searchFolder(portal_type='System Preference', sql_catalog_id=sql_catalog_id) \
                     if x.getObject().getProperty('preference_state', 'broken') in ('enabled', 'global')]
        sys_prefs.sort(key=lambda x: x.getPriority(), reverse=True)
        preference_list = sys_prefs + prefs
        tv[tv_key] = preference_list
      return tv[tv_key]
    finally:
      setSecurityManager(security_manager)
Aurel's avatar
Aurel committed
185

186 187 188 189 190 191 192 193 194 195
  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

196 197
  security.declareProtected(Permissions.View, 'getActivePreference')
  def getActivePreference(self) :
Aurel's avatar
Aurel committed
198
    """ returns the current preference for the user.
199
       Note that this preference may be read only. """
200 201
    return self._getActivePreferenceByPortalType('Preference')

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  security.declareProtected(Permissions.View, 'getActiveUserPreference')
  def getActiveUserPreference(self) :
    """ returns the current user preference for the user.
    If no preference exists, then try to create one with `createUserPreference`
    type based method.

    This method returns a preference that the user will be able to edit or
    None, if `createUserPreference` refused to create a preference.

    It is intendended for "click here to edit your preferences" actions.
    """
    active_preference = self.getActivePreference()
    if active_preference is None or active_preference.getPriority() != Priority.USER:
      # If user does not have a preference, let's try to create one
      user = self.getPortalObject().portal_membership.getAuthenticatedMember().getUserValue()
      if user is not None:
        createUserPreference = user.getTypeBasedMethod('createUserPreference')
        if createUserPreference is not None:
          active_preference = createUserPreference()
    return active_preference

223 224 225 226 227
  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')
228

229
  security.declareProtected(Permissions.View, 'getDocumentTemplateList')
230
  def getDocumentTemplateList(self, folder=None) :
231
    """ returns all document templates that are in acceptable Preferences
232 233
        based on different criteria such as folder, portal_type, etc.
    """
234 235
    if folder is None:
      # as the preference tool is also a Folder, this method is called by
Aurel's avatar
Aurel committed
236
      # page templates to get the list of document templates for self.
237 238
      folder = self

239
    # We must set the user_id as a parameter to make sure each
Jérome Perrin's avatar
Jérome Perrin committed
240
    # user can get a different cache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
241
    def _getDocumentTemplateList(user_id, portal_type=None):
242
      acceptable_template_list = []
243
      for pref in self._getSortedPreferenceList() :
244 245 246
        for doc in pref.contentValues(portal_type=portal_type) :
          acceptable_template_list.append(doc.getRelativeUrl())
      return acceptable_template_list
247 248
    _getDocumentTemplateList = CachingMethod(_getDocumentTemplateList,
                          'portal_preferences.getDocumentTemplateList',
249
                                             cache_factory='erp5_ui_short')
250 251 252 253 254 255

    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
256
      for template_url in _getDocumentTemplateList(user_id, portal_type=portal_type):
257 258 259
        template = self.restrictedTraverse(template_url, None)
        if template is not None:
          template_list.append(template)
260
    return template_list
261

262 263 264 265 266 267 268 269 270 271 272
  security.declareProtected(Permissions.ManagePortal,
                            'createActiveSystemPreference')
  def createActiveSystemPreference(self):
    """ Create a System Preference and enable it if there is no other
        enabled System Preference in present.
    """
    if self.getActiveSystemPreference() is not None:
      raise ValueError("Another Active Preference already exists.")
    system_preference = self.newContent(portal_type='System Preference')
    system_preference.enable()

273 274
  security.declareProtected(Permissions.ManagePortal,
                            'createPreferenceForUser')
275
  def createPreferenceForUser(self, user_id, enable=True):
276 277
    """Creates a preference for a given user, and optionnally enable the
    preference.
278
    """
279
    user_folder = self.acl_users
280
    user = user_folder.getUserById(user_id)
281
    if user is None:
282
      raise ValueError("User %r not found" % (user_id, ))
283 284 285
    security_manager = getSecurityManager()
    try:
      newSecurityManager(None, user.__of__(user_folder))
286 287 288 289
      preference = self.newContent(portal_type='Preference')
      if enable:
        preference.enable()
      return preference
290 291 292
    finally:
      setSecurityManager(security_manager)

293 294
  security.declarePublic('isAuthenticationPolicyEnabled')
  def isAuthenticationPolicyEnabled(self) :
295
    """
296 297 298 299
    Return True if authentication policy is enabled.
    This method exists here due to bootstrap issues.
    It should work even if erp5_authentication_policy bt5 is not installed.
    """
300 301 302 303 304 305 306
    # isPreferredAuthenticationPolicyEnabled exisss if property sheets from
    # erp5_authentication_policy are installed.
    method = getattr(self, 'isPreferredAuthenticationPolicyEnabled', None)
    if method is not None and method():
      return True
    # if it does not exist, for sure authentication policy is not enabled.
    return False
307

308
InitializeClass(PreferenceTool)