Commit 036d773a authored by Hanno Schlichting's avatar Hanno Schlichting

flake8

parent d9ce0e27
......@@ -39,15 +39,18 @@ LOG = getLogger('Cache')
def isCacheable(ob):
return getattr(aq_base(ob), '_isCacheable', 0)
def managersExist(ob):
# Returns 1 if any CacheManagers exist in the context of ob.
if aq_get(ob, ZCM_MANAGERS, None, 1):
return 1
return 0
def filterCacheTab(ob):
return managersExist(ob)
def filterCacheManagers(orig, container, name, value, extra):
'''
This is a filter method for aq_acquire.
......@@ -55,10 +58,11 @@ def filterCacheManagers(orig, container, name, value, extra):
in the list of cache managers.
'''
if (hasattr(aq_base(container), ZCM_MANAGERS) and
name in getattr(container, ZCM_MANAGERS)):
name in getattr(container, ZCM_MANAGERS)):
return 1
return 0
def getVerifiedManagerIds(container):
'''
Gets the list of cache managers in a container, verifying each one.
......@@ -81,11 +85,10 @@ class Cacheable:
'''Mix-in for cacheable objects.
'''
manage_options = ({
'label':'Cache',
'action':'ZCacheable_manage',
'filter':filterCacheTab,
},)
manage_options = (
{'label': 'Cache', 'action': 'ZCacheable_manage',
'filter': filterCacheTab},
)
security = ClassSecurityInfo()
security.setPermissionDefault(ChangeCacheSettingsPermission, ('Manager',))
......@@ -162,8 +165,7 @@ class Cacheable:
mtime_func, default)
return val
except:
LOG.warn('ZCache_get() exception',
exc_info=sys.exc_info())
LOG.warn('ZCache_get() exception')
return default
return default
......@@ -180,8 +182,7 @@ class Cacheable:
c.ZCache_set(ob, data, view_name, keywords,
mtime_func)
except:
LOG.warn('ZCache_set() exception',
exc_info=sys.exc_info())
LOG.warn('ZCache_set() exception')
security.declareProtected(ViewManagementScreensPermission,
'ZCacheable_invalidate')
......@@ -200,8 +201,7 @@ class Cacheable:
except:
exc = sys.exc_info()
try:
LOG.warn('ZCache_invalidate() exception',
exc_info=exc)
LOG.warn('ZCache_invalidate() exception')
message = 'An exception occurred: %s: %s' % exc[:2]
finally:
exc = None
......@@ -262,10 +262,9 @@ class Cacheable:
manager = getattr(ob, id, None)
if manager is not None:
id = manager.getId()
if not used_ids.has_key(id):
title = getattr(aq_base(manager),
'title', '')
rval.append({'id':id, 'title':title})
if id not in used_ids:
title = getattr(aq_base(manager), 'title', '')
rval.append({'id': id, 'title': title})
used_ids[id] = 1
ob = aq_parent(aq_inner(ob))
return tuple(rval)
......@@ -345,7 +344,8 @@ def findCacheables(ob, manager_id, require_assoc, subfolders,
'path': '/'.join(subpath),
'title': getattr(aq_base(subob), 'title', ''),
'icon': None,
'associated': associated,}
'associated': associated,
}
rval.append(info)
# Visit subfolders.
......@@ -356,7 +356,7 @@ def findCacheables(ob, manager_id, require_assoc, subfolders,
subpath = path + (subob.getId(),)
if hasattr(aq_base(subob), 'objectValues'):
if sm.checkPermission(
'Access contents information', subob):
'Access contents information', subob):
findCacheables(
subob, manager_id, require_assoc,
subfolders, meta_types, rval, subpath)
......@@ -415,10 +415,8 @@ class CacheManager:
_isCacheManager = 1
manage_options = (
{'label':'Associate',
'action':'ZCacheManager_associate',
},
)
{'label': 'Associate', 'action': 'ZCacheManager_associate'},
)
def manage_afterAdd(self, item, container):
# Adds self to the list of cache managers in the container.
......@@ -503,8 +501,8 @@ class CacheManager:
if REQUEST is not None:
return self.ZCacheManager_associate(
self, REQUEST, management_view="Associate",
manage_tabs_message='%d association(s) made, %d removed.'%
manage_tabs_message='%d association(s) made, %d removed.' %
(addcount, remcount)
)
)
InitializeClass(CacheManager)
This diff is collapsed.
......@@ -32,6 +32,7 @@ done = 'done'
_marker = [] # Create a new marker object.
class DTMLDocument(PropertyManager, DTMLMethod):
""" DocumentTemplate.HTML objects whose 'self' is the DTML object.
"""
......@@ -41,13 +42,12 @@ class DTMLDocument(PropertyManager, DTMLMethod):
DTMLMethod.manage_options[:2] +
PropertyManager.manage_options +
DTMLMethod.manage_options[2:]
)
)
# Replace change_dtml_methods by change_dtml_documents
__ac_permissions__ = tuple([
(perms[0] == change_dtml_methods)
and (change_dtml_documents, perms[1])
or perms
(perms[0] == change_dtml_methods) and
(change_dtml_documents, perms[1]) or perms
for perms in DTMLMethod.__ac_permissions__])
def manage_upload(self, file='', REQUEST=None):
......@@ -57,7 +57,7 @@ class DTMLDocument(PropertyManager, DTMLMethod):
if self.wl_isLocked():
raise ResourceLockedError('This document has been locked.')
if type(file) is not type(''):
if not isinstance(file, str):
if REQUEST and not file:
raise ValueError('No file specified')
file = file.read()
......@@ -70,7 +70,7 @@ class DTMLDocument(PropertyManager, DTMLMethod):
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
"""Render the document with the given client object.
o If supplied, use REQUEST mapping, Response, and key word arguments.
"""
if not self._cache_namespace_keys:
......@@ -81,7 +81,7 @@ class DTMLDocument(PropertyManager, DTMLMethod):
__traceback_supplement__ = (PathTracebackSupplement, self)
kw['document_id'] = self.getId()
kw['document_title'] =self.title
kw['document_title'] = self.title
if hasattr(self, 'aq_explicit'):
bself = self.aq_explicit
else:
......@@ -92,25 +92,29 @@ class DTMLDocument(PropertyManager, DTMLMethod):
try:
if client is None:
# Called as subtemplate, so don't need error propigation!
r = apply(HTML.__call__, (self, bself, REQUEST), kw)
if RESPONSE is None: result = r
else: result = decapitate(r, RESPONSE)
# Called as subtemplate, so don't need error propagation!
r = HTML.__call__(self, bself, REQUEST, **kw)
if RESPONSE is None:
result = r
else:
result = decapitate(r, RESPONSE)
if not self._cache_namespace_keys:
self.ZCacheable_set(result)
return result
r = apply(HTML.__call__, (self, (client, bself), REQUEST), kw)
if type(r) is not type('') or RESPONSE is None:
r = HTML.__call__(self, (client, bself), REQUEST, **kw)
if RESPONSE is None or not isinstance(r, str):
if not self._cache_namespace_keys:
self.ZCacheable_set(r)
return r
finally: security.removeContext(self)
finally:
security.removeContext(self)
have_key = RESPONSE.headers.has_key
if not (have_key('content-type') or have_key('Content-Type')):
if self.__dict__.has_key('content_type'):
if 'content_type' in self.__dict__:
c = self.content_type
else:
c, e = guess_content_type(self.__name__, r)
......@@ -124,7 +128,7 @@ class DTMLDocument(PropertyManager, DTMLMethod):
InitializeClass(DTMLDocument)
default_dd_html="""<html>
default_dd_html = """<html>
<head><title><dtml-var title_or_id></title>
</head>
<body bgcolor="#FFFFFF">
......@@ -135,17 +139,18 @@ This is the <dtml-var id> Document.
</body>
</html>"""
addForm=DTMLFile('dtml/documentAdd', globals())
addForm = DTMLFile('dtml/documentAdd', globals())
def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None):
"""Add a DTML Document object with the contents of file. If
'file' is empty, default document text is used.
"""
if type(file) is not type(''):
if not isinstance(file, str):
file = file.read()
if not file:
file = default_dd_html
id =str(id)
id = str(id)
title = str(title)
ob = DTMLDocument(file, __name__=id)
ob.title = title
......@@ -156,6 +161,6 @@ def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None):
except:
u = REQUEST['URL1']
if submit == " Add and Edit ":
u = "%s/%s" % (u,quote(id))
REQUEST.RESPONSE.redirect(u+'/manage_main')
u = "%s/%s" % (u, quote(id))
REQUEST.RESPONSE.redirect(u + '/manage_main')
return ''
This diff is collapsed.
......@@ -13,7 +13,11 @@
"""Deprecated - use DTMLMethod
"""
import DTMLMethod
from zope.deferredimport import deprecated
Document=DTMLMethod.DTMLMethod
manage_addDocument=DTMLMethod.addDTMLMethod
# BBB Zope 5.0
deprecated(
'Please import from OFS.DTMLMethod.',
Document='OFS.DTMLMethod:Document',
manage_addDocument='OFS.DTMLMethod:manage_addDocument',
)
......@@ -25,7 +25,6 @@ from interfaces import IFTPAccess
class FTPInterface:
"Interface for FTP objects"
implements(IFTPAccess)
......@@ -34,11 +33,11 @@ class FTPInterface:
# be XML, not marshal, maybe Andrew K's xml-marshal.
# This will probably be changed later.
def manage_FTPstat(self,REQUEST):
def manage_FTPstat(self, REQUEST):
"""Returns a stat-like tuple. (marshalled to a string) Used by
FTP for directory listings, and MDTM and SIZE"""
def manage_FTPlist(self,REQUEST):
def manage_FTPlist(self, REQUEST):
"""Returns a directory listing consisting of a tuple of
(id,stat) tuples, marshaled to a string. Note, the listing it
should include '..' if there is a Folder above the current
......
......@@ -64,9 +64,11 @@ class Folder(
"""
implements(IFolder)
meta_type='Folder'
meta_type = 'Folder'
_properties=({'id':'title', 'type': 'string','mode':'wd'},)
_properties = (
{'id': 'title', 'type': 'string', 'mode': 'wd'},
)
manage_options = (
ObjectManager.manage_options +
......
......@@ -24,7 +24,6 @@ from AccessControl.Permissions import change_images_and_files
from AccessControl.Permissions import view_management_screens
from AccessControl.Permissions import view as View # NOQA
from AccessControl.Permissions import ftp_access
from AccessControl.Permissions import delete_objects
from AccessControl.SecurityInfo import ClassSecurityInfo
from Acquisition import Implicit
from App.Common import rfc1123_date
......
......@@ -18,14 +18,16 @@
and aquisition relationships via a simple interface.
"""
class Moniker:
class Moniker(object):
"""An object moniker is an intelligent reference to a
persistent object. A moniker can be turned back into
a real object that retains its correct version context
and acquisition relationships via a simple interface."""
def __init__(self, ob=None):
if ob is None: return
if ob is None:
return
self.idpath = ob.getPhysicalPath()
def bind(self, app):
......@@ -47,6 +49,8 @@ def loadMoniker(data):
m.idpath = data
return m
def absattr(attr):
if callable(attr): return attr()
if callable(attr):
return attr()
return attr
......@@ -13,7 +13,7 @@
""" Order support for 'Object Manager'.
"""
import warnings
import sys
from AccessControl.class_init import InitializeClass
from AccessControl.Permissions import access_contents_information
......@@ -25,7 +25,10 @@ from zope.interface import implements
from zope.container.contained import notifyContainerModified
from OFS.interfaces import IOrderedContainer as IOrderedContainer
from OFS.ObjectManager import ObjectManager
if sys.version_info >= (3, ):
basestring = str
class OrderSupport(object):
......@@ -46,12 +49,8 @@ class OrderSupport(object):
_default_sort_reverse = 0
manage_options = (
{'label':'Contents', 'action':'manage_main'},
)
#
# ZMI Methods
#
{'label': 'Contents', 'action': 'manage_main'},
)
security.declareProtected(manage_properties, 'manage_move_objects_up')
def manage_move_objects_up(self, REQUEST, ids=None, delta=1):
......@@ -60,9 +59,9 @@ class OrderSupport(object):
if ids:
try:
attempt = self.moveObjectsUp(ids, delta)
message = '%d item%s moved up.' % ( attempt,
( (attempt!=1) and 's' or '' ) )
except ValueError, errmsg:
message = '%d item%s moved up.' % (
attempt, ((attempt != 1) and 's' or ''))
except ValueError as errmsg:
message = 'Error: %s' % (errmsg)
else:
message = 'Error: No items were specified!'
......@@ -76,9 +75,9 @@ class OrderSupport(object):
if ids:
try:
attempt = self.moveObjectsDown(ids, delta)
message = '%d item%s moved down.' % ( attempt,
( (attempt!=1) and 's' or '' ) )
except ValueError, errmsg:
message = '%d item%s moved down.' % (
attempt, ((attempt != 1) and 's' or ''))
except ValueError as errmsg:
message = 'Error: %s' % (errmsg)
else:
message = 'Error: No items were specified!'
......@@ -92,25 +91,26 @@ class OrderSupport(object):
if ids:
try:
attempt = self.moveObjectsToTop(ids)
message = '%d item%s moved to top.' % ( attempt,
( (attempt!=1) and 's' or '' ) )
except ValueError, errmsg:
message = '%d item%s moved to top.' % (
attempt, ((attempt != 1) and 's' or ''))
except ValueError as errmsg:
message = 'Error: %s' % (errmsg)
else:
message = 'Error: No items were specified!'
return self.manage_main(self, REQUEST, skey='position',
manage_tabs_message=message, update_menu=1)
security.declareProtected(manage_properties, 'manage_move_objects_to_bottom')
security.declareProtected(
manage_properties, 'manage_move_objects_to_bottom')
def manage_move_objects_to_bottom(self, REQUEST, ids=None):
""" Move specified sub-objects to bottom of container.
"""
if ids:
try:
attempt = self.moveObjectsToBottom(ids)
message = '%d item%s moved to bottom.' % ( attempt,
( (attempt!=1) and 's' or '' ) )
except ValueError, errmsg:
message = '%d item%s moved to bottom.' % (
attempt, ((attempt != 1) and 's' or ''))
except ValueError as errmsg:
message = 'Error: %s' % (errmsg)
else:
message = 'Error: No items were specified!'
......@@ -124,11 +124,6 @@ class OrderSupport(object):
self.setDefaultSorting(key, reverse)
return self.manage_main(self, REQUEST, update_menu=1)
#
# IOrderedContainer Interface Methods
#
security.declareProtected(manage_properties, 'moveObjectsByDelta')
def moveObjectsByDelta(self, ids, delta, subset_ids=None,
suppress_events=False):
......@@ -150,7 +145,7 @@ class OrderSupport(object):
for id in ids:
old_position = subset_ids.index(id)
new_position = max( old_position - abs(delta), min_position )
new_position = max(old_position - abs(delta), min_position)
if new_position == min_position:
min_position += 1
if not old_position == new_position:
......@@ -163,12 +158,12 @@ class OrderSupport(object):
subset_ids.reverse()
obj_dict = {}
for obj in objects:
obj_dict[ obj['id'] ] = obj
obj_dict[obj['id']] = obj
pos = 0
for i in range( len(objects) ):
for i in range(len(objects)):
if objects[i]['id'] in subset_ids:
try:
objects[i] = obj_dict[ subset_ids[pos] ]
objects[i] = obj_dict[subset_ids[pos]]
pos += 1
except KeyError:
raise ValueError('The object with the id "%s" does '
......@@ -193,21 +188,21 @@ class OrderSupport(object):
security.declareProtected(manage_properties, 'moveObjectsToTop')
def moveObjectsToTop(self, ids, subset_ids=None):
# Move specified sub-objects to top of container.
return self.moveObjectsByDelta( ids, -len(self._objects), subset_ids )
return self.moveObjectsByDelta(ids, -len(self._objects), subset_ids)
security.declareProtected(manage_properties, 'moveObjectsToBottom')
def moveObjectsToBottom(self, ids, subset_ids=None):
# Move specified sub-objects to bottom of container.
return self.moveObjectsByDelta( ids, len(self._objects), subset_ids )
return self.moveObjectsByDelta(ids, len(self._objects), subset_ids)
security.declareProtected(manage_properties, 'orderObjects')
def orderObjects(self, key, reverse=None):
# Order sub-objects by key and direction.
ids = [ id for id, obj in sort( self.objectItems(),
( (key, 'cmp', 'asc'), ) ) ]
ids = [id for id, obj in sort(
self.objectItems(), ((key, 'cmp', 'asc'), ))]
if reverse:
ids.reverse()
return self.moveObjectsByDelta( ids, -len(self._objects) )
return self.moveObjectsByDelta(ids, -len(self._objects))
security.declareProtected(access_contents_information,
'getObjectPosition')
......@@ -236,11 +231,6 @@ class OrderSupport(object):
self._default_sort_key = key
self._default_sort_reverse = reverse and 1 or 0
#
# Override Inherited Method of ObjectManager Subclass
#
def manage_renameObject(self, id, new_id, REQUEST=None):
""" Rename a particular sub-object without changing its position.
"""
......@@ -253,10 +243,11 @@ class OrderSupport(object):
def tpValues(self):
# Return a list of subobjects, used by tree tag.
r=[]
r = []
if hasattr(aq_base(self), 'tree_ids'):
tree_ids=self.tree_ids
try: tree_ids=list(tree_ids)
tree_ids = self.tree_ids
try:
tree_ids = list(tree_ids)
except TypeError:
pass
if hasattr(tree_ids, 'sort'):
......@@ -266,17 +257,13 @@ class OrderSupport(object):
r.append(self._getOb(id))
else:
# this part is different from the ObjectManager code
r = [ obj for obj in self.objectValues()
if getattr(obj, 'isPrincipiaFolderish', False) ]
r = sort( r, ( (self._default_sort_key, 'cmp', 'asc'), ) )
r = [obj for obj in self.objectValues()
if getattr(obj, 'isPrincipiaFolderish', False)]
r = sort(r, ((self._default_sort_key, 'cmp', 'asc'), ))
if self._default_sort_reverse:
r.reverse()
return r
#
# Helper methods
#
def getIdsSubset(self, objects):
return [obj['id'] for obj in objects]
......
......@@ -22,6 +22,7 @@ from OFS.OrderSupport import OrderSupport
manage_addOrderedFolderForm = DTMLFile('dtml/addOrderedFolder', globals())
def manage_addOrderedFolder(self, id, title='', createPublic=0, createUserF=0,
REQUEST=None):
"""Add a new ordered Folder object with id *id*.
......@@ -39,7 +40,9 @@ class OrderedFolder(OrderSupport, Folder):
""" Extends the default Folder by order support.
"""
implements(IOrderedFolder)
meta_type='Folder (Ordered)'
meta_type = 'Folder (Ordered)'
manage_options = ( OrderSupport.manage_options +
Folder.manage_options[1:] )
manage_options = (
OrderSupport.manage_options +
Folder.manage_options[1:]
)
......@@ -31,8 +31,8 @@ from OFS.interfaces import IPropertyManager
from OFS.PropertySheets import DefaultPropertySheets
from OFS.PropertySheets import vps
class PropertyManager(Base):
class PropertyManager(Base):
"""
The PropertyManager mixin class provides an object with
transparent property management. An object which wants to
......@@ -102,26 +102,28 @@ class PropertyManager(Base):
security.setPermissionDefault(access_contents_information,
('Anonymous', 'Manager'))
manage_options=(
{'label':'Properties', 'action':'manage_propertiesForm'},
)
manage_options = (
{'label': 'Properties', 'action': 'manage_propertiesForm'},
)
security.declareProtected(manage_properties, 'manage_propertiesForm')
manage_propertiesForm=DTMLFile('dtml/properties', globals(),
property_extensible_schema__=1)
manage_propertiesForm = DTMLFile(
'dtml/properties', globals(), property_extensible_schema__=1)
security.declareProtected(manage_properties, 'manage_propertyTypeForm')
manage_propertyTypeForm=DTMLFile('dtml/propertyType', globals())
manage_propertyTypeForm = DTMLFile('dtml/propertyType', globals())
title=''
_properties=({'id':'title', 'type': 'string', 'mode':'wd'},)
_reserved_names=()
title = ''
_properties = (
{'id': 'title', 'type': 'string', 'mode': 'wd'},
)
_reserved_names = ()
__propsets__=()
propertysheets=vps(DefaultPropertySheets)
__propsets__ = ()
propertysheets = vps(DefaultPropertySheets)
security.declareProtected(access_contents_information, 'valid_property_id')
def valid_property_id(self, id):
if not id or id[:1]=='_' or (id[:3]=='aq_') \
if not id or id[:1] == '_' or (id[:3] == 'aq_') \
or (' ' in id) or hasattr(aq_base(self), id) or escape(id) != id:
return 0
return 1
......@@ -131,7 +133,7 @@ class PropertyManager(Base):
"""Return true if object has a property 'id'.
"""
for p in self._properties:
if id==p['id']:
if id == p['id']:
return 1
return 0
......@@ -153,24 +155,24 @@ class PropertyManager(Base):
Returns None if no such property exists.
"""
for md in self._properties:
if md['id']==id:
if md['id'] == id:
return md.get('type', 'string')
return None
def _wrapperCheck(self, object):
# Raise an error if an object is wrapped.
if hasattr(object, 'aq_base'):
raise ValueError, 'Invalid property value: wrapped object'
raise ValueError('Invalid property value: wrapped object')
return
def _setPropValue(self, id, value):
self._wrapperCheck(value)
if type(value) == list:
value = tuple(value)
setattr(self,id,value)
setattr(self, id, value)
def _delPropValue(self, id):
delattr(self,id)
delattr(self, id)
def _setProperty(self, id, value, type='string'):
# for selection and multiple selection properties
......@@ -178,19 +180,19 @@ class PropertyManager(Base):
# of the property
self._wrapperCheck(value)
if not self.valid_property_id(id):
raise BadRequest, 'Invalid or duplicate property id'
raise BadRequest('Invalid or duplicate property id')
if type in ('selection', 'multiple selection'):
if not hasattr(self, value):
raise BadRequest, 'No select variable %s' % value
self._properties=self._properties + (
{'id':id, 'type':type, 'select_variable':value},)
if type=='selection':
raise BadRequest('No select variable %s' % value)
self._properties = self._properties + (
{'id': id, 'type': type, 'select_variable': value},)
if type == 'selection':
self._setPropValue(id, '')
else:
self._setPropValue(id, [])
else:
self._properties=self._properties+({'id':id,'type':type},)
self._properties = self._properties + ({'id': id, 'type': type},)
self._setPropValue(id, value)
def _updateProperty(self, id, value):
......@@ -199,18 +201,18 @@ class PropertyManager(Base):
# the value to the type of the existing property.
self._wrapperCheck(value)
if not self.hasProperty(id):
raise BadRequest, 'The property %s does not exist' % escape(id)
if type(value)==type(''):
proptype=self.getPropertyType(id) or 'string'
raise BadRequest('The property %s does not exist' % escape(id))
if isinstance(value, str):
proptype = self.getPropertyType(id) or 'string'
if proptype in type_converters:
value=type_converters[proptype](value)
value = type_converters[proptype](value)
self._setPropValue(id, value)
def _delProperty(self, id):
if not self.hasProperty(id):
raise ValueError, 'The property %s does not exist' % escape(id)
raise ValueError('The property %s does not exist' % escape(id))
self._delPropValue(id)
self._properties=tuple(i for i in self._properties if i['id'] != id)
self._properties = tuple(i for i in self._properties if i['id'] != id)
security.declareProtected(access_contents_information, 'propertyIds')
def propertyIds(self):
......@@ -264,13 +266,11 @@ class PropertyManager(Base):
security.declareProtected(access_contents_information, 'propdict')
def propdict(self):
dict={}
dict = {}
for p in self._properties:
dict[p['id']]=p
dict[p['id']] = p
return dict
# Web interface
security.declareProtected(manage_properties, 'manage_addProperty')
def manage_addProperty(self, id, value, type, REQUEST=None):
"""Add a new property via the web.
......@@ -324,7 +324,7 @@ class PropertyManager(Base):
propdict = self.propdict()
for name, value in props.items():
if self.hasProperty(name):
if not 'w' in propdict[name].get('mode', 'wd'):
if 'w' not in propdict[name].get('mode', 'wd'):
raise BadRequest('%s cannot be changed' % escape(name))
self._updateProperty(name, value)
if REQUEST:
......@@ -332,8 +332,6 @@ class PropertyManager(Base):
return self.manage_propertiesForm(self, REQUEST,
manage_tabs_message=message)
# Note - this is experimental, pending some community input.
security.declareProtected(manage_properties, 'manage_changePropertyTypes')
def manage_changePropertyTypes(self, old_ids, props, REQUEST=None):
"""Replace one set of properties with another
......@@ -353,30 +351,31 @@ class PropertyManager(Base):
if REQUEST is not None:
return self.manage_propertiesForm(self, REQUEST)
security.declareProtected(manage_properties, 'manage_delProperties')
def manage_delProperties(self, ids=None, REQUEST=None):
"""Delete one or more properties specified by 'ids'."""
if REQUEST:
# Bugfix for property named "ids" (Casey)
if ids == self.getProperty('ids', None): ids = None
if ids == self.getProperty('ids', None):
ids = None
ids = REQUEST.get('_ids', ids)
if ids is None:
return MessageDialog(
title='No property specified',
message='No properties were specified!',
action ='./manage_propertiesForm',)
propdict=self.propdict()
nd=self._reserved_names
title='No property specified',
message='No properties were specified!',
action='./manage_propertiesForm')
propdict = self.propdict()
nd = self._reserved_names
for id in ids:
if not hasattr(aq_base(self), id):
raise BadRequest, (
'The property <em>%s</em> does not exist' % escape(id))
if (not 'd' in propdict[id].get('mode', 'wd')) or (id in nd):
raise BadRequest(
'The property <em>%s</em> does not exist' % escape(id))
if ('d' not in propdict[id].get('mode', 'wd')) or (id in nd):
return MessageDialog(
title ='Cannot delete %s' % id,
message='The property <em>%s</em> cannot be deleted.' % escape(id),
action ='manage_propertiesForm')
title='Cannot delete %s' % id,
message='The property <em>%s</em> '
'cannot be deleted.' % escape(id),
action='manage_propertiesForm')
self._delProperty(id)
if REQUEST is not None:
......
......@@ -41,7 +41,7 @@ else:
DAVPropertySheetMixin = bbb.DAVPropertySheetMixin
class Virtual:
class Virtual(object):
"""A virtual propertysheet stores it's properties in it's instance."""
def __init__(self):
......
......@@ -81,8 +81,8 @@ class Item(Base,
security = ClassSecurityInfo()
isPrincipiaFolderish=0
isTopLevelPrincipiaApplicationObject=0
isPrincipiaFolderish = 0
isTopLevelPrincipiaApplicationObject = 0
def manage_afterAdd(self, item, container):
pass
......@@ -132,10 +132,11 @@ class Item(Base,
def title_or_id(self):
"""Return the title if it is not blank and the id otherwise.
"""
title=self.title
title = self.title
if callable(title):
title=title()
if title: return title
title = title()
if title:
return title
return self.getId()
def title_and_id(self):
......@@ -143,11 +144,11 @@ class Item(Base,
If the title is not blank, then the id is included in parens.
"""
title=self.title
title = self.title
if callable(title):
title=title()
title = title()
id = self.getId()
return title and ("%s (%s)" % (title,id)) or id
return title and ("%s (%s)" % (title, id)) or id
def this(self):
# Handy way to talk to ourselves in document templates.
......@@ -163,25 +164,27 @@ class Item(Base,
_manage_editedDialog = DTMLFile('dtml/editedDialog', globals())
def manage_editedDialog(self, REQUEST, **args):
return apply(self._manage_editedDialog,(self, REQUEST), args)
return self._manage_editedDialog(self, REQUEST, **args)
def raise_standardErrorMessage(
self, client=None, REQUEST={},
error_type=None, error_value=None, tb=None,
error_tb=None, error_message='',
tagSearch=re.compile(r'[a-zA-Z]>').search,
error_log_url=''):
self, client=None, REQUEST={},
error_type=None, error_value=None, tb=None,
error_tb=None, error_message='',
tagSearch=re.compile(r'[a-zA-Z]>').search,
error_log_url=''):
try:
if error_type is None: error_type =sys.exc_info()[0]
if error_value is None: error_value=sys.exc_info()[1]
if error_type is None:
error_type = sys.exc_info()[0]
if error_value is None:
error_value = sys.exc_info()[1]
# allow for a few different traceback options
if tb is None and error_tb is None:
tb=sys.exc_info()[2]
if type(tb) is not type('') and (error_tb is None):
tb = sys.exc_info()[2]
if not isinstance(tb, str) and (error_tb is None):
error_tb = pretty_tb(error_type, error_value, tb)
elif type(tb) is type('') and not error_tb:
elif isinstance(tb, str) and not error_tb:
error_tb = tb
if hasattr(self, '_v_eek'):
......@@ -204,7 +207,7 @@ class Item(Base,
except TypeError:
match = None
if match is not None:
error_message=error_value
error_message = error_value
if client is None:
client = self
......@@ -235,24 +238,25 @@ class Item(Base,
logger.error(
'Exception while rendering an error message',
exc_info=True
)
)
try:
strv = repr(error_value) # quotes tainted strings
strv = repr(error_value) # quotes tainted strings
except:
strv = ('<unprintable %s object>' %
str(type(error_value).__name__))
v = strv + (
(" (Also, the following error occurred while attempting "
"to render the standard error message, please see the "
"event log for full details: %s)")%(
html_quote(sys.exc_info()[1]),
"event log for full details: %s)") % (
html_quote(sys.exc_info()[1]),
))
# If we've been asked to handle errors, just return the rendered
# exception and let the ZPublisher Exception Hook deal with it.
return error_type, v, tb
finally:
if hasattr(self, '_v_eek'): del self._v_eek
if hasattr(self, '_v_eek'):
del self._v_eek
tb = None
def manage(self, URL1):
......@@ -264,66 +268,65 @@ class Item(Base,
# objectValues, etc., when used in simple tree tags.
def objectValues(self, spec=None):
return ()
objectIds=objectItems=objectValues
objectIds = objectItems = objectValues
# FTP support methods
def manage_FTPstat(self,REQUEST):
def manage_FTPstat(self, REQUEST):
"""Psuedo stat, used by FTP for directory listings.
"""
from AccessControl.User import nobody
mode=0100000
mode = 0o0100000
if (hasattr(aq_base(self),'manage_FTPget')):
if (hasattr(aq_base(self), 'manage_FTPget')):
try:
if getSecurityManager().validate(
None, self, 'manage_FTPget', self.manage_FTPget):
mode=mode | 0440
None, self, 'manage_FTPget', self.manage_FTPget):
mode = mode | 0o0440
except Unauthorized:
pass
if nobody.allowed(
self.manage_FTPget,
getRoles(self, 'manage_FTPget', self.manage_FTPget, ()),
):
mode=mode | 0004
self.manage_FTPget,
getRoles(self, 'manage_FTPget', self.manage_FTPget, ())):
mode = mode | 0o0004
# check write permissions
if hasattr(aq_base(self),'PUT'):
if hasattr(aq_base(self), 'PUT'):
try:
if getSecurityManager().validate(None, self, 'PUT', self.PUT):
mode=mode | 0220
mode = mode | 0o0220
except Unauthorized:
pass
if nobody.allowed(
self.PUT,
getRoles(self, 'PUT', self.PUT, ()),
):
mode=mode | 0002
self.PUT,
getRoles(self, 'PUT', self.PUT, ())):
mode = mode | 0o0002
# get size
if hasattr(aq_base(self), 'get_size'):
size=self.get_size()
elif hasattr(aq_base(self),'manage_FTPget'):
size=len(self.manage_FTPget())
size = self.get_size()
elif hasattr(aq_base(self), 'manage_FTPget'):
size = len(self.manage_FTPget())
else:
size=0
size = 0
# get modification time
if hasattr(aq_base(self), '_p_mtime'):
mtime=DateTime(self._p_mtime).timeTime()
mtime = DateTime(self._p_mtime).timeTime()
else:
mtime=time.time()
mtime = time.time()
# get owner and group
owner=group='Zope'
owner = group = 'Zope'
if hasattr(aq_base(self), 'get_local_roles'):
for user, roles in self.get_local_roles():
if 'Owner' in roles:
owner=user
owner = user
break
return marshal.dumps((mode,0,0,1,owner,group,size,mtime,mtime,mtime))
return marshal.dumps(
(mode, 0, 0, 1, owner, group, size, mtime, mtime, mtime))
def manage_FTPlist(self,REQUEST):
def manage_FTPlist(self, REQUEST):
"""Directory listing for FTP.
In the case of non-Foldoid objects, the listing should contain one
......@@ -331,17 +334,17 @@ class Item(Base,
"""
from App.Common import is_acquired
# check to see if we are being acquiring or not
ob=self
ob = self
while 1:
if is_acquired(ob):
raise ValueError('FTP List not supported on acquired objects')
if not hasattr(ob,'aq_parent'):
if not hasattr(ob, '__parent__'):
break
ob = aq_parent(ob)
stat=marshal.loads(self.manage_FTPstat(REQUEST))
stat = marshal.loads(self.manage_FTPstat(REQUEST))
id = self.getId()
return marshal.dumps((id,stat))
return marshal.dumps((id, stat))
def __len__(self):
return 1
......@@ -397,11 +400,11 @@ class Item_w__name__(Item):
If the title is not blank, then the id is included in parens.
"""
t=self.title
return t and ("%s (%s)" % (t,self.__name__)) or self.__name__
t = self.title
return t and ("%s (%s)" % (t, self.__name__)) or self.__name__
def _setId(self, id):
self.__name__=id
self.__name__ = id
def getPhysicalPath(self):
# Get the physical path of the object.
......@@ -429,8 +432,6 @@ class SimpleItem(Item,
Implicit,
RoleManager,
):
# Blue-plate special, Zope Masala
"""Mix-in class combining the most common set of basic mix-ins
"""
......@@ -439,8 +440,8 @@ class SimpleItem(Item,
security = ClassSecurityInfo()
security.setPermissionDefault(View, ('Manager',))
manage_options=Item.manage_options+(
manage_options = Item.manage_options + (
{'label': 'Security', 'action': 'manage_access'},
)
)
InitializeClass(SimpleItem)
......@@ -105,7 +105,7 @@ class Traversable:
return path2url(toVirt(spp))
security.declarePrivate('getPhysicalRoot')
getPhysicalRoot=Acquired
getPhysicalRoot = Acquired
security.declarePublic('getPhysicalPath')
def getPhysicalPath(self):
......@@ -162,9 +162,10 @@ class Traversable:
be traversed for any reason (i.e., no object exists at that path or
the object is inaccessible).
restricted -- If false (default) then no security checking is performed.
If true, then all of the objects along the path are validated with
the security machinery. Usually invoked using restrictedTraverse().
restricted -- If false (default) then no security checking is
performed. If true, then all of the objects along the path are
validated with the security machinery. Usually invoked using
restrictedTraverse().
"""
if not path:
return self
......@@ -191,7 +192,7 @@ class Traversable:
path_pop()
obj = self.getPhysicalRoot()
if restricted:
validate(None, None, None, obj) # may raise Unauthorized
validate(None, None, None, obj) # may raise Unauthorized
else:
obj = self
......@@ -221,7 +222,8 @@ class Traversable:
bobo_traverse = getattr(obj, '__bobo_traverse__', None)
try:
if name and name[:1] in '@+' and name != '+' and nsParse(name)[1]:
if (name and name[:1] in '@+' and name != '+' and
nsParse(name)[1]):
# Process URI segment parameters.
ns, nm = nsParse(name)
try:
......@@ -230,39 +232,44 @@ class Traversable:
if IAcquirer.providedBy(next):
next = next.__of__(obj)
if restricted and not validate(
obj, obj, name, next):
obj, obj, name, next):
raise Unauthorized(name)
except LocationError:
raise AttributeError(name)
else:
next = UseTraversalDefault # indicator
next = UseTraversalDefault # indicator
try:
if bobo_traverse is not None:
next = bobo_traverse(REQUEST, name)
if restricted:
if aq_base(next) is not next:
# The object is wrapped, so the acquisition
# context is the container.
# The object is wrapped, so the
# acquisition context is the container.
container = aq_parent(aq_inner(next))
elif getattr(next, 'im_self', None) is not None:
elif getattr(
next, 'im_self', None) is not None:
# Bound method, the bound instance
# is the container
container = next.im_self
elif getattr(aq_base(obj), name, _marker) is next:
# Unwrapped direct attribute of the object so
# object is the container
elif getattr(
aq_base(obj),
name, _marker) is next:
# Unwrapped direct attribute of the
# object so object is the container
container = obj
else:
# Can't determine container
container = None
# If next is a simple unwrapped property, its
# parentage is indeterminate, but it may have
# been acquired safely. In this case validate
# will raise an error, and we can explicitly
# check that our value was acquired safely.
# If next is a simple unwrapped property,
# its parentage is indeterminate, but it
# may have been acquired safely. In this
# case validate will raise an error, and
# we can explicitly check that our value
# was acquired safely.
try:
ok = validate(obj, container, name, next)
ok = validate(
obj, container, name, next)
except Unauthorized:
ok = False
if not ok:
......@@ -271,10 +278,13 @@ class Traversable:
is not next):
raise Unauthorized(name)
except UseTraversalDefault:
# behave as if there had been no '__bobo_traverse__'
# behave as if there had been no
# '__bobo_traverse__'
bobo_traverse = None
if next is UseTraversalDefault:
if getattr(aq_base(obj), name, _marker) is not _marker:
if getattr(
aq_base(obj),
name, _marker) is not _marker:
if restricted:
next = guarded_getattr(obj, name)
else:
......@@ -299,10 +309,11 @@ class Traversable:
obj, obj, None, next):
raise Unauthorized(name)
except (AttributeError, NotFound, KeyError), e:
except (AttributeError, NotFound, KeyError) as e:
# Try to look for a view
next = queryMultiAdapter((obj, aq_acquire(self, 'REQUEST')),
Interface, name)
next = queryMultiAdapter(
(obj, aq_acquire(self, 'REQUEST')),
Interface, name)
if next is not None:
if IAcquirer.providedBy(next):
......
......@@ -25,58 +25,61 @@ from Persistence import Overridable
from ZODB.broken import Broken as ZODB_Broken
from ZODB.broken import persistentBroken
broken_klasses={}
broken_klasses = {}
broken_klasses_lock = allocate_lock()
LOG = getLogger('OFS.Uninstalled')
class BrokenClass(ZODB_Broken, Explicit, Item, Overridable):
_p_changed=0
meta_type='Broken Because Product is Gone'
_p_changed = 0
meta_type = 'Broken Because Product is Gone'
product_name='unknown'
id='broken'
product_name = 'unknown'
id = 'broken'
manage_page_header = Acquired
manage_page_footer = Acquired
def __getattr__(self, name):
if name[:3]=='_p_':
if name[:3] == '_p_':
return BrokenClass.inheritedAttribute('__getattr__')(self, name)
raise AttributeError, escape(name)
raise AttributeError(escape(name))
manage = DTMLFile('dtml/brokenEdit',globals())
manage_main = DTMLFile('dtml/brokenEdit',globals())
manage_workspace = DTMLFile('dtml/brokenEdit',globals())
manage = DTMLFile('dtml/brokenEdit', globals())
manage_main = DTMLFile('dtml/brokenEdit', globals())
manage_workspace = DTMLFile('dtml/brokenEdit', globals())
def Broken(self, oid, pair):
broken_klasses_lock.acquire()
try:
if broken_klasses.has_key(pair):
if pair in broken_klasses:
klass = broken_klasses[pair]
else:
module, klassname = pair
d={'BrokenClass': BrokenClass}
exec ("class %s(BrokenClass): ' '; __module__=%s"
% (klassname, `module`)) in d
d = {'BrokenClass': BrokenClass}
exec("class %s(BrokenClass): ' '; __module__=%r" %
(klassname, module)) in d
klass = broken_klasses[pair] = d[klassname]
module=module.split('.')
if len(module) > 2 and module[0]=='Products':
klass.product_name= module[1]
klass.title=(
module = module.split('.')
if len(module) > 2 and module[0] == 'Products':
klass.product_name = module[1]
klass.title = (
'This object from the %s product '
'is broken!' %
klass.product_name)
klass.info=(
klass.info = (
'This object\'s class was %s in module %s.' %
(klass.__name__, klass.__module__))
klass = persistentBroken(klass)
LOG.warning('Could not import class %s '
'from module %s' % (`klass.__name__`, `klass.__module__`))
LOG.warning(
'Could not import class %r '
'from module %r' % (klass.__name__, klass.__module__))
finally:
broken_klasses_lock.release()
if oid is None: return klass
i=klass()
i._p_oid=oid
i._p_jar=self
if oid is None:
return klass
i = klass()
i._p_oid = oid
i._p_jar = self
return i
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
......@@ -106,10 +106,10 @@ class OFSTraversableAbsoluteURL(BrowserView):
request = self.request
name = context.getId()
if (container is None
or self._isVirtualHostRoot()
or not ITraversable.providedBy(container)):
if (container is None or
self._isVirtualHostRoot() or
not ITraversable.providedBy(container)):
return ({'name': name, 'url': context.absolute_url()},)
view = getMultiAdapter((container, request), IAbsoluteURL)
......@@ -132,8 +132,8 @@ class RootAbsoluteURL(OFSTraversableAbsoluteURL):
"""
def breadcrumbs(self):
context = self.context
request = self.request
return ({'name': context.getId(),
'url': context.absolute_url()
},)
return ({
'name': context.getId(),
'url': context.absolute_url()
},)
......@@ -39,10 +39,6 @@ class ObjectWillBeAddedEvent(ObjectWillBeMovedEvent):
implements(OFS.interfaces.IObjectWillBeAddedEvent)
def __init__(self, object, newParent=None, newName=None):
#if newParent is None:
# newParent = object.__parent__
#if newName is None:
# newName = object.__name__
ObjectWillBeMovedEvent.__init__(self, object, None, None,
newParent, newName)
......@@ -53,10 +49,6 @@ class ObjectWillBeRemovedEvent(ObjectWillBeMovedEvent):
implements(OFS.interfaces.IObjectWillBeRemovedEvent)
def __init__(self, object, oldParent=None, oldName=None):
#if oldParent is None:
# oldParent = object.__parent__
#if oldName is None:
# oldName = object.__name__
ObjectWillBeMovedEvent.__init__(self, object, oldParent, oldName,
None, None)
......
......@@ -241,8 +241,8 @@ class ITraversable(Interface):
def unrestrictedTraverse(path, default=None, restricted=0):
"""Lookup an object by path.
path -- The path to the object. May be a sequence of strings or a slash
separated string. If the path begins with an empty path element
path -- The path to the object. May be a sequence of strings or a
slash separated string. If the path begins with an empty path element
(i.e., an empty string or a slash) then the lookup is performed
from the application root. Otherwise, the lookup is relative to
self. Two dots (..) as a path element indicates an upward traversal
......@@ -252,9 +252,10 @@ class ITraversable(Interface):
be traversed for any reason (i.e., no object exists at that path or
the object is inaccessible).
restricted -- If false (default) then no security checking is performed.
If true, then all of the objects along the path are validated with
the security machinery. Usually invoked using restrictedTraverse().
restricted -- If false (default) then no security checking is
performed. If true, then all of the objects along the path are
validated with the security machinery. Usually invoked using
restrictedTraverse().
"""
def restrictedTraverse(path, default=None):
......@@ -270,12 +271,12 @@ class IZopeObject(Interface):
isPrincipiaFolderish = Bool(
title=u"Is a folderish object",
description=u"Should be false for simple items",
)
)
meta_type = BytesLine(
title=u"Meta type",
description=u"The object's Zope2 meta type",
)
)
# XXX: might contain non-API methods and outdated comments;
......@@ -287,9 +288,7 @@ class IManageable(Interface):
manage_tabs = Attribute("""Management tabs""")
manage_options = Tuple(
title=u"Manage options",
)
manage_options = Tuple(title=u"Manage options")
def manage(URL1):
"""Show management screen"""
......@@ -523,13 +522,9 @@ class ILockItem(Interface):
class IItem(IZopeObject, IManageable, IFTPAccess,
ICopySource, ITraversable, IOwned):
__name__ = BytesLine(
title=u"Name"
)
__name__ = BytesLine(title=u"Name")
title = BytesLine(
title=u"Title"
)
title = BytesLine(title=u"Title")
def getId():
"""Return the id of the object as a string.
......@@ -673,11 +668,11 @@ class IObjectManager(IZopeObject, ICopyContainer, INavigation, IManageable,
meta_types = Tuple(
title=u"Meta types",
description=u"Sub-object types that are specific to this object",
)
)
isAnObjectManager = Bool(
title=u"Is an object manager",
)
)
manage_main = Attribute(""" """)
manage_index_main = Attribute(""" """)
......@@ -852,15 +847,11 @@ class IPropertyManager(Interface):
manage_propertiesForm = Attribute(""" """)
manage_propertyTypeForm = Attribute(""" """)
title = BytesLine(
title=u"Title"
)
title = BytesLine(title=u"Title")
_properties = Tuple(
title=u"Properties",
)
_properties = Tuple(title=u"Properties")
propertysheets = Attribute(""" """)
propertysheets = Attribute(" ")
def valid_property_id(id):
"""
......@@ -1002,8 +993,8 @@ class IApplication(IFolder, IRoot):
"""Top-level system object"""
isTopLevelPrincipiaApplicationObject = Bool(
title=u"Is top level Principa application object",
)
title=u"Is top level application object",
)
p_ = Attribute(""" """)
misc_ = Attribute("Misc.")
......
......@@ -89,7 +89,7 @@ def _registerPackage(module_, init_func=None):
"""Registers the given python package as a Zope 2 style product
"""
if not hasattr(module_, '__path__'):
raise ValueError("Must be a package and the " \
raise ValueError("Must be a package and the "
"package must be filesystem based")
registered_packages = get_registered_packages()
......@@ -108,10 +108,10 @@ def registerPackage(_context, package, initialize=None):
"""
_context.action(
discriminator = ('registerPackage', package),
callable = _registerPackage,
args = (package,initialize)
)
discriminator=('registerPackage', package),
callable=_registerPackage,
args=(package, initialize)
)
def _registerClass(class_, meta_type, permission, addview, icon, global_):
......@@ -140,10 +140,11 @@ def _registerClass(class_, meta_type, permission, addview, icon, global_):
def registerClass(_context, class_, meta_type, permission, addview=None,
icon=None, global_=True):
_context.action(
discriminator = ('registerClass', meta_type),
callable = _registerClass,
args = (class_, meta_type, permission, addview, icon, global_)
)
discriminator=('registerClass', meta_type),
callable=_registerClass,
args=(class_, meta_type, permission, addview, icon, global_)
)
def unregisterClass(class_):
delattr(class_, 'meta_type')
......@@ -159,7 +160,7 @@ def deprecatedManageAddDelete(_context, class_):
discriminator=('five:deprecatedManageAddDelete', class_),
callable=setDeprecatedManageAddDelete,
args=(class_,),
)
)
def cleanUp():
......@@ -183,6 +184,6 @@ def cleanUp():
_meta_type_regs = []
from zope.testing.cleanup import addCleanUp
from zope.testing.cleanup import addCleanUp # NOQA
addCleanUp(cleanUp)
del addCleanUp
......@@ -10,12 +10,10 @@ class IDeprecatedManageAddDeleteDirective(Interface):
"""
class_ = GlobalObject(
title=u"Class",
required=True,
)
required=True)
class IRegisterClassDirective(Interface):
"""registerClass directive schema.
Register content with Zope 2.
......@@ -24,43 +22,37 @@ class IRegisterClassDirective(Interface):
class_ = GlobalObject(
title=u'Instance Class',
description=u'Dotted name of the class that is registered.',
required=True
)
required=True)
meta_type = ASCII(
title=u'Meta Type',
description=u'A human readable unique identifier for the class.',
required=True
)
required=True)
permission = Permission(
title=u'Add Permission',
description=u'The permission for adding objects of this class.',
required=True
)
required=True)
addview = ASCII(
title=u'Add View ID',
description=u'The ID of the add view used in the ZMI. Consider this '
u'required unless you know exactly what you do.',
default=None,
required=False
)
required=False)
icon = ASCII(
title=u'Icon ID',
description=u'The ID of the icon used in the ZMI.',
default=None,
required=False
)
required=False)
global_ = Bool(
title=u'Global scope?',
description=u'If "global" is False the class is only available in '
u'containers that explicitly allow one of its interfaces.',
default=True,
required=False
)
required=False)
class IRegisterPackageDirective(Interface):
......@@ -70,12 +62,10 @@ class IRegisterPackageDirective(Interface):
package = GlobalObject(
title=u'Target package',
required=True
)
required=True)
initialize = GlobalObject(
title=u'Initialization function to invoke',
description=u'The dotted name of a function that will get invoked '
u'with a ProductContext instance',
required=False
)
required=False)
......@@ -44,11 +44,16 @@ class Misc_:
security.declareObjectPublic()
def __init__(self, name, dict):
self._d=dict
self.__name__=name
self._d = dict
self.__name__ = name
def __str__(self): return self.__name__
def __getitem__(self, name): return self._d[name]
def __setitem__(self, name, v): self._d[name]=v
def __str__(self):
return self.__name__
def __getitem__(self, name):
return self._d[name]
def __setitem__(self, name, v):
self._d[name] = v
InitializeClass(Misc_)
......@@ -37,10 +37,10 @@ class Owned(BaseOwned):
security = ClassSecurityInfo()
security.setPermissionDefault(take_ownership, ('Owner', ))
manage_options=({'label': 'Ownership',
'action': 'manage_owner',
'filter': ownableFilter},
)
manage_options = (
{'label': 'Ownership', 'action': 'manage_owner',
'filter': ownableFilter},
)
security.declareProtected(view_management_screens, 'manage_owner')
manage_owner = DTMLFile('dtml/owner', globals())
......@@ -52,11 +52,11 @@ class Owned(BaseOwned):
If 'recursive' is true, then also take ownership of all sub-objects.
"""
security=getSecurityManager()
want_referer=REQUEST['URL1']+'/manage_owner'
got_referer=("%s://%s%s" %
urlparse.urlparse(REQUEST['HTTP_REFERER'])[:3])
__traceback_info__=want_referer, got_referer
security = getSecurityManager()
want_referer = REQUEST['URL1'] + '/manage_owner'
got_referer = ("%s://%s%s" %
urlparse.urlparse(REQUEST['HTTP_REFERER'])[:3])
__traceback_info__ = want_referer, got_referer
if (want_referer != got_referer or security.calledByExecutable()):
raise Unauthorized(
'manage_takeOwnership was called from an invalid context')
......@@ -71,13 +71,13 @@ class Owned(BaseOwned):
RESPONSE=None, REQUEST=None):
"""Change the type (implicit or explicit) of ownership.
"""
old=getattr(self, '_owner', None)
old = getattr(self, '_owner', None)
if explicit:
if old is not None:
return
owner = self.getOwnerTuple()
if owner is not None and owner is not UnownableOwner:
self._owner=owner
self._owner = owner
else:
if old is None:
return
......
......@@ -33,13 +33,13 @@ class RoleManager(BaseRoleManager):
security = ClassSecurityInfo()
manage_options=(
manage_options = (
{'label': 'Security', 'action': 'manage_access'},
)
)
security.declareProtected(change_permissions, 'manage_roleForm')
manage_roleForm=DTMLFile('dtml/roleEdit', globals(),
management_view='Security')
manage_roleForm = DTMLFile('dtml/roleEdit', globals(),
management_view='Security')
security.declareProtected(change_permissions, 'manage_role')
@requestmethod('POST')
......@@ -52,8 +52,8 @@ class RoleManager(BaseRoleManager):
return self.manage_access(REQUEST)
security.declareProtected(change_permissions, 'manage_acquiredForm')
manage_acquiredForm=DTMLFile('dtml/acquiredEdit', globals(),
management_view='Security')
manage_acquiredForm = DTMLFile('dtml/acquiredEdit', globals(),
management_view='Security')
security.declareProtected(change_permissions, 'manage_acquiredPermissions')
@requestmethod('POST')
......@@ -66,8 +66,8 @@ class RoleManager(BaseRoleManager):
return self.manage_access(REQUEST)
security.declareProtected(change_permissions, 'manage_permissionForm')
manage_permissionForm=DTMLFile('dtml/permissionEdit', globals(),
management_view='Security')
manage_permissionForm = DTMLFile('dtml/permissionEdit', globals(),
management_view='Security')
security.declareProtected(change_permissions, 'manage_permission')
@requestmethod('POST')
......@@ -84,25 +84,24 @@ class RoleManager(BaseRoleManager):
if REQUEST is not None:
return self.manage_access(REQUEST)
_normal_manage_access=DTMLFile('dtml/access', globals())
manage_reportUserPermissions=DTMLFile(
_normal_manage_access = DTMLFile('dtml/access', globals())
manage_reportUserPermissions = DTMLFile(
'dtml/reportUserPermissions', globals())
security.declareProtected(change_permissions, 'manage_access')
def manage_access(self, REQUEST, **kw):
"""Return an interface for making permissions settings.
"""
return apply(self._normal_manage_access, (), kw)
return self._normal_manage_access(**kw)
security.declareProtected(change_permissions, 'manage_changePermissions')
@requestmethod('POST')
def manage_changePermissions(self, REQUEST):
"""Change all permissions settings, called by management screen.
"""
valid_roles=self.valid_roles()
indexes=range(len(valid_roles))
have=REQUEST.has_key
permissions=self.ac_inherited_permissions(1)
valid_roles = self.valid_roles()
have = REQUEST.has_key
permissions = self.ac_inherited_permissions(1)
fails = []
for ip in range(len(permissions)):
permission_name = permissions[ip][0]
......@@ -117,28 +116,29 @@ class RoleManager(BaseRoleManager):
try:
p = Permission(name, value, self)
if not have('acquire_%s' % permission_hash):
roles=tuple(roles)
roles = tuple(roles)
p.setRoles(roles)
except:
fails.append(name)
if fails:
return MessageDialog(title="Warning!",
message="Some permissions had errors: "
+ escape(', '.join(fails)),
action='manage_access')
return MessageDialog(
title="Warning!",
message="Some permissions had errors: " +
escape(', '.join(fails)),
action='manage_access')
return MessageDialog(
title = 'Success!',
message = 'Your changes have been saved',
action = 'manage_access')
title='Success!',
message='Your changes have been saved',
action='manage_access')
security.declareProtected(change_permissions, 'manage_listLocalRoles')
manage_listLocalRoles=DTMLFile('dtml/listLocalRoles', globals(),
management_view='Security')
manage_listLocalRoles = DTMLFile('dtml/listLocalRoles', globals(),
management_view='Security')
security.declareProtected(change_permissions, 'manage_editLocalRoles')
manage_editLocalRoles=DTMLFile('dtml/editLocalRoles', globals(),
management_view='Security')
manage_editLocalRoles = DTMLFile('dtml/editLocalRoles', globals(),
management_view='Security')
security.declareProtected(change_permissions, 'manage_addLocalRoles')
@requestmethod('POST')
......@@ -146,7 +146,7 @@ class RoleManager(BaseRoleManager):
"""Set local roles for a user."""
BaseRoleManager.manage_addLocalRoles(self, userid, roles)
if REQUEST is not None:
stat='Your changes have been saved.'
stat = 'Your changes have been saved.'
return self.manage_listLocalRoles(self, REQUEST, stat=stat)
security.declareProtected(change_permissions, 'manage_setLocalRoles')
......@@ -155,7 +155,7 @@ class RoleManager(BaseRoleManager):
"""Set local roles for a user."""
BaseRoleManager.manage_setLocalRoles(self, userid, roles)
if REQUEST is not None:
stat='Your changes have been saved.'
stat = 'Your changes have been saved.'
return self.manage_listLocalRoles(self, REQUEST, stat=stat)
security.declareProtected(change_permissions, 'manage_delLocalRoles')
......@@ -164,20 +164,19 @@ class RoleManager(BaseRoleManager):
"""Remove all local roles for a user."""
BaseRoleManager.manage_delLocalRoles(self, userids)
if REQUEST is not None:
stat='Your changes have been saved.'
stat = 'Your changes have been saved.'
return self.manage_listLocalRoles(self, REQUEST, stat=stat)
security.declareProtected(change_permissions, 'manage_defined_roles')
def manage_defined_roles(self, submit=None, REQUEST=None):
"""Called by management screen.
"""
if submit=='Add Role':
role=reqattr(REQUEST, 'role').strip()
if submit == 'Add Role':
role = reqattr(REQUEST, 'role').strip()
return self._addRole(role, REQUEST)
if submit=='Delete Role':
roles=reqattr(REQUEST, 'roles')
if submit == 'Delete Role':
roles = reqattr(REQUEST, 'roles')
return self._delRoles(roles, REQUEST)
return self.manage_access(REQUEST)
......@@ -186,17 +185,17 @@ class RoleManager(BaseRoleManager):
def _addRole(self, role, REQUEST=None):
if not role:
return MessageDialog(
title='Incomplete',
message='You must specify a role name',
action='manage_access')
title='Incomplete',
message='You must specify a role name',
action='manage_access')
if role in self.__ac_roles__:
return MessageDialog(
title='Role Exists',
message='The given role is already defined',
action='manage_access')
title='Role Exists',
message='The given role is already defined',
action='manage_access')
data = list(self.__ac_roles__)
data.append(role)
self.__ac_roles__=tuple(data)
self.__ac_roles__ = tuple(data)
if REQUEST is not None:
return self.manage_access(REQUEST)
......@@ -204,9 +203,9 @@ class RoleManager(BaseRoleManager):
def _delRoles(self, roles, REQUEST=None):
if not roles:
return MessageDialog(
title='Incomplete',
message='You must specify a role name',
action='manage_access')
title='Incomplete',
message='You must specify a role name',
action='manage_access')
data = list(self.__ac_roles__)
for role in roles:
try:
......@@ -222,8 +221,9 @@ class RoleManager(BaseRoleManager):
# Compatibility names only!!
smallRolesWidget=selectedRoles=aclAChecked=aclPChecked=aclEChecked=''
validRoles=BaseRoleManager.valid_roles
smallRolesWidget = selectedRoles = ''
aclAChecked = aclPChecked = aclEChecked = ''
validRoles = BaseRoleManager.valid_roles
def manage_editRoles(self, REQUEST, acl_type='A', acl_roles=[]):
pass
......
......@@ -34,6 +34,7 @@ deprecatedManageAddDeleteClasses = []
LOG = getLogger('OFS.subscribers')
def compatibilityCall(method_name, *args):
"""Call a method if events have not been setup yet.
......@@ -50,6 +51,7 @@ def compatibilityCall(method_name, *args):
else:
callManageAfterClone(*args)
def maybeWarnDeprecated(ob, method_name):
"""Send a warning if a method is deprecated.
"""
......@@ -66,7 +68,6 @@ def maybeWarnDeprecated(ob, method_name):
"%s.%s.%s is discouraged. You should use event subscribers instead." %
(class_.__module__, class_.__name__, method_name))
##################################################
class ObjectManagerSublocations(object):
"""Get the sublocations for an ObjectManager.
......@@ -91,6 +92,7 @@ class ObjectManagerSublocations(object):
# could have a simple subscriber for IObjectManager that directly calls
# dispatchToSublocations.
@zope.component.adapter(OFS.interfaces.IItem,
OFS.interfaces.IObjectWillBeMovedEvent)
def dispatchObjectWillBeMovedEvent(ob, event):
......@@ -102,6 +104,7 @@ def dispatchObjectWillBeMovedEvent(ob, event):
# Next, do the manage_beforeDelete dance
callManageBeforeDelete(ob, event.object, event.oldParent)
@zope.component.adapter(OFS.interfaces.IItem, IObjectMovedEvent)
def dispatchObjectMovedEvent(ob, event):
"""Multi-subscriber for IItem + IObjectMovedEvent.
......@@ -112,6 +115,7 @@ def dispatchObjectMovedEvent(ob, event):
if OFS.interfaces.IObjectManager.providedBy(ob):
dispatchToSublocations(ob, event)
@zope.component.adapter(OFS.interfaces.IItem,
OFS.interfaces.IObjectClonedEvent)
def dispatchObjectClonedEvent(ob, event):
......@@ -123,6 +127,7 @@ def dispatchObjectClonedEvent(ob, event):
if OFS.interfaces.IObjectManager.providedBy(ob):
dispatchToSublocations(ob, event)
@zope.component.adapter(OFS.interfaces.IItem, IObjectCopiedEvent)
def dispatchObjectCopiedEvent(ob, event):
"""Multi-subscriber for IItem + IObjectCopiedEvent.
......@@ -142,6 +147,7 @@ def callManageAfterAdd(ob, item, container):
maybeWarnDeprecated(ob, 'manage_afterAdd')
ob.manage_afterAdd(item, container)
def callManageBeforeDelete(ob, item, container):
"""Compatibility subscriber for manage_beforeDelete.
"""
......@@ -150,7 +156,7 @@ def callManageBeforeDelete(ob, item, container):
if getattr(aq_base(ob), 'manage_beforeDelete', None) is None:
return
maybeWarnDeprecated(ob, 'manage_beforeDelete')
import OFS.ObjectManager # avoid circular imports
import OFS.ObjectManager # avoid circular imports
try:
ob.manage_beforeDelete(item, container)
except OFS.ObjectManager.BeforeDeleteException:
......@@ -164,6 +170,7 @@ def callManageBeforeDelete(ob, item, container):
if not getSecurityManager().getUser().has_role('Manager'):
raise
def callManageAfterClone(ob, item):
"""Compatibility subscriber for manage_afterClone.
"""
......
......@@ -26,7 +26,7 @@ from OFS.SimpleItem import Item
from AccessControl import ClassSecurityInfo
from AccessControl.class_init import InitializeClass
from AccessControl.Permissions import manage_users as ManageUsers
from AccessControl.Permissions import manage_users as ManageUsers # NOQA
from AccessControl.requestmethod import requestmethod
from AccessControl.rolemanager import DEFAULTMAXLISTUSERS
from AccessControl import userfolder as accesscontrol_userfolder
......@@ -45,14 +45,13 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
# Note: use of the '_super' name is deprecated.
_super = emergency_user
manage_options=(
(
manage_options = ((
{'label': 'Contents', 'action': 'manage_main'},
{'label': 'Properties', 'action': 'manage_userFolderProperties'},
)
+RoleManager.manage_options
+Item.manage_options
)
) +
RoleManager.manage_options +
Item.manage_options
)
security.declareProtected(ManageUsers, 'userFolderAddUser')
@requestmethod('POST')
......@@ -85,12 +84,12 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
return self._doDelUsers(names)
raise NotImplementedError
_mainUser=DTMLFile('dtml/mainUser', globals())
_add_User=DTMLFile('dtml/addUser', globals(),
remote_user_mode__=_remote_user_mode)
_editUser=DTMLFile('dtml/editUser', globals(),
remote_user_mode__=_remote_user_mode)
manage=manage_main=_mainUser
_mainUser = DTMLFile('dtml/mainUser', globals())
_add_User = DTMLFile('dtml/addUser', globals(),
remote_user_mode__=_remote_user_mode)
_editUser = DTMLFile('dtml/editUser', globals(),
remote_user_mode__=_remote_user_mode)
manage = manage_main = _mainUser
manage_main._setName('manage_main')
_userFolderProperties = DTMLFile('dtml/userFolderProps', globals())
......@@ -143,26 +142,26 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
def _addUser(self, name, password, confirm, roles, domains, REQUEST=None):
if not name:
return MessageDialog(
title='Illegal value',
message='A username must be specified',
action='manage_main')
title='Illegal value',
message='A username must be specified',
action='manage_main')
if not password or not confirm:
if not domains:
return MessageDialog(
title='Illegal value',
message='Password and confirmation must be specified',
action='manage_main')
title='Illegal value',
message='Password and confirmation must be specified',
action='manage_main')
if self.getUser(name) or (self._emergency_user and
name == self._emergency_user.getUserName()):
return MessageDialog(
title='Illegal value',
message='A user with the specified name already exists',
action='manage_main')
title='Illegal value',
message='A user with the specified name already exists',
action='manage_main')
if (password or confirm) and (password != confirm):
return MessageDialog(
title='Illegal value',
message='Password and confirmation do not match',
action='manage_main')
title='Illegal value',
message='Password and confirmation do not match',
action='manage_main')
if not roles:
roles = []
......@@ -171,9 +170,9 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
if domains and not self.domainSpecValidate(domains):
return MessageDialog(
title='Illegal value',
message='Illegal domain specification',
action='manage_main')
title='Illegal value',
message='Illegal domain specification',
action='manage_main')
self._doAddUser(name, password, roles, domains)
if REQUEST:
return self._mainUser(self, REQUEST)
......@@ -186,25 +185,25 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
password = confirm = None
if not name:
return MessageDialog(
title='Illegal value',
message='A username must be specified',
action='manage_main')
title='Illegal value',
message='A username must be specified',
action='manage_main')
if password == confirm == '':
if not domains:
return MessageDialog(
title='Illegal value',
message='Password and confirmation must be specified',
action='manage_main')
title='Illegal value',
message='Password and confirmation must be specified',
action='manage_main')
if not self.getUser(name):
return MessageDialog(
title='Illegal value',
message='Unknown user',
action='manage_main')
title='Illegal value',
message='Unknown user',
action='manage_main')
if (password or confirm) and (password != confirm):
return MessageDialog(
title='Illegal value',
message='Password and confirmation do not match',
action='manage_main')
title='Illegal value',
message='Password and confirmation do not match',
action='manage_main')
if not roles:
roles = []
......@@ -213,9 +212,9 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
if domains and not self.domainSpecValidate(domains):
return MessageDialog(
title='Illegal value',
message='Illegal domain specification',
action='manage_main')
title='Illegal value',
message='Illegal domain specification',
action='manage_main')
self._doChangeUser(name, password, roles, domains)
if REQUEST:
return self._mainUser(self, REQUEST)
......@@ -224,9 +223,9 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
def _delUsers(self, names, REQUEST=None):
if not names:
return MessageDialog(
title='Illegal value',
message='No users specified',
action='manage_main')
title='Illegal value',
message='No users specified',
action='manage_main')
self._doDelUsers(names)
if REQUEST:
return self._mainUser(self, REQUEST)
......@@ -237,12 +236,12 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
of the ZMI. Application code (code that is outside of the forms
that implement the UI of a user folder) are encouraged to use
manage_std_addUser"""
if submit=='Add...':
if submit == 'Add...':
return self._add_User(self, REQUEST)
if submit=='Edit':
if submit == 'Edit':
try:
user=self.getUser(reqattr(REQUEST, 'name'))
user = self.getUser(reqattr(REQUEST, 'name'))
except:
return MessageDialog(
title='Illegal value',
......@@ -250,7 +249,7 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
action='manage_main')
return self._editUser(self, REQUEST, user=user, password=user.__)
if submit=='Add':
if submit == 'Add':
name = reqattr(REQUEST, 'name')
password = reqattr(REQUEST, 'password')
confirm = reqattr(REQUEST, 'confirm')
......@@ -259,7 +258,7 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
return self._addUser(name, password, confirm, roles,
domains, REQUEST)
if submit=='Change':
if submit == 'Change':
name = reqattr(REQUEST, 'name')
password = reqattr(REQUEST, 'password')
confirm = reqattr(REQUEST, 'confirm')
......@@ -268,7 +267,7 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
return self._changeUser(name, password, confirm, roles,
domains, REQUEST)
if submit=='Delete':
if submit == 'Delete':
names = reqattr(REQUEST, 'names')
return self._delUsers(names, REQUEST)
......@@ -349,4 +348,4 @@ def manage_addUserFolder(self, dtself=None, REQUEST=None, **ignored):
action='%s/manage_main' % REQUEST['URL1'])
self.__allow_groups__ = f
if REQUEST is not None:
REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_main')
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment