Commit 477d8bc1 authored by Martijn Pieters's avatar Martijn Pieters

Clean up indentation and trailing whitespace.

As the 'if 1:' block for diff preservation was heavily tabbed anyway, I
removed an indent level and the 'if 1:' statement.
parent 4ba09362
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__doc__='''Application support __doc__='''Application support
$Id: Application.py,v 1.186 2002/08/09 14:51:53 chrism Exp $''' $Id: Application.py,v 1.187 2002/08/14 21:42:55 mj Exp $'''
__version__='$Revision: 1.186 $'[11:-2] __version__='$Revision: 1.187 $'[11:-2]
import Globals,Folder,os,sys,App.Product, App.ProductRegistry, misc_ import Globals,Folder,os,sys,App.Product, App.ProductRegistry, misc_
import time, traceback, os, Products import time, traceback, os, Products
...@@ -57,7 +57,7 @@ class Application(Globals.ApplicationDefaultPermissions, ...@@ -57,7 +57,7 @@ class Application(Globals.ApplicationDefaultPermissions,
# emergency user can still access the system if the top-level # emergency user can still access the system if the top-level
# UserFolder is deleted. This is necessary to allow people # UserFolder is deleted. This is necessary to allow people
# to replace the top-level UserFolder object. # to replace the top-level UserFolder object.
__allow_groups__=UserFolder() __allow_groups__=UserFolder()
# Set the universal default method to index_html # Set the universal default method to index_html
...@@ -129,7 +129,7 @@ class Application(Globals.ApplicationDefaultPermissions, ...@@ -129,7 +129,7 @@ class Application(Globals.ApplicationDefaultPermissions,
"""Move a resource to a new location.""" """Move a resource to a new location."""
self.dav__init(REQUEST, RESPONSE) self.dav__init(REQUEST, RESPONSE)
raise 'Forbidden', 'This resource cannot be moved.' raise 'Forbidden', 'This resource cannot be moved.'
test_url___allow_groups__=None test_url___allow_groups__=None
test_url=ZopeAttributionButton test_url=ZopeAttributionButton
...@@ -276,7 +276,7 @@ def initialize(app): ...@@ -276,7 +276,7 @@ def initialize(app):
get_transaction().note('Added temp_folder') get_transaction().note('Added temp_folder')
get_transaction().commit() get_transaction().commit()
del tf del tf
# Ensure that there is a transient container in the temp folder # Ensure that there is a transient container in the temp folder
tf = app.temp_folder tf = app.temp_folder
if not hasattr(aq_base(tf), 'session_data'): if not hasattr(aq_base(tf), 'session_data'):
...@@ -344,7 +344,7 @@ def initialize(app): ...@@ -344,7 +344,7 @@ def initialize(app):
del delnotify del delnotify
del timeout_spec del timeout_spec
del env_has del env_has
del tf del tf
# Ensure that a browser ID manager exists # Ensure that a browser ID manager exists
...@@ -437,7 +437,7 @@ def initialize(app): ...@@ -437,7 +437,7 @@ def initialize(app):
# Check for dangling pointers (broken zclass dependencies) in the # Check for dangling pointers (broken zclass dependencies) in the
# global class registry. If found, rebuild the registry. Note that # global class registry. If found, rebuild the registry. Note that
# if the check finds problems but fails to successfully rebuild the # if the check finds problems but fails to successfully rebuild the
# registry we abort the transaction so that we don't leave it in an # registry we abort the transaction so that we don't leave it in an
# indeterminate state. # indeterminate state.
...@@ -528,37 +528,36 @@ def import_product(product_dir, product_name, raise_exc=0, log_exc=1): ...@@ -528,37 +528,36 @@ def import_product(product_dir, product_name, raise_exc=0, log_exc=1):
modules=sys.modules modules=sys.modules
have_module=modules.has_key have_module=modules.has_key
if 1: # Preserve indentation for diff :-) try:
package_dir=path_join(product_dir, product_name)
if not isdir(package_dir): return
if not exists(path_join(package_dir, '__init__.py')):
if not exists(path_join(package_dir, '__init__.pyc')):
if not exists(path_join(package_dir, '__init__.pyo')):
return
pname="Products.%s" % product_name
try: try:
package_dir=path_join(product_dir, product_name) product=__import__(pname, global_dict, global_dict, silly)
if not isdir(package_dir): return if hasattr(product, '__module_aliases__'):
if not exists(path_join(package_dir, '__init__.py')): for k, v in product.__module_aliases__:
if not exists(path_join(package_dir, '__init__.pyc')): if not have_module(k):
if not exists(path_join(package_dir, '__init__.pyo')): if type(v) is _st and have_module(v): v=modules[v]
return modules[k]=v
except:
pname="Products.%s" % product_name exc = sys.exc_info()
try: if log_exc:
product=__import__(pname, global_dict, global_dict, silly) LOG('Zope', ERROR, 'Could not import %s' % pname,
if hasattr(product, '__module_aliases__'): error=exc)
for k, v in product.__module_aliases__: f=StringIO()
if not have_module(k): traceback.print_exc(100,f)
if type(v) is _st and have_module(v): v=modules[v] f=f.getvalue()
modules[k]=v try: modules[pname].__import_error__=f
except: except: pass
exc = sys.exc_info() if raise_exc:
if log_exc: raise exc[0], exc[1], exc[2]
LOG('Zope', ERROR, 'Could not import %s' % pname, finally:
error=exc) exc = None
f=StringIO()
traceback.print_exc(100,f)
f=f.getvalue()
try: modules[pname].__import_error__=f
except: pass
if raise_exc:
raise exc[0], exc[1], exc[2]
finally:
exc = None
def install_products(app): def install_products(app):
...@@ -608,115 +607,115 @@ def install_product(app, product_dir, product_name, meta_types, ...@@ -608,115 +607,115 @@ def install_product(app, product_dir, product_name, meta_types,
silly=('__doc__',) silly=('__doc__',)
if 1: # Preserve indentation for diff :-) if 1: # Preserve indentation for diff :-)
package_dir=path_join(product_dir, product_name) package_dir=path_join(product_dir, product_name)
__traceback_info__=product_name __traceback_info__=product_name
if not isdir(package_dir): return if not isdir(package_dir): return
if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.py')):
if not exists(path_join(package_dir, '__init__.pyc')): if not exists(path_join(package_dir, '__init__.pyc')):
if not exists(path_join(package_dir, '__init__.pyo')): if not exists(path_join(package_dir, '__init__.pyo')):
return return
try: try:
product=__import__("Products.%s" % product_name, product=__import__("Products.%s" % product_name,
global_dict, global_dict, silly) global_dict, global_dict, silly)
# Install items into the misc_ namespace, used by products # Install items into the misc_ namespace, used by products
# and the framework itself to store common static resources # and the framework itself to store common static resources
# like icon images. # like icon images.
misc_=pgetattr(product, 'misc_', {}) misc_=pgetattr(product, 'misc_', {})
if misc_: if misc_:
if type(misc_) is DictType: if type(misc_) is DictType:
misc_=Misc_(product_name, misc_) misc_=Misc_(product_name, misc_)
Application.misc_.__dict__[product_name]=misc_ Application.misc_.__dict__[product_name]=misc_
# Here we create a ProductContext object which contains # Here we create a ProductContext object which contains
# information about the product and provides an interface # information about the product and provides an interface
# for registering things like classes and help topics that # for registering things like classes and help topics that
# should be associated with that product. Products are # should be associated with that product. Products are
# expected to implement a method named 'initialize' in # expected to implement a method named 'initialize' in
# their __init__.py that takes the ProductContext as an # their __init__.py that takes the ProductContext as an
# argument. # argument.
productObject=App.Product.initializeProduct( productObject=App.Product.initializeProduct(
product, product_name, package_dir, app) product, product_name, package_dir, app)
context=ProductContext(productObject, app, product) context=ProductContext(productObject, app, product)
# Look for an 'initialize' method in the product. If it does # Look for an 'initialize' method in the product. If it does
# not exist, then this is an old product that has never been # not exist, then this is an old product that has never been
# updated. In that case, we will analyze the product and # updated. In that case, we will analyze the product and
# build up enough information to do initialization manually. # build up enough information to do initialization manually.
initmethod=pgetattr(product, 'initialize', None) initmethod=pgetattr(product, 'initialize', None)
if initmethod is not None: if initmethod is not None:
initmethod(context) initmethod(context)
# Support old-style product metadata. Older products may # Support old-style product metadata. Older products may
# define attributes to name their permissions, meta_types, # define attributes to name their permissions, meta_types,
# constructors, etc. # constructors, etc.
permissions={} permissions={}
new_permissions={} new_permissions={}
for p in pgetattr(product, '__ac_permissions__', ()): for p in pgetattr(product, '__ac_permissions__', ()):
permission, names, default = ( permission, names, default = (
tuple(p)+('Manager',))[:3] tuple(p)+('Manager',))[:3]
if names: if names:
for name in names: for name in names:
permissions[name]=permission permissions[name]=permission
elif not folder_permissions.has_key(permission): elif not folder_permissions.has_key(permission):
new_permissions[permission]=() new_permissions[permission]=()
for meta_type in pgetattr(product, 'meta_types', ()): for meta_type in pgetattr(product, 'meta_types', ()):
# Modern product initialization via a ProductContext # Modern product initialization via a ProductContext
# adds 'product' and 'permission' keys to the meta_type # adds 'product' and 'permission' keys to the meta_type
# mapping. We have to add these here for old products. # mapping. We have to add these here for old products.
pname=permissions.get(meta_type['action'], None) pname=permissions.get(meta_type['action'], None)
if pname is not None: if pname is not None:
meta_type['permission']=pname meta_type['permission']=pname
meta_type['product']=productObject.id meta_type['product']=productObject.id
meta_type['visibility'] = 'Global' meta_type['visibility'] = 'Global'
meta_types.append(meta_type) meta_types.append(meta_type)
for name,method in pgetattr( for name,method in pgetattr(
product, 'methods', {}).items(): product, 'methods', {}).items():
if not hasattr(Folder.Folder, name): if not hasattr(Folder.Folder, name):
setattr(Folder.Folder, name, method) setattr(Folder.Folder, name, method)
if name[-9:]!='__roles__': # not Just setting roles if name[-9:]!='__roles__': # not Just setting roles
if (permissions.has_key(name) and if (permissions.has_key(name) and
not folder_permissions.has_key( not folder_permissions.has_key(
permissions[name])): permissions[name])):
permission=permissions[name] permission=permissions[name]
if new_permissions.has_key(permission): if new_permissions.has_key(permission):
new_permissions[permission].append(name) new_permissions[permission].append(name)
else: else:
new_permissions[permission]=[name] new_permissions[permission]=[name]
if new_permissions: if new_permissions:
new_permissions=new_permissions.items() new_permissions=new_permissions.items()
for permission, names in new_permissions: for permission, names in new_permissions:
folder_permissions[permission]=names folder_permissions[permission]=names
new_permissions.sort() new_permissions.sort()
Folder.Folder.__dict__['__ac_permissions__']=tuple( Folder.Folder.__dict__['__ac_permissions__']=tuple(
list(Folder.Folder.__ac_permissions__)+new_permissions) list(Folder.Folder.__ac_permissions__)+new_permissions)
if (os.environ.get('ZEO_CLIENT') and if (os.environ.get('ZEO_CLIENT') and
not os.environ.get('FORCE_PRODUCT_LOAD')): not os.environ.get('FORCE_PRODUCT_LOAD')):
# we don't want to install products from clients # we don't want to install products from clients
# (unless FORCE_PRODUCT_LOAD is defined). # (unless FORCE_PRODUCT_LOAD is defined).
get_transaction().abort()
else:
get_transaction().note('Installed product '+product_name)
get_transaction().commit()
except:
if log_exc:
LOG('Zope',ERROR,'Couldn\'t install %s' % product_name,
error=sys.exc_info())
get_transaction().abort() get_transaction().abort()
if raise_exc: else:
raise get_transaction().note('Installed product '+product_name)
get_transaction().commit()
except:
if log_exc:
LOG('Zope',ERROR,'Couldn\'t install %s' % product_name,
error=sys.exc_info())
get_transaction().abort()
if raise_exc:
raise
def install_standards(app): def install_standards(app):
# Check to see if we've already done this before # Check to see if we've already done this before
# Don't do it twice (Casey) # Don't do it twice (Casey)
if getattr(app, '_standard_objects_have_been_added', 0): if getattr(app, '_standard_objects_have_been_added', 0):
return return
# Install the replaceable standard objects # Install the replaceable standard objects
from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.PageTemplateFile import PageTemplateFile
std_dir = os.path.join(Globals.package_home(globals()), 'standard') std_dir = os.path.join(Globals.package_home(globals()), 'standard')
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__doc__="""Cacheable object and cache management base classes. __doc__="""Cacheable object and cache management base classes.
$Id: Cache.py,v 1.9 2002/02/07 17:20:59 andreasjung Exp $""" $Id: Cache.py,v 1.10 2002/08/14 21:42:56 mj Exp $"""
__version__='$Revision: 1.9 $'[11:-2] __version__='$Revision: 1.10 $'[11:-2]
import time, sys import time, sys
import Globals import Globals
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__doc__="""Copy interface""" __doc__="""Copy interface"""
__version__='$Revision: 1.81 $'[11:-2] __version__='$Revision: 1.82 $'[11:-2]
import sys, Globals, Moniker, tempfile, ExtensionClass import sys, Globals, Moniker, tempfile, ExtensionClass
from marshal import loads, dumps from marshal import loads, dumps
...@@ -77,7 +77,7 @@ class CopyContainer(ExtensionClass.Base): ...@@ -77,7 +77,7 @@ class CopyContainer(ExtensionClass.Base):
REQUEST['__cp'] = cp REQUEST['__cp'] = cp
return self.manage_main(self, REQUEST) return self.manage_main(self, REQUEST)
return cp return cp
def manage_copyObjects(self, ids=None, REQUEST=None, RESPONSE=None): def manage_copyObjects(self, ids=None, REQUEST=None, RESPONSE=None):
"""Put a reference to the objects named in ids in the clip board""" """Put a reference to the objects named in ids in the clip board"""
if ids is None and REQUEST is not None: if ids is None and REQUEST is not None:
...@@ -130,7 +130,7 @@ class CopyContainer(ExtensionClass.Base): ...@@ -130,7 +130,7 @@ class CopyContainer(ExtensionClass.Base):
cp=REQUEST['__cp'] cp=REQUEST['__cp']
if cp is None: if cp is None:
raise CopyError, eNoData raise CopyError, eNoData
try: cp=_cb_decode(cp) try: cp=_cb_decode(cp)
except: raise CopyError, eInvalid except: raise CopyError, eInvalid
...@@ -186,7 +186,7 @@ class CopyContainer(ExtensionClass.Base): ...@@ -186,7 +186,7 @@ class CopyContainer(ExtensionClass.Base):
# try to make ownership explicit so that it gets carried # try to make ownership explicit so that it gets carried
# along to the new location if needed. # along to the new location if needed.
ob.manage_changeOwnershipType(explicit=1) ob.manage_changeOwnershipType(explicit=1)
aq_parent(aq_inner(ob))._delObject(id) aq_parent(aq_inner(ob))._delObject(id)
ob = aq_base(ob) ob = aq_base(ob)
orig_id=id orig_id=id
...@@ -232,7 +232,7 @@ class CopyContainer(ExtensionClass.Base): ...@@ -232,7 +232,7 @@ class CopyContainer(ExtensionClass.Base):
action ='manage_main') action ='manage_main')
ob=self._getOb(id) ob=self._getOb(id)
if not ob.cb_isMoveable(): if not ob.cb_isMoveable():
raise CopyError, eNotSupported % id raise CopyError, eNotSupported % id
self._verifyObjectPaste(ob) self._verifyObjectPaste(ob)
try: ob._notifyOfCopyTo(self, op=1) try: ob._notifyOfCopyTo(self, op=1)
except: raise CopyError, MessageDialog( except: raise CopyError, MessageDialog(
...@@ -242,7 +242,7 @@ class CopyContainer(ExtensionClass.Base): ...@@ -242,7 +242,7 @@ class CopyContainer(ExtensionClass.Base):
self._delObject(id) self._delObject(id)
ob = aq_base(ob) ob = aq_base(ob)
ob._setId(new_id) ob._setId(new_id)
# Note - because a rename always keeps the same context, we # Note - because a rename always keeps the same context, we
# can just leave the ownership info unchanged. # can just leave the ownership info unchanged.
self._setObject(new_id, ob, set_owner=0) self._setObject(new_id, ob, set_owner=0)
...@@ -308,7 +308,7 @@ class CopyContainer(ExtensionClass.Base): ...@@ -308,7 +308,7 @@ class CopyContainer(ExtensionClass.Base):
# #
# Passing a false value for the validate_src argument will skip # Passing a false value for the validate_src argument will skip
# checking the passed in object in its existing context. This is # checking the passed in object in its existing context. This is
# mainly useful for situations where the passed in object has no # mainly useful for situations where the passed in object has no
# existing context, such as checking an object during an import # existing context, such as checking an object during an import
# (the object will not yet have been connected to the acquisition # (the object will not yet have been connected to the acquisition
# heirarchy). # heirarchy).
...@@ -390,7 +390,7 @@ class CopySource(ExtensionClass.Base): ...@@ -390,7 +390,7 @@ class CopySource(ExtensionClass.Base):
__ac_permissions__=( __ac_permissions__=(
('Copy or Move', (), ('Anonymous', 'Manager',)), ('Copy or Move', (), ('Anonymous', 'Manager',)),
) )
def _canCopy(self, op=0): def _canCopy(self, op=0):
"""Called to make sure this object is copyable. The op var """Called to make sure this object is copyable. The op var
is 0 for a copy, 1 for a move.""" is 0 for a copy, 1 for a move."""
...@@ -430,7 +430,7 @@ class CopySource(ExtensionClass.Base): ...@@ -430,7 +430,7 @@ class CopySource(ExtensionClass.Base):
# Called after the copy is finished to accomodate special cases. # Called after the copy is finished to accomodate special cases.
# The op var is 0 for a copy, 1 for a move. # The op var is 0 for a copy, 1 for a move.
pass pass
def _setId(self, id): def _setId(self, id):
# Called to set the new id of a copied object. # Called to set the new id of a copied object.
self.id=id self.id=id
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""DTML Document objects.""" """DTML Document objects."""
__version__='$Revision: 1.47 $'[11:-2] __version__='$Revision: 1.48 $'[11:-2]
from ZPublisher.Converters import type_converters from ZPublisher.Converters import type_converters
from Globals import HTML, DTMLFile, MessageDialog from Globals import HTML, DTMLFile, MessageDialog
...@@ -87,12 +87,12 @@ class DTMLDocument(PropertyManager, DTMLMethod): ...@@ -87,12 +87,12 @@ class DTMLDocument(PropertyManager, DTMLMethod):
if self.wl_isLocked(): if self.wl_isLocked():
raise ResourceLockedError, ( raise ResourceLockedError, (
'This document has been locked via WebDAV.') 'This document has been locked via WebDAV.')
if type(file) is not type(''): if type(file) is not type(''):
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()
self.munge(file) self.munge(file)
self.ZCacheable_invalidate() self.ZCacheable_invalidate()
if REQUEST: if REQUEST:
...@@ -114,7 +114,7 @@ class DTMLDocument(PropertyManager, DTMLMethod): ...@@ -114,7 +114,7 @@ class DTMLDocument(PropertyManager, DTMLMethod):
if hasattr(self, 'aq_explicit'): if hasattr(self, 'aq_explicit'):
bself=self.aq_explicit bself=self.aq_explicit
else: bself=self else: bself=self
security=getSecurityManager() security=getSecurityManager()
security.addContext(self) security.addContext(self)
...@@ -178,5 +178,3 @@ def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None): ...@@ -178,5 +178,3 @@ def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None):
if submit==" Add and Edit ": u="%s/%s" % (u,quote(id)) if submit==" Add and Edit ": u="%s/%s" % (u,quote(id))
REQUEST.RESPONSE.redirect(u+'/manage_main') REQUEST.RESPONSE.redirect(u+'/manage_main')
return '' return ''
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""DTML Method objects.""" """DTML Method objects."""
__version__='$Revision: 1.78 $'[11:-2] __version__='$Revision: 1.79 $'[11:-2]
import History import History
from Globals import HTML, DTMLFile, MessageDialog from Globals import HTML, DTMLFile, MessageDialog
...@@ -101,7 +101,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -101,7 +101,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
if data is not _marker: if data is not _marker:
# Return cached results. # Return cached results.
return data return data
kw['document_id'] =self.getId() kw['document_id'] =self.getId()
kw['document_title']=self.title kw['document_title']=self.title
...@@ -113,7 +113,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -113,7 +113,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
self.__dict__['validate'] = security.DTMLValidate self.__dict__['validate'] = security.DTMLValidate
first_time_through = 1 first_time_through = 1
try: try:
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=apply(HTML.__call__, (self, client, REQUEST), kw)
...@@ -179,7 +179,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -179,7 +179,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
Returns the cacheNamespaceKeys. Returns the cacheNamespaceKeys.
''' '''
return self._cache_namespace_keys return self._cache_namespace_keys
def setCacheNamespaceKeys(self, keys, REQUEST=None): def setCacheNamespaceKeys(self, keys, REQUEST=None):
''' '''
Sets the list of names that should be looked up in the Sets the list of names that should be looked up in the
...@@ -220,14 +220,14 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -220,14 +220,14 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
def _er(self,data,title,SUBMIT,dtpref_cols,dtpref_rows,REQUEST): def _er(self,data,title,SUBMIT,dtpref_cols,dtpref_rows,REQUEST):
dr,dc = self._size_changes[SUBMIT] dr,dc = self._size_changes[SUBMIT]
rows=str(max(1,int(dtpref_rows)+dr)) rows=str(max(1,int(dtpref_rows)+dr))
if dtpref_cols[-1]=='%': if dtpref_cols[-1]=='%':
cols= str(min(100, max(25,int(dtpref_cols[:-1])+dc)))+'%' cols= str(min(100, max(25,int(dtpref_cols[:-1])+dc)))+'%'
else: else:
cols=str(max(35,int(dtpref_cols)+dc)) cols=str(max(35,int(dtpref_cols)+dc))
e=(DateTime('GMT') + 365).rfc822() e=(DateTime('GMT') + 365).rfc822()
resp=REQUEST['RESPONSE'] resp=REQUEST['RESPONSE']
resp.setCookie('dtpref_rows',str(rows),path='/',expires=e) resp.setCookie('dtpref_rows',str(rows),path='/',expires=e)
...@@ -267,11 +267,11 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -267,11 +267,11 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
if self.wl_isLocked(): if self.wl_isLocked():
raise ResourceLockedError, 'This DTML Method is locked via WebDAV' raise ResourceLockedError, 'This DTML Method is locked via WebDAV'
if type(file) is not type(''): if type(file) is not type(''):
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()
self.munge(file) self.munge(file)
self.ZCacheable_invalidate() self.ZCacheable_invalidate()
if REQUEST: if REQUEST:
...@@ -297,7 +297,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -297,7 +297,7 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
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-->' % (self.__name__, u, roles)) 'do not have proxy roles.\n<!--%s, %s-->' % (self.__name__, u, roles))
def manage_proxy(self, roles=(), REQUEST=None): def manage_proxy(self, roles=(), REQUEST=None):
"Change Proxy Roles" "Change Proxy Roles"
...@@ -368,11 +368,11 @@ def decapitate(html, RESPONSE=None): ...@@ -368,11 +368,11 @@ def decapitate(html, RESPONSE=None):
headers.append(header) headers.append(header)
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 = find(html, '\r\n', spos) eol = find(html, '\r\n', spos)
if eol <> -1: if eol <> -1:
eolen = 2 eolen = 2
else: else:
eol = find(html, '\n', spos) eol = find(html, '\n', spos)
if eol < 0: return html if eol < 0: return html
eolen = 1 eolen = 1
header.append(strip(html[spos:eol])) header.append(strip(html[spos:eol]))
...@@ -387,7 +387,7 @@ def decapitate(html, RESPONSE=None): ...@@ -387,7 +387,7 @@ def decapitate(html, RESPONSE=None):
default_dm_html="""<dtml-var standard_html_header> default_dm_html="""<dtml-var standard_html_header>
<h2><dtml-var title_or_id> <dtml-var document_title></h2> <h2><dtml-var title_or_id> <dtml-var document_title></h2>
<p> <p>
This is the <dtml-var document_id> Document This is the <dtml-var document_id> Document
in the <dtml-var title_and_id> Folder. in the <dtml-var title_and_id> Folder.
</p> </p>
<dtml-var standard_html_footer>""" <dtml-var standard_html_footer>"""
...@@ -411,4 +411,3 @@ def addDTMLMethod(self, id, title='', file='', REQUEST=None, submit=None): ...@@ -411,4 +411,3 @@ def addDTMLMethod(self, id, title='', file='', REQUEST=None, submit=None):
if submit==" Add and Edit ": u="%s/%s" % (u,quote(id)) if submit==" Add and Edit ": u="%s/%s" % (u,quote(id))
REQUEST.RESPONSE.redirect(u+'/manage_main') REQUEST.RESPONSE.redirect(u+'/manage_main')
return '' return ''
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__doc__="""Implement Observable interface (see __doc__="""Implement Observable interface (see
http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification) http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification)
This class is intended to be used as a mixin (note that it doesn't derive This class is intended to be used as a mixin (note that it doesn't derive
from any Zope persistence classes, for instance). from any Zope persistence classes, for instance).
$Id: DefaultObservable.py,v 1.5 2002/02/07 17:20:59 andreasjung Exp $""" $Id: DefaultObservable.py,v 1.6 2002/08/14 21:42:56 mj Exp $"""
__version__='$Revision: 1.5 $'[11:-2] __version__='$Revision: 1.6 $'[11:-2]
from types import StringType from types import StringType
...@@ -57,12 +57,12 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification ...@@ -57,12 +57,12 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification
def __init__( self, debug=0 ): def __init__( self, debug=0 ):
self._observers = [] self._observers = []
self._debug = debug self._debug = debug
def _normalize( self, observer ): def _normalize( self, observer ):
# Assert that observer is a string or a sequence of strings. # Assert that observer is a string or a sequence of strings.
if type( observer ) != StringType: if type( observer ) != StringType:
observer = '/'.join( observer) observer = '/'.join( observer)
return observer return observer
...@@ -102,13 +102,13 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification ...@@ -102,13 +102,13 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification
traceback.print_exc() traceback.print_exc()
else: else:
bozos.append( observer ) bozos.append( observer )
for bozo in bozos: for bozo in bozos:
try: # avoid race condition if unregister() called before now try: # avoid race condition if unregister() called before now
self._observers.remove( bozo ) self._observers.remove( bozo )
except: except:
pass pass
# #
# Unit tests # Unit tests
...@@ -117,7 +117,7 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification ...@@ -117,7 +117,7 @@ http://www.zope.org/Members/michel/Projects/Interfaces/ObserverAndNotification
if __name__ == '__main__': if __name__ == '__main__':
class DontGoHere( Exception ): pass class DontGoHere( Exception ): pass
class TestSubject( DefaultObservable ): class TestSubject( DefaultObservable ):
def __init__( self, paths ): def __init__( self, paths ):
...@@ -134,29 +134,29 @@ if __name__ == '__main__': ...@@ -134,29 +134,29 @@ if __name__ == '__main__':
if cbrec is None: if cbrec is None:
cbrec = callbacks[ name ] = [] cbrec = callbacks[ name ] = []
cbrec.append( ( subject, event ) ) cbrec.append( ( subject, event ) )
class TestObserver: class TestObserver:
def __call__( self, subject, event ): def __call__( self, subject, event ):
recordCallback( 'direct', subject, event ) recordCallback( 'direct', subject, event )
def namedCallback( self, subject, event ): def namedCallback( self, subject, event ):
recordCallback( 'named', subject, event ) recordCallback( 'named', subject, event )
def named2Callback( self, subject, event ): def named2Callback( self, subject, event ):
recordCallback( 'named2', subject, event ) recordCallback( 'named2', subject, event )
def boundCallback( self, subject, event ): def boundCallback( self, subject, event ):
recordCallback( 'bound', subject, event ) recordCallback( 'bound', subject, event )
def freefuncObserver( subject, event ): def freefuncObserver( subject, event ):
recordCallback( 'freefunc', subject, event ) recordCallback( 'freefunc', subject, event )
def tryVeto( subject, event ): def tryVeto( subject, event ):
""" Simulate attempted veto. """ """ Simulate attempted veto. """
raise 'Idawanna!' raise 'Idawanna!'
observer = TestObserver() observer = TestObserver()
# Simulate Zope's path traversal mechanism. # Simulate Zope's path traversal mechanism.
...@@ -204,4 +204,3 @@ if __name__ == '__main__': ...@@ -204,4 +204,3 @@ if __name__ == '__main__':
print '[%s]' % key print '[%s]' % key
for cb in callbacks[ key ]: for cb in callbacks[ key ]:
print ' %s' % `cb` print ' %s' % `cb`
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Deprecated - use DTMLMethod""" """Deprecated - use DTMLMethod"""
__version__='$Revision: 1.75 $'[11:-2] __version__='$Revision: 1.76 $'[11:-2]
import DTMLMethod import DTMLMethod
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""FTP Support for Zope classes. """FTP Support for Zope classes.
...@@ -23,11 +23,11 @@ All FTP methods should be governed by a single permission: ...@@ -23,11 +23,11 @@ All FTP methods should be governed by a single permission:
class FTPInterface: class FTPInterface:
"Interface for FTP objects" "Interface for FTP objects"
# XXX The stat and list marshal format should probably # XXX The stat and list marshal format should probably
# 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"""
...@@ -37,13 +37,13 @@ class FTPInterface: ...@@ -37,13 +37,13 @@ class FTPInterface:
(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
one. one.
In the case of non-foldoid objects it should return a single In the case of non-foldoid objects it should return a single
tuple (id,stat) representing itself.""" tuple (id,stat) representing itself."""
# Optional method to support FTP download. # Optional method to support FTP download.
# Should not be implemented by Foldoid objects. # Should not be implemented by Foldoid objects.
def manage_FTPget(self): def manage_FTPget(self):
"""Returns the source content of an object. For example, the """Returns the source content of an object. For example, the
source text of a Document, or the data of a file.""" source text of a Document, or the data of a file."""
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__doc__="""Find support""" __doc__="""Find support"""
__version__='$Revision: 1.30 $'[11:-2] __version__='$Revision: 1.31 $'[11:-2]
import sys, os, time, Globals, ExtensionClass import sys, os, time, Globals, ExtensionClass
...@@ -42,10 +42,10 @@ class FindSupport(ExtensionClass.Base): ...@@ -42,10 +42,10 @@ class FindSupport(ExtensionClass.Base):
('manage_findFrame', 'manage_findForm', 'manage_findAdv', ('manage_findFrame', 'manage_findForm', 'manage_findAdv',
'manage_findResult')), 'manage_findResult')),
) )
manage_options=( manage_options=(
{'label':'Find', 'action':'manage_findForm', {'label':'Find', 'action':'manage_findForm',
'help':('OFSP','Find.stx')}, 'help':('OFSP','Find.stx')},
) )
def ZopeFind(self, obj, obj_ids=None, obj_metatypes=None, def ZopeFind(self, obj, obj_ids=None, obj_metatypes=None,
...@@ -61,7 +61,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -61,7 +61,7 @@ class FindSupport(ExtensionClass.Base):
if obj_metatypes and 'all' in obj_metatypes: if obj_metatypes and 'all' in obj_metatypes:
obj_metatypes=None obj_metatypes=None
if obj_mtime and type(obj_mtime)==type('s'): if obj_mtime and type(obj_mtime)==type('s'):
obj_mtime=DateTime(obj_mtime).timeTime() obj_mtime=DateTime(obj_mtime).timeTime()
...@@ -70,7 +70,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -70,7 +70,7 @@ class FindSupport(ExtensionClass.Base):
if obj_roles and type(obj_roles) is type('s'): if obj_roles and type(obj_roles) is type('s'):
obj_roles=[obj_roles] obj_roles=[obj_roles]
if obj_expr: if obj_expr:
# Setup expr machinations # Setup expr machinations
md=td() md=td()
...@@ -97,7 +97,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -97,7 +97,7 @@ class FindSupport(ExtensionClass.Base):
for id, ob in items: for id, ob in items:
if pre: p="%s/%s" % (pre, id) if pre: p="%s/%s" % (pre, id)
else: p=id else: p=id
dflag=0 dflag=0
if hasattr(ob, '_p_changed') and (ob._p_changed == None): if hasattr(ob, '_p_changed') and (ob._p_changed == None):
dflag=1 dflag=1
...@@ -148,9 +148,9 @@ class FindSupport(ExtensionClass.Base): ...@@ -148,9 +148,9 @@ class FindSupport(ExtensionClass.Base):
PrincipiaFind=ZopeFind PrincipiaFind=ZopeFind
def ZopeFindAndApply(self, obj, obj_ids=None, obj_metatypes=None, def ZopeFindAndApply(self, obj, obj_ids=None, obj_metatypes=None,
obj_searchterm=None, obj_expr=None, obj_searchterm=None, obj_expr=None,
obj_mtime=None, obj_mspec=None, obj_mtime=None, obj_mspec=None,
...@@ -165,7 +165,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -165,7 +165,7 @@ class FindSupport(ExtensionClass.Base):
if obj_metatypes and 'all' in obj_metatypes: if obj_metatypes and 'all' in obj_metatypes:
obj_metatypes=None obj_metatypes=None
if obj_mtime and type(obj_mtime)==type('s'): if obj_mtime and type(obj_mtime)==type('s'):
obj_mtime=DateTime(obj_mtime).timeTime() obj_mtime=DateTime(obj_mtime).timeTime()
...@@ -174,7 +174,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -174,7 +174,7 @@ class FindSupport(ExtensionClass.Base):
if obj_roles and type(obj_roles) is type('s'): if obj_roles and type(obj_roles) is type('s'):
obj_roles=[obj_roles] obj_roles=[obj_roles]
if obj_expr: if obj_expr:
# Setup expr machinations # Setup expr machinations
md=td() md=td()
...@@ -196,7 +196,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -196,7 +196,7 @@ class FindSupport(ExtensionClass.Base):
for id, ob in items: for id, ob in items:
if pre: p="%s/%s" % (pre, id) if pre: p="%s/%s" % (pre, id)
else: p=id else: p=id
dflag=0 dflag=0
if hasattr(ob, '_p_changed') and (ob._p_changed == None): if hasattr(ob, '_p_changed') and (ob._p_changed == None):
dflag=1 dflag=1
...@@ -229,7 +229,7 @@ class FindSupport(ExtensionClass.Base): ...@@ -229,7 +229,7 @@ class FindSupport(ExtensionClass.Base):
else: else:
add_result((p, ob)) add_result((p, ob))
dflag=0 dflag=0
if search_sub and hasattr(bs, 'objectItems'): if search_sub and hasattr(bs, 'objectItems'):
self.ZopeFindAndApply(ob, obj_ids, obj_metatypes, self.ZopeFindAndApply(ob, obj_ids, obj_metatypes,
obj_searchterm, obj_expr, obj_searchterm, obj_expr,
...@@ -261,14 +261,14 @@ def expr_match(ob, ed, c=InstanceDict, r=0): ...@@ -261,14 +261,14 @@ def expr_match(ob, ed, c=InstanceDict, r=0):
def mtime_match(ob, t, q, fn=hasattr): def mtime_match(ob, t, q, fn=hasattr):
if not fn(ob, '_p_mtime'): if not fn(ob, '_p_mtime'):
return 0 return 0
return q=='<' and (ob._p_mtime < t) or (ob._p_mtime > t) return q=='<' and (ob._p_mtime < t) or (ob._p_mtime > t)
def role_match(ob, permission, roles, lt=type([]), tt=type(())): def role_match(ob, permission, roles, lt=type([]), tt=type(())):
pr=[] pr=[]
fn=pr.append fn=pr.append
while 1: while 1:
if hasattr(ob, permission): if hasattr(ob, permission):
p=getattr(ob, permission) p=getattr(ob, permission)
...@@ -307,5 +307,3 @@ def absattr(attr): ...@@ -307,5 +307,3 @@ def absattr(attr):
def p_name(name): def p_name(name):
return '_' + translate(name, name_trans) + '_Permission' return '_' + translate(name, name_trans) + '_Permission'
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Folder object """Folder object
Folders are the basic container objects and are analogous to directories. Folders are the basic container objects and are analogous to directories.
$Id: Folder.py,v 1.100 2002/06/07 18:10:31 caseman Exp $""" $Id: Folder.py,v 1.101 2002/08/14 21:42:56 mj Exp $"""
__version__='$Revision: 1.100 $'[11:-2] __version__='$Revision: 1.101 $'[11:-2]
import Globals, SimpleItem, ObjectManager, PropertyManager import Globals, SimpleItem, ObjectManager, PropertyManager
import AccessControl.Role, webdav.Collection, FindSupport import AccessControl.Role, webdav.Collection, FindSupport
...@@ -46,7 +46,7 @@ def manage_addFolder(self, id, title='', ...@@ -46,7 +46,7 @@ def manage_addFolder(self, id, title='',
self._setObject(id, ob) self._setObject(id, ob)
ob=self._getOb(id) ob=self._getOb(id)
checkPermission=getSecurityManager().checkPermission checkPermission=getSecurityManager().checkPermission
if createUserF: if createUserF:
if not checkPermission('Add User Folders', ob): if not checkPermission('Add User Folders', ob):
...@@ -61,7 +61,7 @@ def manage_addFolder(self, id, title='', ...@@ -61,7 +61,7 @@ def manage_addFolder(self, id, title='',
'You are not authorized to add Page Templates.' 'You are not authorized to add Page Templates.'
) )
ob.manage_addProduct['PageTemplates'].manage_addPageTemplate( ob.manage_addProduct['PageTemplates'].manage_addPageTemplate(
id='index_html', title='') id='index_html', title='')
if REQUEST is not None: if REQUEST is not None:
return self.manage_main(self, REQUEST, update_menu=1) return self.manage_main(self, REQUEST, update_menu=1)
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Object Histories""" """Object Histories"""
__version__='$Revision: 1.13 $'[11:-2] __version__='$Revision: 1.14 $'[11:-2]
import Globals, ExtensionClass, difflib import Globals, ExtensionClass, difflib
from DateTime import DateTime from DateTime import DateTime
...@@ -92,7 +92,7 @@ class Historical(ExtensionClass.Base): ...@@ -92,7 +92,7 @@ class Historical(ExtensionClass.Base):
) )
), ),
) )
manage_options=({'label':'History', 'action':'manage_change_history_page', manage_options=({'label':'History', 'action':'manage_change_history_page',
'help':('OFSP','History.stx') 'help':('OFSP','History.stx')
}, },
...@@ -110,7 +110,7 @@ class Historical(ExtensionClass.Base): ...@@ -110,7 +110,7 @@ class Historical(ExtensionClass.Base):
if request is not None: if request is not None:
first=request.get('first_transaction', first) first=request.get('first_transaction', first)
last=request.get('last_transaction',last) last=request.get('last_transaction',last)
r=self._p_jar.db().history(self._p_oid, None, last) r=self._p_jar.db().history(self._p_oid, None, last)
r=r[first:] r=r[first:]
...@@ -146,7 +146,7 @@ class Historical(ExtensionClass.Base): ...@@ -146,7 +146,7 @@ class Historical(ExtensionClass.Base):
base._p_deactivate() base._p_deactivate()
base.__setstate__(state) base.__setstate__(state)
base._p_changed=1 base._p_changed=1
self.manage_afterHistoryCopy() self.manage_afterHistoryCopy()
if RESPONSE is not None and URL1 is not None: if RESPONSE is not None and URL1 is not None:
...@@ -154,7 +154,7 @@ class Historical(ExtensionClass.Base): ...@@ -154,7 +154,7 @@ class Historical(ExtensionClass.Base):
def manage_afterHistoryCopy(self): pass # ? (Hook) def manage_afterHistoryCopy(self): pass # ? (Hook)
_manage_historyComparePage=Globals.DTMLFile( _manage_historyComparePage=Globals.DTMLFile(
'dtml/historyCompare', globals(), management_view='History') 'dtml/historyCompare', globals(), management_view='History')
def manage_historyCompare(self, rev1, rev2, REQUEST, def manage_historyCompare(self, rev1, rev2, REQUEST,
...@@ -174,10 +174,10 @@ class Historical(ExtensionClass.Base): ...@@ -174,10 +174,10 @@ class Historical(ExtensionClass.Base):
if len(keys) > 2: if len(keys) > 2:
raise HistorySelectionError, ( raise HistorySelectionError, (
"Only two historical revision can be compared<p>") "Only two historical revision can be compared<p>")
serial=apply(pack, ('>HHHH',)+tuple(map(int, keys[-1].split('.')))) serial=apply(pack, ('>HHHH',)+tuple(map(int, keys[-1].split('.'))))
rev1=historicalRevision(self, serial) rev1=historicalRevision(self, serial)
if len(keys)==2: if len(keys)==2:
serial=apply(pack, serial=apply(pack,
('>HHHH',)+tuple(map(int, keys[0].split('.')))) ('>HHHH',)+tuple(map(int, keys[0].split('.'))))
...@@ -187,7 +187,7 @@ class Historical(ExtensionClass.Base): ...@@ -187,7 +187,7 @@ class Historical(ExtensionClass.Base):
rev2=self rev2=self
return self.manage_historyCompare(rev1, rev2, REQUEST) return self.manage_historyCompare(rev1, rev2, REQUEST)
Globals.default__class_init__(Historical) Globals.default__class_init__(Historical)
def dump(tag, x, lo, hi, r): def dump(tag, x, lo, hi, r):
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Image object""" """Image object"""
__version__='$Revision: 1.139 $'[11:-2] __version__='$Revision: 1.140 $'[11:-2]
import Globals, struct import Globals, struct
from OFS.content_types import guess_content_type from OFS.content_types import guess_content_type
...@@ -45,7 +45,7 @@ def manage_addFile(self,id,file='',title='',precondition='', content_type='', ...@@ -45,7 +45,7 @@ def manage_addFile(self,id,file='',title='',precondition='', content_type='',
title=str(title) title=str(title)
content_type=str(content_type) content_type=str(content_type)
precondition=str(precondition) precondition=str(precondition)
id, title = cookId(id, title, file) id, title = cookId(id, title, file)
self=self.this() self=self.this()
...@@ -66,11 +66,11 @@ def manage_addFile(self,id,file='',title='',precondition='', content_type='', ...@@ -66,11 +66,11 @@ def manage_addFile(self,id,file='',title='',precondition='', content_type='',
class File(Persistent, Implicit, PropertyManager, class File(Persistent, Implicit, PropertyManager,
RoleManager, Item_w__name__, Cacheable): RoleManager, Item_w__name__, Cacheable):
"""A File object is a content object for arbitrary files.""" """A File object is a content object for arbitrary files."""
__implements__ = (WriteLockInterface, HTTPRangeSupport.HTTPRangeInterface) __implements__ = (WriteLockInterface, HTTPRangeSupport.HTTPRangeInterface)
meta_type='File' meta_type='File'
precondition='' precondition=''
size=None size=None
...@@ -79,7 +79,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -79,7 +79,7 @@ class File(Persistent, Implicit, PropertyManager,
manage_editForm._setName('manage_editForm') manage_editForm._setName('manage_editForm')
manage=manage_main=manage_editForm manage=manage_main=manage_editForm
manage_uploadForm=manage_editForm manage_uploadForm=manage_editForm
manage_options=( manage_options=(
( (
{'label':'Edit', 'action':'manage_main', {'label':'Edit', 'action':'manage_main',
...@@ -107,7 +107,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -107,7 +107,7 @@ class File(Persistent, Implicit, PropertyManager,
('Delete objects', ('Delete objects',
('DELETE',)), ('DELETE',)),
) )
_properties=({'id':'title', 'type': 'string'}, _properties=({'id':'title', 'type': 'string'},
{'id':'content_type', 'type':'string'}, {'id':'content_type', 'type':'string'},
...@@ -117,7 +117,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -117,7 +117,7 @@ class File(Persistent, Implicit, PropertyManager,
self.__name__=id self.__name__=id
self.title=title self.title=title
self.precondition=precondition self.precondition=precondition
data, size = self._read_data(file) data, size = self._read_data(file)
content_type=self._get_content_type(file, data, id, content_type) content_type=self._get_content_type(file, data, id, content_type)
self.update_data(data, content_type, size) self.update_data(data, content_type, size)
...@@ -162,8 +162,8 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -162,8 +162,8 @@ class File(Persistent, Implicit, PropertyManager,
return '' return ''
if self.precondition and hasattr(self,self.precondition): if self.precondition and hasattr(self,self.precondition):
# Grab whatever precondition was defined and then # Grab whatever precondition was defined and then
# execute it. The precondition will raise an exception # execute it. The precondition will raise an exception
# if something violates its terms. # if something violates its terms.
c=getattr(self,self.precondition) c=getattr(self,self.precondition)
if hasattr(c,'isDocTemp') and c.isDocTemp: if hasattr(c,'isDocTemp') and c.isDocTemp:
...@@ -217,7 +217,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -217,7 +217,7 @@ class File(Persistent, Implicit, PropertyManager,
break break
if not satisfiable: if not satisfiable:
RESPONSE.setHeader('Content-Range', RESPONSE.setHeader('Content-Range',
'bytes */%d' % self.size) 'bytes */%d' % self.size)
RESPONSE.setHeader('Accept-Ranges', 'bytes') RESPONSE.setHeader('Accept-Ranges', 'bytes')
RESPONSE.setHeader('Last-Modified', RESPONSE.setHeader('Last-Modified',
...@@ -229,18 +229,18 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -229,18 +229,18 @@ class File(Persistent, Implicit, PropertyManager,
# Can we optimize? # Can we optimize?
ranges = HTTPRangeSupport.optimizeRanges(ranges, self.size) ranges = HTTPRangeSupport.optimizeRanges(ranges, self.size)
if len(ranges) == 1: if len(ranges) == 1:
# Easy case, set extra header and return partial set. # Easy case, set extra header and return partial set.
start, end = ranges[0] start, end = ranges[0]
size = end - start size = end - start
RESPONSE.setHeader('Last-Modified', RESPONSE.setHeader('Last-Modified',
rfc1123_date(self._p_mtime)) rfc1123_date(self._p_mtime))
RESPONSE.setHeader('Content-Type', self.content_type) RESPONSE.setHeader('Content-Type', self.content_type)
RESPONSE.setHeader('Content-Length', size) RESPONSE.setHeader('Content-Length', size)
RESPONSE.setHeader('Accept-Ranges', 'bytes') RESPONSE.setHeader('Accept-Ranges', 'bytes')
RESPONSE.setHeader('Content-Range', RESPONSE.setHeader('Content-Range',
'bytes %d-%d/%d' % (start, end - 1, self.size)) 'bytes %d-%d/%d' % (start, end - 1, self.size))
RESPONSE.setStatus(206) # Partial content RESPONSE.setStatus(206) # Partial content
...@@ -258,11 +258,11 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -258,11 +258,11 @@ class File(Persistent, Implicit, PropertyManager,
lstart = l - (pos - start) lstart = l - (pos - start)
if lstart < 0: lstart = 0 if lstart < 0: lstart = 0
# find the endpoint # find the endpoint
if end <= pos: if end <= pos:
lend = l - (pos - end) lend = l - (pos - end)
# Send and end transmission # Send and end transmission
RESPONSE.write(data[lstart:lend]) RESPONSE.write(data[lstart:lend])
break break
...@@ -271,26 +271,26 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -271,26 +271,26 @@ class File(Persistent, Implicit, PropertyManager,
RESPONSE.write(data[lstart:]) RESPONSE.write(data[lstart:])
data = data.next data = data.next
return '' return ''
else: else:
# When we get here, ranges have been optimized, so they are # When we get here, ranges have been optimized, so they are
# in order, non-overlapping, and start and end values are # in order, non-overlapping, and start and end values are
# positive integers. # positive integers.
boundary = choose_boundary() boundary = choose_boundary()
# Calculate the content length # Calculate the content length
size = (8 + len(boundary) + # End marker length size = (8 + len(boundary) + # End marker length
len(ranges) * ( # Constant lenght per set len(ranges) * ( # Constant lenght per set
49 + len(boundary) + len(self.content_type) + 49 + len(boundary) + len(self.content_type) +
len('%d' % self.size))) len('%d' % self.size)))
for start, end in ranges: for start, end in ranges:
# Variable length per set # Variable length per set
size = (size + len('%d%d' % (start, end - 1)) + size = (size + len('%d%d' % (start, end - 1)) +
end - start) end - start)
# Some clients implement an earlier draft of the spec, they # Some clients implement an earlier draft of the spec, they
# will only accept x-byteranges. # will only accept x-byteranges.
draftprefix = (request_range is not None) and 'x-' or '' draftprefix = (request_range is not None) and 'x-' or ''
...@@ -313,7 +313,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -313,7 +313,7 @@ class File(Persistent, Implicit, PropertyManager,
self.content_type) self.content_type)
RESPONSE.write( RESPONSE.write(
'Content-Range: bytes %d-%d/%d\r\n\r\n' % ( 'Content-Range: bytes %d-%d/%d\r\n\r\n' % (
start, end - 1, self.size)) start, end - 1, self.size))
if type(data) is StringType: if type(data) is StringType:
RESPONSE.write(data[start:end]) RESPONSE.write(data[start:end])
...@@ -328,11 +328,11 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -328,11 +328,11 @@ class File(Persistent, Implicit, PropertyManager,
lstart = l - (pos - start) lstart = l - (pos - start)
if lstart < 0: lstart = 0 if lstart < 0: lstart = 0
# find the endpoint # find the endpoint
if end <= pos: if end <= pos:
lend = l - (pos - end) lend = l - (pos - end)
# Send and loop to next range # Send and loop to next range
RESPONSE.write(data[lstart:lend]) RESPONSE.write(data[lstart:lend])
# Back up the position marker, it will # Back up the position marker, it will
...@@ -420,7 +420,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -420,7 +420,7 @@ class File(Persistent, Implicit, PropertyManager,
if REQUEST: if REQUEST:
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 _get_content_type(self, file, body, id, content_type=None): def _get_content_type(self, file, body, id, content_type=None):
headers=getattr(file, 'headers', None) headers=getattr(file, 'headers', None)
if headers and headers.has_key('content-type'): if headers and headers.has_key('content-type'):
...@@ -432,9 +432,9 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -432,9 +432,9 @@ class File(Persistent, Implicit, PropertyManager,
return content_type return content_type
def _read_data(self, file): def _read_data(self, file):
n=1 << 16 n=1 << 16
if type(file) is StringType: if type(file) is StringType:
size=len(file) size=len(file)
if size < n: return file, size if size < n: return file, size
...@@ -448,7 +448,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -448,7 +448,7 @@ class File(Persistent, Implicit, PropertyManager,
seek=file.seek seek=file.seek
read=file.read read=file.read
seek(0,2) seek(0,2)
size=end=file.tell() size=end=file.tell()
...@@ -460,9 +460,9 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -460,9 +460,9 @@ class File(Persistent, Implicit, PropertyManager,
# Make sure we have an _p_jar, even if we are a new object, by # Make sure we have an _p_jar, even if we are a new object, by
# doing a sub-transaction commit. # doing a sub-transaction commit.
get_transaction().commit(1) get_transaction().commit(1)
jar=self._p_jar jar=self._p_jar
if jar is None: if jar is None:
# Ugh # Ugh
seek(0) seek(0)
...@@ -478,7 +478,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -478,7 +478,7 @@ class File(Persistent, Implicit, PropertyManager,
if pos < n: pos=0 # we always want at least n bytes if pos < n: pos=0 # we always want at least n bytes
seek(pos) seek(pos)
data=Pdata(read(end-pos)) data=Pdata(read(end-pos))
# Woooop Woooop Woooop! This is a trick. # Woooop Woooop Woooop! This is a trick.
# We stuff the data directly into our jar to reduce the # We stuff the data directly into our jar to reduce the
# number of updates necessary. # number of updates necessary.
...@@ -487,17 +487,17 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -487,17 +487,17 @@ class File(Persistent, Implicit, PropertyManager,
# This is needed and has side benefit of getting # This is needed and has side benefit of getting
# the thing registered: # the thing registered:
data.next=next data.next=next
# Now make it get saved in a sub-transaction! # Now make it get saved in a sub-transaction!
get_transaction().commit(1) get_transaction().commit(1)
# Now make it a ghost to free the memory. We # Now make it a ghost to free the memory. We
# don't need it anymore! # don't need it anymore!
data._p_changed=None data._p_changed=None
next=data next=data
end=pos end=pos
return next, size return next, size
def PUT(self, REQUEST, RESPONSE): def PUT(self, REQUEST, RESPONSE):
...@@ -507,7 +507,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -507,7 +507,7 @@ class File(Persistent, Implicit, PropertyManager,
type=REQUEST.get_header('content-type', None) type=REQUEST.get_header('content-type', None)
file=REQUEST['BODYFILE'] file=REQUEST['BODYFILE']
data, size = self._read_data(file) data, size = self._read_data(file)
content_type=self._get_content_type(file, data, self.__name__, content_type=self._get_content_type(file, data, self.__name__,
type or self.content_type) type or self.content_type)
...@@ -515,7 +515,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -515,7 +515,7 @@ class File(Persistent, Implicit, PropertyManager,
RESPONSE.setStatus(204) RESPONSE.setStatus(204)
return RESPONSE return RESPONSE
def get_size(self): def get_size(self):
"""Get the size of a file or image. """Get the size of a file or image.
...@@ -538,7 +538,7 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -538,7 +538,7 @@ class File(Persistent, Implicit, PropertyManager,
def __str__(self): return str(self.data) def __str__(self): return str(self.data)
def __len__(self): return 1 def __len__(self): return 1
manage_FTPget=index_html manage_FTPget=index_html
...@@ -563,13 +563,13 @@ def manage_addImage(self, id, file, title='', precondition='', content_type='', ...@@ -563,13 +563,13 @@ def manage_addImage(self, id, file, title='', precondition='', content_type='',
# First, we create the image without data: # First, we create the image without data:
self._setObject(id, Image(id,title,'',content_type, precondition)) self._setObject(id, Image(id,title,'',content_type, precondition))
# Now we "upload" the data. By doing this in two steps, we # Now we "upload" the data. By doing this in two steps, we
# can use a database trick to make the upload more efficient. # can use a database trick to make the upload more efficient.
self._getOb(id).manage_upload(file) self._getOb(id).manage_upload(file)
if content_type: if content_type:
self._getOb(id).content_type=content_type self._getOb(id).content_type=content_type
if REQUEST is not None: if REQUEST is not None:
try: url=self.DestinationURL() try: url=self.DestinationURL()
except: url=REQUEST['URL1'] except: url=REQUEST['URL1']
...@@ -584,7 +584,7 @@ def getImageInfo(data): ...@@ -584,7 +584,7 @@ def getImageInfo(data):
width = -1 width = -1
content_type = '' content_type = ''
# handle GIFs # handle GIFs
if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'): if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
# Check to see if content_type is correct # Check to see if content_type is correct
content_type = 'image/gif' content_type = 'image/gif'
...@@ -601,7 +601,7 @@ def getImageInfo(data): ...@@ -601,7 +601,7 @@ def getImageInfo(data):
w, h = struct.unpack(">LL", data[16:24]) w, h = struct.unpack(">LL", data[16:24])
width = int(w) width = int(w)
height = int(h) height = int(h)
# Maybe this is for an older PNG version. # Maybe this is for an older PNG version.
elif (size >= 16) and (data[:8] == '\211PNG\r\n\032\n'): elif (size >= 16) and (data[:8] == '\211PNG\r\n\032\n'):
# Check to see if we have the right content type # Check to see if we have the right content type
...@@ -642,7 +642,7 @@ class Image(File): ...@@ -642,7 +642,7 @@ class Image(File):
__implements__ = (WriteLockInterface,) __implements__ = (WriteLockInterface,)
meta_type='Image' meta_type='Image'
height='' height=''
width='' width=''
...@@ -683,7 +683,7 @@ class Image(File): ...@@ -683,7 +683,7 @@ class Image(File):
manage_editForm._setName('manage_editForm') manage_editForm._setName('manage_editForm')
manage=manage_main=manage_editForm manage=manage_main=manage_editForm
manage_uploadForm=manage_editForm manage_uploadForm=manage_editForm
# private # private
update_data__roles__=() update_data__roles__=()
def update_data(self, data, content_type=None, size=None): def update_data(self, data, content_type=None, size=None):
...@@ -773,14 +773,14 @@ def cookId(id, title, file): ...@@ -773,14 +773,14 @@ def cookId(id, title, file):
id=filename[max(filename.rfind('/'), id=filename[max(filename.rfind('/'),
filename.rfind('\\'), filename.rfind('\\'),
filename.rfind(':'), filename.rfind(':'),
)+1:] )+1:]
return id, title return id, title
class Pdata(Persistent, Implicit): class Pdata(Persistent, Implicit):
# Wrapper for possibly large data # Wrapper for possibly large data
next=None next=None
def __init__(self, data): def __init__(self, data):
self.data=data self.data=data
...@@ -800,14 +800,5 @@ class Pdata(Persistent, Implicit): ...@@ -800,14 +800,5 @@ class Pdata(Persistent, Implicit):
self=next self=next
r.append(self.data) r.append(self.data)
next=self.next next=self.next
return ''.join(r)
return ''.join(r)
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Object monikers """Object monikers
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
and aquisition relationships via a simple interface. and aquisition relationships via a simple interface.
""" """
__version__='$Revision: 1.15 $'[11:-2] __version__='$Revision: 1.16 $'[11:-2]
import Globals import Globals
...@@ -28,7 +28,7 @@ class Moniker: ...@@ -28,7 +28,7 @@ class Moniker:
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()
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
__doc__="""Object Manager __doc__="""Object Manager
$Id: ObjectManager.py,v 1.157 2002/08/14 19:59:18 mj Exp $""" $Id: ObjectManager.py,v 1.158 2002/08/14 21:42:56 mj Exp $"""
__version__='$Revision: 1.157 $'[11:-2] __version__='$Revision: 1.158 $'[11:-2]
import App.Management, Acquisition, Globals, CopySupport, Products import App.Management, Acquisition, Globals, CopySupport, Products
import os, App.FactoryDispatcher, re, Products import os, App.FactoryDispatcher, re, Products
...@@ -102,7 +102,7 @@ class ObjectManager( ...@@ -102,7 +102,7 @@ class ObjectManager(
): ):
"""Generic object manager """Generic object manager
This class provides core behavior for collections of heterogeneous objects. This class provides core behavior for collections of heterogeneous objects.
""" """
__ac_permissions__=( __ac_permissions__=(
...@@ -123,7 +123,7 @@ class ObjectManager( ...@@ -123,7 +123,7 @@ class ObjectManager(
meta_type ='Object Manager' meta_type ='Object Manager'
meta_types=() # Sub-object types that are specific to this object meta_types=() # Sub-object types that are specific to this object
_objects =() _objects =()
manage_main=DTMLFile('dtml/main', globals()) manage_main=DTMLFile('dtml/main', globals())
...@@ -148,7 +148,7 @@ class ObjectManager( ...@@ -148,7 +148,7 @@ class ObjectManager(
except: pass except: pass
mt.sort() mt.sort()
self.meta_types=tuple(mt) self.meta_types=tuple(mt)
default__class_init__(self) default__class_init__(self)
def all_meta_types(self, interfaces=None): def all_meta_types(self, interfaces=None):
...@@ -179,11 +179,11 @@ class ObjectManager( ...@@ -179,11 +179,11 @@ class ObjectManager(
eil = entry.get('interfaces',None) eil = entry.get('interfaces',None)
if eil is not None: if eil is not None:
for ei in eil: for ei in eil:
for i in interfaces: for i in interfaces:
if ei is i or ei.extends(i): if ei is i or ei.extends(i):
interface_constrained_meta_types.append(entry) interface_constrained_meta_types.append(entry)
raise BreakoutException # only append 1ce raise BreakoutException # only append 1ce
except BreakoutException: except BreakoutException:
pass pass
# Meta types specified by this instance are not checked against the # Meta types specified by this instance are not checked against the
...@@ -316,7 +316,7 @@ class ObjectManager( ...@@ -316,7 +316,7 @@ class ObjectManager(
self._objects=tuple(filter(lambda i,n=id: i['id']!=n, self._objects)) self._objects=tuple(filter(lambda i,n=id: i['id']!=n, self._objects))
self._delOb(id) self._delOb(id)
# Indicate to the object that it has been deleted. This is # Indicate to the object that it has been deleted. This is
# necessary for object DB mount points. Note that we have to # necessary for object DB mount points. Note that we have to
# tolerate failure here because the object being deleted could # tolerate failure here because the object being deleted could
# be a Broken object, and it is not possible to set attributes # be a Broken object, and it is not possible to set attributes
...@@ -410,7 +410,7 @@ class ObjectManager( ...@@ -410,7 +410,7 @@ class ObjectManager(
vals.append(get(id)) vals.append(get(id))
seen[physicalPath]=1 seen[physicalPath]=1
except: pass except: pass
if hasattr(obj,'aq_parent'): if hasattr(obj,'aq_parent'):
obj=obj.aq_parent obj=obj.aq_parent
relativePhysicalPath = ('..',) + relativePhysicalPath relativePhysicalPath = ('..',) + relativePhysicalPath
...@@ -424,7 +424,7 @@ class ObjectManager( ...@@ -424,7 +424,7 @@ class ObjectManager(
def manage_delObjects(self, ids=[], REQUEST=None): def manage_delObjects(self, ids=[], REQUEST=None):
"""Delete a subordinate object """Delete a subordinate object
The objects specified in 'ids' get deleted. The objects specified in 'ids' get deleted.
""" """
if type(ids) is type(''): ids=[ids] if type(ids) is type(''): ids=[ids]
...@@ -447,7 +447,7 @@ class ObjectManager( ...@@ -447,7 +447,7 @@ class ObjectManager(
self._delObject(id) self._delObject(id)
del ids[-1] del ids[-1]
if REQUEST is not None: if REQUEST is not None:
return self.manage_main(self, REQUEST, update_menu=1) return self.manage_main(self, REQUEST, update_menu=1)
def tpValues(self): def tpValues(self):
...@@ -475,7 +475,7 @@ class ObjectManager( ...@@ -475,7 +475,7 @@ class ObjectManager(
def manage_exportObject(self, id='', download=None, toxml=None, def manage_exportObject(self, id='', download=None, toxml=None,
RESPONSE=None,REQUEST=None): RESPONSE=None,REQUEST=None):
"""Exports an object to a file and returns that file.""" """Exports an object to a file and returns that file."""
if not id: if not id:
# can't use getId() here (breaks on "old" exported objects) # can't use getId() here (breaks on "old" exported objects)
id=self.id id=self.id
...@@ -484,7 +484,7 @@ class ObjectManager( ...@@ -484,7 +484,7 @@ class ObjectManager(
else: ob=self._getOb(id) else: ob=self._getOb(id)
suffix=toxml and 'xml' or 'zexp' suffix=toxml and 'xml' or 'zexp'
if download: if download:
f=StringIO() f=StringIO()
if toxml: XMLExportImport.exportXML(ob._p_jar, ob._p_oid, f) if toxml: XMLExportImport.exportXML(ob._p_jar, ob._p_oid, f)
...@@ -502,7 +502,7 @@ class ObjectManager( ...@@ -502,7 +502,7 @@ class ObjectManager(
ob._p_jar.exportFile(ob._p_oid, f) ob._p_jar.exportFile(ob._p_oid, f)
if REQUEST is not None: if REQUEST is not None:
return self.manage_main(self, REQUEST, return self.manage_main(self, REQUEST,
manage_tabs_message= manage_tabs_message=
'<em>%s</em> sucessfully exported to <em>%s</em>' % (id,f), '<em>%s</em> sucessfully exported to <em>%s</em>' % (id,f),
title = 'Object exported') title = 'Object exported')
...@@ -518,7 +518,7 @@ class ObjectManager( ...@@ -518,7 +518,7 @@ class ObjectManager(
instance_home = INSTANCE_HOME instance_home = INSTANCE_HOME
zope_home = ZOPE_HOME zope_home = ZOPE_HOME
for impath in (instance_home, zope_home): for impath in (instance_home, zope_home):
filepath = os.path.join(impath, 'import', file) filepath = os.path.join(impath, 'import', file)
if os.path.exists(filepath): if os.path.exists(filepath):
...@@ -528,9 +528,9 @@ class ObjectManager( ...@@ -528,9 +528,9 @@ class ObjectManager(
self._importObjectFromFile(filepath, verify=not not REQUEST, self._importObjectFromFile(filepath, verify=not not REQUEST,
set_owner=set_owner) set_owner=set_owner)
if REQUEST is not None: if REQUEST is not None:
return self.manage_main(self, REQUEST, return self.manage_main(self, REQUEST,
manage_tabs_message='<em>%s</em> sucessfully imported' % id, manage_tabs_message='<em>%s</em> sucessfully imported' % id,
title = 'Object imported', title = 'Object imported',
update_menu=1) update_menu=1)
...@@ -556,7 +556,7 @@ class ObjectManager( ...@@ -556,7 +556,7 @@ class ObjectManager(
ob.manage_changeOwnershipType(explicit=0) ob.manage_changeOwnershipType(explicit=0)
# FTP support methods # FTP support methods
def manage_FTPlist(self, REQUEST): def manage_FTPlist(self, REQUEST):
"Directory listing for FTP" "Directory listing for FTP"
out=() out=()
...@@ -569,7 +569,7 @@ class ObjectManager( ...@@ -569,7 +569,7 @@ class ObjectManager(
if not hasattr(ob,'aq_parent'): if not hasattr(ob,'aq_parent'):
break break
ob=ob.aq_parent ob=ob.aq_parent
files=self.objectItems() files=self.objectItems()
# recursive ride through all subfolders (ls -R) (ajung) # recursive ride through all subfolders (ls -R) (ajung)
...@@ -582,7 +582,7 @@ class ObjectManager( ...@@ -582,7 +582,7 @@ class ObjectManager(
all_files.extend(findChilds(f[1])) all_files.extend(findChilds(f[1]))
else: else:
all_files.append(f) all_files.append(f)
files = all_files files = all_files
try: try:
...@@ -592,7 +592,7 @@ class ObjectManager( ...@@ -592,7 +592,7 @@ class ObjectManager(
files.sort() files.sort()
# Perform globbing on list of files (ajung) # Perform globbing on list of files (ajung)
globbing = REQUEST.environ.get('GLOBBING','') globbing = REQUEST.environ.get('GLOBBING','')
if globbing : if globbing :
files = filter(lambda x,g=globbing: fnmatch.fnmatch(x[0],g) , files) files = filter(lambda x,g=globbing: fnmatch.fnmatch(x[0],g) , files)
...@@ -602,7 +602,7 @@ class ObjectManager( ...@@ -602,7 +602,7 @@ class ObjectManager(
except AttributeError: except AttributeError:
files=list(files) files=list(files)
files.sort() files.sort()
if not (hasattr(self,'isTopLevelPrincipiaApplicationObject') and if not (hasattr(self,'isTopLevelPrincipiaApplicationObject') and
self.isTopLevelPrincipiaApplicationObject): self.isTopLevelPrincipiaApplicationObject):
files.insert(0,('..',self.aq_parent)) files.insert(0,('..',self.aq_parent))
...@@ -614,7 +614,7 @@ class ObjectManager( ...@@ -614,7 +614,7 @@ class ObjectManager(
except: stat=None except: stat=None
if stat is not None: if stat is not None:
out=out+((k,stat),) out=out+((k,stat),)
return marshal.dumps(out) return marshal.dumps(out)
def manage_FTPstat(self,REQUEST): def manage_FTPstat(self,REQUEST):
"Psuedo stat used for FTP listings" "Psuedo stat used for FTP listings"
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
...@@ -8,11 +8,11 @@ ...@@ -8,11 +8,11 @@
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Property management""" """Property management"""
__version__='$Revision: 1.45 $'[11:-2] __version__='$Revision: 1.46 $'[11:-2]
import ExtensionClass, Globals import ExtensionClass, Globals
import ZDOM import ZDOM
...@@ -90,9 +90,9 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes): ...@@ -90,9 +90,9 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
manage_options=( manage_options=(
{'label':'Properties', 'action':'manage_propertiesForm', {'label':'Properties', 'action':'manage_propertiesForm',
'help':('OFSP','Properties.stx')}, 'help':('OFSP','Properties.stx')},
) )
manage_propertiesForm=DTMLFile('dtml/properties', globals(), manage_propertiesForm=DTMLFile('dtml/properties', globals(),
property_extensible_schema__=1) property_extensible_schema__=1)
manage_propertyTypeForm=DTMLFile('dtml/propertyType', globals()) manage_propertyTypeForm=DTMLFile('dtml/propertyType', globals())
...@@ -134,7 +134,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes): ...@@ -134,7 +134,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
return 0 return 0
def getProperty(self, id, d=None): def getProperty(self, id, d=None):
"""Get the property 'id', returning the optional second """Get the property 'id', returning the optional second
argument or None if no such property is found.""" argument or None if no such property is found."""
if self.hasProperty(id): if self.hasProperty(id):
return getattr(self, id) return getattr(self, id)
...@@ -165,7 +165,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes): ...@@ -165,7 +165,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
# for selection and multiple selection properties # for selection and multiple selection properties
# the value argument indicates the select variable # the value argument indicates the select variable
# 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 'Bad Request', 'Invalid or duplicate property id' raise 'Bad Request', 'Invalid or duplicate property id'
...@@ -213,7 +213,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes): ...@@ -213,7 +213,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
def propertyItems(self): def propertyItems(self):
"""Return a list of (id,property) tuples """ """Return a list of (id,property) tuples """
return map(lambda i,s=self: (i['id'],getattr(s,i['id'])), return map(lambda i,s=self: (i['id'],getattr(s,i['id'])),
self._properties) self._properties)
def _propertyMap(self): def _propertyMap(self):
"""Return a tuple of mappings, giving meta-data for properties """ """Return a tuple of mappings, giving meta-data for properties """
...@@ -289,7 +289,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes): ...@@ -289,7 +289,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
return self.manage_propertiesForm(self,REQUEST,manage_tabs_message=message) return self.manage_propertiesForm(self,REQUEST,manage_tabs_message=message)
# Note - this is experimental, pending some community input. # Note - this is experimental, pending some community input.
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
...@@ -307,7 +307,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes): ...@@ -307,7 +307,7 @@ class PropertyManager(ExtensionClass.Base, ZDOM.ElementWithAttributes):
self._setProperty(prop.new_id, prop.new_value, prop.new_type) self._setProperty(prop.new_id, prop.new_value, prop.new_type)
if REQUEST is not None: if REQUEST is not None:
return self.manage_propertiesForm(self, REQUEST) return self.manage_propertiesForm(self, REQUEST)
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'."""
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Property sheets""" """Property sheets"""
__version__='$Revision: 1.86 $'[11:-2] __version__='$Revision: 1.87 $'[11:-2]
import time, App.Management, Globals import time, App.Management, Globals
from webdav.WriteLockInterface import WriteLockInterface from webdav.WriteLockInterface import WriteLockInterface
...@@ -43,7 +43,7 @@ class View(App.Management.Tabs, Base): ...@@ -43,7 +43,7 @@ class View(App.Management.Tabs, Base):
RESPONSE.redirect(URL1+'/manage') RESPONSE.redirect(URL1+'/manage')
def tpURL(self): return self.getId() def tpURL(self): return self.getId()
def manage_options(self): def manage_options(self):
"""Return a manage option data structure for me instance """Return a manage option data structure for me instance
""" """
...@@ -58,7 +58,7 @@ class View(App.Management.Tabs, Base): ...@@ -58,7 +58,7 @@ class View(App.Management.Tabs, Base):
if l >= 0: if l >= 0:
pre=pre[:l] pre=pre[:l]
pre=pre+'/' pre=pre+'/'
r=[] r=[]
for d in self.aq_parent.aq_parent.manage_options: for d in self.aq_parent.aq_parent.manage_options:
path=d['action'] path=d['action']
...@@ -109,7 +109,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -109,7 +109,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
), ),
) )
__reserved_ids= ('values','items') __reserved_ids= ('values','items')
def property_extensible_schema__(self): def property_extensible_schema__(self):
"""Return a flag indicating whether new properties may be """Return a flag indicating whether new properties may be
...@@ -195,7 +195,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -195,7 +195,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
if hasattr(aq_base(self),id): if hasattr(aq_base(self),id):
if not (id=='title' and not self.__dict__.has_key(id)): if not (id=='title' and not self.__dict__.has_key(id)):
raise 'Bad Request', ( raise 'Bad Request', (
'Invalid property id, <em>%s</em>. It is in use.' % 'Invalid property id, <em>%s</em>. It is in use.' %
escape(id)) escape(id))
if meta is None: meta={} if meta is None: meta={}
prop={'id':id, 'type':type, 'meta':meta} prop={'id':id, 'type':type, 'meta':meta}
...@@ -261,7 +261,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -261,7 +261,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
def propertyItems(self): def propertyItems(self):
# Return a list of (id, property) tuples. # Return a list of (id, property) tuples.
return map(lambda i, s=self: (i['id'], s.getProperty(i['id'])), return map(lambda i, s=self: (i['id'], s.getProperty(i['id'])),
self._propertyMap()) self._propertyMap())
def propertyInfo(self, id): def propertyInfo(self, id):
...@@ -316,7 +316,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -316,7 +316,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
attrs=''.join(attrs) attrs=''.join(attrs)
else: else:
# Quote non-xml items here? # Quote non-xml items here?
attrs='' attrs=''
if hasattr(self,"dav__"+name): if hasattr(self,"dav__"+name):
prop=' <n:%s%s>%s</n:%s>' % (name, attrs, value, name) prop=' <n:%s%s>%s</n:%s>' % (name, attrs, value, name)
...@@ -326,7 +326,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -326,7 +326,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
result.append(prop) result.append(prop)
if not result: return '' if not result: return ''
result='\n'.join(result) result='\n'.join(result)
return propstat % (self.xml_namespace(), result, '200 OK', '') return propstat % (self.xml_namespace(), result, '200 OK', '')
def dav__propnames(self, propstat=propstat): def dav__propnames(self, propstat=propstat):
...@@ -375,7 +375,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -375,7 +375,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
if not result.has_key(code): if not result.has_key(code):
result[code]=[prop] result[code]=[prop]
else: result[code].append(prop) else: result[code].append(prop)
return return
del propstat del propstat
...@@ -383,7 +383,7 @@ class PropertySheet(Traversable, Persistent, Implicit): ...@@ -383,7 +383,7 @@ class PropertySheet(Traversable, Persistent, Implicit):
# Web interface # Web interface
manage=DTMLFile('dtml/properties', globals()) manage=DTMLFile('dtml/properties', globals())
def manage_propertiesForm(self, URL1): def manage_propertiesForm(self, URL1):
" " " "
...@@ -456,7 +456,7 @@ class Virtual: ...@@ -456,7 +456,7 @@ class Virtual:
def __init__(self): def __init__(self):
pass pass
def v_self(self): def v_self(self):
return self.aq_parent.aq_parent return self.aq_parent.aq_parent
...@@ -485,7 +485,7 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -485,7 +485,7 @@ class DAVProperties(Virtual, PropertySheet, View):
{'id':'supportedlock', 'mode':'r'}, {'id':'supportedlock', 'mode':'r'},
{'id':'lockdiscovery', 'mode':'r'}, {'id':'lockdiscovery', 'mode':'r'},
) )
def getProperty(self, id, default=None): def getProperty(self, id, default=None):
method='dav__%s' % id method='dav__%s' % id
if not hasattr(self, method): if not hasattr(self, method):
...@@ -506,10 +506,10 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -506,10 +506,10 @@ class DAVProperties(Virtual, PropertySheet, View):
if hasattr(self.v_self(), '_p_mtime'): if hasattr(self.v_self(), '_p_mtime'):
return self.pm + ({'id':'getlastmodified', 'mode':'r'},) return self.pm + ({'id':'getlastmodified', 'mode':'r'},)
return self.pm return self.pm
def propertyMap(self): def propertyMap(self):
return map(lambda dict: dict.copy(), self._propertyMap()) return map(lambda dict: dict.copy(), self._propertyMap())
def dav__creationdate(self): def dav__creationdate(self):
return iso8601_date(43200.0) return iso8601_date(43200.0)
...@@ -518,7 +518,7 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -518,7 +518,7 @@ class DAVProperties(Virtual, PropertySheet, View):
def dav__resourcetype(self): def dav__resourcetype(self):
vself=self.v_self() vself=self.v_self()
if (isDavCollection(vself) or if (isDavCollection(vself) or
getattr(aq_base(vself), 'isAnObjectManager', None)): getattr(aq_base(vself), 'isAnObjectManager', None)):
return '<n:collection/>' return '<n:collection/>'
return '' return ''
...@@ -559,7 +559,7 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -559,7 +559,7 @@ class DAVProperties(Virtual, PropertySheet, View):
def dav__lockdiscovery(self): def dav__lockdiscovery(self):
security = getSecurityManager() security = getSecurityManager()
user = security.getUser().getUserName() user = security.getUser().getUserName()
vself = self.v_self() vself = self.v_self()
out = '\n' out = '\n'
...@@ -570,9 +570,9 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -570,9 +570,9 @@ class DAVProperties(Virtual, PropertySheet, View):
creator = lock.getCreator()[-1] creator = lock.getCreator()[-1]
if creator == user: fake=0 if creator == user: fake=0
else: fake=1 else: fake=1
out = '%s\n%s' % (out, lock.asLockDiscoveryProperty('n',fake=fake)) out = '%s\n%s' % (out, lock.asLockDiscoveryProperty('n',fake=fake))
out = '%s\n' % out out = '%s\n' % out
return out return out
...@@ -584,7 +584,7 @@ Globals.default__class_init__(DAVProperties) ...@@ -584,7 +584,7 @@ Globals.default__class_init__(DAVProperties)
class PropertySheets(Traversable, Implicit, App.Management.Tabs): class PropertySheets(Traversable, Implicit, App.Management.Tabs):
"""A tricky container to keep property sets from polluting """A tricky container to keep property sets from polluting
an object's direct attribute namespace.""" an object's direct attribute namespace."""
id='propertysheets' id='propertysheets'
__ac_permissions__=( __ac_permissions__=(
...@@ -603,7 +603,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs): ...@@ -603,7 +603,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs):
webdav =DAVProperties() webdav =DAVProperties()
def _get_defaults(self): def _get_defaults(self):
return (self.webdav,) return (self.webdav,)
def __propsets__(self): def __propsets__(self):
propsets=self.aq_parent.__propsets__ propsets=self.aq_parent.__propsets__
__traceback_info__= propsets, type(propsets) __traceback_info__= propsets, type(propsets)
...@@ -631,7 +631,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs): ...@@ -631,7 +631,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs):
r.append((id, n.__of__(self))) r.append((id, n.__of__(self)))
return r return r
def get(self, name, default=None): def get(self, name, default=None):
for propset in self.__propsets__(): for propset in self.__propsets__():
if propset.id==name or (hasattr(propset, 'xml_namespace') and \ if propset.id==name or (hasattr(propset, 'xml_namespace') and \
...@@ -657,7 +657,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs): ...@@ -657,7 +657,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs):
if propset.getId() != name and propset.xml_namespace() != name: if propset.getId() != name and propset.xml_namespace() != name:
result.append(propset) result.append(propset)
self.parent.__propsets__=tuple(result) self.parent.__propsets__=tuple(result)
def __len__(self): def __len__(self):
return len(self.__propsets__()) return len(self.__propsets__())
...@@ -683,7 +683,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs): ...@@ -683,7 +683,7 @@ class PropertySheets(Traversable, Implicit, App.Management.Tabs):
if l >= 0: if l >= 0:
pre=pre[:l] pre=pre[:l]
pre=pre+'/' pre=pre+'/'
r=[] r=[]
for d in self.aq_parent.manage_options: for d in self.aq_parent.manage_options:
r.append({'label': d['label'], 'action': pre+d['action']}) r.append({'label': d['label'], 'action': pre+d['action']})
...@@ -734,7 +734,7 @@ class FixedSchema(PropertySheet): ...@@ -734,7 +734,7 @@ class FixedSchema(PropertySheet):
if 'd' in mode: if 'd' in mode:
d['mode']=filter(lambda c: c != 'd', mode) d['mode']=filter(lambda c: c != 'd', mode)
r.append(d) r.append(d)
return tuple(r) return tuple(r)
def propertyMap(self): def propertyMap(self):
...@@ -745,7 +745,7 @@ class FixedSchema(PropertySheet): ...@@ -745,7 +745,7 @@ class FixedSchema(PropertySheet):
return self._base._extensible return self._base._extensible
Globals.default__class_init__(FixedSchema) Globals.default__class_init__(FixedSchema)
class vps(Base): class vps(Base):
...@@ -757,7 +757,7 @@ class vps(Base): ...@@ -757,7 +757,7 @@ class vps(Base):
""" """
def __init__(self, c=PropertySheets): def __init__(self, c=PropertySheets):
self.c=c self.c=c
def __of__(self, parent): def __of__(self, parent):
return self.c().__of__(parent) return self.c().__of__(parent)
...@@ -771,7 +771,7 @@ def xml_escape(v): ...@@ -771,7 +771,7 @@ def xml_escape(v):
""" convert any content from ISO-8859-1 to UTF-8 """ convert any content from ISO-8859-1 to UTF-8
The main use is to escape non-US object property values The main use is to escape non-US object property values
(e.g. containing accented characters). Also we convert "<" and ">" (e.g. containing accented characters). Also we convert "<" and ">"
to entities to keep the properties XML compliant. to entities to keep the properties XML compliant.
""" """
v = str(v) v = str(v)
v = v.replace('&', '&amp;') v = v.replace('&', '&amp;')
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
'''This module implements a simple item mix-in for objects that have a '''This module implements a simple item mix-in for objects that have a
very simple (e.g. one-screen) management interface, like documents, very simple (e.g. one-screen) management interface, like documents,
Aqueduct database adapters, etc. Aqueduct database adapters, etc.
This module can also be used as a simple template for implementing new This module can also be used as a simple template for implementing new
item types. item types.
$Id: SimpleItem.py,v 1.101 2002/06/25 20:52:56 caseman Exp $''' $Id: SimpleItem.py,v 1.102 2002/08/14 21:42:56 mj Exp $'''
__version__='$Revision: 1.101 $'[11:-2] __version__='$Revision: 1.102 $'[11:-2]
import re, sys, Globals, App.Management, Acquisition, App.Undo import re, sys, Globals, App.Management, Acquisition, App.Undo
import AccessControl.Role, AccessControl.Owned, App.Common import AccessControl.Role, AccessControl.Owned, App.Common
...@@ -49,7 +49,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -49,7 +49,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
"""A common base class for simple, non-container objects.""" """A common base class for simple, non-container objects."""
isPrincipiaFolderish=0 isPrincipiaFolderish=0
isTopLevelPrincipiaApplicationObject=0 isTopLevelPrincipiaApplicationObject=0
def manage_afterAdd(self, item, container): pass def manage_afterAdd(self, item, container): pass
def manage_beforeDelete(self, item, container): pass def manage_beforeDelete(self, item, container): pass
def manage_afterClone(self, item): pass def manage_afterClone(self, item): pass
...@@ -81,17 +81,17 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -81,17 +81,17 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
# Meta type used for selecting all objects of a given type. # Meta type used for selecting all objects of a given type.
meta_type='simple item' meta_type='simple item'
# Default title. # Default title.
title='' title=''
# Default propertysheet info: # Default propertysheet info:
__propsets__=() __propsets__=()
manage_options=( manage_options=(
App.Undo.UndoSupport.manage_options App.Undo.UndoSupport.manage_options
+AccessControl.Owned.Owned.manage_options +AccessControl.Owned.Owned.manage_options
) )
# Attributes that must be acquired # Attributes that must be acquired
REQUEST=Acquisition.Acquired REQUEST=Acquisition.Acquired
...@@ -121,7 +121,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -121,7 +121,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
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.
return self return self
...@@ -147,7 +147,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -147,7 +147,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
try: try:
if error_type is None: error_type =sys.exc_info()[0] if error_type is None: error_type =sys.exc_info()[0]
if error_value is None: error_value=sys.exc_info()[1] 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]
...@@ -171,7 +171,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -171,7 +171,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
# Stop if there is recursion. # Stop if there is recursion.
raise error_type, error_value, tb raise error_type, error_value, tb
self._v_eek=1 self._v_eek=1
if str(error_type).lower() in ('redirect',): if str(error_type).lower() in ('redirect',):
raise error_type, error_value, tb raise error_type, error_value, tb
...@@ -227,7 +227,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -227,7 +227,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
def manage(self, URL1): def manage(self, URL1):
" " " "
raise 'Redirect', "%s/manage_main" % URL1 raise 'Redirect', "%s/manage_main" % URL1
# This keeps simple items from acquiring their parents # This keeps simple items from acquiring their parents
# objectValues, etc., when used in simple tree tags. # objectValues, etc., when used in simple tree tags.
...@@ -236,14 +236,14 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -236,14 +236,14 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
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=0100000
# check read permissions # check read permissions
if (hasattr(aq_base(self),'manage_FTPget') and if (hasattr(aq_base(self),'manage_FTPget') and
hasattr(self.manage_FTPget, '__roles__')): hasattr(self.manage_FTPget, '__roles__')):
try: try:
if getSecurityManager().validateValue(self.manage_FTPget): if getSecurityManager().validateValue(self.manage_FTPget):
...@@ -252,17 +252,17 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -252,17 +252,17 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
if nobody.allowed(self.manage_FTPget, if nobody.allowed(self.manage_FTPget,
self.manage_FTPget.__roles__): self.manage_FTPget.__roles__):
mode=mode | 0004 mode=mode | 0004
# check write permissions # check write permissions
if hasattr(aq_base(self),'PUT') and hasattr(self.PUT, '__roles__'): if hasattr(aq_base(self),'PUT') and hasattr(self.PUT, '__roles__'):
try: try:
if getSecurityManager().validateValue(self.PUT): if getSecurityManager().validateValue(self.PUT):
mode=mode | 0220 mode=mode | 0220
except: pass except: pass
if nobody.allowed(self.PUT, self.PUT.__roles__): if nobody.allowed(self.PUT, self.PUT.__roles__):
mode=mode | 0002 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()
...@@ -295,7 +295,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable, ...@@ -295,7 +295,7 @@ class Item(Base, Resource, CopySource, App.Management.Tabs, Traversable,
if not hasattr(ob,'aq_parent'): if not hasattr(ob,'aq_parent'):
break break
ob=ob.aq_parent ob=ob.aq_parent
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))
...@@ -331,11 +331,11 @@ class Item_w__name__(Item): ...@@ -331,11 +331,11 @@ class Item_w__name__(Item):
and getPhysicalPath() are designed to operate together. and getPhysicalPath() are designed to operate together.
''' '''
path = (self.__name__,) path = (self.__name__,)
p = aq_parent(aq_inner(self)) p = aq_parent(aq_inner(self))
if p is not None: if p is not None:
path = p.getPhysicalPath() + path path = p.getPhysicalPath() + path
return path return path
...@@ -358,7 +358,7 @@ class SimpleItem(Item, Globals.Persistent, ...@@ -358,7 +358,7 @@ class SimpleItem(Item, Globals.Persistent,
'action':'manage_access', 'action':'manage_access',
'help':('OFSP', 'Security.stx')}, 'help':('OFSP', 'Security.stx')},
) )
__ac_permissions__=(('View', ()),) __ac_permissions__=(('View', ()),)
def __repr__(self): def __repr__(self):
...@@ -385,4 +385,3 @@ class SimpleItem(Item, Globals.Persistent, ...@@ -385,4 +385,3 @@ class SimpleItem(Item, Globals.Persistent,
res += ' used for %s' % context_path res += ' used for %s' % context_path
res += '>' res += '>'
return res return res
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
'''This module implements a mix-in for traversable objects. '''This module implements a mix-in for traversable objects.
$Id: Traversable.py,v 1.14 2002/02/07 17:20:59 andreasjung Exp $''' $Id: Traversable.py,v 1.15 2002/08/14 21:42:56 mj Exp $'''
__version__='$Revision: 1.14 $'[11:-2] __version__='$Revision: 1.15 $'[11:-2]
from Acquisition import Acquired, aq_inner, aq_parent, aq_base from Acquisition import Acquired, aq_inner, aq_parent, aq_base
...@@ -57,9 +57,9 @@ class Traversable: ...@@ -57,9 +57,9 @@ class Traversable:
and getPhysicalPath() are designed to operate together. and getPhysicalPath() are designed to operate together.
''' '''
path = (self.getId(),) path = (self.getId(),)
p = aq_parent(aq_inner(self)) p = aq_parent(aq_inner(self))
if p is not None: if p is not None:
path = p.getPhysicalPath() + path path = p.getPhysicalPath() + path
return path return path
...@@ -94,7 +94,7 @@ class Traversable: ...@@ -94,7 +94,7 @@ class Traversable:
self=self.getPhysicalRoot() self=self.getPhysicalRoot()
if (restricted and not securityManager.validateValue(self)): if (restricted and not securityManager.validateValue(self)):
raise Unauthorized, name raise Unauthorized, name
try: try:
object = self object = self
while path: while path:
...@@ -127,7 +127,7 @@ class Traversable: ...@@ -127,7 +127,7 @@ class Traversable:
if (not securityManager.validate(object, if (not securityManager.validate(object,
container, name, o)): container, name, o)):
raise Unauthorized, name raise Unauthorized, name
else: else:
o=get(object, name, M) o=get(object, name, M)
if o is not M: if o is not M:
...@@ -142,7 +142,7 @@ class Traversable: ...@@ -142,7 +142,7 @@ class Traversable:
if not securityManager.validate( if not securityManager.validate(
object, N, name, o): object, N, name, o):
raise Unauthorized, name raise Unauthorized, name
else: else:
o=object[name] o=object[name]
if (restricted and not securityManager.validate( if (restricted and not securityManager.validate(
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
""" """
Objects for packages that have been uninstalled. Objects for packages that have been uninstalled.
...@@ -23,7 +23,7 @@ from cgi import escape ...@@ -23,7 +23,7 @@ from cgi import escape
broken_klasses={} broken_klasses={}
broken_klasses_lock = allocate_lock() broken_klasses_lock = allocate_lock()
class BrokenClass(Acquisition.Explicit, SimpleItem.Item, class BrokenClass(Acquisition.Explicit, SimpleItem.Item,
Persistence.Overridable): Persistence.Overridable):
_p_changed=0 _p_changed=0
meta_type='Broken Because Product is Gone' meta_type='Broken Because Product is Gone'
...@@ -47,7 +47,7 @@ class BrokenClass(Acquisition.Explicit, SimpleItem.Item, ...@@ -47,7 +47,7 @@ class BrokenClass(Acquisition.Explicit, SimpleItem.Item,
manage=manage_main=Globals.DTMLFile('dtml/brokenEdit',globals()) manage=manage_main=Globals.DTMLFile('dtml/brokenEdit',globals())
manage_workspace=manage manage_workspace=manage
def Broken(self, oid, pair): def Broken(self, oid, pair):
broken_klasses_lock.acquire() broken_klasses_lock.acquire()
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
import Shared.DC.xml.ppml import Shared.DC.xml.ppml
ppml=Shared.DC.xml.ppml ppml=Shared.DC.xml.ppml
...@@ -117,4 +117,3 @@ def importXML(jar, file, clue=''): ...@@ -117,4 +117,3 @@ def importXML(jar, file, clue=''):
r=p.Parse(data) r=p.Parse(data)
outfile.seek(0) outfile.seek(0)
return jar.importFile(outfile,clue) return jar.importFile(outfile,clue)
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
""" """
DOM implementation in ZOPE : Read-Only methods DOM implementation in ZOPE : Read-Only methods
...@@ -88,12 +88,12 @@ class Node: ...@@ -88,12 +88,12 @@ class Node:
'getChildNodes', 'getFirstChild', 'getLastChild', 'getChildNodes', 'getFirstChild', 'getLastChild',
'getPreviousSibling', 'getNextSibling', 'getOwnerDocument', 'getPreviousSibling', 'getNextSibling', 'getOwnerDocument',
'getAttributes', 'hasChildNodes'), 'getAttributes', 'hasChildNodes'),
), ),
) )
# DOM attributes # DOM attributes
# -------------- # --------------
def getNodeName(self): def getNodeName(self):
"""The name of this node, depending on its type""" """The name of this node, depending on its type"""
return None return None
...@@ -136,7 +136,7 @@ class Node: ...@@ -136,7 +136,7 @@ class Node:
"""Returns a NamedNodeMap containing the attributes """Returns a NamedNodeMap containing the attributes
of this node (if it is an element) or None otherwise.""" of this node (if it is an element) or None otherwise."""
return None return None
def getOwnerDocument(self): def getOwnerDocument(self):
"""The Document object associated with this node. """The Document object associated with this node.
When this is a document this is None""" When this is a document this is None"""
...@@ -145,30 +145,30 @@ class Node: ...@@ -145,30 +145,30 @@ class Node:
node = self.aq_parent node = self.aq_parent
return node.getOwnerDocument() return node.getOwnerDocument()
return node return node
# DOM Methods # DOM Methods
# ----------- # -----------
def hasChildNodes(self): def hasChildNodes(self):
"""Returns true if the node has any children, false """Returns true if the node has any children, false
if it doesn't. """ if it doesn't. """
return len(self.objectIds()) return len(self.objectIds())
class Document(Acquisition.Explicit, Node): class Document(Acquisition.Explicit, Node):
""" """
Document Interface Document Interface
""" """
__ac_permissions__=( __ac_permissions__=(
('Access contents information', ('Access contents information',
('getImplementation', 'getDoctype', 'getDocumentElement'), ('getImplementation', 'getDoctype', 'getDocumentElement'),
), ),
) )
# Document Methods # Document Methods
# ---------------- # ----------------
def getImplementation(self): def getImplementation(self):
""" """
The DOMImplementation object that handles this document. The DOMImplementation object that handles this document.
...@@ -182,14 +182,14 @@ class Document(Acquisition.Explicit, Node): ...@@ -182,14 +182,14 @@ class Document(Acquisition.Explicit, Node):
a document type declaration this returns null. a document type declaration this returns null.
""" """
return None return None
def getDocumentElement(self): def getDocumentElement(self):
""" """
This is a convenience attribute that allows direct access to This is a convenience attribute that allows direct access to
the child node that is the root element of the document. the child node that is the root element of the document.
""" """
return self.aq_parent return self.aq_parent
# Node Methods # Node Methods
# ------------ # ------------
...@@ -199,13 +199,13 @@ class Document(Acquisition.Explicit, Node): ...@@ -199,13 +199,13 @@ class Document(Acquisition.Explicit, Node):
def getNodeType(self): def getNodeType(self):
"""A code representing the type of the node.""" """A code representing the type of the node."""
return DOCUMENT_NODE return DOCUMENT_NODE
def getOwnerDocument(self): def getOwnerDocument(self):
"""The Document object associated with this node. """The Document object associated with this node.
When this is a document this is None""" When this is a document this is None"""
return self return self
def getChildNodes(self): def getChildNodes(self):
"""Returns a NodeList that contains all children of this node. """Returns a NodeList that contains all children of this node.
If there are no children, this is a empty NodeList""" If there are no children, this is a empty NodeList"""
...@@ -225,7 +225,7 @@ class Document(Acquisition.Explicit, Node): ...@@ -225,7 +225,7 @@ class Document(Acquisition.Explicit, Node):
"""Returns true if the node has any children, false """Returns true if the node has any children, false
if it doesn't. """ if it doesn't. """
return 1 return 1
class DOMImplementation: class DOMImplementation:
""" """
...@@ -235,11 +235,11 @@ class DOMImplementation: ...@@ -235,11 +235,11 @@ class DOMImplementation:
__ac_permissions__=( __ac_permissions__=(
('Access contents information', ('Access contents information',
('hasFeature'), ('hasFeature'),
), ),
) )
def hasFeature(self, feature, version = None): def hasFeature(self, feature, version = None):
""" """
hasFeature - Test if the DOM implementation implements a specific hasFeature - Test if the DOM implementation implements a specific
feature. Parameters: feature The package name of the feature to feature. Parameters: feature The package name of the feature to
test. In Level 1, the legal values are "HTML" and "XML" test. In Level 1, the legal values are "HTML" and "XML"
...@@ -255,7 +255,7 @@ class DOMImplementation: ...@@ -255,7 +255,7 @@ class DOMImplementation:
if version is None: return 1 if version is None: return 1
if version == '1.0': return 1 if version == '1.0': return 1
return 0 return 0
class Element(Node): class Element(Node):
""" """
...@@ -266,27 +266,27 @@ class Element(Node): ...@@ -266,27 +266,27 @@ class Element(Node):
('Access contents information', ('Access contents information',
('getTagName', 'getAttribute', 'getAttributeNode', ('getTagName', 'getAttribute', 'getAttributeNode',
'getElementsByTagName'), 'getElementsByTagName'),
), ),
) )
# Element Attributes # Element Attributes
# ------------------ # ------------------
def getTagName(self): def getTagName(self):
"""The name of the element""" """The name of the element"""
return self.__class__.__name__ return self.__class__.__name__
# Node Attributes # Node Attributes
# --------------- # ---------------
def getNodeName(self): def getNodeName(self):
"""The name of this node, depending on its type""" """The name of this node, depending on its type"""
return self.getTagName() return self.getTagName()
def getNodeType(self): def getNodeType(self):
"""A code representing the type of the node.""" """A code representing the type of the node."""
return ELEMENT_NODE return ELEMENT_NODE
def getParentNode(self): def getParentNode(self):
"""The parent of this node. All nodes except Document """The parent of this node. All nodes except Document
DocumentFragment and Attr may have a parent""" DocumentFragment and Attr may have a parent"""
...@@ -296,7 +296,7 @@ class Element(Node): ...@@ -296,7 +296,7 @@ class Element(Node):
"""Returns a NodeList that contains all children of this node. """Returns a NodeList that contains all children of this node.
If there are no children, this is a empty NodeList""" If there are no children, this is a empty NodeList"""
return NodeList(self.objectValues()) return NodeList(self.objectValues())
def getFirstChild(self): def getFirstChild(self):
"""The first child of this node. If there is no such node """The first child of this node. If there is no such node
this returns None""" this returns None"""
...@@ -340,10 +340,10 @@ class Element(Node): ...@@ -340,10 +340,10 @@ class Element(Node):
if index >= len(ids)-1: return None if index >= len(ids)-1: return None
return parent.objectValues()[index+1] return parent.objectValues()[index+1]
return None return None
# Element Methods # Element Methods
# --------------- # ---------------
def getAttribute(self, name): def getAttribute(self, name):
"""Retrieves an attribute value by name.""" """Retrieves an attribute value by name."""
return None return None
...@@ -369,15 +369,15 @@ class Element(Node): ...@@ -369,15 +369,15 @@ class Element(Node):
n1 = child.getElementsByTagName(tagname) n1 = child.getElementsByTagName(tagname)
nodeList = nodeList + n1._data nodeList = nodeList + n1._data
return NodeList(nodeList) return NodeList(nodeList)
class ElementWithAttributes(Element): class ElementWithAttributes(Element):
""" """
Elements that allow DOM access to Zope properties of type 'string'. Elements that allow DOM access to Zope properties of type 'string'.
Note: This sub-class should only be used by PropertyManagers Note: This sub-class should only be used by PropertyManagers
""" """
def getAttributes(self): def getAttributes(self):
"""Returns a NamedNodeMap containing the attributes """Returns a NamedNodeMap containing the attributes
of this node (if it is an element) or None otherwise.""" of this node (if it is an element) or None otherwise."""
...@@ -388,12 +388,12 @@ class ElementWithAttributes(Element): ...@@ -388,12 +388,12 @@ class ElementWithAttributes(Element):
attrib=Attr(name, self.getProperty(name,'')).__of__(self) attrib=Attr(name, self.getProperty(name,'')).__of__(self)
attribs[name]=attrib attribs[name]=attrib
return NamedNodeMap(attribs) return NamedNodeMap(attribs)
def getAttribute(self, name): def getAttribute(self, name):
"""Retrieves an attribute value by name.""" """Retrieves an attribute value by name."""
if self.getPropertyType(name) == 'string': if self.getPropertyType(name) == 'string':
return self.getProperty(name,'') return self.getProperty(name,'')
def getAttributeNode(self, name): def getAttributeNode(self, name):
"""Retrieves an Attr node by name or None if """Retrieves an Attr node by name or None if
there is no such attribute. """ there is no such attribute. """
...@@ -405,10 +405,10 @@ class ElementWithAttributes(Element): ...@@ -405,10 +405,10 @@ class ElementWithAttributes(Element):
class ElementWithTitle(Element): class ElementWithTitle(Element):
""" """
Elements that allow DOM access to Zope 'title' property. Elements that allow DOM access to Zope 'title' property.
Note: Don't use this sub-class for PropertyManagers Note: Don't use this sub-class for PropertyManagers
""" """
def getAttributes(self): def getAttributes(self):
"""Returns a NamedNodeMap containing the attributes """Returns a NamedNodeMap containing the attributes
of this node (if it is an element) or None otherwise.""" of this node (if it is an element) or None otherwise."""
...@@ -416,13 +416,13 @@ class ElementWithTitle(Element): ...@@ -416,13 +416,13 @@ class ElementWithTitle(Element):
if title is not None: if title is not None:
return NamedNodeMap({'title':title}) return NamedNodeMap({'title':title})
return NamedNodeMap() return NamedNodeMap()
def getAttribute(self, name): def getAttribute(self, name):
"""Retrieves an attribute value by name.""" """Retrieves an attribute value by name."""
if name=='title' and hasattr(self.aq_base, 'title'): if name=='title' and hasattr(self.aq_base, 'title'):
return self.title return self.title
return '' return ''
def getAttributeNode(self, name): def getAttributeNode(self, name):
"""Retrieves an Attr node by name or None if """Retrieves an Attr node by name or None if
there is no such attribute. """ there is no such attribute. """
...@@ -431,22 +431,22 @@ class ElementWithTitle(Element): ...@@ -431,22 +431,22 @@ class ElementWithTitle(Element):
return Attr(name, value).__of__(self) return Attr(name, value).__of__(self)
return None return None
class Root(ElementWithAttributes): class Root(ElementWithAttributes):
""" """
The top-level Zope object. The top-level Zope object.
""" """
def getOwnerDocument(self): def getOwnerDocument(self):
""" """
""" """
return Document().__of__(self) return Document().__of__(self)
class NodeList: class NodeList:
"""NodeList interface - Provides the abstraction of an ordered """NodeList interface - Provides the abstraction of an ordered
collection of nodes. collection of nodes.
Python extensions: can use sequence-style 'len', 'getitem', and Python extensions: can use sequence-style 'len', 'getitem', and
'for..in' constructs. 'for..in' constructs.
""" """
...@@ -458,35 +458,35 @@ class NodeList: ...@@ -458,35 +458,35 @@ class NodeList:
def __init__(self,list=None): def __init__(self,list=None):
self._data = list or [] self._data = list or []
def __getitem__(self, index): def __getitem__(self, index):
return self._data[index] return self._data[index]
def item(self, index): def item(self, index):
"""Returns the index-th item in the collection""" """Returns the index-th item in the collection"""
try: return self._data[index] try: return self._data[index]
except IndexError: return None except IndexError: return None
def getLength(self): def getLength(self):
"""The length of the NodeList""" """The length of the NodeList"""
return len(self._data) return len(self._data)
__len__=getLength __len__=getLength
class NamedNodeMap: class NamedNodeMap:
""" """
NamedNodeMap interface - Is used to represent collections NamedNodeMap interface - Is used to represent collections
of nodes that can be accessed by name. NamedNodeMaps are not of nodes that can be accessed by name. NamedNodeMaps are not
maintained in any particular order. maintained in any particular order.
Python extensions: can use sequence-style 'len', 'getitem', and Python extensions: can use sequence-style 'len', 'getitem', and
'for..in' constructs, and mapping-style 'getitem'. 'for..in' constructs, and mapping-style 'getitem'.
""" """
# Tell the security machinery to allow access to items. # Tell the security machinery to allow access to items.
__allow_access_to_unprotected_subobjects__=1 __allow_access_to_unprotected_subobjects__=1
def __init__(self, data=None): def __init__(self, data=None):
if data is None : data = {} if data is None : data = {}
self._data = data self._data = data
...@@ -495,26 +495,26 @@ class NamedNodeMap: ...@@ -495,26 +495,26 @@ class NamedNodeMap:
"""Returns the index-th item in the map""" """Returns the index-th item in the map"""
try: return self._data.values()[index] try: return self._data.values()[index]
except IndexError: return None except IndexError: return None
def __getitem__(self, key): def __getitem__(self, key):
if type(key)==type(1): if type(key)==type(1):
return self._data.values()[key] return self._data.values()[key]
else: else:
return self._data[key] return self._data[key]
def getLength(self): def getLength(self):
"""The length of the NodeList""" """The length of the NodeList"""
return len(self._data) return len(self._data)
__len__ = getLength __len__ = getLength
def getNamedItem(self, name): def getNamedItem(self, name):
"""Retrieves a node specified by name. Parameters: """Retrieves a node specified by name. Parameters:
name Name of a node to retrieve. Return Value A Node (of any name Name of a node to retrieve. Return Value A Node (of any
type) with the specified name, or None if the specified name type) with the specified name, or None if the specified name
did not identify any node in the map. did not identify any node in the map.
""" """
if self._data.has_key(name): if self._data.has_key(name):
return self._data[name] return self._data[name]
return None return None
...@@ -529,7 +529,7 @@ class Attr(Acquisition.Implicit, Node): ...@@ -529,7 +529,7 @@ class Attr(Acquisition.Implicit, Node):
self.name = name self.name = name
self.value = value self.value = value
self.specified = 1 self.specified = 1
def getNodeName(self): def getNodeName(self):
"""The name of this node, depending on its type""" """The name of this node, depending on its type"""
return self.name return self.name
...@@ -537,7 +537,7 @@ class Attr(Acquisition.Implicit, Node): ...@@ -537,7 +537,7 @@ class Attr(Acquisition.Implicit, Node):
def getName(self): def getName(self):
"""Returns the name of this attribute.""" """Returns the name of this attribute."""
return self.name return self.name
def getNodeValue(self): def getNodeValue(self):
"""The value of this node, depending on its type""" """The value of this node, depending on its type"""
return self.value return self.value
...@@ -550,5 +550,3 @@ class Attr(Acquisition.Implicit, Node): ...@@ -550,5 +550,3 @@ class Attr(Acquisition.Implicit, Node):
"""If this attribute was explicitly given a value in the """If this attribute was explicitly given a value in the
original document, this is true; otherwise, it is false.""" original document, this is true; otherwise, it is false."""
return self.specified return self.specified
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""A utility module for content-type handling.""" """A utility module for content-type handling."""
__version__='$Revision: 1.17 $'[11:-2] __version__='$Revision: 1.18 $'[11:-2]
import re, mimetypes import re, mimetypes
...@@ -86,15 +86,14 @@ def guess_content_type(name='', body='', default=None): ...@@ -86,15 +86,14 @@ def guess_content_type(name='', body='', default=None):
if find_binary(body) is not None: if find_binary(body) is not None:
type=default or 'application/octet-stream' type=default or 'application/octet-stream'
else: else:
type=(default or text_type(body) type=(default or text_type(body)
or 'text/x-unknown-content-type') or 'text/x-unknown-content-type')
else: else:
type=default or 'text/x-unknown-content-type' type=default or 'text/x-unknown-content-type'
return type.lower(), enc and enc.lower() or None return type.lower(), enc and enc.lower() or None
if __name__=='__main__': if __name__=='__main__':
items=mimetypes.types_map.items() items=mimetypes.types_map.items()
items.sort() items.sort()
for item in items: print "%s:\t%s" % item for item in items: print "%s:\t%s" % item
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
from App.ImageFile import ImageFile from App.ImageFile import ImageFile
...@@ -21,7 +21,7 @@ class misc_: ...@@ -21,7 +21,7 @@ class misc_:
class p_: class p_:
"Shared system information" "Shared system information"
__roles__=None __roles__=None
broken=ImageFile('www/broken.gif', globals()) broken=ImageFile('www/broken.gif', globals())
User_icon =ImageFile('AccessControl/www/User_icon.gif') User_icon =ImageFile('AccessControl/www/User_icon.gif')
......
...@@ -14,7 +14,7 @@ Print a human-friendly file difference report to stdout. Both inter- ...@@ -14,7 +14,7 @@ Print a human-friendly file difference report to stdout. Both inter-
and intra-line differences are noted. In the second form, recreate file1 and intra-line differences are noted. In the second form, recreate file1
(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin. (-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.
In the first form, if -q ("quiet") is not specified, the first two lines In the first form, if -q ("quiet") is not specified, the first two lines
of output are of output are
-: file1 -: file1
...@@ -28,7 +28,7 @@ Each remaining line begins with a two-letter code: ...@@ -28,7 +28,7 @@ Each remaining line begins with a two-letter code:
"? " line not present in either input file "? " line not present in either input file
Lines beginning with "? " attempt to guide the eye to intraline Lines beginning with "? " attempt to guide the eye to intraline
differences, and were not present in either input file. These lines can differences, and were not present in either input file. These lines can
be confusing if the source files contain tab characters. be confusing if the source files contain tab characters.
The first file can be recovered by retaining only lines that begin with The first file can be recovered by retaining only lines that begin with
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
"""Restricted unpickler""" """Restricted unpickler"""
__version__='$Revision: 1.5 $'[11:-2] __version__='$Revision: 1.6 $'[11:-2]
import pickle import pickle
...@@ -42,5 +42,3 @@ def register(mod, cls, obj): ...@@ -42,5 +42,3 @@ def register(mod, cls, obj):
def unregister(mod, cls): def unregister(mod, cls):
"""Unregister a class""" """Unregister a class"""
del reg[(mod,cls)] del reg[(mod,cls)]
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