PreferenceTool.py 11.6 KB
Newer Older
1 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
##############################################################################
#
# 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.
#
##############################################################################

29
from AccessControl import ClassSecurityInfo, getSecurityManager
30
from MethodObject import Method
31
from Globals import InitializeClass, DTMLFile
32
from zLOG import LOG, PROBLEM
33 34 35

from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.Tool.BaseTool import BaseTool
36
from Products.ERP5Type import Permissions, PropertySheet
37 38
from Products.ERP5Type.Cache import CachingMethod
from Products.ERP5Type.Utils import convertToUpperCase
39
from Products.ERP5Type.Accessor.TypeDefinition import list_types
40
from Products.ERP5Form import _dtmldir
41
from Products.ERP5Form.Document.Preference import Priority
42

43
_marker = []
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
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

61

62
def createPreferenceToolAccessorList(portal) :
63 64 65 66 67 68 69
  """
    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'
70 71
  """
  attr_list = []
72 73
  typestool = getToolByName(portal, 'portal_types')
  pref_portal_type = typestool.getTypeInfo('Preference')
74 75 76

  # 'Dynamic' property sheets added through ZMI
  zmi_property_sheet_list = []
77
  if pref_portal_type is None:
78
    LOG('ERP5Form.PreferenceTool', PROBLEM,
79
           'Preference type information is not installed.')
80 81 82 83 84 85 86 87
  else:
    for property_sheet in pref_portal_type.property_sheet_list :
      try:
        zmi_property_sheet_list.append(
                    getattr(__import__(property_sheet), property_sheet))
      except ImportError, e :
        LOG('ERP5Form.PreferenceTool', PROBLEM,
             'unable to import Property Sheet %s' % property_sheet, e)
88

89
  # 'Static' property sheets defined on the class
90 91 92
  # 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
93
  class_property_sheet_list = Preference.property_sheets
94
  # We can now merge
95 96
  for property_sheet in ( tuple(zmi_property_sheet_list) +
                                class_property_sheet_list ) :
97
    # then generate common method names
98 99 100 101 102 103 104 105 106 107 108
    for prop in property_sheet._properties :
      if not prop.get('preference', 0) :
        # only properties marked as preference are used
        continue
      attribute = prop['id']
      attr_list = [ 'get%s' % convertToUpperCase(attribute)]
      if prop['type'] in list_types :
        attr_list +=  ['get%sList' % convertToUpperCase(attribute), ]
      for attribute_name in attr_list:
        method = PreferenceMethod(attribute_name)
        setattr(PreferenceTool, attribute_name, method)
109 110 111 112


class func_code: pass

113
class PreferenceMethod(Method):
114 115 116 117 118 119 120
  """ 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 = ()

121
  def __init__(self, attribute):
122
    self._preference_name = attribute
123 124
    self._preference_cache_id = 'PreferenceTool.CachingMethod.%s' % attribute
    self._null = (None, '', (), [])
125

126
  def __call__(self, instance, *args, **kw):
127
    def _getPreference(*args, **kw):
128
      value = None
Aurel's avatar
Aurel committed
129
      for pref in instance._getSortedPreferenceList(*args, **kw):
130
        value = getattr(pref, self._preference_name, _marker)
131 132
        # XXX-JPS Why don't we use accessors here such as:
        # value = pref.getProperty(self._preference_name, _marker)
133
        if value is not _marker:
134 135
          # If callable, store the return value.
          if callable(value):
Aurel's avatar
Aurel committed
136
            value = value(*args, **kw)
137 138 139 140
          if value not in self._null:
            break
      return value
    _getPreference = CachingMethod(_getPreference,
141 142
            id='%s.%s' % (self._preference_cache_id,
                          getSecurityManager().getUser().getId()),
143
            cache_factory='erp5_ui_short')
144
    value = _getPreference(*args, **kw)
145 146 147 148
    # XXX Preference Tool has a strange assumption that, even if
    # all values are null values, one of them must be returned.
    # Therefore, return a default value, only if explicitly specified,
    # instead of returning None.
149 150 151 152 153 154 155
    default = _marker
    if 'default' in kw:
      default = kw['default']
    elif args:
      default = args[0]
    if value in self._null and default is not _marker:
      return default
156
    return value
Aurel's avatar
Aurel committed
157

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

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

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

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

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

205 206 207 208
  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})
209

210
  def _getSortedPreferenceList(self, *args, **kw) :
211
    """ return the most appropriate preferences objects,
212 213
        sorted so that the first in the list should be applied first
    """
214
    prefs = []
215 216 217
    # XXX will also cause problems with Manager (too long)
    # XXX For manager, create a manager specific preference
    #                  or better solution
218 219
    user = getToolByName(self, 'portal_membership').getAuthenticatedMember()
    user_is_manager = 'Manager' in user.getRolesInContext(self)
220
    for pref in self.searchFolder(portal_type='Preference', **kw) :
221
      pref = pref.getObject()
222
      if pref is not None and pref.getProperty('preference_state',
223
                                'broken') in ('enabled', 'global'):
224 225 226 227 228 229 230
        # XXX quick workaround so that manager only see user preference
        # they actually own.
        if user_is_manager and pref.getPriority() == Priority.USER :
          if user.allowed(pref, ('Owner',)):
            prefs.append(pref)
        else :
          prefs.append(pref)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
231
    prefs.sort(key=lambda x: x.getPriority(), reverse=True)
232
    # add system preferences after user preferences
233 234
    sys_prefs = [x.getObject() for x in self.searchFolder(portal_type='System Preference', **kw) \
                 if x.getObject().getProperty('preference_state', 'broken') in ('enabled', 'global')]
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
235
    sys_prefs.sort(key=lambda x: x.getPriority(), reverse=True)
236
    return sys_prefs + prefs
Aurel's avatar
Aurel committed
237

238 239
  security.declareProtected(Permissions.View, 'getActivePreference')
  def getActivePreference(self) :
Aurel's avatar
Aurel committed
240
    """ returns the current preference for the user.
241
       Note that this preference may be read only. """
242
    enabled_prefs = self._getSortedPreferenceList()
243 244 245
    if len(enabled_prefs) > 0 :
      return enabled_prefs[0]

246
  security.declareProtected(Permissions.View, 'getDocumentTemplateList')
247
  def getDocumentTemplateList(self, folder=None) :
248
    """ returns all document templates that are in acceptable Preferences
249 250
        based on different criteria such as folder, portal_type, etc.
    """
251 252
    if folder is None:
      # as the preference tool is also a Folder, this method is called by
Aurel's avatar
Aurel committed
253
      # page templates to get the list of document templates for self.
254 255
      folder = self

256
    # We must set the user_id as a parameter to make sure each
Jérome Perrin's avatar
Jérome Perrin committed
257
    # user can get a different cache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
258
    def _getDocumentTemplateList(user_id, portal_type=None):
259 260
      acceptable_templates = []
      for pref in self._getSortedPreferenceList() :
Jérome Perrin's avatar
Jérome Perrin committed
261
        for doc in pref.contentValues() :
262 263 264 265 266
          if doc.getPortalType() == portal_type:
            acceptable_templates.append(doc.getRelativeUrl())
      return acceptable_templates
    _getDocumentTemplateList = CachingMethod(_getDocumentTemplateList,
                          'portal_preferences.getDocumentTemplateList',
Aurel's avatar
Aurel committed
267
                                             cache_factory='erp5_ui_medium')
268 269 270 271 272 273

    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
274
      for template_url in _getDocumentTemplateList(user_id, portal_type=portal_type):
275 276
        template_list.append(self.restrictedTraverse(template_url))
    return template_list
277 278 279

InitializeClass(PreferenceTool)