PreferenceTool.py 8.23 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 Globals import InitializeClass, DTMLFile
31
from zLOG import LOG, INFO, PROBLEM
32 33 34 35 36 37

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

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
from MethodObject import Method

class func_code: pass

def createPreferenceMethods(portal) :
  """Initialize all Preference methods on the preference tool.
  This method must be called on startup.
  """
  attr_list = []
  pref_portal_type = getToolByName(portal,
                                  'portal_types')['Preference']
  # 'Dynamic' property sheets added through ZMI
  zmi_property_sheet_list = []
  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('createPreferenceMethods', PROBLEM,
           'unable to import Property Sheet %s' % property_sheet, e)
  # 'Static' property sheets defined on the class
  class_property_sheet_list = Preference.property_sheets
  for property_sheet in ( tuple(zmi_property_sheet_list) +
                                class_property_sheet_list ) :
    # then generate common method names 
    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)
  LOG('PreferenceTool', INFO, 'Preference methods generated')

class PreferenceMethod(Method) :
  """ 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 = ()

  def __init__(self, attribute) :
    self._preference_name = attribute

  def __call__(self, instance, *args, **kw) :
    def _getPreference(user_name="") :
      found = 0
      MARKER = []
      for pref in instance._getSortedPreferenceList() :
        attr = getattr(pref, self._preference_name, MARKER)
        if attr is not MARKER :
          found = 1
          # test the attr is set
          if callable(attr) :
            value = attr()
          else :
            value = attr
          if value not in (None, '', (), []) :
            return value
      if found :
        return value
    _getPreference = CachingMethod( _getPreference,
            id='PreferenceTool.CachingMethod.%s' % self._preference_name)
    user_name = getSecurityManager().getUser().getId()
    return _getPreference(user_name=user_name)
    
113 114 115 116 117
class PreferenceTool(BaseTool):
  """ PreferenceTool manages User Preferences / User profiles. """
  id            = 'portal_preferences'
  meta_type     = 'ERP5 Preference Tool'
  portal_type   = 'Preference Tool'
Jérome Perrin's avatar
Jérome Perrin committed
118
  title         = 'Preferences'
119 120 121 122 123 124
  allowed_types = ( 'ERP5 Preference',)
  security      = ClassSecurityInfo()

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

126 127 128 129 130 131 132 133
  security.declarePrivate('manage_afterAdd')
  def manage_afterAdd(self, item, container) :
    """ init the permissions right after creation """
    item.manage_permission(Permissions.AddPortalContent,
          ['Member', 'Author', 'Manager'])
    item.manage_permission(Permissions.View,
          ['Member', 'Auditor', 'Manager'])
    BaseTool.inheritedAttribute('manage_afterAdd')(self, item, container)
134

135 136 137
  security.declareProtected(Permissions.View, "getPreference")
  def getPreference(self, pref_name) :
    """ get the preference on the most appopriate Preference object. """
Jérome Perrin's avatar
Jérome Perrin committed
138 139
    LOG("PreferenceTool", PROBLEM, 'calling getPreference directly on the '+
                                   'tool is deprecated, no caching happens !')
140
    def _getPreference(pref_name="") :
141 142
      found = 0
      MARKER = []
143
      for pref in self._getSortedPreferenceList() :
144 145 146 147 148 149 150 151 152 153 154
        attr = getattr(pref, pref_name, MARKER)
        if attr is not MARKER :
          found = 1
          # test the attr is set
          if callable(attr) :
            value = attr()
          else :
            value = attr
          if value not in (None, '', (), []) :
            return attr
      if found :
155
        return value
156
    return _getPreference(pref_name=pref_name)
157

158 159 160 161
  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})
162 163 164

  security.declarePrivate('_getSortedPreferenceList')
  def _getSortedPreferenceList(self) :
165
    """ return the most appropriate preferences objects,
166 167
        sorted so that the first in the list should be applied first
    """
168
    prefs = []
169 170 171
    # XXX will also cause problems with Manager (too long)
    # XXX For manager, create a manager specific preference
    #                  or better solution
Jérome Perrin's avatar
Jérome Perrin committed
172
    for pref in self.searchFolder(spec=('ERP5 Preference', )) :
173
      pref = pref.getObject()
174
      if pref.getPreferenceState() == 'enabled' :
175 176 177
        prefs.append(pref)
    prefs.sort(lambda b, a: cmp(a.getPriority(), b.getPriority()))
    return prefs
178
    
179 180 181 182
  security.declareProtected(Permissions.View, 'getActivePreference')
  def getActivePreference(self) :
    """ returns the current preference for the user. 
       Note that this preference may be read only. """
183
    enabled_prefs = self._getSortedPreferenceList()
184 185 186
    if len(enabled_prefs) > 0 :
      return enabled_prefs[0]

187
  security.declareProtected(Permissions.View, 'getDocumentTemplateList')
188
  def getDocumentTemplateList(self, folder=None) :
189
    """ returns all document templates that are in acceptable Preferences 
190 191
        based on different criteria such as folder, portal_type, etc.
    """
192 193 194
    if folder is None :
      # as the preference tool is also a Folder, this method is called by
      # page templates to get the list of document templates for self.
195
      folder = self
196

197
    acceptable_templates = []
198 199
    allowed_content_types = map(lambda pti: pti.id,
                                folder.allowedContentTypes())
200
    for pref in self._getSortedPreferenceList() :
201
      for doc in pref.objectValues() :
202
        if doc.getPortalType() in allowed_content_types:
203 204 205 206 207
          acceptable_templates.append (doc)
    return acceptable_templates

InitializeClass(PreferenceTool)