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

flake8

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