Commit 4ba09362 authored by Martijn Pieters's avatar Martijn Pieters

Clean up indentation and trailing whitespace.

parent a034b0a5
############################################################################## ##############################################################################
# #
# 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 time, thread import time, thread
...@@ -17,27 +17,27 @@ class DebugLogger: ...@@ -17,27 +17,27 @@ class DebugLogger:
""" """
Logs debugging information about how ZServer is handling requests Logs debugging information about how ZServer is handling requests
and responses. This log can be used to help locate troublesome requests. and responses. This log can be used to help locate troublesome requests.
The format is: The format is:
<code> <request id> <time> <data> <code> <request id> <time> <data>
where: where:
'code' is B for begin, I for received input, A for received output, 'code' is B for begin, I for received input, A for received output,
E for sent output. E for sent output.
'request id' is a unique request id. 'request id' is a unique request id.
'time' is the time in localtime ISO format. 'time' is the time in localtime ISO format.
'data' is the HTTP method and the PATH INFO for B, the size of the input 'data' is the HTTP method and the PATH INFO for B, the size of the input
for I, the HTTP status code and the size of the output for A, or for I, the HTTP status code and the size of the output for A, or
nothing for E. nothing for E.
Note: This facility will be probably be adapted to the zLOG framework. Note: This facility will be probably be adapted to the zLOG framework.
""" """
def __init__(self, filename): def __init__(self, filename):
self.filename = filename self.filename = filename
self.file=open(filename, 'a+b') self.file=open(filename, 'a+b')
...@@ -45,7 +45,7 @@ class DebugLogger: ...@@ -45,7 +45,7 @@ class DebugLogger:
self._acquire=l.acquire self._acquire=l.acquire
self._release=l.release self._release=l.release
self.log('U', '000000000', 'System startup') self.log('U', '000000000', 'System startup')
def reopen(self): def reopen(self):
self.file.close() self.file.close()
self.file=open(self.filename, 'a+b') self.file=open(self.filename, 'a+b')
...@@ -64,4 +64,3 @@ class DebugLogger: ...@@ -64,4 +64,3 @@ class DebugLogger:
def log(*args): pass def log(*args): pass
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
...@@ -271,7 +271,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -271,7 +271,7 @@ class FCGIChannel(asynchat.async_chat):
""" """
closed=0 closed=0
using_temp_stdin=None using_temp_stdin=None
def __init__(self, server, sock, addr): def __init__(self, server, sock, addr):
self.server = server self.server = server
self.addr = addr self.addr = addr
...@@ -361,7 +361,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -361,7 +361,7 @@ class FCGIChannel(asynchat.async_chat):
# Read some name-value pairs (the CGI environment) # Read some name-value pairs (the CGI environment)
elif rec.recType == FCGI_PARAMS: elif rec.recType == FCGI_PARAMS:
if rec.contentLength == 0: # end of the stream if rec.contentLength == 0: # end of the stream
if self.env.has_key('REQUEST_METHOD'): if self.env.has_key('REQUEST_METHOD'):
method=self.env['REQUEST_METHOD'] method=self.env['REQUEST_METHOD']
else: else:
...@@ -370,8 +370,8 @@ class FCGIChannel(asynchat.async_chat): ...@@ -370,8 +370,8 @@ class FCGIChannel(asynchat.async_chat):
path=self.env['PATH_INFO'] path=self.env['PATH_INFO']
else: else:
path='' path=''
DebugLogger.log('B', id(self), '%s %s' % (method, path)) DebugLogger.log('B', id(self), '%s %s' % (method, path))
self.remainingRecs = self.remainingRecs - 1 self.remainingRecs = self.remainingRecs - 1
self.content_length=string.atoi(self.env.get( self.content_length=string.atoi(self.env.get(
'CONTENT_LENGTH','0')) 'CONTENT_LENGTH','0'))
...@@ -383,7 +383,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -383,7 +383,7 @@ class FCGIChannel(asynchat.async_chat):
if rec.contentLength == 0: # end of the stream if rec.contentLength == 0: # end of the stream
self.remainingRecs = self.remainingRecs - 1 self.remainingRecs = self.remainingRecs - 1
else: else:
# see if stdin is getting too big, and # see if stdin is getting too big, and
# replace it with a tempfile if necessary # replace it with a tempfile if necessary
if len(rec.content) + self.stdin.tell() > 1048576 and \ if len(rec.content) + self.stdin.tell() > 1048576 and \
not self.using_temp_stdin: not self.using_temp_stdin:
...@@ -392,7 +392,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -392,7 +392,7 @@ class FCGIChannel(asynchat.async_chat):
self.stdin=t self.stdin=t
self.using_temp_stdin=1 self.using_temp_stdin=1
self.stdin.write(rec.content) self.stdin.write(rec.content)
# read some filter data # read some filter data
elif rec.recType == FCGI_DATA: elif rec.recType == FCGI_DATA:
...@@ -435,7 +435,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -435,7 +435,7 @@ class FCGIChannel(asynchat.async_chat):
def log_request(self, bytes): def log_request(self, bytes):
DebugLogger.log('E', id(self)) DebugLogger.log('E', id(self))
if self.env.has_key('HTTP_USER_AGENT'): if self.env.has_key('HTTP_USER_AGENT'):
...@@ -446,7 +446,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -446,7 +446,7 @@ class FCGIChannel(asynchat.async_chat):
referer=self.env['HTTP_REFERER'] referer=self.env['HTTP_REFERER']
else: else:
referer='' referer=''
if self.env.has_key('PATH_INFO'): if self.env.has_key('PATH_INFO'):
path=self.env['PATH_INFO'] path=self.env['PATH_INFO']
else: else:
...@@ -525,7 +525,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -525,7 +525,7 @@ class FCGIChannel(asynchat.async_chat):
hdr = string.join(map(chr, hdr), '') hdr = string.join(map(chr, hdr), '')
self.push(hdr, 0) self.push(hdr, 0)
self.push(p, 0) self.push(p, 0)
self.push(padLen * '\000', 0) self.push(padLen * '\000', 0)
def sendStreamTerminator(self, recType): def sendStreamTerminator(self, recType):
rec = FCGIRecord() rec = FCGIRecord()
...@@ -545,7 +545,7 @@ class FCGIChannel(asynchat.async_chat): ...@@ -545,7 +545,7 @@ class FCGIChannel(asynchat.async_chat):
def push(self, producer, send=1): def push(self, producer, send=1):
# this is thread-safe when send is false # this is thread-safe when send is false
# note, that strings are not wrapped in # note, that strings are not wrapped in
# producers by default # producers by default
if self.closed: if self.closed:
return return
...@@ -660,17 +660,17 @@ class FCGIServer(asyncore.dispatcher): ...@@ -660,17 +660,17 @@ class FCGIServer(asyncore.dispatcher):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
class FCGIResponse(HTTPResponse): class FCGIResponse(HTTPResponse):
_tempfile=None _tempfile=None
_templock=None _templock=None
_tempstart=0 _tempstart=0
def setChannel(self, channel): def setChannel(self, channel):
self.channel = channel self.channel = channel
def write(self, data): def write(self, data):
stdout=self.stdout stdout=self.stdout
if not self._wrote: if not self._wrote:
l=self.headers.get('content-length', None) l=self.headers.get('content-length', None)
if l is not None: if l is not None:
...@@ -680,7 +680,7 @@ class FCGIResponse(HTTPResponse): ...@@ -680,7 +680,7 @@ class FCGIResponse(HTTPResponse):
self._tempfile=TemporaryFile() self._tempfile=TemporaryFile()
self._templock=thread.allocate_lock() self._templock=thread.allocate_lock()
except: pass except: pass
stdout.write(str(self)) stdout.write(str(self))
self._wrote=1 self._wrote=1
...@@ -709,10 +709,10 @@ class FCGIResponse(HTTPResponse): ...@@ -709,10 +709,10 @@ class FCGIResponse(HTTPResponse):
def _finish(self): def _finish(self):
self.channel.reply_code=self.status self.channel.reply_code=self.status
DebugLogger.log('A', id(self.channel), '%d %d' % ( DebugLogger.log('A', id(self.channel), '%d %d' % (
self.status, self.stdout.length)) self.status, self.stdout.length))
t=self._tempfile t=self._tempfile
if t is not None: if t is not None:
self.stdout.write((file_close_producer(t), 0)) self.stdout.write((file_close_producer(t), 0))
...@@ -764,6 +764,3 @@ class FCGIPipe: ...@@ -764,6 +764,3 @@ class FCGIPipe:
#---------------------------------------------------------------------- #----------------------------------------------------------------------
############################################################################## ##############################################################################
# #
# 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 Request class for FTP server. FTP Request class for FTP server.
...@@ -30,18 +30,18 @@ class FTPRequest(HTTPRequest): ...@@ -30,18 +30,18 @@ class FTPRequest(HTTPRequest):
environ=None,globbing=None,recursive=0): environ=None,globbing=None,recursive=0):
# we need to store the globbing information to pass it # we need to store the globbing information to pass it
# to the ZPublisher and the manage_FTPlist function # to the ZPublisher and the manage_FTPlist function
# (ajung) # (ajung)
self.globbing = globbing self.globbing = globbing
self.recursive= recursive self.recursive= recursive
if stdin is None: stdin=StringIO() if stdin is None: stdin=StringIO()
if environ is None: if environ is None:
environ=self._get_env(path, command, channel, stdin) environ=self._get_env(path, command, channel, stdin)
self._orig_env=environ self._orig_env=environ
HTTPRequest.__init__(self, stdin, environ, response, clean=1) HTTPRequest.__init__(self, stdin, environ, response, clean=1)
# support for cookies and cookie authentication # support for cookies and cookie authentication
self.cookies=channel.cookies self.cookies=channel.cookies
if not self.cookies.has_key('__ac') and channel.userid != 'anonymous': if not self.cookies.has_key('__ac') and channel.userid != 'anonymous':
...@@ -50,8 +50,8 @@ class FTPRequest(HTTPRequest): ...@@ -50,8 +50,8 @@ class FTPRequest(HTTPRequest):
for k,v in self.cookies.items(): for k,v in self.cookies.items():
if not self.other.has_key(k): if not self.other.has_key(k):
self.other[k]=v self.other[k]=v
def retry(self): def retry(self):
self.retry_count=self.retry_count+1 self.retry_count=self.retry_count+1
r=self.__class__(stdin=self.stdin, r=self.__class__(stdin=self.stdin,
...@@ -60,7 +60,7 @@ class FTPRequest(HTTPRequest): ...@@ -60,7 +60,7 @@ class FTPRequest(HTTPRequest):
channel=self, # For my cookies channel=self, # For my cookies
) )
return r return r
def _get_env(self, path, command, channel, stdin): def _get_env(self, path, command, channel, stdin):
"Returns a CGI style environment" "Returns a CGI style environment"
env={} env={}
...@@ -74,35 +74,35 @@ class FTPRequest(HTTPRequest): ...@@ -74,35 +74,35 @@ class FTPRequest(HTTPRequest):
env['SERVER_PORT']=str(channel.server.port) env['SERVER_PORT']=str(channel.server.port)
env['REMOTE_ADDR']=channel.client_addr[0] env['REMOTE_ADDR']=channel.client_addr[0]
env['GATEWAY_INTERFACE']='CGI/1.1' # that's stretching it ;-) env['GATEWAY_INTERFACE']='CGI/1.1' # that's stretching it ;-)
# FTP commands # FTP commands
# #
if type(command)==type(()): if type(command)==type(()):
args=command[1:] args=command[1:]
command=command[0] command=command[0]
if command in ('LST','CWD','PASS'): if command in ('LST','CWD','PASS'):
env['PATH_INFO']=self._join_paths(channel.path, env['PATH_INFO']=self._join_paths(channel.path,
path, 'manage_FTPlist') path, 'manage_FTPlist')
elif command in ('MDTM','SIZE'): elif command in ('MDTM','SIZE'):
env['PATH_INFO']=self._join_paths(channel.path, env['PATH_INFO']=self._join_paths(channel.path,
path, 'manage_FTPstat') path, 'manage_FTPstat')
elif command=='RETR': elif command=='RETR':
env['PATH_INFO']=self._join_paths(channel.path, env['PATH_INFO']=self._join_paths(channel.path,
path, 'manage_FTPget') path, 'manage_FTPget')
elif command in ('RMD','DELE'): elif command in ('RMD','DELE'):
env['PATH_INFO']=self._join_paths(channel.path, env['PATH_INFO']=self._join_paths(channel.path,
path, 'manage_delObjects') path, 'manage_delObjects')
env['QUERY_STRING']='ids=%s' % args[0] env['QUERY_STRING']='ids=%s' % args[0]
elif command=='MKD': elif command=='MKD':
env['PATH_INFO']=self._join_paths(channel.path, env['PATH_INFO']=self._join_paths(channel.path,
path, 'manage_addFolder') path, 'manage_addFolder')
env['QUERY_STRING']='id=%s' % args[0] env['QUERY_STRING']='id=%s' % args[0]
elif command=='RNTO': elif command=='RNTO':
env['PATH_INFO']=self._join_paths(channel.path, env['PATH_INFO']=self._join_paths(channel.path,
path, 'manage_renameObject') path, 'manage_renameObject')
env['QUERY_STRING']='id=%s&new_id=%s' % (args[0],args[1]) env['QUERY_STRING']='id=%s&new_id=%s' % (args[0],args[1])
elif command=='STOR': elif command=='STOR':
env['PATH_INFO']=self._join_paths(channel.path, path) env['PATH_INFO']=self._join_paths(channel.path, path)
env['REQUEST_METHOD']='PUT' env['REQUEST_METHOD']='PUT'
...@@ -110,22 +110,15 @@ class FTPRequest(HTTPRequest): ...@@ -110,22 +110,15 @@ class FTPRequest(HTTPRequest):
else: else:
env['PATH_INFO']=self._join_paths(channel.path, path, command) env['PATH_INFO']=self._join_paths(channel.path, path, command)
# Fake in globbing information # Fake in globbing information
env['GLOBBING'] = self.globbing env['GLOBBING'] = self.globbing
env['FTP_RECURSIVE'] = self.recursive env['FTP_RECURSIVE'] = self.recursive
return env return env
def _join_paths(self,*args): def _join_paths(self,*args):
path=apply(os.path.join,args) path=apply(os.path.join,args)
path=os.path.normpath(path) path=os.path.normpath(path)
if os.sep != '/': if os.sep != '/':
path=path.replace(os.sep,'/') path=path.replace(os.sep,'/')
return path return path
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
Response class for the FTP Server. Response class for the FTP Server.
...@@ -41,7 +41,7 @@ class FTPResponse(ZServerHTTPResponse): ...@@ -41,7 +41,7 @@ class FTPResponse(ZServerHTTPResponse):
self.cookies[name]=self.cookies[name] + value self.cookies[name]=self.cookies[name] + value
def expireCookie(self, name, **kw): def expireCookie(self, name, **kw):
if self.cookies.has_key(name): if self.cookies.has_key(name):
del self.cookies[name] del self.cookies[name]
def _cookie_list(self): def _cookie_list(self):
...@@ -55,7 +55,7 @@ class FTPResponse(ZServerHTTPResponse): ...@@ -55,7 +55,7 @@ class FTPResponse(ZServerHTTPResponse):
def getMessage(self): def getMessage(self):
return getattr(self, '_message', '') return getattr(self, '_message', '')
class CallbackPipe: class CallbackPipe:
""" """
Sends response object to a callback. Doesn't write anything. Sends response object to a callback. Doesn't write anything.
...@@ -65,27 +65,27 @@ class CallbackPipe: ...@@ -65,27 +65,27 @@ class CallbackPipe:
self._callback=callback self._callback=callback
self._args=args self._args=args
self._producers=[] self._producers=[]
def close(self): def close(self):
pass pass
def write(self, text, l=None): def write(self, text, l=None):
if text: if text:
self._producers.append(text) self._producers.append(text)
def finish(self, response): def finish(self, response):
self._response=response self._response=response
Wakeup(self.apply) # move callback to medusas thread Wakeup(self.apply) # move callback to medusas thread
def apply(self): def apply(self):
result=apply(self._callback, self._args+(self._response,)) result=apply(self._callback, self._args+(self._response,))
# break cycles # break cycles
self._callback=None self._callback=None
self._response=None self._response=None
self._args=None self._args=None
return result return result
def make_response(channel, callback, *args): def make_response(channel, callback, *args):
# XXX should this be the FTPResponse constructor instead? # XXX should this be the FTPResponse constructor instead?
......
This diff is collapsed.
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
ZServer HTTPResponse ZServer HTTPResponse
...@@ -39,7 +39,7 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -39,7 +39,7 @@ class ZServerHTTPResponse(HTTPResponse):
# HTTP/1.1 should use chunked encoding # HTTP/1.1 should use chunked encoding
http_chunk=1 http_chunk=1
http_chunk_size=1024 http_chunk_size=1024
# defaults # defaults
_http_version='1.0' _http_version='1.0'
_http_connection='close' _http_connection='close'
...@@ -75,16 +75,16 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -75,16 +75,16 @@ class ZServerHTTPResponse(HTTPResponse):
not self._streaming: not self._streaming:
self.setHeader('content-length',len(body)) self.setHeader('content-length',len(body))
content_length= headers.get('content-length', None) content_length= headers.get('content-length', None)
if content_length>0 : if content_length>0 :
self.setHeader('content-length', content_length) self.setHeader('content-length', content_length)
headersl=[] headersl=[]
append=headersl.append append=headersl.append
status=headers.get('status', '200 OK') status=headers.get('status', '200 OK')
# status header must come first. # status header must come first.
append("HTTP/%s %s" % (self._http_version or '1.0' , status)) append("HTTP/%s %s" % (self._http_version or '1.0' , status))
if headers.has_key('status'): if headers.has_key('status'):
...@@ -92,9 +92,9 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -92,9 +92,9 @@ class ZServerHTTPResponse(HTTPResponse):
if not headers.has_key("Etag"): if not headers.has_key("Etag"):
self.setHeader('Etag','') self.setHeader('Etag','')
# add zserver headers # add zserver headers
append('Server: %s' % self._server_version) append('Server: %s' % self._server_version)
append('Date: %s' % build_http_date(time.time())) append('Date: %s' % build_http_date(time.time()))
if self._http_version=='1.0': if self._http_version=='1.0':
...@@ -103,7 +103,7 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -103,7 +103,7 @@ class ZServerHTTPResponse(HTTPResponse):
self.setHeader('Connection','Keep-Alive') self.setHeader('Connection','Keep-Alive')
else: else:
self.setHeader('Connection','close') self.setHeader('Connection','close')
# Close the connection if we have been asked to. # Close the connection if we have been asked to.
# Use chunking if streaming output. # Use chunking if streaming output.
if self._http_version=='1.1': if self._http_version=='1.1':
...@@ -114,8 +114,8 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -114,8 +114,8 @@ class ZServerHTTPResponse(HTTPResponse):
self.setHeader('Transfer-Encoding','chunked') self.setHeader('Transfer-Encoding','chunked')
self._chunking=1 self._chunking=1
else: else:
self.setHeader('Connection','close') self.setHeader('Connection','close')
for key, val in headers.items(): for key, val in headers.items():
if key.lower()==key: if key.lower()==key:
# only change non-literal header names # only change non-literal header names
...@@ -135,7 +135,7 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -135,7 +135,7 @@ class ZServerHTTPResponse(HTTPResponse):
_tempfile=None _tempfile=None
_templock=None _templock=None
_tempstart=0 _tempstart=0
def write(self,data): def write(self,data):
"""\ """\
Return data as a stream Return data as a stream
...@@ -148,11 +148,11 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -148,11 +148,11 @@ class ZServerHTTPResponse(HTTPResponse):
cookies on the response object. cookies on the response object.
Note that published objects must not generate any errors Note that published objects must not generate any errors
after beginning stream-oriented output. after beginning stream-oriented output.
""" """
stdout=self.stdout stdout=self.stdout
if not self._wrote: if not self._wrote:
l=self.headers.get('content-length', None) l=self.headers.get('content-length', None)
if l is not None: if l is not None:
...@@ -173,7 +173,7 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -173,7 +173,7 @@ class ZServerHTTPResponse(HTTPResponse):
data = '%x\r\n%s\r\n' % (len(data),data) data = '%x\r\n%s\r\n' % (len(data),data)
l=len(data) l=len(data)
t=self._tempfile t=self._tempfile
if t is None or l<200: if t is None or l<200:
stdout.write(data) stdout.write(data)
...@@ -188,7 +188,7 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -188,7 +188,7 @@ class ZServerHTTPResponse(HTTPResponse):
self._templock.release() self._templock.release()
self._tempstart=e self._tempstart=e
stdout.write(file_part_producer(t,self._templock,b,e), l) stdout.write(file_part_producer(t,self._templock,b,e), l)
_retried_response = None _retried_response = None
def _finish(self): def _finish(self):
...@@ -204,10 +204,10 @@ class ZServerHTTPResponse(HTTPResponse): ...@@ -204,10 +204,10 @@ class ZServerHTTPResponse(HTTPResponse):
if t is not None: if t is not None:
stdout.write(file_close_producer(t), 0) stdout.write(file_close_producer(t), 0)
self._tempfile=None self._tempfile=None
stdout.finish(self) stdout.finish(self)
stdout.close() stdout.close()
self.stdout=None # need to break cycle? self.stdout=None # need to break cycle?
self._request=None self._request=None
...@@ -239,7 +239,7 @@ class ChannelPipe: ...@@ -239,7 +239,7 @@ class ChannelPipe:
self._shutdown=0 self._shutdown=0
self._close=0 self._close=0
self._bytes=0 self._bytes=0
def write(self, text, l=None): def write(self, text, l=None):
if self._channel.closed: if self._channel.closed:
return return
...@@ -247,9 +247,9 @@ class ChannelPipe: ...@@ -247,9 +247,9 @@ class ChannelPipe:
self._bytes=self._bytes + l self._bytes=self._bytes + l
self._channel.push(text,0) self._channel.push(text,0)
Wakeup() Wakeup()
def close(self): def close(self):
DebugLogger.log('A', id(self._request), DebugLogger.log('A', id(self._request),
'%s %s' % (self._request.reply_code, self._bytes)) '%s %s' % (self._request.reply_code, self._bytes))
if not self._channel.closed: if not self._channel.closed:
self._channel.push(LoggingProducer(self._request, self._bytes), 0) self._channel.push(LoggingProducer(self._request, self._bytes), 0)
...@@ -277,7 +277,7 @@ class ChannelPipe: ...@@ -277,7 +277,7 @@ class ChannelPipe:
self._request=None self._request=None
def flush(self): pass # yeah, whatever def flush(self): pass # yeah, whatever
def finish(self, response): def finish(self, response):
if response._shutdownRequested(): if response._shutdownRequested():
self._shutdown = 1 self._shutdown = 1
...@@ -285,15 +285,15 @@ class ChannelPipe: ...@@ -285,15 +285,15 @@ class ChannelPipe:
response.headers.get('Connection','') == 'close': response.headers.get('Connection','') == 'close':
self._close=1 self._close=1
self._request.reply_code=response.status self._request.reply_code=response.status
is_proxying_match = re.compile(r'[^ ]* [^ \\]*:').match is_proxying_match = re.compile(r'[^ ]* [^ \\]*:').match
proxying_connection_re = re.compile ('Proxy-Connection: (.*)', re.IGNORECASE) proxying_connection_re = re.compile ('Proxy-Connection: (.*)', re.IGNORECASE)
def make_response(request, headers): def make_response(request, headers):
"Simple http response factory" "Simple http response factory"
# should this be integrated into the HTTPResponse constructor? # should this be integrated into the HTTPResponse constructor?
response=ZServerHTTPResponse(stdout=ChannelPipe(request), stderr=StringIO()) response=ZServerHTTPResponse(stdout=ChannelPipe(request), stderr=StringIO())
response._http_version=request.version response._http_version=request.version
if request.version=='1.0' and is_proxying_match(request.request): if request.version=='1.0' and is_proxying_match(request.request):
...@@ -308,4 +308,3 @@ def make_response(request, headers): ...@@ -308,4 +308,3 @@ def make_response(request, headers):
request.header).lower() request.header).lower()
response._server_version=request.channel.server.SERVER_IDENT response._server_version=request.channel.server.SERVER_IDENT
return response return response
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
...@@ -18,7 +18,7 @@ changes from Medusa's http_server ...@@ -18,7 +18,7 @@ changes from Medusa's http_server
Request Threads -- Requests are processed by threads from a thread Request Threads -- Requests are processed by threads from a thread
pool. pool.
Output Handling -- Output is pushed directly into the producer Output Handling -- Output is pushed directly into the producer
fifo by the request-handling thread. The HTTP server does not do fifo by the request-handling thread. The HTTP server does not do
any post-processing such as chunking. any post-processing such as chunking.
...@@ -29,8 +29,8 @@ changes from Medusa's http_server ...@@ -29,8 +29,8 @@ changes from Medusa's http_server
doesn't wait for the response before sending another request. The doesn't wait for the response before sending another request. The
server must ensure that responses are sent back in the same order server must ensure that responses are sent back in the same order
as requests are received. as requests are received.
""" """
import sys import sys
import re import re
import os import os
...@@ -105,17 +105,17 @@ class zhttp_handler: ...@@ -105,17 +105,17 @@ class zhttp_handler:
"A medusa style handler for zhttp_server" "A medusa style handler for zhttp_server"
_force_connection_close = 0 _force_connection_close = 0
def __init__ (self, module, uri_base=None, env=None): def __init__ (self, module, uri_base=None, env=None):
"""Creates a zope_handler """Creates a zope_handler
module -- string, the name of the module to publish module -- string, the name of the module to publish
uri_base -- string, the base uri of the published module uri_base -- string, the base uri of the published module
defaults to '/<module name>' if not given. defaults to '/<module name>' if not given.
env -- dictionary, environment variables to be overridden. env -- dictionary, environment variables to be overridden.
Replaces standard variables with supplied ones. Replaces standard variables with supplied ones.
""" """
self.module_name=module self.module_name=module
self.env_override=env or {} self.env_override=env or {}
self.hits = counter.counter() self.hits = counter.counter()
...@@ -128,9 +128,9 @@ class zhttp_handler: ...@@ -128,9 +128,9 @@ class zhttp_handler:
uri_base='/' uri_base='/'
else: else:
if uri_base[0] != '/': if uri_base[0] != '/':
uri_base='/'+uri_base uri_base='/'+uri_base
if uri_base[-1] == '/': if uri_base[-1] == '/':
uri_base=uri_base[:-1] uri_base=uri_base[:-1]
self.uri_base=uri_base self.uri_base=uri_base
uri_regex='%s.*' % self.uri_base uri_regex='%s.*' % self.uri_base
self.uri_regex = re.compile(uri_regex) self.uri_regex = re.compile(uri_regex)
...@@ -166,7 +166,7 @@ class zhttp_handler: ...@@ -166,7 +166,7 @@ class zhttp_handler:
(path, params, query, fragment) = request.split_uri() (path, params, query, fragment) = request.split_uri()
if params: path = path + params # undo medusa bug! if params: path = path + params # undo medusa bug!
while path and path[0] == '/': while path and path[0] == '/':
path = path[1:] path = path[1:]
if '%' in path: if '%' in path:
...@@ -250,12 +250,12 @@ class zhttp_handler: ...@@ -250,12 +250,12 @@ class zhttp_handler:
def continue_request(self, sin, request): def continue_request(self, sin, request):
"continue handling request now that we have the stdin" "continue handling request now that we have the stdin"
s=get_header(CONTENT_LENGTH, request.header) s=get_header(CONTENT_LENGTH, request.header)
if s: if s:
s=int(s) s=int(s)
else: else:
s=0 s=0
DebugLogger.log('I', id(request), s) DebugLogger.log('I', id(request), s)
env=self.get_environment(request) env=self.get_environment(request)
...@@ -283,22 +283,22 @@ class zhttp_channel(http_channel): ...@@ -283,22 +283,22 @@ class zhttp_channel(http_channel):
closed=0 closed=0
zombie_timeout=100*60 # 100 minutes zombie_timeout=100*60 # 100 minutes
def __init__(self, server, conn, addr): def __init__(self, server, conn, addr):
http_channel.__init__(self, server, conn, addr) http_channel.__init__(self, server, conn, addr)
requestCloseOnExec(conn) requestCloseOnExec(conn)
self.queue=[] self.queue=[]
self.working=0 self.working=0
def push(self, producer, send=1): def push(self, producer, send=1):
# this is thread-safe when send is false # this is thread-safe when send is false
# note, that strings are not wrapped in # note, that strings are not wrapped in
# producers by default # producers by default
if self.closed: if self.closed:
return return
self.producer_fifo.push(producer) self.producer_fifo.push(producer)
if send: self.initiate_send() if send: self.initiate_send()
push_with_producer=push push_with_producer=push
def work(self): def work(self):
...@@ -337,11 +337,11 @@ class zhttp_channel(http_channel): ...@@ -337,11 +337,11 @@ class zhttp_channel(http_channel):
channel.close() channel.close()
class zhttp_server(http_server): class zhttp_server(http_server):
"http server" "http server"
SERVER_IDENT='Zope/%s ZServer/%s' % (ZOPE_VERSION,ZSERVER_VERSION) SERVER_IDENT='Zope/%s ZServer/%s' % (ZOPE_VERSION,ZSERVER_VERSION)
channel_class = zhttp_channel channel_class = zhttp_channel
shutup=0 shutup=0
...@@ -351,10 +351,10 @@ class zhttp_server(http_server): ...@@ -351,10 +351,10 @@ class zhttp_server(http_server):
self.shutup=0 self.shutup=0
self.log_info('HTTP server started at %s\n' self.log_info('HTTP server started at %s\n'
'\tHostname: %s\n\tPort: %d' % ( '\tHostname: %s\n\tPort: %d' % (
time.ctime(time.time()), time.ctime(time.time()),
self.server_name, self.server_name,
self.server_port self.server_port
)) ))
def log_info(self, message, type='info'): def log_info(self, message, type='info'):
if self.shutup: return if self.shutup: return
...@@ -372,4 +372,3 @@ class zhttp_server(http_server): ...@@ -372,4 +372,3 @@ class zhttp_server(http_server):
# override asyncore limits for nt's listen queue size # override asyncore limits for nt's listen queue size
self.accepting = 1 self.accepting = 1
return self.socket.listen (num) return self.socket.listen (num)
...@@ -33,7 +33,7 @@ ICP_OP_DENIED = 22 ...@@ -33,7 +33,7 @@ ICP_OP_DENIED = 22
class BaseICPServer(asyncore.dispatcher): class BaseICPServer(asyncore.dispatcher):
REQUESTS_PER_LOOP = 4 REQUESTS_PER_LOOP = 4
def __init__ (self,ip,port): def __init__ (self,ip,port):
asyncore.dispatcher.__init__(self) asyncore.dispatcher.__init__(self)
self.create_socket (socket.AF_INET, socket.SOCK_DGRAM) self.create_socket (socket.AF_INET, socket.SOCK_DGRAM)
...@@ -44,7 +44,7 @@ class BaseICPServer(asyncore.dispatcher): ...@@ -44,7 +44,7 @@ class BaseICPServer(asyncore.dispatcher):
else: else:
addr = ip addr = ip
self.log_info('ICP server started\n\tAddress: %s\n\tPort: %s' % (addr,port) ) self.log_info('ICP server started\n\tAddress: %s\n\tPort: %s' % (addr,port) )
def handle_read(self): def handle_read(self):
for i in range(self.REQUESTS_PER_LOOP): for i in range(self.REQUESTS_PER_LOOP):
try: try:
...@@ -90,7 +90,7 @@ class BaseICPServer(asyncore.dispatcher): ...@@ -90,7 +90,7 @@ class BaseICPServer(asyncore.dispatcher):
url = url[:-1] url = url[:-1]
out_opcode = self.check_url(url) out_opcode = self.check_url(url)
return struct.pack('!BBHIIII',out_opcode,2,20,number,0,0,0) return struct.pack('!BBHIIII',out_opcode,2,20,number,0,0,0)
def check_url(self,url): def check_url(self,url):
# derived classes replace this with a more # derived classes replace this with a more
# useful policy # useful policy
...@@ -103,7 +103,7 @@ class ICPServer(BaseICPServer): ...@@ -103,7 +103,7 @@ class ICPServer(BaseICPServer):
# they must return an ICP_OP code from above or None. The first # they must return an ICP_OP code from above or None. The first
# non-None return is used as the ICP response # non-None return is used as the ICP response
hooks = [] hooks = []
def check_url(self,url): def check_url(self,url):
for hook in self.hooks: for hook in self.hooks:
r = hook(url) r = hook(url)
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
...@@ -22,7 +22,7 @@ It should work with both inet and unix domain sockets. ...@@ -22,7 +22,7 @@ It should work with both inet and unix domain sockets.
Why would you want to use it? Using PCGI to connect to ZServer from Why would you want to use it? Using PCGI to connect to ZServer from
another webserver is similar to using the web server as a proxy, another webserver is similar to using the web server as a proxy,
with the difference, that the web server gets to control the with the difference, that the web server gets to control the
environment and headers completely. environment and headers completely.
Note that ZServer can operate multiple PCGI servers. Note that ZServer can operate multiple PCGI servers.
...@@ -50,13 +50,13 @@ from types import StringType, TupleType ...@@ -50,13 +50,13 @@ from types import StringType, TupleType
tz_for_log=compute_timezone_for_log() tz_for_log=compute_timezone_for_log()
class PCGIChannel(asynchat.async_chat): class PCGIChannel(asynchat.async_chat):
"""Processes a PCGI request by collecting the env and stdin and """Processes a PCGI request by collecting the env and stdin and
then passing them to ZPublisher. The result is wrapped in a then passing them to ZPublisher. The result is wrapped in a
producer and sent back.""" producer and sent back."""
closed=0 closed=0
def __init__(self,server,sock,addr): def __init__(self,server,sock,addr):
self.server = server self.server = server
self.addr = addr self.addr = addr
...@@ -67,7 +67,7 @@ class PCGIChannel(asynchat.async_chat): ...@@ -67,7 +67,7 @@ class PCGIChannel(asynchat.async_chat):
self.set_terminator(10) self.set_terminator(10)
self.size=None self.size=None
self.done=None self.done=None
def found_terminator(self): def found_terminator(self):
if self.size is None: if self.size is None:
# read the next size header # read the next size header
...@@ -76,10 +76,10 @@ class PCGIChannel(asynchat.async_chat): ...@@ -76,10 +76,10 @@ class PCGIChannel(asynchat.async_chat):
self.size=string.atoi(self.data.read()) self.size=string.atoi(self.data.read())
self.set_terminator(self.size) self.set_terminator(self.size)
if self.size==0: if self.size==0:
DebugLogger.log('I', id(self), 0) DebugLogger.log('I', id(self), 0)
self.set_terminator('\r\n') self.set_terminator('\r\n')
self.data=StringIO() self.data=StringIO()
self.send_response() self.send_response()
elif self.size > 1048576: elif self.size > 1048576:
...@@ -98,7 +98,7 @@ class PCGIChannel(asynchat.async_chat): ...@@ -98,7 +98,7 @@ class PCGIChannel(asynchat.async_chat):
except: except:
pass pass
# Hack around broken IIS PATH_INFO # Hack around broken IIS PATH_INFO
# maybe, this should go in ZPublisher... # maybe, this should go in ZPublisher...
if self.env.has_key('SERVER_SOFTWARE') and \ if self.env.has_key('SERVER_SOFTWARE') and \
string.find(self.env['SERVER_SOFTWARE'], string.find(self.env['SERVER_SOFTWARE'],
'Microsoft-IIS') != -1: 'Microsoft-IIS') != -1:
...@@ -109,37 +109,37 @@ class PCGIChannel(asynchat.async_chat): ...@@ -109,37 +109,37 @@ class PCGIChannel(asynchat.async_chat):
self.env['PATH_INFO'] = '/' + string.join(path[len(script):],'/') self.env['PATH_INFO'] = '/' + string.join(path[len(script):],'/')
self.data=StringIO() self.data=StringIO()
DebugLogger.log('B', id(self), DebugLogger.log('B', id(self),
'%s %s' % (self.env['REQUEST_METHOD'], '%s %s' % (self.env['REQUEST_METHOD'],
self.env.get('PATH_INFO' ,'/'))) self.env.get('PATH_INFO' ,'/')))
# now read the next size header # now read the next size header
self.set_terminator(10) self.set_terminator(10)
else: else:
DebugLogger.log('I', id(self), self.terminator) DebugLogger.log('I', id(self), self.terminator)
# we're done, we've got both env and stdin # we're done, we've got both env and stdin
self.set_terminator('\r\n') self.set_terminator('\r\n')
self.data.seek(0) self.data.seek(0)
self.send_response() self.send_response()
def send_response(self): def send_response(self):
# create an output pipe by passing request to ZPublisher, # create an output pipe by passing request to ZPublisher,
# and requesting a callback of self.log with the module # and requesting a callback of self.log with the module
# name and PATH_INFO as an argument. # name and PATH_INFO as an argument.
self.done=1 self.done=1
response=PCGIResponse(stdout=PCGIPipe(self), stderr=StringIO()) response=PCGIResponse(stdout=PCGIPipe(self), stderr=StringIO())
request=HTTPRequest(self.data, self.env, response) request=HTTPRequest(self.data, self.env, response)
handle(self.server.module, request, response) handle(self.server.module, request, response)
def collect_incoming_data(self, data): def collect_incoming_data(self, data):
self.data.write(data) self.data.write(data)
def readable(self): def readable(self):
if not self.done: if not self.done:
return 1 return 1
def log_request(self, bytes): def log_request(self, bytes):
if self.env.has_key('HTTP_USER_AGENT'): if self.env.has_key('HTTP_USER_AGENT'):
user_agent=self.env['HTTP_USER_AGENT'] user_agent=self.env['HTTP_USER_AGENT']
...@@ -183,15 +183,15 @@ class PCGIChannel(asynchat.async_chat): ...@@ -183,15 +183,15 @@ class PCGIChannel(asynchat.async_chat):
method, path, self.reply_code, bytes, method, path, self.reply_code, bytes,
referer, user_agent referer, user_agent
) )
) )
def push(self, producer, send=1): def push(self, producer, send=1):
# this is thread-safe when send is false # this is thread-safe when send is false
# note, that strings are not wrapped in # note, that strings are not wrapped in
# producers by default # producers by default
self.producer_fifo.push(producer) self.producer_fifo.push(producer)
if send: self.initiate_send() if send: self.initiate_send()
def __repr__(self): def __repr__(self):
return "<PCGIChannel at %x>" % id(self) return "<PCGIChannel at %x>" % id(self)
...@@ -202,13 +202,13 @@ class PCGIChannel(asynchat.async_chat): ...@@ -202,13 +202,13 @@ class PCGIChannel(asynchat.async_chat):
if p is not None and type(p) != StringType: if p is not None and type(p) != StringType:
p.more() # free up resources held by producer p.more() # free up resources held by producer
self.producer_fifo.pop() self.producer_fifo.pop()
asyncore.dispatcher.close(self) asyncore.dispatcher.close(self)
class PCGIServer(asyncore.dispatcher): class PCGIServer(asyncore.dispatcher):
"""Accepts PCGI requests and hands them off to the PCGIChannel for """Accepts PCGI requests and hands them off to the PCGIChannel for
handling. handling.
PCGIServer can be configured with either a PCGI info file or by PCGIServer can be configured with either a PCGI info file or by
directly specifying the module, pid_file, and either port (for directly specifying the module, pid_file, and either port (for
inet sockets) or socket_file (for unix domain sockets.) inet sockets) or socket_file (for unix domain sockets.)
...@@ -217,7 +217,7 @@ class PCGIServer(asyncore.dispatcher): ...@@ -217,7 +217,7 @@ class PCGIServer(asyncore.dispatcher):
the server will accept connections, '' indicates all addresses. If the server will accept connections, '' indicates all addresses. If
you only want to accept connections from the localhost, set ip to you only want to accept connections from the localhost, set ip to
'127.0.0.1'.""" '127.0.0.1'."""
channel_class=PCGIChannel channel_class=PCGIChannel
def __init__ (self, def __init__ (self,
...@@ -239,23 +239,23 @@ class PCGIServer(asyncore.dispatcher): ...@@ -239,23 +239,23 @@ class PCGIServer(asyncore.dispatcher):
self.logger = logger.resolving_logger (resolver, logger_object) self.logger = logger.resolving_logger (resolver, logger_object)
else: else:
self.logger = logger.unresolving_logger (logger_object) self.logger = logger.unresolving_logger (logger_object)
# get configuration # get configuration
self.module=module self.module=module
self.port=port self.port=port
self.pid_file=pid_file self.pid_file=pid_file
self.socket_file=socket_file self.socket_file=socket_file
if pcgi_file is not None: if pcgi_file is not None:
self.read_info(pcgi_file) self.read_info(pcgi_file)
# write pid file # write pid file
try: try:
f = open(self.pid_file, 'w') f = open(self.pid_file, 'w')
f.write(str(os.getpid())) f.write(str(os.getpid()))
f.close() f.close()
except IOError: except IOError:
self.log_info("Cannot write PID file.", 'error') self.log_info("Cannot write PID file.", 'error')
# setup sockets # setup sockets
if self.port: if self.port:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
...@@ -278,7 +278,7 @@ class PCGIServer(asyncore.dispatcher): ...@@ -278,7 +278,7 @@ class PCGIServer(asyncore.dispatcher):
except os.error: except os.error:
pass pass
self.log_info( self.log_info(
'PCGI Server started at %s\n' 'PCGI Server started at %s\n'
'\tUnix socket: %s' % (time.ctime(time.time()), self.socket_file) '\tUnix socket: %s' % (time.ctime(time.time()), self.socket_file)
) )
self.listen(256) self.listen(256)
...@@ -300,7 +300,7 @@ class PCGIServer(asyncore.dispatcher): ...@@ -300,7 +300,7 @@ class PCGIServer(asyncore.dispatcher):
directives[string.strip(k)]=string.strip(v) directives[string.strip(k)]=string.strip(v)
except: except:
raise 'ParseError', 'Error parsing PCGI info file' raise 'ParseError', 'Error parsing PCGI info file'
self.pid_file=directives.get('PCGI_PID_FILE',None) self.pid_file=directives.get('PCGI_PID_FILE',None)
self.socket_file=directives.get('PCGI_SOCKET_FILE',None) self.socket_file=directives.get('PCGI_SOCKET_FILE',None)
if directives.has_key('PCGI_PORT'): if directives.has_key('PCGI_PORT'):
...@@ -312,7 +312,7 @@ class PCGIServer(asyncore.dispatcher): ...@@ -312,7 +312,7 @@ class PCGIServer(asyncore.dispatcher):
path,module=os.path.split(path) path,module=os.path.split(path)
module,ext=os.path.splitext(module) module,ext=os.path.splitext(module)
self.module=module self.module=module
def handle_accept (self): def handle_accept (self):
self.count.increment() self.count.increment()
try: try:
...@@ -321,19 +321,19 @@ class PCGIServer(asyncore.dispatcher): ...@@ -321,19 +321,19 @@ class PCGIServer(asyncore.dispatcher):
self.log_info('Server accept() threw an exception', 'warning') self.log_info('Server accept() threw an exception', 'warning')
return return
self.channel_class(self, conn, addr) self.channel_class(self, conn, addr)
def readable(self): def readable(self):
return len(asyncore.socket_map) < CONNECTION_LIMIT return len(asyncore.socket_map) < CONNECTION_LIMIT
def writable (self): def writable (self):
return 0 return 0
def listen(self, num): def listen(self, num):
# override asyncore limits for nt's listen queue size # override asyncore limits for nt's listen queue size
self.accepting = 1 self.accepting = 1
return self.socket.listen (num) return self.socket.listen (num)
class PCGIResponse(HTTPResponse): class PCGIResponse(HTTPResponse):
def write(self, data): def write(self, data):
...@@ -341,42 +341,42 @@ class PCGIResponse(HTTPResponse): ...@@ -341,42 +341,42 @@ class PCGIResponse(HTTPResponse):
self.stdout.write(str(self)) self.stdout.write(str(self))
self._wrote=1 self._wrote=1
self.stdout.write(data) self.stdout.write(data)
def _finish(self): def _finish(self):
self.stdout.finish(self) self.stdout.finish(self)
self.stdout.close() self.stdout.close()
self.stdout=None self.stdout=None
self._request=None self._request=None
class PCGIPipe: class PCGIPipe:
""" """
Formats a HTTP response in PCGI format Formats a HTTP response in PCGI format
10 digits indicating len of STDOUT 10 digits indicating len of STDOUT
STDOUT STDOUT
10 digits indicating len of STDERR 10 digits indicating len of STDERR
STDERR STDERR
Note that this implementation never sends STDERR Note that this implementation never sends STDERR
""" """
def __init__(self, channel): def __init__(self, channel):
self._channel=channel self._channel=channel
self._data=StringIO() self._data=StringIO()
self._shutdown=0 self._shutdown=0
def write(self,text): def write(self,text):
self._data.write(text) self._data.write(text)
def close(self): def close(self):
if not self._channel.closed: if not self._channel.closed:
data=self._data.getvalue() data=self._data.getvalue()
l=len(data) l=len(data)
DebugLogger.log('A', id(self._channel), DebugLogger.log('A', id(self._channel),
'%s %s' % (self._channel.reply_code, l)) '%s %s' % (self._channel.reply_code, l))
self._channel.push('%010d%s%010d' % (l, data, 0), 0) self._channel.push('%010d%s%010d' % (l, data, 0), 0)
self._channel.push(LoggingProducer(self._channel, l, 'log_request'), 0) self._channel.push(LoggingProducer(self._channel, l, 'log_request'), 0)
self._channel.push(CallbackProducer( self._channel.push(CallbackProducer(
lambda t=('E', id(self._channel)): apply(DebugLogger.log,t)), 0) lambda t=('E', id(self._channel)): apply(DebugLogger.log,t)), 0)
...@@ -391,7 +391,7 @@ class PCGIPipe: ...@@ -391,7 +391,7 @@ class PCGIPipe:
Wakeup() Wakeup()
self._data=None self._data=None
self._channel=None self._channel=None
def finish(self, response): def finish(self, response):
if response._shutdownRequested(): if response._shutdownRequested():
self._shutdown = 1 self._shutdown = 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
# #
############################################################################## ##############################################################################
""" """
ZServer pipe utils. These producers basically function as callbacks. ZServer pipe utils. These producers basically function as callbacks.
...@@ -19,14 +19,14 @@ import sys ...@@ -19,14 +19,14 @@ import sys
class ShutdownProducer: class ShutdownProducer:
"shuts down medusa" "shuts down medusa"
def more(self): def more(self):
asyncore.close_all() asyncore.close_all()
class LoggingProducer: class LoggingProducer:
"logs request" "logs request"
def __init__(self, logger, bytes, method='log'): def __init__(self, logger, bytes, method='log'):
self.logger=logger self.logger=logger
self.bytes=bytes self.bytes=bytes
...@@ -36,14 +36,14 @@ class LoggingProducer: ...@@ -36,14 +36,14 @@ class LoggingProducer:
getattr(self.logger, self.method)(self.bytes) getattr(self.logger, self.method)(self.bytes)
self.logger=None self.logger=None
return '' return ''
class CallbackProducer: class CallbackProducer:
"Performs a callback in the channel's thread" "Performs a callback in the channel's thread"
def __init__(self, callback): def __init__(self, callback):
self.callback=callback self.callback=callback
def more(self): def more(self):
self.callback() self.callback()
self.callback=None self.callback=None
...@@ -55,7 +55,7 @@ class file_part_producer: ...@@ -55,7 +55,7 @@ class file_part_producer:
# match http_channel's outgoing buffer size # match http_channel's outgoing buffer size
out_buffer_size = 1<<16 out_buffer_size = 1<<16
def __init__(self, file, lock, start, end): def __init__(self, file, lock, start, end):
self.file=file self.file=file
self.lock=lock self.lock=lock
...@@ -79,7 +79,7 @@ class file_part_producer: ...@@ -79,7 +79,7 @@ class file_part_producer:
data = file.read(size) data = file.read(size)
finally: finally:
self.lock.release() self.lock.release()
if data: if data:
start=start+len(data) start=start+len(data)
if start < end: if start < end:
...@@ -102,4 +102,3 @@ class file_close_producer: ...@@ -102,4 +102,3 @@ class file_close_producer:
file.close() file.close()
self.file=None self.file=None
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
# #
############################################################################## ##############################################################################
"""Simple Event Manager Based on Pipes """Simple Event Manager Based on Pipes
...@@ -31,8 +31,7 @@ def Wakeup(thunk=None): ...@@ -31,8 +31,7 @@ def Wakeup(thunk=None):
# this broken pipe as a result of perhaps a signal # this broken pipe as a result of perhaps a signal
# we want to handle this gracefully so we get rid of the old # we want to handle this gracefully so we get rid of the old
# trigger and install a new one. # trigger and install a new one.
if why[0] == 32: if why[0] == 32:
del socket_map[the_trigger._fileno] del socket_map[the_trigger._fileno]
the_trigger = simple_trigger() # adds itself back into socket_map the_trigger = simple_trigger() # adds itself back into socket_map
the_trigger.pull_trigger(thunk) the_trigger.pull_trigger(thunk)
############################################################################## ##############################################################################
# #
# 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 thread import thread
......
############################################################################## ##############################################################################
# #
# 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 ZPublisher import publish_module from ZPublisher import publish_module
class ZServerPublisher: class ZServerPublisher:
def __init__(self, accept): def __init__(self, accept):
while 1: while 1:
try: try:
name, request, response=accept() name, request, response=accept()
publish_module( publish_module(
name, name,
request=request, request=request,
response=response) response=response)
finally: finally:
response._finish() response._finish()
request=response=None request=response=None
############################################################################## ##############################################################################
# #
# 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 ZRendezvous import ZRendezvous
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
...@@ -34,7 +34,7 @@ class WebDAVSrcHandler( zhttp_handler ): ...@@ -34,7 +34,7 @@ class WebDAVSrcHandler( zhttp_handler ):
# Set a flag to indicate this request came through the WebDAV source # Set a flag to indicate this request came through the WebDAV source
# port server. # port server.
env['WEBDAV_SOURCE_PORT'] = 1 env['WEBDAV_SOURCE_PORT'] = 1
if env['REQUEST_METHOD'] == 'GET': if env['REQUEST_METHOD'] == 'GET':
path_info = env['PATH_INFO'] path_info = env['PATH_INFO']
path_info = os.path.join( path_info, 'manage_FTPget' ) path_info = os.path.join( path_info, 'manage_FTPget' )
...@@ -51,9 +51,9 @@ class WebDAVSrcHandler( zhttp_handler ): ...@@ -51,9 +51,9 @@ class WebDAVSrcHandler( zhttp_handler ):
if env.get("HTTP_USER_AGENT","").find("Microsoft Data Access Internet Publishing Provider")>-1: if env.get("HTTP_USER_AGENT","").find("Microsoft Data Access Internet Publishing Provider")>-1:
if env["PATH_INFO"][-1]=='.': if env["PATH_INFO"][-1]=='.':
env["PATH_INFO"] = env["PATH_INFO"][:-1] env["PATH_INFO"] = env["PATH_INFO"][:-1]
if env["PATH_TRANSLATED"][-1]=='.': if env["PATH_TRANSLATED"][-1]=='.':
env["PATH_TRANSLATED"] = env["PATH_TRANSLATED"][:-1] env["PATH_TRANSLATED"] = env["PATH_TRANSLATED"][:-1]
return env return env
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
""" """
ZServer as a NT service. ZServer as a NT service.
...@@ -16,7 +16,7 @@ ZServer as a NT service. ...@@ -16,7 +16,7 @@ ZServer as a NT service.
The serice starts up and monitors a ZServer process. The serice starts up and monitors a ZServer process.
Features: Features:
* When you start the service it starts ZServer * When you start the service it starts ZServer
* When you stop the serivice it stops ZServer * When you stop the serivice it stops ZServer
* It monitors ZServer and restarts it if it exits abnormally * It monitors ZServer and restarts it if it exits abnormally
...@@ -26,82 +26,82 @@ Features: ...@@ -26,82 +26,82 @@ Features:
Usage: Usage:
Installation Installation
The ZServer service should be installed by the Zope Windows The ZServer service should be installed by the Zope Windows
installer. You can manually install, uninstall the service from installer. You can manually install, uninstall the service from
the commandline. the commandline.
ZService.py [options] install|update|remove|start [...] ZService.py [options] install|update|remove|start [...]
|stop|restart [...]|debug [...] |stop|restart [...]|debug [...]
Options for 'install' and 'update' commands only: Options for 'install' and 'update' commands only:
--username domain\username : The Username the service is to run --username domain\username : The Username the service is to run
under under
--password password : The password for the username --password password : The password for the username
--startup [manual|auto|disabled] : How the service starts, --startup [manual|auto|disabled] : How the service starts,
default = manual default = manual
Commands Commands
install : Installs the service install : Installs the service
update : Updates the service, use this when you change update : Updates the service, use this when you change
ZServer.py ZServer.py
remove : Removes the service remove : Removes the service
start : Starts the service, this can also be done from the start : Starts the service, this can also be done from the
services control panel services control panel
stop : Stops the service, this can also be done from the stop : Stops the service, this can also be done from the
services control panel services control panel
restart : Restarts the service restart : Restarts the service
debug : Runs the service in debug mode debug : Runs the service in debug mode
You can view the usage options by running ZServer.py without any You can view the usage options by running ZServer.py without any
arguments. arguments.
Note: you may have to register the Python service program first, Note: you may have to register the Python service program first,
win32\pythonservice.exe /register win32\pythonservice.exe /register
Starting Zope Starting Zope
Start Zope by clicking the 'start' button in the services control Start Zope by clicking the 'start' button in the services control
panel. You can set Zope to automatically start at boot time by panel. You can set Zope to automatically start at boot time by
choosing 'Auto' startup by clicking the 'statup' button. choosing 'Auto' startup by clicking the 'statup' button.
Stopping Zope Stopping Zope
Stop Zope by clicking the 'stop' button in the services control Stop Zope by clicking the 'stop' button in the services control
panel. You can also stop Zope through the web by going to the panel. You can also stop Zope through the web by going to the
Zope control panel and by clicking 'Shutdown'. Zope control panel and by clicking 'Shutdown'.
Event logging Event logging
Zope events are logged to the NT application event log. Use the Zope events are logged to the NT application event log. Use the
event viewer to keep track of Zope events. event viewer to keep track of Zope events.
Registry Settings Registry Settings
You can change how the service starts ZServer by editing a registry You can change how the service starts ZServer by editing a registry
key. key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
<Service Name>\Parameters\start <Service Name>\Parameters\start
The value of this key is the command which the service uses to The value of this key is the command which the service uses to
start ZServer. For example: start ZServer. For example:
"C:\Program Files\Zope\bin\python.exe" "C:\Program Files\Zope\bin\python.exe"
"C:\Program Files\Zope\z2.py" -w 8888 "C:\Program Files\Zope\z2.py" -w 8888
TODO: TODO:
* Integrate it into the Windows installer. * Integrate it into the Windows installer.
...@@ -168,15 +168,15 @@ class ZServerService(win32serviceutil.ServiceFramework): ...@@ -168,15 +168,15 @@ class ZServerService(win32serviceutil.ServiceFramework):
file.close() file.close()
_svc_display_name_ = "Zope (%s)" % _svc_name_ _svc_display_name_ = "Zope (%s)" % _svc_name_
restart_min_time=5 # if ZServer restarts before this many restart_min_time=5 # if ZServer restarts before this many
# seconds then we have a problem, and # seconds then we have a problem, and
# need to stop the service. # need to stop the service.
def __init__(self, args): def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args) win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self): def SvcDoRun(self):
self.start_zserver() self.start_zserver()
while 1: while 1:
...@@ -186,12 +186,12 @@ class ZServerService(win32serviceutil.ServiceFramework): ...@@ -186,12 +186,12 @@ class ZServerService(win32serviceutil.ServiceFramework):
break break
else: else:
self.restart_zserver() self.restart_zserver()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000)
def SvcStop(self): def SvcStop(self):
servicemanager.LogInfoMsg('Stopping Zope.') servicemanager.LogInfoMsg('Stopping Zope.')
try: try:
self.stop_zserver() self.stop_zserver()
except: except:
pass pass
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
...@@ -204,10 +204,10 @@ class ZServerService(win32serviceutil.ServiceFramework): ...@@ -204,10 +204,10 @@ class ZServerService(win32serviceutil.ServiceFramework):
self.hZServer=result[0] self.hZServer=result[0]
self.last_start_time=time.time() self.last_start_time=time.time()
servicemanager.LogInfoMsg('Starting Zope.') servicemanager.LogInfoMsg('Starting Zope.')
def stop_zserver(self): def stop_zserver(self):
win32process.TerminateProcess(self.hZServer,0) win32process.TerminateProcess(self.hZServer,0)
def restart_zserver(self): def restart_zserver(self):
if time.time() - self.last_start_time < self.restart_min_time: if time.time() - self.last_start_time < self.restart_min_time:
servicemanager.LogErrorMsg('Zope died and could not be restarted.') servicemanager.LogErrorMsg('Zope died and could not be restarted.')
...@@ -223,15 +223,15 @@ class ZServerService(win32serviceutil.ServiceFramework): ...@@ -223,15 +223,15 @@ class ZServerService(win32serviceutil.ServiceFramework):
def get_start_command(self): def get_start_command(self):
return win32serviceutil.GetServiceCustomOption(self,'start') return win32serviceutil.GetServiceCustomOption(self,'start')
def set_start_command(value): def set_start_command(value):
"sets the ZServer start command if the start command is not already set" "sets the ZServer start command if the start command is not already set"
current=win32serviceutil.GetServiceCustomOption(ZServerService, current=win32serviceutil.GetServiceCustomOption(ZServerService,
'start', None) 'start', None)
if current is None: if current is None:
win32serviceutil.SetServiceCustomOption(ZServerService,'start',value) win32serviceutil.SetServiceCustomOption(ZServerService,'start',value)
if __name__=='__main__': if __name__=='__main__':
win32serviceutil.HandleCommandLine(ZServerService) win32serviceutil.HandleCommandLine(ZServerService)
......
############################################################################## ##############################################################################
# #
# 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 sys, os import sys, os
...@@ -55,7 +55,7 @@ try: ...@@ -55,7 +55,7 @@ try:
message == 'Computing default hostname': message == 'Computing default hostname':
LOG('ZServer', BLATHER, message) LOG('ZServer', BLATHER, message)
else: else:
LOG('ZServer', severity[type], message) LOG('ZServer', severity[type], message)
import asyncore import asyncore
asyncore.dispatcher.log_info=log_info asyncore.dispatcher.log_info=log_info
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Try to do all of the installation steps. """Try to do all of the installation steps.
...@@ -40,22 +40,22 @@ def main(args): ...@@ -40,22 +40,22 @@ def main(args):
-p -- Supply the path to the PCGI resource file. -p -- Supply the path to the PCGI resource file.
This defaults to %s. This defaults to %s.
Note that this path must include the file name. Note that this path must include the file name.
-g -- Supply the name of the unix group to which -g -- Supply the name of the unix group to which
the user that runs your web server belongs. the user that runs your web server belongs.
If not specified, the installer will attempt If not specified, the installer will attempt
to determine the group itself. If no group to determine the group itself. If no group
is specified and the installer is unable to is specified and the installer is unable to
determine the group, the install will fail. determine the group, the install will fail.
-u -- Supply the name of the unix user used to -u -- Supply the name of the unix user used to
run your web server. If not specified, this run your web server. If not specified, this
defaults to the userid of the current user, defaults to the userid of the current user,
or 'nobody' is the current user is root. or 'nobody' is the current user is root.
-h -- Show command summary -h -- Show command summary
""" % (pcgi) """ % (pcgi)
try: options, args = getopt.getopt(sys.argv[1:], 'p:g:hu:') try: options, args = getopt.getopt(sys.argv[1:], 'p:g:hu:')
except: error(usage, sys.exc_info()) except: error(usage, sys.exc_info())
if args: error('', ('Unexpected arguments', args)) if args: error('', ('Unexpected arguments', args))
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Build the Zope Extension Modules """Build the Zope Extension Modules
...@@ -22,4 +22,3 @@ print '-'*78 ...@@ -22,4 +22,3 @@ print '-'*78
print 'Building extension modules' print 'Building extension modules'
do('%s setup.py build_ext -i' % sys.executable) do('%s setup.py build_ext -i' % sys.executable)
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Build a PCGI """Build a PCGI
......
############################################################################## ##############################################################################
# #
# 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 compileall, os, sys import compileall, os, sys
...@@ -58,7 +58,7 @@ except: ...@@ -58,7 +58,7 @@ except:
success = 0 success = 0
import traceback import traceback
traceback.print_exc() traceback.print_exc()
if not success: if not success:
print print
print '!' * 78 print '!' * 78
......
############################################################################## ##############################################################################
# #
# 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 os import os
...@@ -29,7 +29,3 @@ def main(home, user='', group=''): ...@@ -29,7 +29,3 @@ def main(home, user='', group=''):
print 'creating default database' print 'creating default database'
open(db_path,'wb').write(open(dd_path,'rb').read()) open(db_path,'wb').write(open(dd_path,'rb').read())
ch(db_path, user, group) ch(db_path, user, group)
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Shared routines used by the various scripts. """Shared routines used by the various scripts.
...@@ -49,13 +49,13 @@ def ch(path, user, group, mode=0600, quiet=0): ...@@ -49,13 +49,13 @@ def ch(path, user, group, mode=0600, quiet=0):
do("chown %s %s" % (user, path), 0, quiet) do("chown %s %s" % (user, path), 0, quiet)
do("chmod %s %s" % (oct(mode), path), 0, quiet) do("chmod %s %s" % (oct(mode), path), 0, quiet)
def make(*args): def make(*args):
print print
print '-'*48 print '-'*48
print 'Compiling extensions in %s' % string.join(args,'/') print 'Compiling extensions in %s' % string.join(args,'/')
for a in args: os.chdir(a) for a in args: os.chdir(a)
# Copy over and use the prototype extensions makefile from python dist: # Copy over and use the prototype extensions makefile from python dist:
do("cp %s ." % wheres_Makefile_pre_in()) do("cp %s ." % wheres_Makefile_pre_in())
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Make an INSTANCE_HOME.""" """Make an INSTANCE_HOME."""
...@@ -86,7 +86,7 @@ def main(me): ...@@ -86,7 +86,7 @@ def main(me):
print print
print ('Now to create a starting user. Leave the username ' print ('Now to create a starting user. Leave the username '
'blank if you want to skip this step.') 'blank if you want to skip this step.')
print print
sys.path.insert(0, home) sys.path.insert(0, home)
choose_inituser(ih) choose_inituser(ih)
...@@ -100,7 +100,7 @@ def choose_inituser(home): ...@@ -100,7 +100,7 @@ def choose_inituser(home):
username = raw_input("Username: ") username = raw_input("Username: ")
if username == '': if username == '':
return return
while 1: while 1:
pw = getpass.getpass("Password: ") pw = getpass.getpass("Password: ")
verify = getpass.getpass("Verify password: ") verify = getpass.getpass("Verify password: ")
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Build a PCGI resource file. """Build a PCGI resource file.
...@@ -39,4 +39,3 @@ INSTANCE_HOME=%(cwd)s ...@@ -39,4 +39,3 @@ INSTANCE_HOME=%(cwd)s
''' % vars()) ''' % vars())
ch(name, user, group, 0755) ch(name, user, group, 0755)
############################################################################## ##############################################################################
# #
# 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 sys, os import sys, os
......
############################################################################## ##############################################################################
# #
# 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 os, sys import os, sys
...@@ -41,7 +41,7 @@ def scrub(list, dirname, filelist): ...@@ -41,7 +41,7 @@ def scrub(list, dirname, filelist):
full = os.path.join(dirname, name) full = os.path.join(dirname, name)
os.unlink(full) os.unlink(full)
if DEBUG: print full if DEBUG: print full
if __name__ == '__main__': if __name__ == '__main__':
DEBUG = 1 DEBUG = 1
walkandscrub(os.getcwd()) walkandscrub(os.getcwd())
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
# #
# Copyright (c) 2001, 2002 Zope Corporation and Contributors. # Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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
# #
############################################################################## ##############################################################################
"""Support for Python classes implemented in C """Support for Python classes implemented in C
...@@ -18,16 +18,16 @@ A lightweight mechanism has been developed for making Python ...@@ -18,16 +18,16 @@ A lightweight mechanism has been developed for making Python
extension types more class-like. Classes can be developed in an extension types more class-like. Classes can be developed in an
extension language, such as C or C++, and these classes can be extension language, such as C or C++, and these classes can be
treated like other python classes: treated like other python classes:
- They can be sub-classed in python, - They can be sub-classed in python,
- They provide access to method documentation strings, and - They provide access to method documentation strings, and
- They can be used to directly create new instances. - They can be used to directly create new instances.
An example class shows how extension classes are implemented and how An example class shows how extension classes are implemented and how
they differ from extension types. they differ from extension types.
Extension classes provide additional extensions to class and Extension classes provide additional extensions to class and
instance semantics, including: instance semantics, including:
...@@ -41,11 +41,11 @@ instance semantics, including: ...@@ -41,11 +41,11 @@ instance semantics, including:
- A protocol for class initialization that supports execution of a - A protocol for class initialization that supports execution of a
special '__class_init__' method after a class has been special '__class_init__' method after a class has been
initialized. initialized.
Extension classes illustrate how the Python class mechanism can be Extension classes illustrate how the Python class mechanism can be
extended and may provide a basis for improved or specialized class extended and may provide a basis for improved or specialized class
models. models.
""" """
# Setup file for ExtensionClass # Setup file for ExtensionClass
...@@ -79,7 +79,7 @@ Sync = Extension(name = 'Sync', sources = ['src/Sync.c']) ...@@ -79,7 +79,7 @@ Sync = Extension(name = 'Sync', sources = ['src/Sync.c'])
ThreadLock = Extension(name = 'ThreadLock', ThreadLock = Extension(name = 'ThreadLock',
sources = ['src/ThreadLock.c']) sources = ['src/ThreadLock.c'])
setup(name = "ExtensionClass", setup(name = "ExtensionClass",
version = "1.3", version = "1.3",
description = "Support for Python classes implemented in C", description = "Support for Python classes implemented in C",
maintainer = "Digital Creations", maintainer = "Digital Creations",
......
...@@ -2,17 +2,17 @@ ...@@ -2,17 +2,17 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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
# #
############################################################################## ##############################################################################
# Compatibility module # Compatibility module
# $Id: Xaq.py,v 1.2 2002/06/10 22:48:46 jeremy Exp $ # $Id: Xaq.py,v 1.3 2002/08/14 21:24:48 mj Exp $
import Acquisition import Acquisition
Acquirer = Acquisition.Explicit Acquirer = Acquisition.Explicit
...@@ -4,14 +4,14 @@ ...@@ -4,14 +4,14 @@
# #
# Copyright (c) 2001, 2002 Zope Corporation and Contributors. # Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 os import os
......
...@@ -2,20 +2,20 @@ ...@@ -2,20 +2,20 @@
# #
# Copyright (c) 2001, 2002 Zope Corporation and Contributors. # Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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__='''Examples from the Acquisition Algebra Presentation __doc__='''Examples from the Acquisition Algebra Presentation
$Id: test_AqAlg.py,v 1.4 2002/06/10 22:48:47 jeremy Exp $''' $Id: test_AqAlg.py,v 1.5 2002/08/14 21:24:48 mj Exp $'''
__version__='$Revision: 1.4 $'[11:-2] __version__='$Revision: 1.5 $'[11:-2]
import Acquisition import Acquisition
...@@ -99,4 +99,3 @@ def main(): ...@@ -99,4 +99,3 @@ def main():
if __name__=='__main__': if __name__=='__main__':
main() main()
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 pprint import pprint from pprint import pprint
from MultiMapping import * from MultiMapping import *
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 Sync import Synchronized from Sync import Synchronized
import thread import thread
...@@ -22,18 +22,18 @@ class P(Synchronized): ...@@ -22,18 +22,18 @@ class P(Synchronized):
self.count=0 self.count=0
def inc(self): def inc(self):
c = self.count c = self.count
if random() > 0.7: if random() > 0.7:
sleep(1) sleep(1)
self.count = self.count + 1 self.count = self.count + 1
return c, self.count return c, self.count
def incn(self,n): def incn(self,n):
c = self.count c = self.count
for i in range(n): for i in range(n):
self.inc() self.inc()
return c, self.count return c, self.count
p = P(1, 2, spam=3) p = P(1, 2, spam=3)
def test(): def test():
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 ThreadLock, thread import ThreadLock, thread
from random import random from random import random
...@@ -41,21 +41,21 @@ class P(Base): ...@@ -41,21 +41,21 @@ class P(Base):
self.__call_method__=lock.guarded_apply self.__call_method__=lock.guarded_apply
def inc(self): def inc(self):
c=self.count c=self.count
if random() > 0.7: if random() > 0.7:
sleep(1) sleep(1)
self.count=self.count+1 self.count=self.count+1
return c,self.count return c,self.count
def incn(self,n): def incn(self,n):
c=self.count c=self.count
for i in range(n): self.inc() for i in range(n): self.inc()
return c,self.count return c,self.count
p=P(1,2,spam=3) p=P(1,2,spam=3)
def test(): def test():
for i in range(8): for i in range(8):
n = 3 n = 3
old, new = p.incn(n) old, new = p.incn(n)
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 ExtensionClass import Base from ExtensionClass import Base
import Acquisition import Acquisition
...@@ -51,11 +51,11 @@ def checkContext(self, o): ...@@ -51,11 +51,11 @@ def checkContext(self, o):
subob = self subob = self
o = aq_base(o) o = aq_base(o)
while 1: while 1:
if aq_base(subob) is o: return 1 if aq_base(subob) is o: return 1
self = aq_inner(subob) self = aq_inner(subob)
if self is None: break if self is None: break
subob = aq_parent(self) subob = aq_parent(self)
if subob is None: break if subob is None: break
assert checkContext(b.c, b) assert checkContext(b.c, b)
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 ExtensionClass import * from ExtensionClass import *
......
...@@ -2,29 +2,28 @@ ...@@ -2,29 +2,28 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 ExtensionClass import Base from ExtensionClass import Base
from MethodObject import Method from MethodObject import Method
class foo(Method): class foo(Method):
def __call__(self, ob, *args, **kw): def __call__(self, ob, *args, **kw):
print 'called', ob, args, kw print 'called', ob, args, kw
class bar(Base): class bar(Base):
def __repr__(self): def __repr__(self):
return "bar()" return "bar()"
hi = foo() hi = foo()
x=bar() x=bar()
hi=x.hi hi=x.hi
print type(hi) print type(hi)
hi(1,2,3,name='spam') hi(1,2,3,name='spam')
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 ExtensionClass import Base from ExtensionClass import Base
import Acquisition import Acquisition
...@@ -30,4 +30,3 @@ try: ...@@ -30,4 +30,3 @@ try:
A().hi() A().hi()
raise 'Program error', 'spam' raise 'Program error', 'spam'
except AttributeError: pass except AttributeError: pass
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
# #
# Copyright (c) 1996-2002 Zope Corporation and Contributors. # Copyright (c) 1996-2002 Zope Corporation and Contributors.
# All Rights Reserved. # 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 ExtensionClass import ExtensionClass
......
...@@ -18,4 +18,3 @@ def pickle_complex(c): ...@@ -18,4 +18,3 @@ def pickle_complex(c):
return complex, (c.real, c.imag) return complex, (c.real, c.imag)
pickle(type(1j), pickle_complex, complex) pickle(type(1j), pickle_complex, complex)
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
import sha, binascii import sha, binascii
from binascii import b2a_base64, a2b_base64 from binascii import b2a_base64, a2b_base64
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
'''Add security system support to Document Templates '''Add security system support to Document Templates
$Id: DTML.py,v 1.9 2001/11/28 15:50:51 matt Exp $''' $Id: DTML.py,v 1.10 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.9 $'[11:-2] __version__='$Revision: 1.10 $'[11:-2]
from DocumentTemplate import DT_Util from DocumentTemplate import DT_Util
import SecurityManagement, string, math, whrandom, random import SecurityManagement, string, math, whrandom, random
...@@ -46,7 +46,7 @@ else: ...@@ -46,7 +46,7 @@ else:
''' '''
A mix-in for derivatives of DT_String.String that adds Zope security. A mix-in for derivatives of DT_String.String that adds Zope security.
''' '''
# Allow access to unprotected attributes # Allow access to unprotected attributes
DT_Util.TemplateDict.__allow_access_to_unprotected_subobjects__=1 DT_Util.TemplateDict.__allow_access_to_unprotected_subobjects__=1
...@@ -67,15 +67,15 @@ class DTMLSecurityAPI: ...@@ -67,15 +67,15 @@ class DTMLSecurityAPI:
"""Validate access. """Validate access.
Arguments: Arguments:
accessed -- the object that was being accessed accessed -- the object that was being accessed
container -- the object the value was found in container -- the object the value was found in
name -- The name used to access the value name -- The name used to access the value
value -- The value retrieved though the access. value -- The value retrieved though the access.
The arguments may be provided as keyword arguments. Some of these The arguments may be provided as keyword arguments. Some of these
arguments may be ommitted, however, the policy may reject access arguments may be ommitted, however, the policy may reject access
in some cases when arguments are ommitted. It is best to provide in some cases when arguments are ommitted. It is best to provide
...@@ -99,9 +99,9 @@ class DTMLSecurityAPI: ...@@ -99,9 +99,9 @@ class DTMLSecurityAPI:
the given object. the given object.
Arguments: Arguments:
permission -- A permission name permission -- A permission name
object -- The object being accessed according to the permission object -- The object being accessed according to the permission
""" """
return (SecurityManagement return (SecurityManagement
...@@ -127,4 +127,3 @@ class DTMLSecurityAPI: ...@@ -127,4 +127,3 @@ class DTMLSecurityAPI:
return r return r
DT_Util.TemplateDict.__dict__.update(DTMLSecurityAPI.__dict__) DT_Util.TemplateDict.__dict__.update(DTMLSecurityAPI.__dict__)
############################################################################## ##############################################################################
# #
# 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__='''Support for owned objects __doc__='''Support for owned objects
$Id: Owned.py,v 1.17 2002/06/12 18:14:39 shane Exp $''' $Id: Owned.py,v 1.18 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.17 $'[11:-2] __version__='$Revision: 1.18 $'[11:-2]
import Globals, urlparse, SpecialUsers, ExtensionClass import Globals, urlparse, SpecialUsers, ExtensionClass
from AccessControl import getSecurityManager, Unauthorized from AccessControl import getSecurityManager, Unauthorized
...@@ -39,14 +39,14 @@ class Owned(ExtensionClass.Base): ...@@ -39,14 +39,14 @@ class Owned(ExtensionClass.Base):
('manage_takeOwnership','manage_changeOwnershipType'), ('manage_takeOwnership','manage_changeOwnershipType'),
("Owner",)), ("Owner",)),
) )
manage_options=({'label': 'Ownership', manage_options=({'label': 'Ownership',
'action': 'manage_owner', 'action': 'manage_owner',
'help': ('OFSP','Ownership.stx'), 'help': ('OFSP','Ownership.stx'),
'filter': ownableFilter 'filter': ownableFilter
}, },
) )
manage_owner=Globals.DTMLFile('dtml/owner', globals()) manage_owner=Globals.DTMLFile('dtml/owner', globals())
def owner_info(self): def owner_info(self):
...@@ -60,7 +60,7 @@ class Owned(ExtensionClass.Base): ...@@ -60,7 +60,7 @@ class Owned(ExtensionClass.Base):
getSecurityManager().checkPermission('Take ownership', self) getSecurityManager().checkPermission('Take ownership', self)
} }
return d return d
getOwner__roles__=() getOwner__roles__=()
def getOwner(self, info=0, def getOwner(self, info=0,
aq_get=aq_get, None=None, aq_get=aq_get, None=None,
...@@ -108,7 +108,7 @@ class Owned(ExtensionClass.Base): ...@@ -108,7 +108,7 @@ class Owned(ExtensionClass.Base):
else: else:
# make ownership explicit # make ownership explicit
child._owner=new child._owner=new
if old is not UnownableOwner: if old is not UnownableOwner:
self._owner=new self._owner=new
...@@ -134,7 +134,7 @@ class Owned(ExtensionClass.Base): ...@@ -134,7 +134,7 @@ class Owned(ExtensionClass.Base):
if (want_referer != got_referer or security.calledByExecutable()): if (want_referer != got_referer or security.calledByExecutable()):
raise Unauthorized, ( raise Unauthorized, (
'manage_takeOwnership was called from an invalid context' 'manage_takeOwnership was called from an invalid context'
) )
self.changeOwnership(security.getUser(), recursive) self.changeOwnership(security.getUser(), recursive)
...@@ -159,7 +159,7 @@ class Owned(ExtensionClass.Base): ...@@ -159,7 +159,7 @@ class Owned(ExtensionClass.Base):
del self._owner del self._owner
if RESPONSE is not None: RESPONSE.redirect(REQUEST['HTTP_REFERER']) if RESPONSE is not None: RESPONSE.redirect(REQUEST['HTTP_REFERER'])
def _deleteOwnershipAfterAdd(self): def _deleteOwnershipAfterAdd(self):
# Only delete _owner if it is an instance attribute. # Only delete _owner if it is an instance attribute.
...@@ -172,7 +172,7 @@ class Owned(ExtensionClass.Base): ...@@ -172,7 +172,7 @@ class Owned(ExtensionClass.Base):
try: object._deleteOwnershipAfterAdd() try: object._deleteOwnershipAfterAdd()
except: pass except: pass
if s is None: object._p_deactivate() if s is None: object._p_deactivate()
def manage_fixupOwnershipAfterAdd(self): def manage_fixupOwnershipAfterAdd(self):
# Sigh, get the parent's _owner # Sigh, get the parent's _owner
...@@ -216,7 +216,7 @@ class Owned(ExtensionClass.Base): ...@@ -216,7 +216,7 @@ class Owned(ExtensionClass.Base):
except: pass except: pass
if s is None: object._p_deactivate() if s is None: object._p_deactivate()
Globals.default__class_init__(Owned) Globals.default__class_init__(Owned)
class EmergencyUserCannotOwn(Exception): class EmergencyUserCannotOwn(Exception):
...@@ -224,7 +224,7 @@ class EmergencyUserCannotOwn(Exception): ...@@ -224,7 +224,7 @@ class EmergencyUserCannotOwn(Exception):
class EditUnowned(Exception): class EditUnowned(Exception):
"Can't edit unowned executables" "Can't edit unowned executables"
def absattr(attr): def absattr(attr):
if callable(attr): return attr() if callable(attr): return attr()
...@@ -253,4 +253,3 @@ def ownerInfo(user, ...@@ -253,4 +253,3 @@ def ownerInfo(user,
path.reverse() path.reverse()
return path, uid return path, uid
############################################################################## ##############################################################################
# #
# 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__='''short description __doc__='''short description
$Id: Permission.py,v 1.9 2001/12/13 14:24:26 andreasjung Exp $''' $Id: Permission.py,v 1.10 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.9 $'[11:-2] __version__='$Revision: 1.10 $'[11:-2]
import string, Products, Globals import string, Products, Globals
...@@ -79,7 +79,7 @@ class Permission: ...@@ -79,7 +79,7 @@ class Permission:
if roles is None: return ['Manager','Anonymous'] if roles is None: return ['Manager','Anonymous']
if roles is _marker: return ['Manager'] if roles is _marker: return ['Manager']
return roles return roles
def setRoles(self, roles): def setRoles(self, roles):
...@@ -89,7 +89,7 @@ class Permission: ...@@ -89,7 +89,7 @@ class Permission:
if hasattr(obj, self._p): delattr(obj, self._p) if hasattr(obj, self._p): delattr(obj, self._p)
else: else:
setattr(obj, self._p, roles) setattr(obj, self._p, roles)
for name in self.data: for name in self.data:
if name=='': attr=obj if name=='': attr=obj
else: attr=getattr(obj, name) else: attr=getattr(obj, name)
...@@ -112,7 +112,7 @@ class Permission: ...@@ -112,7 +112,7 @@ class Permission:
if type(roles) is ListType: roles.append(role) if type(roles) is ListType: roles.append(role)
else: roles=roles+(role,) else: roles=roles+(role,)
self.setRoles(roles) self.setRoles(roles)
def __len__(self): return 1 def __len__(self): return 1
def __str__(self): return self.name def __str__(self): return self.name
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Permission Mapping """Permission Mapping
...@@ -40,14 +40,14 @@ class RoleManager: ...@@ -40,14 +40,14 @@ class RoleManager:
perms={} perms={}
for p in self.possible_permissions(): for p in self.possible_permissions():
perms[pname(p)]=p perms[pname(p)]=p
r=[] r=[]
a=r.append a=r.append
for ac_perms in self.ac_inherited_permissions(1): for ac_perms in self.ac_inherited_permissions(1):
p=perms.get(getPermissionMapping(ac_perms[0], wrapper), '') p=perms.get(getPermissionMapping(ac_perms[0], wrapper), '')
a({'permission_name': ac_perms[0], 'class_permission': p}) a({'permission_name': ac_perms[0], 'class_permission': p})
return r return r
def manage_setPermissionMapping(self, def manage_setPermissionMapping(self,
permission_names=[], permission_names=[],
class_permissions=[], REQUEST=None): class_permissions=[], REQUEST=None):
...@@ -66,7 +66,7 @@ class RoleManager: ...@@ -66,7 +66,7 @@ class RoleManager:
"""Attempted to map a permission to a permission, %s, """Attempted to map a permission to a permission, %s,
that is not valid. This should never happen. (Waaa). that is not valid. This should never happen. (Waaa).
""" % escape(p)) """ % escape(p))
setPermissionMapping(name, wrapper, p) setPermissionMapping(name, wrapper, p)
...@@ -74,7 +74,7 @@ class RoleManager: ...@@ -74,7 +74,7 @@ class RoleManager:
if REQUEST is not None: if REQUEST is not None:
return self.manage_access( return self.manage_access(
REQUEST, REQUEST,
manage_tabs_message='The permission mapping has been updated') manage_tabs_message='The permission mapping has been updated')
def _isBeingUsedAsAMethod(self, REQUEST =None, wannaBe=0): def _isBeingUsedAsAMethod(self, REQUEST =None, wannaBe=0):
...@@ -94,9 +94,9 @@ class RoleManager: ...@@ -94,9 +94,9 @@ class RoleManager:
p=getattr(self,'aq_parent',None) p=getattr(self,'aq_parent',None)
if p is None: return 0 # Not wrapped if p is None: return 0 # Not wrapped
base=getattr(p, 'aq_base', None) base=getattr(p, 'aq_base', None)
return type(base) is PermissionMapper return type(base) is PermissionMapper
def getPermissionMapping(name, obj, st=type('')): def getPermissionMapping(name, obj, st=type('')):
obj=getattr(obj, 'aq_base', obj) obj=getattr(obj, 'aq_base', obj)
name=pname(name) name=pname(name)
...@@ -114,13 +114,13 @@ class PM(ExtensionClass.Base): ...@@ -114,13 +114,13 @@ class PM(ExtensionClass.Base):
_View_Permission='_View_Permission' _View_Permission='_View_Permission'
_is_wrapperish = 1 _is_wrapperish = 1
def __getattr__(self, name): def __getattr__(self, name):
# We want to make sure that any non-explicitly set methods are # We want to make sure that any non-explicitly set methods are
# private! # private!
if name.startswith('_') and name.endswith("_Permission"): return '' if name.startswith('_') and name.endswith("_Permission"): return ''
raise AttributeError, escape(name) raise AttributeError, escape(name)
PermissionMapper=PM PermissionMapper=PM
def aqwrap(object, wrapper, parent): def aqwrap(object, wrapper, parent):
......
############################################################################## ##############################################################################
# #
# 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__='''Objects that implement Permission-based roles. __doc__='''Objects that implement Permission-based roles.
$Id: PermissionRole.py,v 1.15 2001/12/13 14:24:41 andreasjung Exp $''' $Id: PermissionRole.py,v 1.16 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.15 $'[11:-2] __version__='$Revision: 1.16 $'[11:-2]
_use_python_impl = 0 _use_python_impl = 0
import os import os
...@@ -132,7 +132,7 @@ if _use_python_impl: ...@@ -132,7 +132,7 @@ if _use_python_impl:
def __getitem__(self, i): def __getitem__(self, i):
try: try:
v=self._v v=self._v
except: except:
v=self._v=self.__of__(self._pa) v=self._v=self.__of__(self._pa)
del self._pa del self._pa
...@@ -141,13 +141,13 @@ if _use_python_impl: ...@@ -141,13 +141,13 @@ if _use_python_impl:
def __len__(self): def __len__(self):
try: try:
v=self._v v=self._v
except: except:
v=self._v=self.__of__(self._pa) v=self._v=self.__of__(self._pa)
del self._pa del self._pa
return len(v) return len(v)
############################################################################## ##############################################################################
# Test functions: # Test functions:
# #
...@@ -177,7 +177,7 @@ def main(): ...@@ -177,7 +177,7 @@ def main():
a._z_Permission=('zee',) a._z_Permission=('zee',)
a.b.c._y_Permission=('Manage',) a.b.c._y_Permission=('Manage',)
a.b._z_Permission=['also'] a.b._z_Permission=['also']
print a.x.__roles__, list(a.x.__roles__) print a.x.__roles__, list(a.x.__roles__)
print a.b.x.__roles__ print a.b.x.__roles__
print a.b.c.x.__roles__ print a.b.c.x.__roles__
...@@ -185,7 +185,7 @@ def main(): ...@@ -185,7 +185,7 @@ def main():
print a.b.q.x.__roles__ print a.b.q.x.__roles__
print a.b.c.q.x.__roles__ print a.b.c.q.x.__roles__
print print
print a.y.__roles__, list(a.y.__roles__) print a.y.__roles__, list(a.y.__roles__)
print a.b.y.__roles__ print a.b.y.__roles__
print a.b.c.y.__roles__ print a.b.c.y.__roles__
...@@ -193,7 +193,7 @@ def main(): ...@@ -193,7 +193,7 @@ def main():
print a.b.q.y.__roles__ print a.b.q.y.__roles__
print a.b.c.q.y.__roles__ print a.b.c.q.y.__roles__
print print
print a.z.__roles__, list(a.z.__roles__) print a.z.__roles__, list(a.z.__roles__)
print a.b.z.__roles__ print a.b.z.__roles__
print a.b.c.z.__roles__ print a.b.c.z.__roles__
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Constant definitions for built-in Zope permissions""" """Constant definitions for built-in Zope permissions"""
__version__='$Revision: 1.4 $'[11:-2] __version__='$Revision: 1.5 $'[11:-2]
access_contents_information='Access contents information' access_contents_information='Access contents information'
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Access control support""" """Access control support"""
__version__='$Revision: 1.54 $'[11:-2] __version__='$Revision: 1.55 $'[11:-2]
from Globals import DTMLFile, MessageDialog, Dictionary from Globals import DTMLFile, MessageDialog, Dictionary
...@@ -61,7 +61,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -61,7 +61,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
'filter': _isBeingUsedAsAMethod, 'filter': _isBeingUsedAsAMethod,
}, },
) )
__ac_roles__=('Manager', 'Owner', 'Anonymous', 'Authenticated') __ac_roles__=('Manager', 'Owner', 'Anonymous', 'Authenticated')
permissionMappingPossibleValues=Acquired permissionMappingPossibleValues=Acquired
...@@ -75,19 +75,19 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -75,19 +75,19 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
d={} d={}
perms=self.__ac_permissions__ perms=self.__ac_permissions__
for p in perms: d[p[0]]=None for p in perms: d[p[0]]=None
r=gather_permissions(self.__class__, [], d) r=gather_permissions(self.__class__, [], d)
if all: if all:
if hasattr(self, '_subobject_permissions'): if hasattr(self, '_subobject_permissions'):
for p in self._subobject_permissions(): for p in self._subobject_permissions():
pname=p[0] pname=p[0]
if not d.has_key(pname): if not d.has_key(pname):
d[pname]=1 d[pname]=1
r.append(p) r.append(p)
r=list(perms)+r r=list(perms)+r
r.sort() r.sort()
return tuple(r) return tuple(r)
def permission_settings(self): def permission_settings(self):
...@@ -147,12 +147,12 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -147,12 +147,12 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
else: p.setRoles(tuple(roles)) else: p.setRoles(tuple(roles))
if REQUEST is not None: return self.manage_access(REQUEST) if REQUEST is not None: return self.manage_access(REQUEST)
manage_permissionForm=DTMLFile('dtml/permissionEdit', globals(), manage_permissionForm=DTMLFile('dtml/permissionEdit', globals(),
management_view='Security', management_view='Security',
help_topic='Security_Manage-Permission.stx', help_topic='Security_Manage-Permission.stx',
help_product='OFSP') help_product='OFSP')
def manage_permission(self, permission_to_manage, def manage_permission(self, permission_to_manage,
roles=[], acquire=0, REQUEST=None): roles=[], acquire=0, REQUEST=None):
"""Change the settings for the given permission """Change the settings for the given permission
...@@ -172,13 +172,13 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -172,13 +172,13 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
return return
raise 'Invalid Permission', ( raise 'Invalid Permission', (
"The permission <em>%s</em> is invalid." % "The permission <em>%s</em> is invalid." %
escape(permission_to_manage)) escape(permission_to_manage))
_normal_manage_access=DTMLFile('dtml/access', globals()) _normal_manage_access=DTMLFile('dtml/access', globals())
_method_manage_access=DTMLFile('dtml/methodAccess', globals()) _method_manage_access=DTMLFile('dtml/methodAccess', globals())
def manage_access(self, REQUEST, **kw): def manage_access(self, REQUEST, **kw):
"Return an interface for making permissions settings" "Return an interface for making permissions settings"
if hasattr(self, '_isBeingUsedAsAMethod') and \ if hasattr(self, '_isBeingUsedAsAMethod') and \
...@@ -186,7 +186,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -186,7 +186,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
return apply(self._method_manage_access,(), kw) return apply(self._method_manage_access,(), kw)
else: else:
return apply(self._normal_manage_access,(), kw) return apply(self._normal_manage_access,(), kw)
def manage_changePermissions(self, REQUEST): def manage_changePermissions(self, REQUEST):
"Change all permissions settings, called by management screen" "Change all permissions settings, called by management screen"
self._isBeingUsedAsAMethod(REQUEST, 0) self._isBeingUsedAsAMethod(REQUEST, 0)
...@@ -244,7 +244,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -244,7 +244,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
'selected': role in roles and 'SELECTED' or '', 'selected': role in roles and 'SELECTED' or '',
}, },
valid_roles) valid_roles)
raise 'Invalid Permission', ( raise 'Invalid Permission', (
"The permission <em>%s</em> is invalid." % escape(permission)) "The permission <em>%s</em> is invalid." % escape(permission))
...@@ -256,7 +256,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -256,7 +256,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
p=Permission(name,value,self) p=Permission(name,value,self)
roles=p.getRoles() roles=p.getRoles()
return type(roles) is ListType and 'CHECKED' or '' return type(roles) is ListType and 'CHECKED' or ''
raise 'Invalid Permission', ( raise 'Invalid Permission', (
"The permission <em>%s</em> is invalid." % escape(permission)) "The permission <em>%s</em> is invalid." % escape(permission))
...@@ -268,7 +268,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -268,7 +268,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
# of a particular object (and its children). When a user is given # of a particular object (and its children). When a user is given
# extra roles in a particular object, an entry for that user is made # extra roles in a particular object, an entry for that user is made
# in the __ac_local_roles__ dict containing the extra roles. # in the __ac_local_roles__ dict containing the extra roles.
__ac_local_roles__=None __ac_local_roles__=None
manage_listLocalRoles=DTMLFile('dtml/listLocalRoles', globals(), manage_listLocalRoles=DTMLFile('dtml/listLocalRoles', globals(),
...@@ -384,13 +384,13 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -384,13 +384,13 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
if key.find('__roles__') >= 0: if key.find('__roles__') >= 0:
_add({'name': key, 'value': value, 'class': 0}) _add({'name': key, 'value': value, 'class': 0})
if hasattr(value, '__roles__'): if hasattr(value, '__roles__'):
_add({'name': '%s.__roles__' % key, 'value': value.__roles__, _add({'name': '%s.__roles__' % key, 'value': value.__roles__,
'class': 0}) 'class': 0})
for key, value in clas.items(): for key, value in clas.items():
if key.find('__roles__') >= 0: if key.find('__roles__') >= 0:
_add({'name': key, 'value': value, 'class' : 1}) _add({'name': key, 'value': value, 'class' : 1})
if hasattr(value, '__roles__'): if hasattr(value, '__roles__'):
_add({'name': '%s.__roles__' % key, 'value': value.__roles__, _add({'name': '%s.__roles__' % key, 'value': value.__roles__,
'class': 1}) 'class': 1})
return data return data
...@@ -479,7 +479,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -479,7 +479,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
def _has_user_defined_role(self, role): def _has_user_defined_role(self, role):
return role in self.__ac_roles__ return role in self.__ac_roles__
# Compatibility names only!! # Compatibility names only!!
...@@ -505,7 +505,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager): ...@@ -505,7 +505,7 @@ class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
d=d.keys() d=d.keys()
d.sort() d.sort()
return d return d
...@@ -562,4 +562,3 @@ def gather_permissions(klass, result, seen): ...@@ -562,4 +562,3 @@ def gather_permissions(klass, result, seen):
seen[name]=None seen[name]=None
gather_permissions(base, result, seen) gather_permissions(base, result, seen)
return result return result
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""SecurityInfo objects and access control constants. """SecurityInfo objects and access control constants.
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
More information on using SecurityInfo and guide to Zope security More information on using SecurityInfo and guide to Zope security
for developers can be found in the dev.zope.org "Declarative Security" for developers can be found in the dev.zope.org "Declarative Security"
project: project:
http://dev.zope.org/Wikis/DevSite/Projects/DeclarativeSecurity http://dev.zope.org/Wikis/DevSite/Projects/DeclarativeSecurity
While SecurityInfo objects largely remove the need for Python While SecurityInfo objects largely remove the need for Python
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
must set __roles__ attributes directly. (the constants are also must set __roles__ attributes directly. (the constants are also
accessible from the AccessControl namespace). The defined access accessible from the AccessControl namespace). The defined access
control constants and their meanings are: control constants and their meanings are:
ACCESS_PUBLIC: accessible from restricted code and possibly ACCESS_PUBLIC: accessible from restricted code and possibly
through the web (if object has a docstring) through the web (if object has a docstring)
...@@ -58,7 +58,7 @@ class SecurityInfo(Acquisition.Implicit): ...@@ -58,7 +58,7 @@ class SecurityInfo(Acquisition.Implicit):
"""Encapsulate security information.""" """Encapsulate security information."""
__security_info__ = 1 __security_info__ = 1
__roles__ = ACCESS_PRIVATE __roles__ = ACCESS_PRIVATE
def __init__(self): def __init__(self):
...@@ -76,7 +76,7 @@ class SecurityInfo(Acquisition.Implicit): ...@@ -76,7 +76,7 @@ class SecurityInfo(Acquisition.Implicit):
self._warnings = 1 self._warnings = 1
self.names[name] = access self.names[name] = access
declarePublic__roles__=ACCESS_PRIVATE declarePublic__roles__=ACCESS_PRIVATE
def declarePublic(self, *names): def declarePublic(self, *names):
"""Declare names to be publicly accessible.""" """Declare names to be publicly accessible."""
self._setaccess(names, ACCESS_PUBLIC) self._setaccess(names, ACCESS_PUBLIC)
...@@ -91,7 +91,7 @@ class SecurityInfo(Acquisition.Implicit): ...@@ -91,7 +91,7 @@ class SecurityInfo(Acquisition.Implicit):
"""Declare names to be associated with a permission.""" """Declare names to be associated with a permission."""
self._setaccess(names, permission_name) self._setaccess(names, permission_name)
declareObjectPublic__roles__=ACCESS_PRIVATE declareObjectPublic__roles__=ACCESS_PRIVATE
def declareObjectPublic(self): def declareObjectPublic(self):
"""Declare the object to be publicly accessible.""" """Declare the object to be publicly accessible."""
self._setaccess((), ACCESS_PUBLIC) self._setaccess((), ACCESS_PUBLIC)
...@@ -144,7 +144,7 @@ class ClassSecurityInfo(SecurityInfo): ...@@ -144,7 +144,7 @@ class ClassSecurityInfo(SecurityInfo):
apply__roles__ = ACCESS_PRIVATE apply__roles__ = ACCESS_PRIVATE
def apply(self, classobj): def apply(self, classobj):
"""Apply security information to the given class object.""" """Apply security information to the given class object."""
dict = classobj.__dict__ dict = classobj.__dict__
# Check the class for an existing __ac_permissions__ and # Check the class for an existing __ac_permissions__ and
...@@ -244,13 +244,13 @@ class _ModuleSecurityInfo(SecurityInfo): ...@@ -244,13 +244,13 @@ class _ModuleSecurityInfo(SecurityInfo):
access = self.names.get(name, _marker) access = self.names.get(name, _marker)
if access is not _marker: if access is not _marker:
return access == ACCESS_PUBLIC return access == ACCESS_PUBLIC
return getattr(self, 'access', 0) return getattr(self, 'access', 0)
apply__roles__ = ACCESS_PRIVATE apply__roles__ = ACCESS_PRIVATE
def apply(self, dict): def apply(self, dict):
"""Apply security information to the given module dict.""" """Apply security information to the given module dict."""
# Start with default attribute access policy # Start with default attribute access policy
access = getattr(self, 'access', _marker) access = getattr(self, 'access', _marker)
if access is not _marker or len(self.names): if access is not _marker or len(self.names):
......
############################################################################## ##############################################################################
# #
# 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__='''short description __doc__='''short description
$Id: SecurityManagement.py,v 1.6 2001/11/28 15:50:51 matt Exp $''' $Id: SecurityManagement.py,v 1.7 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
def getSecurityManager(): def getSecurityManager():
"""Get a security manager, for the current thread. """Get a security manager, for the current thread.
...@@ -26,7 +26,7 @@ def getSecurityManager(): ...@@ -26,7 +26,7 @@ def getSecurityManager():
thread_id, thread_id,
SecurityContext(SpecialUsers.nobody)) SecurityContext(SpecialUsers.nobody))
_managers[thread_id]=manager _managers[thread_id]=manager
return manager return manager
import SpecialUsers import SpecialUsers
...@@ -49,10 +49,10 @@ def newSecurityManager(request, user): ...@@ -49,10 +49,10 @@ def newSecurityManager(request, user):
def noSecurityManager(): def noSecurityManager():
try: del _managers[get_ident()] try: del _managers[get_ident()]
except: pass except: pass
def setSecurityPolicy(aSecurityPolicy): def setSecurityPolicy(aSecurityPolicy):
"""Set the system default security policy. """Set the system default security policy.
This method should only be caused by system startup code. It should This method should only be caused by system startup code. It should
never, for example, be called during a web request. never, for example, be called during a web request.
...@@ -68,5 +68,3 @@ class SecurityContext: ...@@ -68,5 +68,3 @@ class SecurityContext:
self.stack=[] self.stack=[]
self.user=user self.user=user
self.objectCache = {} self.objectCache = {}
############################################################################## ##############################################################################
# #
# 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__='''short description __doc__='''short description
$Id: SecurityManager.py,v 1.12 2001/12/13 14:23:44 andreasjung Exp $''' $Id: SecurityManager.py,v 1.13 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.12 $'[11:-2] __version__='$Revision: 1.13 $'[11:-2]
import ZopeSecurityPolicy, os import ZopeSecurityPolicy, os
...@@ -30,7 +30,7 @@ else: authenticated=1 ...@@ -30,7 +30,7 @@ else: authenticated=1
_defaultPolicy=ZopeSecurityPolicy.ZopeSecurityPolicy(ownerous=ownerous, _defaultPolicy=ZopeSecurityPolicy.ZopeSecurityPolicy(ownerous=ownerous,
authenticated=authenticated) authenticated=authenticated)
def setSecurityPolicy(aSecurityPolicy): def setSecurityPolicy(aSecurityPolicy):
"""Set the system default security policy. """Set the system default security policy.
This method should only be caused by system startup code. It should This method should only be caused by system startup code. It should
never, for example, be called during a web request. never, for example, be called during a web request.
......
############################################################################## ##############################################################################
# #
# 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__='''Collect rules for access to objects that don\'t have roles. __doc__='''Collect rules for access to objects that don\'t have roles.
$Id: SimpleObjectPolicies.py,v 1.11 2002/03/12 19:37:14 evan Exp $''' $Id: SimpleObjectPolicies.py,v 1.12 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.11 $'[11:-2] __version__='$Revision: 1.12 $'[11:-2]
_noroles=[] # this is imported from various places _noroles=[] # this is imported from various places
...@@ -58,4 +58,3 @@ def allow_type(Type, allowed=1): ...@@ -58,4 +58,3 @@ def allow_type(Type, allowed=1):
if not (isinstance(allowed, IntType) or isinstance(allowed, DictType)): if not (isinstance(allowed, IntType) or isinstance(allowed, DictType)):
raise ValueError, "The 'allowed' argument must be an int or dict." raise ValueError, "The 'allowed' argument must be an int or dict."
ContainerAssertions[Type] = allowed ContainerAssertions[Type] = allowed
############################################################################## ##############################################################################
# #
# 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__='''Place to find special users __doc__='''Place to find special users
This is needed to avoid a circular import problem. This is needed to avoid a circular import problem.
$Id: SpecialUsers.py,v 1.3 2001/11/28 15:50:52 matt Exp $''' $Id: SpecialUsers.py,v 1.4 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.3 $'[11:-2] __version__='$Revision: 1.4 $'[11:-2]
This diff is collapsed.
############################################################################# #############################################################################
# #
# 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,10 +8,10 @@ ...@@ -8,10 +8,10 @@
# 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
# #
############################################################################## ##############################################################################
__version__='$Revision: 1.10 $'[11:-2] __version__='$Revision: 1.11 $'[11:-2]
from RestrictedPython.Guards import safe_builtins, _full_read_guard, \ from RestrictedPython.Guards import safe_builtins, _full_read_guard, \
full_write_guard full_write_guard
......
############################################################################## ##############################################################################
# #
# 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__='''Define Zope\'s default security policy __doc__='''Define Zope\'s default security policy
$Id: ZopeSecurityPolicy.py,v 1.18 2002/01/11 17:14:27 evan Exp $''' $Id: ZopeSecurityPolicy.py,v 1.19 2002/08/14 21:29:07 mj Exp $'''
__version__='$Revision: 1.18 $'[11:-2] __version__='$Revision: 1.19 $'[11:-2]
_use_python_impl = 0 _use_python_impl = 0
...@@ -59,7 +59,7 @@ if _use_python_impl: ...@@ -59,7 +59,7 @@ if _use_python_impl:
The default is true. The default is true.
authenticated -- Allow access to resources based on the authenticated -- Allow access to resources based on the
privaledges of the authenticated user. privaledges of the authenticated user.
The argument must have a truth value. The argument must have a truth value.
The default is true. The default is true.
...@@ -70,7 +70,7 @@ if _use_python_impl: ...@@ -70,7 +70,7 @@ if _use_python_impl:
clients allow only public access and other clients allow only public access and other
clients allow full management. clients allow full management.
""" """
self._ownerous=ownerous self._ownerous=ownerous
self._authenticated=authenticated self._authenticated=authenticated
......
############################################################################## ##############################################################################
# #
# 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 unauthorized import Unauthorized from unauthorized import Unauthorized
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
class ResultObject: class ResultObject:
""" result object used for keeping results from the """ result object used for keeping results from the
ZPublisher.Zope() calls ZPublisher.Zope() calls
$Id: ResultObject.py,v 1.3 2001/11/28 15:50:52 matt Exp $ $Id: ResultObject.py,v 1.4 2002/08/14 21:27:32 mj Exp $
""" """
def __str__(self,expected=-1,with_output=1): def __str__(self,expected=-1,with_output=1):
...@@ -31,9 +31,8 @@ class ResultObject: ...@@ -31,9 +31,8 @@ class ResultObject:
s+= "\n" s+= "\n"
return s return s
__repr__ = __str__ __repr__ = __str__
def __call__(self,expected=-1): def __call__(self,expected=-1):
return self.__str__(expected) return self.__str__(expected)
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
...@@ -38,8 +38,8 @@ __bobo_before__=AccessControl.SecurityManagement.noSecurityManager ...@@ -38,8 +38,8 @@ __bobo_before__=AccessControl.SecurityManagement.noSecurityManager
class SecurityBase(unittest.TestCase) : class SecurityBase(unittest.TestCase) :
""" Base class for all security tests """ Base class for all security tests
$Id: SecurityBase.py,v 1.6 2001/11/28 15:50:52 matt Exp $ $Id: SecurityBase.py,v 1.7 2002/08/14 21:27:32 mj Exp $
""" """
status_regex = re.compile("Status: ([0-9]{1,4}) (.*)",re.I)\ status_regex = re.compile("Status: ([0-9]{1,4}) (.*)",re.I)\
...@@ -66,7 +66,7 @@ class SecurityBase(unittest.TestCase) : ...@@ -66,7 +66,7 @@ class SecurityBase(unittest.TestCase) :
if obj.meta_type in ['Folder','TestFolder']: if obj.meta_type in ['Folder','TestFolder']:
folderObjs.append(obj) folderObjs.append(obj)
else: else:
print ' '*(1+len(root.getPhysicalPath())),obj.getId(), print ' '*(1+len(root.getPhysicalPath())),obj.getId(),
print getattr(obj,"__roles__",(None,)) print getattr(obj,"__roles__",(None,))
...@@ -82,11 +82,11 @@ class SecurityBase(unittest.TestCase) : ...@@ -82,11 +82,11 @@ class SecurityBase(unittest.TestCase) :
""" permission check on an objects for a given user. """ permission check on an objects for a given user.
-- 'user' is a user object as returned from a user folder -- 'user' is a user object as returned from a user folder
-- 'hier' is the path to the object in the notation 'f1.f2.f3.obj' -- 'hier' is the path to the object in the notation 'f1.f2.f3.obj'
-- 'perm' is a permission name -- 'perm' is a permission name
-- 'expected' is either 0 or 1 -- 'expected' is either 0 or 1
""" """
...@@ -95,7 +95,7 @@ class SecurityBase(unittest.TestCase) : ...@@ -95,7 +95,7 @@ class SecurityBase(unittest.TestCase) :
res = user.has_permission(perm,obj) res = user.has_permission(perm,obj)
if res != expected: if res != expected:
raise AssertionError, \ raise AssertionError, \
self._perm_debug (s,perm,res,expected) self._perm_debug (s,perm,res,expected)
...@@ -108,7 +108,7 @@ class SecurityBase(unittest.TestCase) : ...@@ -108,7 +108,7 @@ class SecurityBase(unittest.TestCase) :
-- 'expected_roles' is a sequence of expected roles -- 'expected_roles' is a sequence of expected roles
""" """
s = "self.root.%s.__roles__" % hier s = "self.root.%s.__roles__" % hier
roles = eval(s) roles = eval(s)
...@@ -127,18 +127,18 @@ class SecurityBase(unittest.TestCase) : ...@@ -127,18 +127,18 @@ class SecurityBase(unittest.TestCase) :
same = 1 same = 1
if not same: if not same:
raise AssertionError, self._roles_debug(hier,roles,expected_roles) raise AssertionError, self._roles_debug(hier,roles,expected_roles)
def _checkRequest(self,*args,**kw): def _checkRequest(self,*args,**kw):
""" perform a ZPublisher request """ """ perform a ZPublisher request """
expected_code = kw.get('expected',200) expected_code = kw.get('expected',200)
del kw['expected'] del kw['expected']
res = apply(self._request,args,kw) res = apply(self._request,args,kw)
if expected_code != res.code: if expected_code != res.code:
raise AssertionError, \ raise AssertionError, \
self._request_debug(res,expected_code,args,kw) self._request_debug(res,expected_code,args,kw)
################################################################ ################################################################
...@@ -147,12 +147,12 @@ class SecurityBase(unittest.TestCase) : ...@@ -147,12 +147,12 @@ class SecurityBase(unittest.TestCase) :
def _perm_debug(self, obj , perm, res, expected): def _perm_debug(self, obj , perm, res, expected):
s+= 'Object: %s' % obj s+= 'Object: %s' % obj
s+= ', Permission: %s' % perm s+= ', Permission: %s' % perm
s+= ', has permission: %s' % res s+= ', has permission: %s' % res
s+= ', expected: %s' % expected s+= ', expected: %s' % expected
return s return s
def _roles_debug(self,hier,got_roles,expected_roles): def _roles_debug(self,hier,got_roles,expected_roles):
...@@ -164,13 +164,13 @@ class SecurityBase(unittest.TestCase) : ...@@ -164,13 +164,13 @@ class SecurityBase(unittest.TestCase) :
def _request_debug(self,res,expected,args,kw): def _request_debug(self,res,expected,args,kw):
s = 'Args: %s' % str(args) s = 'Args: %s' % str(args)
s+= ', KW: %s' % str(kw) s+= ', KW: %s' % str(kw)
s+= '\n%s\n' % res.__str__(with_output=0,expected=expected) s+= '\n%s\n' % res.__str__(with_output=0,expected=expected)
return s return s
def _request(self,*args,**kw): def _request(self,*args,**kw):
""" perform a Zope request """ """ perform a Zope request """
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
###################################################################### ######################################################################
...@@ -42,5 +42,3 @@ if not sys.modules.has_key('Testing'): ...@@ -42,5 +42,3 @@ if not sys.modules.has_key('Testing'):
import Testing, unittest import Testing, unittest
execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py')) execfile(os.path.join(os.path.split(Testing.__file__)[0], 'common.py'))
...@@ -3,17 +3,17 @@ ...@@ -3,17 +3,17 @@
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
# $Id: regressionSecurity.py,v 1.4 2001/11/28 15:50:52 matt Exp $ # $Id: regressionSecurity.py,v 1.5 2002/08/14 21:27:32 mj Exp $
import os, sys, unittest import os, sys, unittest
...@@ -91,9 +91,9 @@ class TestFolder(Folder): ...@@ -91,9 +91,9 @@ class TestFolder(Folder):
def __init__(self,id): def __init__(self,id):
self.id = id self.id = id
def getId(self): return self.id
def getId(self): return self.id
meta_type = 'TestFolder' meta_type = 'TestFolder'
...@@ -154,7 +154,7 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase): ...@@ -154,7 +154,7 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase):
for user in USERS: for user in USERS:
try: acl._delUsers( user.username ) try: acl._delUsers( user.username )
except: pass except: pass
for user in USERS: for user in USERS:
acl._addUser(user.username,user.password,user.password, acl._addUser(user.username,user.password,user.password,
user.roles, []) user.roles, [])
...@@ -162,7 +162,7 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase): ...@@ -162,7 +162,7 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase):
# try to remove old crap # try to remove old crap
if 'test' in self.root.objectIds(): if 'test' in self.root.objectIds():
self.root._delObject('test') self.root._delObject('test')
# setup Folder hierarchy # setup Folder hierarchy
...@@ -185,12 +185,12 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase): ...@@ -185,12 +185,12 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase):
def testNobody(self): def testNobody(self):
""" check permissions for nobody user """ """ check permissions for nobody user """
self._checkPermission(nobody,'test.f1', 'View',1) self._checkPermission(nobody,'test.f1', 'View',1)
self._checkPermission(nobody,'test.f2', 'View',1) self._checkPermission(nobody,'test.f2', 'View',1)
self._checkPermission(nobody,'test.f2.f3','View',1) self._checkPermission(nobody,'test.f2.f3','View',1)
self._checkPermission(nobody,'test.f1', MAGIC_PERMISSION1, None) self._checkPermission(nobody,'test.f1', MAGIC_PERMISSION1, None)
self._checkPermission(nobody,'test.f2', MAGIC_PERMISSION1, None) self._checkPermission(nobody,'test.f2', MAGIC_PERMISSION1, None)
self._checkPermission(nobody,'test.f2.f3',MAGIC_PERMISSION1, None) self._checkPermission(nobody,'test.f2.f3',MAGIC_PERMISSION1, None)
def testPermissionAccess(self): def testPermissionAccess(self):
...@@ -242,7 +242,7 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase): ...@@ -242,7 +242,7 @@ class AVeryBasicSecurityTest(SecurityBase.SecurityBase):
def test_suite(): def test_suite():
return unittest.makeSuite(AVeryBasicSecurityTest) return unittest.makeSuite(AVeryBasicSecurityTest)
def main(): def main():
unittest.TextTestRunner().run(test_suite()) unittest.TextTestRunner().run(test_suite())
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Tests for the DeprecationWarning thrown by accessing hasRole """Tests for the DeprecationWarning thrown by accessing hasRole
...@@ -17,8 +16,8 @@ To be removed together with the API in due time. ...@@ -17,8 +16,8 @@ To be removed together with the API in due time.
""" """
__rcs_id__='$Id: testDeprecatedAPI.py,v 1.3 2001/11/28 15:50:52 matt Exp $' __rcs_id__='$Id: testDeprecatedAPI.py,v 1.4 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.3 $'[11:-2] __version__='$Revision: 1.4 $'[11:-2]
import ZODB # Sigh. Persistent needs to be set, so we import ZODB. import ZODB # Sigh. Persistent needs to be set, so we import ZODB.
from AccessControl import User from AccessControl import User
...@@ -29,7 +28,7 @@ class DeprecatedAPI(unittest.TestCase): ...@@ -29,7 +28,7 @@ class DeprecatedAPI(unittest.TestCase):
# We test for warnings by turning them into exceptions # We test for warnings by turning them into exceptions
warnings.filterwarnings('error', category=DeprecationWarning, warnings.filterwarnings('error', category=DeprecationWarning,
module='AccessControl') module='AccessControl')
def testDeprecatedHasRole(self): def testDeprecatedHasRole(self):
"""hasRole has been deprecated, we expect a warning.""" """hasRole has been deprecated, we expect a warning."""
try: try:
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Module Import Tests """Module Import Tests
""" """
__rcs_id__='$Id: testModuleSecurity.py,v 1.2 2002/01/11 17:14:27 evan Exp $' __rcs_id__='$Id: testModuleSecurity.py,v 1.3 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.2 $'[11:-2] __version__='$Revision: 1.3 $'[11:-2]
import os, sys, unittest import os, sys, unittest
...@@ -65,7 +65,7 @@ class SecurityTests(unittest.TestCase): ...@@ -65,7 +65,7 @@ class SecurityTests(unittest.TestCase):
for fromlist in (), ('pub',): for fromlist in (), ('pub',):
self.assertAuth( self.assertAuth(
'AccessControl.tests.public_module%s' % name, 'AccessControl.tests.public_module%s' % name,
fromlist) fromlist)
def test_suite(): def test_suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Test of AuthEncoding """Test of AuthEncoding
""" """
__rcs_id__='$Id: testPasswordDigest.py,v 1.3 2001/11/28 15:50:52 matt Exp $' __rcs_id__='$Id: testPasswordDigest.py,v 1.4 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.3 $'[11:-2] __version__='$Revision: 1.4 $'[11:-2]
import os, sys, unittest import os, sys, unittest
...@@ -68,7 +68,7 @@ class PasswordDigestTests (unittest.TestCase): ...@@ -68,7 +68,7 @@ class PasswordDigestTests (unittest.TestCase):
# crypt truncates passwords and would fail these tests. # crypt truncates passwords and would fail these tests.
assert not AuthEncoding.pw_validate(enc, pw[:-2]) assert not AuthEncoding.pw_validate(enc, pw[:-2])
assert not AuthEncoding.pw_validate(enc, pw[2:]) assert not AuthEncoding.pw_validate(enc, pw[2:])
def testBlankPassword(self): def testBlankPassword(self):
pw = '' pw = ''
for id in AuthEncoding.listSchemes(): for id in AuthEncoding.listSchemes():
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Tests of PermissionRole """Tests of PermissionRole
""" """
__rcs_id__='$Id: testPermissionRole.py,v 1.2 2001/11/28 15:50:52 matt Exp $' __rcs_id__='$Id: testPermissionRole.py,v 1.3 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.2 $'[11:-2] __version__='$Revision: 1.3 $'[11:-2]
import os, sys, unittest import os, sys, unittest
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Document Template Tests """Document Template Tests
""" """
__rcs_id__='$Id: testSecurity.py,v 1.9 2002/04/03 20:59:49 shane Exp $' __rcs_id__='$Id: testSecurity.py,v 1.10 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.9 $'[11:-2] __version__='$Revision: 1.10 $'[11:-2]
import os, sys, unittest import os, sys, unittest
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""User folder tests """User folder tests
""" """
__rcs_id__='$Id: testUserFolder.py,v 1.4 2001/11/28 15:50:52 matt Exp $' __rcs_id__='$Id: testUserFolder.py,v 1.5 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.4 $'[11:-2] __version__='$Revision: 1.5 $'[11:-2]
import os, sys, unittest import os, sys, unittest
...@@ -39,7 +39,7 @@ class SecurityTests (DTMLTests): ...@@ -39,7 +39,7 @@ class SecurityTests (DTMLTests):
self.acl_users = self self.acl_users = self
for i in xrange(count): for i in xrange(count):
self.users.append("Nobody") self.users.append("Nobody")
def getUsers(self): def getUsers(self):
return self.users return self.users
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Tests of ZopeSecurityPolicy """Tests of ZopeSecurityPolicy
""" """
__rcs_id__='$Id: testZopeSecurityPolicy.py,v 1.4 2002/01/11 17:14:27 evan Exp $' __rcs_id__='$Id: testZopeSecurityPolicy.py,v 1.5 2002/08/14 21:28:08 mj Exp $'
__version__='$Revision: 1.4 $'[11:-2] __version__='$Revision: 1.5 $'[11:-2]
import os, sys, unittest import os, sys, unittest
...@@ -216,7 +216,7 @@ class ZopeSecurityPolicyTests (unittest.TestCase): ...@@ -216,7 +216,7 @@ class ZopeSecurityPolicyTests (unittest.TestCase):
o_context = SecurityContext(self.uf.getUserById('theowner')) o_context = SecurityContext(self.uf.getUserById('theowner'))
v = self.policy.checkPermission('View', r_item, o_context) v = self.policy.checkPermission('View', r_item, o_context)
assert v, '_View_Permission should grant access to theowner' assert v, '_View_Permission should grant access to theowner'
def testAqNames(self): def testAqNames(self):
policy = self.policy policy = self.policy
assert not policy.validate('', '', 'aq_self', '', None) assert not policy.validate('', '', 'aq_self', '', None)
...@@ -255,4 +255,3 @@ def main(): ...@@ -255,4 +255,3 @@ def main():
if __name__ == '__main__': if __name__ == '__main__':
main() main()
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Access control exceptions """Access control exceptions
""" """
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
import zExceptions import zExceptions
class Unauthorized(zExceptions.Unauthorized): class Unauthorized(zExceptions.Unauthorized):
def getValueName(self): def getValueName(self):
v=self.value v=self.value
n=getattr(v, 'getId', v) n=getattr(v, 'getId', v)
...@@ -31,4 +31,3 @@ class Unauthorized(zExceptions.Unauthorized): ...@@ -31,4 +31,3 @@ class Unauthorized(zExceptions.Unauthorized):
c = getattr(v, '__class__', type(v)) c = getattr(v, '__class__', type(v))
c = getattr(c, '__name__', 'object') c = getattr(c, '__name__', 'object')
return "a particular %s" % c return "a particular %s" % c
############################################################################## ##############################################################################
# #
# 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__="""System management components""" __doc__="""System management components"""
__version__='$Revision: 1.80 $'[11:-2] __version__='$Revision: 1.81 $'[11:-2]
import sys,os,time,Globals, Acquisition, os, Undo import sys,os,time,Globals, Acquisition, os, Undo
...@@ -82,7 +82,7 @@ class VersionManager(Fake, SimpleItem.Item, Acquisition.Implicit): ...@@ -82,7 +82,7 @@ class VersionManager(Fake, SimpleItem.Item, Acquisition.Implicit):
'help':('OFSP','Version-Management_Version.stx')}, 'help':('OFSP','Version-Management_Version.stx')},
) )
) )
Globals.default__class_init__(VersionManager) Globals.default__class_init__(VersionManager)
...@@ -110,7 +110,7 @@ class DebugManager(Fake, SimpleItem.Item, Acquisition.Implicit): ...@@ -110,7 +110,7 @@ class DebugManager(Fake, SimpleItem.Item, Acquisition.Implicit):
) )
manage_debug=DTMLFile('dtml/debug', globals()) manage_debug=DTMLFile('dtml/debug', globals())
def refcount(self, n=None, t=(type(Fake), type(Acquisition.Implicit))): def refcount(self, n=None, t=(type(Fake), type(Acquisition.Implicit))):
# return class reference info # return class reference info
dict={} dict={}
...@@ -212,7 +212,7 @@ class ApplicationManager(Folder,CacheManager): ...@@ -212,7 +212,7 @@ class ApplicationManager(Folder,CacheManager):
def version_txt(self): def version_txt(self):
if not hasattr(self, '_v_version_txt'): if not hasattr(self, '_v_version_txt'):
self._v_version_txt=version_txt() self._v_version_txt=version_txt()
return self._v_version_txt return self._v_version_txt
def sys_version(self): return sys.version def sys_version(self): return sys.version
...@@ -238,7 +238,7 @@ class ApplicationManager(Folder,CacheManager): ...@@ -238,7 +238,7 @@ class ApplicationManager(Folder,CacheManager):
) )
+Undo.UndoSupport.manage_options +Undo.UndoSupport.manage_options
) )
id ='Control_Panel' id ='Control_Panel'
name=title='Control Panel' name=title='Control Panel'
meta_type ='Control Panel' meta_type ='Control Panel'
...@@ -284,13 +284,13 @@ class ApplicationManager(Folder,CacheManager): ...@@ -284,13 +284,13 @@ class ApplicationManager(Folder,CacheManager):
raise 'Redirect', URL2+'/manage' raise 'Redirect', URL2+'/manage'
def process_time(self): def process_time(self):
s=int(time.time())-self.process_start s=int(time.time())-self.process_start
d=int(s/86400) d=int(s/86400)
s=s-(d*86400) s=s-(d*86400)
h=int(s/3600) h=int(s/3600)
s=s-(h*3600) s=s-(h*3600)
m=int(s/60) m=int(s/60)
s=s-(m*60) s=s-(m*60)
d=d and ('%d day%s' % (d, (d != 1 and 's' or ''))) or '' d=d and ('%d day%s' % (d, (d != 1 and 's' or ''))) or ''
h=h and ('%d hour%s' % (h, (h != 1 and 's' or ''))) or '' h=h and ('%d hour%s' % (h, (h != 1 and 's' or ''))) or ''
m=m and ('%d min' % m) or '' m=m and ('%d min' % m) or ''
...@@ -315,7 +315,7 @@ class ApplicationManager(Folder,CacheManager): ...@@ -315,7 +315,7 @@ class ApplicationManager(Folder,CacheManager):
if hasattr(sys, 'ZMANAGED'): if hasattr(sys, 'ZMANAGED'):
manage_restartable=1 manage_restartable=1
def manage_restart(self, URL1): def manage_restart(self, URL1):
"""Shut down the application""" """Shut down the application"""
...@@ -412,7 +412,7 @@ class ApplicationManager(Folder,CacheManager): ...@@ -412,7 +412,7 @@ class ApplicationManager(Folder,CacheManager):
db.abortVersion(v) db.abortVersion(v)
if REQUEST is not None: if REQUEST is not None:
REQUEST['RESPONSE'].redirect(REQUEST['URL1']+'/manage_main') REQUEST['RESPONSE'].redirect(REQUEST['URL1']+'/manage_main')
def getSOFTWARE_HOME(self): def getSOFTWARE_HOME(self):
return SOFTWARE_HOME return SOFTWARE_HOME
...@@ -441,4 +441,3 @@ class ApplicationManager(Folder,CacheManager): ...@@ -441,4 +441,3 @@ class ApplicationManager(Folder,CacheManager):
self._objects = tuple(lst) self._objects = tuple(lst)
return Folder.objectIds(self, spec) return Folder.objectIds(self, spec)
############################################################################## ##############################################################################
# #
# 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__='''Cache management support __doc__='''Cache management support
$Id: CacheManager.py,v 1.25 2002/06/10 20:20:43 shane Exp $''' $Id: CacheManager.py,v 1.26 2002/08/14 21:31:40 mj Exp $'''
__version__='$Revision: 1.25 $'[11:-2] __version__='$Revision: 1.26 $'[11:-2]
import Globals, time, sys import Globals, time, sys
from DateTime import DateTime from DateTime import DateTime
...@@ -43,10 +43,10 @@ class CacheManager: ...@@ -43,10 +43,10 @@ class CacheManager:
else: return db.cacheSize() else: return db.cacheSize()
def cache_detail_length(self): def cache_detail_length(self):
try: db=self._p_jar.db() try: db=self._p_jar.db()
except: except:
return () return ()
else: return db.cacheDetailSize() else: return db.cacheDetailSize()
def database_size(self): def database_size(self):
try: db=self._p_jar.db() try: db=self._p_jar.db()
...@@ -99,7 +99,7 @@ class CacheManager: ...@@ -99,7 +99,7 @@ class CacheManager:
"set cache size" "set cache size"
try: try:
v=self._p_jar.getVersion() v=self._p_jar.getVersion()
except: except:
# BoboPOS2: # BoboPOS2:
if self._p_jar.db is not Globals.Bobobase._jar.db: if self._p_jar.db is not Globals.Bobobase._jar.db:
raise 'Version Error', ( raise 'Version Error', (
...@@ -137,7 +137,7 @@ class CacheManager: ...@@ -137,7 +137,7 @@ class CacheManager:
)) ))
), ),
) )
# BoboPOS 2 # BoboPOS 2
def cache_mean_age(self): def cache_mean_age(self):
...@@ -320,7 +320,7 @@ class CacheManager: ...@@ -320,7 +320,7 @@ class CacheManager:
load_len = max(int(segment_height * loads / limit), 1) load_len = max(int(segment_height * loads / limit), 1)
else: else:
load_len = 0 load_len = 0
t = div['end'] - analysis[-1]['end'] # Show negative numbers. t = div['end'] - analysis[-1]['end'] # Show negative numbers.
if segment_time >= 3600: if segment_time >= 3600:
# Show hours. # Show hours.
...@@ -362,4 +362,3 @@ class CacheManager: ...@@ -362,4 +362,3 @@ class CacheManager:
Globals.default__class_init__(CacheManager) Globals.default__class_init__(CacheManager)
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Commonly used utility functions.""" """Commonly used utility functions."""
__version__='$Revision: 1.14 $'[11:-2] __version__='$Revision: 1.15 $'[11:-2]
import sys, os, time import sys, os, time
...@@ -85,7 +85,7 @@ def is_acquired(ob, hasattr=hasattr, aq_base=aq_base, absattr=absattr): ...@@ -85,7 +85,7 @@ def is_acquired(ob, hasattr=hasattr, aq_base=aq_base, absattr=absattr):
if hasattr(parent, absId): if hasattr(parent, absId):
# Consider direct attributes not acquired # Consider direct attributes not acquired
return 0 return 0
if hasattr(parent, '__getitem__'): if hasattr(parent, '__getitem__'):
# Use __getitem__ as opposed to has_key to avoid TTW namespace # Use __getitem__ as opposed to has_key to avoid TTW namespace
# issues, and to support the most minimal mapping objects # issues, and to support the most minimal mapping objects
...@@ -94,8 +94,8 @@ def is_acquired(ob, hasattr=hasattr, aq_base=aq_base, absattr=absattr): ...@@ -94,8 +94,8 @@ def is_acquired(ob, hasattr=hasattr, aq_base=aq_base, absattr=absattr):
# This object is an item of the aq_parent, its not acquired # This object is an item of the aq_parent, its not acquired
return 0 return 0
except KeyError: except KeyError:
pass pass
if hasattr(parent,'_objects'): if hasattr(parent,'_objects'):
# XXX This is really icky # XXX This is really icky
# This ugly mess is for ZClass methods I think # This ugly mess is for ZClass methods I think
...@@ -126,7 +126,7 @@ def attrget(o,name,default): ...@@ -126,7 +126,7 @@ def attrget(o,name,default):
return default return default
def Dictionary(**kw): return kw # Sorry Guido def Dictionary(**kw): return kw # Sorry Guido
def realpath(p): def realpath(p):
""" Computes the 'real' path of a file or directory devoid of """ Computes the 'real' path of a file or directory devoid of
any symlink in any element of the path """ any symlink in any element of the path """
......
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
__version__ = "$Revision: 1.7 $"[11:-2] __version__ = "$Revision: 1.8 $"[11:-2]
import OFS, Acquisition, Globals import OFS, Acquisition, Globals
from AccessControl import getSecurityManager, ClassSecurityInfo from AccessControl import getSecurityManager, ClassSecurityInfo
...@@ -37,7 +37,7 @@ class DavLockManager(OFS.SimpleItem.Item, Acquisition.Implicit): ...@@ -37,7 +37,7 @@ class DavLockManager(OFS.SimpleItem.Item, Acquisition.Implicit):
{'label': 'Write Locks', 'action': 'manage_main', {'label': 'Write Locks', 'action': 'manage_main',
'help': ('OFSP', 'DavLocks-ManageLocks.stx'), }, 'help': ('OFSP', 'DavLocks-ManageLocks.stx'), },
) )
def locked_in_version(self): return 0 def locked_in_version(self): return 0
def findLockedObjects(self, frompath=''): def findLockedObjects(self, frompath=''):
...@@ -104,5 +104,5 @@ class DavLockManager(OFS.SimpleItem.Item, Acquisition.Implicit): ...@@ -104,5 +104,5 @@ class DavLockManager(OFS.SimpleItem.Item, Acquisition.Implicit):
return result return result
Globals.default__class_init__(DavLockManager) Globals.default__class_init__(DavLockManager)
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Common HTML dialog boxes """Common HTML dialog boxes
MessageDialog(title, message, action, [target]) MessageDialog(title, message, action, [target])
A very simple dialog used to display an HTML page titled title, A very simple dialog used to display an HTML page titled title,
displaying message message and an OK button. Clicking the OK displaying message message and an OK button. Clicking the OK
button will take the browser to the URL specified in action. button will take the browser to the URL specified in action.
The *optional* target argument can be used to force a (frames The *optional* target argument can be used to force a (frames
capable) browser to load the URL specified in action into a specific capable) browser to load the URL specified in action into a specific
frame. (Specifying '_new' will cause the browser to load the frame. (Specifying '_new' will cause the browser to load the
specified URL into a new window, for example). specified URL into a new window, for example).
...@@ -31,9 +31,9 @@ ...@@ -31,9 +31,9 @@
target='_top') target='_top')
</PRE>""" </PRE>"""
__version__='$Revision: 1.7 $'[11:-2] __version__='$Revision: 1.8 $'[11:-2]
from Globals import HTML from Globals import HTML
MessageDialog = HTML(""" MessageDialog = HTML("""
......
############################################################################## ##############################################################################
# #
# 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__='''Standard routines for handling extensions. __doc__='''Standard routines for handling extensions.
Extensions currently include external methods and pluggable brains. Extensions currently include external methods and pluggable brains.
$Id: Extensions.py,v 1.18 2002/02/07 17:37:10 andreasjung Exp $''' $Id: Extensions.py,v 1.19 2002/08/14 21:31:40 mj Exp $'''
__version__='$Revision: 1.18 $'[11:-2] __version__='$Revision: 1.19 $'[11:-2]
import os, zlib, rotor, imp import os, zlib, rotor, imp
import Products import Products
path_split=os.path.split path_split=os.path.split
path_join=os.path.join path_join=os.path.join
exists=os.path.exists exists=os.path.exists
class FuncCode: class FuncCode:
def __init__(self, f, im=0): def __init__(self, f, im=0):
...@@ -71,20 +71,20 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',)): ...@@ -71,20 +71,20 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',)):
The search takes on multiple homes which are INSTANCE_HOME, The search takes on multiple homes which are INSTANCE_HOME,
the directory containing the directory containing SOFTWARE_HOME, and the directory containing the directory containing SOFTWARE_HOME, and
possibly product areas. possibly product areas.
""" """
d,n = path_split(name) d,n = path_split(name)
if d: raise ValueError, ( if d: raise ValueError, (
'The file name, %s, should be a simple file name' % name) 'The file name, %s, should be a simple file name' % name)
if checkProduct: if checkProduct:
l = name.find('.') l = name.find('.')
if l > 0: if l > 0:
p = name[:l] p = name[:l]
n = name[l + 1:] n = name[l + 1:]
for product_dir in Products.__path__: for product_dir in Products.__path__:
r = _getPath(product_dir, os.path.join(p, prefix), n, suffixes) r = _getPath(product_dir, os.path.join(p, prefix), n, suffixes)
if r is not None: return r if r is not None: return r
sw=path_split(path_split(SOFTWARE_HOME)[0])[0] sw=path_split(path_split(SOFTWARE_HOME)[0])[0]
for home in (INSTANCE_HOME, sw): for home in (INSTANCE_HOME, sw):
...@@ -94,7 +94,7 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',)): ...@@ -94,7 +94,7 @@ def getPath(prefix, name, checkProduct=1, suffixes=('',)):
def getObject(module, name, reload=0, def getObject(module, name, reload=0,
# The use of a mutable default is intentional here, # The use of a mutable default is intentional here,
# because modules is a module cache. # because modules is a module cache.
modules={} modules={}
): ):
# The use of modules here is not thread safe, however, there is # The use of modules here is not thread safe, however, there is
...@@ -134,7 +134,7 @@ def getObject(module, name, reload=0, ...@@ -134,7 +134,7 @@ def getObject(module, name, reload=0,
execsrc=compile(data, module, 'exec') execsrc=compile(data, module, 'exec')
m={} m={}
exec execsrc in m exec execsrc in m
else: else:
try: execsrc=open(p) try: execsrc=open(p)
except: raise "Module Error", ( except: raise "Module Error", (
...@@ -169,5 +169,5 @@ def getBrain(module, class_name, reload=0): ...@@ -169,5 +169,5 @@ def getBrain(module, class_name, reload=0):
if not hasattr(c,'__bases__'): raise ValueError, ( if not hasattr(c,'__bases__'): raise ValueError, (
'%s, is not a class' % class_name) '%s, is not a class' % class_name)
return c return c
############################################################################## ##############################################################################
# #
# 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__='''Factory objects __doc__='''Factory objects
$Id: Factory.py,v 1.25 2001/11/28 15:50:52 matt Exp $''' $Id: Factory.py,v 1.26 2002/08/14 21:31:40 mj Exp $'''
__version__='$Revision: 1.25 $'[11:-2] __version__='$Revision: 1.26 $'[11:-2]
import OFS.SimpleItem, Acquisition, Globals, AccessControl.Role import OFS.SimpleItem, Acquisition, Globals, AccessControl.Role
import Products, Product import Products, Product
...@@ -29,7 +29,7 @@ class Factory( ...@@ -29,7 +29,7 @@ class Factory(
permission='' # Waaaa permission='' # Waaaa
_setObject=_getOb=Acquisition.Acquired _setObject=_getOb=Acquisition.Acquired
__ac_permissions__=( __ac_permissions__=(
('Edit Factories', ('manage_edit','manage_main')), ('Edit Factories', ('manage_edit','manage_main')),
('Use Factories', ('index_html','')), ('Use Factories', ('index_html','')),
...@@ -43,7 +43,7 @@ class Factory( ...@@ -43,7 +43,7 @@ class Factory(
+AccessControl.Role.RoleManager.manage_options +AccessControl.Role.RoleManager.manage_options
+OFS.SimpleItem.Item.manage_options +OFS.SimpleItem.Item.manage_options
) )
def __init__(self, id, title, object_type, initial, permission=''): def __init__(self, id, title, object_type, initial, permission=''):
self.id=id self.id=id
self.title=title self.title=title
...@@ -112,4 +112,3 @@ class Factory( ...@@ -112,4 +112,3 @@ class Factory(
) )
class ProductFactory(Factory): pass class ProductFactory(Factory): pass
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
...@@ -60,7 +60,7 @@ class FactoryDispatcher(Acquisition.Implicit): ...@@ -60,7 +60,7 @@ class FactoryDispatcher(Acquisition.Implicit):
return self.__dict__['_d'] # we don't want to wrap the result! return self.__dict__['_d'] # we don't want to wrap the result!
this=Destination this=Destination
this__roles__=Destination__roles__=None this__roles__=Destination__roles__=None
def DestinationURL(self): def DestinationURL(self):
"Return the URL for the destination for factory output" "Return the URL for the destination for factory output"
...@@ -79,14 +79,14 @@ class FactoryDispatcher(Acquisition.Implicit): ...@@ -79,14 +79,14 @@ class FactoryDispatcher(Acquisition.Implicit):
w=getattr(m, '_permissionMapper', None) w=getattr(m, '_permissionMapper', None)
if w is not None: if w is not None:
m=ofWrapper(aqwrap(m, getattr(w,'aq_base',w), self)) m=ofWrapper(aqwrap(m, getattr(w,'aq_base',w), self))
return m return m
# Waaa # Waaa
m='Products.%s' % p.id m='Products.%s' % p.id
if sys.modules.has_key(m) and sys.modules[m]._m.has_key(name): if sys.modules.has_key(m) and sys.modules[m]._m.has_key(name):
return sys.modules[m]._m[name] return sys.modules[m]._m[name]
raise AttributeError, name raise AttributeError, name
# Provide acquired indicators for critical OM methods: # Provide acquired indicators for critical OM methods:
...@@ -99,7 +99,7 @@ class FactoryDispatcher(Acquisition.Implicit): ...@@ -99,7 +99,7 @@ class FactoryDispatcher(Acquisition.Implicit):
def manage_main(trueself, self, REQUEST, update_menu=0): def manage_main(trueself, self, REQUEST, update_menu=0):
"""Implement a contents view by redirecting to the true view """Implement a contents view by redirecting to the true view
""" """
d = update_menu and '/manage_main?update_menu=1' or '/manage_main' d = update_menu and '/manage_main?update_menu=1' or '/manage_main'
REQUEST['RESPONSE'].redirect(self.DestinationURL()+d) REQUEST['RESPONSE'].redirect(self.DestinationURL()+d)
...@@ -109,5 +109,3 @@ class ofWrapper(ExtensionClass.Base): ...@@ -109,5 +109,3 @@ class ofWrapper(ExtensionClass.Base):
self._o=o self._o=o
def __of__(self, parent): return self.__dict__['_o'] def __of__(self, parent): return self.__dict__['_o']
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Commonly used utility functions.""" """Commonly used utility functions."""
__version__='$Revision: 1.10 $'[11:-2] __version__='$Revision: 1.11 $'[11:-2]
import os, sys, Products import os, sys, Products
from Common import package_home, realpath from Common import package_home, realpath
...@@ -25,7 +25,7 @@ except: ...@@ -25,7 +25,7 @@ except:
home=package_home(Products.__dict__) home=package_home(Products.__dict__)
if not os.path.isabs(home): if not os.path.isabs(home):
home=path_join(os.getcwd(), home) home=path_join(os.getcwd(), home)
home,e=path_split(home) home,e=path_split(home)
if path_split(home)[1]=='.': home=path_split(home)[0] if path_split(home)[1]=='.': home=path_split(home)[0]
if path_split(home)[1]=='..': if path_split(home)[1]=='..':
...@@ -76,7 +76,7 @@ if os.path.isdir(ip) and ip not in ppath: ...@@ -76,7 +76,7 @@ if os.path.isdir(ip) and ip not in ppath:
if disallow in ('no', 'off', '0', ''): if disallow in ('no', 'off', '0', ''):
ppath.insert(0, ip) ppath.insert(0, ip)
ippart = 1 ippart = 1
ppathpat = os.environ.get('PRODUCTS_PATH', None) ppathpat = os.environ.get('PRODUCTS_PATH', None)
if ppathpat is not None: if ppathpat is not None:
psep = os.pathsep psep = os.pathsep
......
############################################################################## ##############################################################################
# #
# 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 version_txt import getZopeVersion from version_txt import getZopeVersion
...@@ -57,4 +57,3 @@ def beforeApplyHotfix(id, req_major, req_minor, req_micro): ...@@ -57,4 +57,3 @@ def beforeApplyHotfix(id, req_major, req_minor, req_micro):
apply_hotfix = APPLY apply_hotfix = APPLY
logHotfix(id, apply_hotfix) logHotfix(id, apply_hotfix)
return apply_hotfix return apply_hotfix
############################################################################## ##############################################################################
# #
# 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 that is stored in a file""" """Image object that is stored in a file"""
__version__='$Revision: 1.17 $'[11:-2] __version__='$Revision: 1.18 $'[11:-2]
from OFS.content_types import guess_content_type from OFS.content_types import guess_content_type
from Globals import package_home from Globals import package_home
...@@ -35,7 +35,7 @@ class ImageFile(Acquisition.Explicit): ...@@ -35,7 +35,7 @@ class ImageFile(Acquisition.Explicit):
self.path=path self.path=path
if Globals.DevelopmentMode: if Globals.DevelopmentMode:
# In development mode, a shorter time is handy # In development mode, a shorter time is handy
max_age = 60 # One minute max_age = 60 # One minute
else: else:
# A longer time reduces latency in production mode # A longer time reduces latency in production mode
max_age = 3600 # One hour max_age = 3600 # One hour
...@@ -96,8 +96,7 @@ class ImageFile(Acquisition.Explicit): ...@@ -96,8 +96,7 @@ class ImageFile(Acquisition.Explicit):
def __len__(self): def __len__(self):
# This is bogus and needed because of the way Python tests truth. # This is bogus and needed because of the way Python tests truth.
return 1 return 1
def __str__(self): def __str__(self):
return '<img src="%s" alt="" />' % self.__name__ return '<img src="%s" alt="" />' % self.__name__
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Standard management interface support """Standard management interface support
$Id: Management.py,v 1.60 2002/04/12 19:45:33 Brian Exp $""" $Id: Management.py,v 1.61 2002/08/14 21:31:40 mj Exp $"""
__version__='$Revision: 1.60 $'[11:-2] __version__='$Revision: 1.61 $'[11:-2]
import sys, Globals, ExtensionClass, urllib import sys, Globals, ExtensionClass, urllib
from Dialogs import MessageDialog from Dialogs import MessageDialog
...@@ -27,7 +27,7 @@ class Tabs(ExtensionClass.Base): ...@@ -27,7 +27,7 @@ class Tabs(ExtensionClass.Base):
manage_tabs__roles__=('Anonymous',) manage_tabs__roles__=('Anonymous',)
manage_tabs=DTMLFile('dtml/manage_tabs', globals()) manage_tabs=DTMLFile('dtml/manage_tabs', globals())
manage_options =() manage_options =()
...@@ -35,7 +35,7 @@ class Tabs(ExtensionClass.Base): ...@@ -35,7 +35,7 @@ class Tabs(ExtensionClass.Base):
def filtered_manage_options(self, REQUEST=None): def filtered_manage_options(self, REQUEST=None):
validate=getSecurityManager().validate validate=getSecurityManager().validate
result=[] result=[]
try: options=tuple(self.manage_options) try: options=tuple(self.manage_options)
...@@ -61,8 +61,8 @@ class Tabs(ExtensionClass.Base): ...@@ -61,8 +61,8 @@ class Tabs(ExtensionClass.Base):
result.append(d) result.append(d)
return result return result
manage_workspace__roles__=('Authenticated',) manage_workspace__roles__=('Authenticated',)
def manage_workspace(self, REQUEST): def manage_workspace(self, REQUEST):
"""Dispatch to first interface in manage_options """Dispatch to first interface in manage_options
...@@ -78,9 +78,9 @@ class Tabs(ExtensionClass.Base): ...@@ -78,9 +78,9 @@ class Tabs(ExtensionClass.Base):
if m.find('/'): if m.find('/'):
raise 'Redirect', ( raise 'Redirect', (
"%s/%s" % (REQUEST['URL1'], m)) "%s/%s" % (REQUEST['URL1'], m))
return getattr(self, m)(self, REQUEST) return getattr(self, m)(self, REQUEST)
def tabs_path_default(self, REQUEST, def tabs_path_default(self, REQUEST,
# Static var # Static var
unquote=urllib.unquote, unquote=urllib.unquote,
......
############################################################################## ##############################################################################
# #
# 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__='''Zope registerable permissions __doc__='''Zope registerable permissions
$Id: Permission.py,v 1.7 2001/11/28 15:50:52 matt Exp $''' $Id: Permission.py,v 1.8 2002/08/14 21:31:40 mj Exp $'''
__version__='$Revision: 1.7 $'[11:-2] __version__='$Revision: 1.8 $'[11:-2]
import OFS.SimpleItem, Acquisition, Globals, ExtensionClass, AccessControl.Role import OFS.SimpleItem, Acquisition, Globals, ExtensionClass, AccessControl.Role
...@@ -33,7 +33,7 @@ class Permission( ...@@ -33,7 +33,7 @@ class Permission(
+AccessControl.Role.RoleManager.manage_options +AccessControl.Role.RoleManager.manage_options
+OFS.SimpleItem.Item.manage_options +OFS.SimpleItem.Item.manage_options
) )
def __init__(self, id, title, name): def __init__(self, id, title, name):
self.id=id self.id=id
self.title=title self.title=title
...@@ -89,4 +89,3 @@ class PermissionManager(ExtensionClass.Base): ...@@ -89,4 +89,3 @@ class PermissionManager(ExtensionClass.Base):
self._setObject(id,i) self._setObject(id,i)
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
# #
############################################################################## ##############################################################################
from class_init import default__class_init__ from class_init import default__class_init__
...@@ -24,7 +24,7 @@ class PersistentUtil: ...@@ -24,7 +24,7 @@ class PersistentUtil:
jar=self._p_jar jar=self._p_jar
oid=self._p_oid oid=self._p_oid
if jar is None or oid is None: return DateTime() if jar is None or oid is None: return DateTime()
try: try:
t=self._p_mtime t=self._p_mtime
if t is None: return DateTime() if t is None: return DateTime()
...@@ -40,7 +40,7 @@ class PersistentUtil: ...@@ -40,7 +40,7 @@ class PersistentUtil:
try: mv=jar.modifiedInVersion try: mv=jar.modifiedInVersion
except: pass except: pass
else: return mv(oid) else: return mv(oid)
# BoboPOS 2 code: # BoboPOS 2 code:
oid=self._p_oid oid=self._p_oid
return (oid return (oid
...@@ -68,5 +68,5 @@ class PersistentUtil: ...@@ -68,5 +68,5 @@ class PersistentUtil:
try: jar.db[self._p_oid] try: jar.db[self._p_oid]
except: return 0 except: return 0
return 1 return 1
for k, v in PersistentUtil.__dict__.items(): Persistent.__dict__[k]=v for k, v in PersistentUtil.__dict__.items(): Persistent.__dict__[k]=v
############################################################################## ##############################################################################
# #
# 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
# #
############################################################################## ##############################################################################
"""Product objects """Product objects
""" """
# The new Product model: # The new Product model:
# #
# Products may be defined in the Products folder or by placing directories # Products may be defined in the Products folder or by placing directories
# in lib/python/Products. # in lib/python/Products.
# #
# Products in lib/python/Products may have up to three sources of information: # Products in lib/python/Products may have up to three sources of information:
# #
# - Static information defined via Python. This information is # - Static information defined via Python. This information is
# described and made available via __init__.py. # described and made available via __init__.py.
# #
# - Dynamic object data that gets copied into the Bobobase. # - Dynamic object data that gets copied into the Bobobase.
# This is contained in product.dat (which is obfuscated). # This is contained in product.dat (which is obfuscated).
# #
# - Static extensions supporting the dynamic data. These too # - Static extensions supporting the dynamic data. These too
# are obfuscated. # are obfuscated.
# #
# Products may be copied and pasted only within the products folder. # Products may be copied and pasted only within the products folder.
# #
# If a product is deleted (or cut), it is automatically recreated # If a product is deleted (or cut), it is automatically recreated
# on restart if there is still a product directory. # on restart if there is still a product directory.
...@@ -106,8 +106,8 @@ class Product(Folder, PermissionManager): ...@@ -106,8 +106,8 @@ class Product(Folder, PermissionManager):
start = match.start() start = match.start()
end = match.end() end = match.end()
return v[:start] + str(1 + int(v[start:end])) + v[end:] return v[:start] + str(1 + int(v[start:end])) + v[end:]
meta_types=( meta_types=(
ZClasses.meta_types+PermissionManager.meta_types+ ZClasses.meta_types+PermissionManager.meta_types+
( (
...@@ -117,7 +117,7 @@ class Product(Folder, PermissionManager): ...@@ -117,7 +117,7 @@ class Product(Folder, PermissionManager):
}, },
) )
) )
manage_addZClassForm=ZClasses.methods['manage_addZClassForm'] manage_addZClassForm=ZClasses.methods['manage_addZClassForm']
manage_addZClass =ZClasses.methods['manage_addZClass'] manage_addZClass =ZClasses.methods['manage_addZClass']
manage_subclassableClassNames=ZClasses.methods[ manage_subclassableClassNames=ZClasses.methods[
...@@ -164,7 +164,7 @@ class Product(Folder, PermissionManager): ...@@ -164,7 +164,7 @@ class Product(Folder, PermissionManager):
self._setObject('Help', ProductHelp('Help', id)) self._setObject('Help', ProductHelp('Help', id))
except: except:
pass pass
def Destination(self): def Destination(self):
"Return the destination for factory output" "Return the destination for factory output"
return self return self
...@@ -185,14 +185,14 @@ class Product(Folder, PermissionManager): ...@@ -185,14 +185,14 @@ class Product(Folder, PermissionManager):
self.redistributable=redistributable self.redistributable=redistributable
RESPONSE.redirect('Distributions/%s-%s.tar.gz' % RESPONSE.redirect('Distributions/%s-%s.tar.gz' %
(quote(self.id), quote(version))) (quote(self.id), quote(version)))
def _distribution(self): def _distribution(self):
# Return a distribution # Return a distribution
if self.__dict__.has_key('manage_options'): if self.__dict__.has_key('manage_options'):
raise TypeError, 'This product is <b>not</b> redistributable.' raise TypeError, 'This product is <b>not</b> redistributable.'
id=self.id id=self.id
import tar import tar
rot=rotor.newrotor(id+' shshsh') rot=rotor.newrotor(id+' shshsh')
ar=tar.tgzarchive("%s-%s" % (id, self.version)) ar=tar.tgzarchive("%s-%s" % (id, self.version))
...@@ -471,7 +471,7 @@ class CompressedInputFile: ...@@ -471,7 +471,7 @@ class CompressedInputFile:
class Distribution: class Distribution:
"A distribution builder" "A distribution builder"
def __init__(self, product): def __init__(self, product):
self._product=product self._product=product
...@@ -500,7 +500,7 @@ def initializeProduct(productp, name, home, app): ...@@ -500,7 +500,7 @@ def initializeProduct(productp, name, home, app):
# Version hasn't changed. Don't reinitialize. # Version hasn't changed. Don't reinitialize.
return old return old
except: pass except: pass
disable_distribution = 1 disable_distribution = 1
try: try:
f=CompressedInputFile(open(home+'/product.dat','rb'), name+' shshsh') f=CompressedInputFile(open(home+'/product.dat','rb'), name+' shshsh')
......
############################################################################## ##############################################################################
# #
# 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 providing context for product initialization """Objects providing context for product initialization
""" """
...@@ -41,7 +41,7 @@ class ProductContext: ...@@ -41,7 +41,7 @@ class ProductContext:
self.__app=app self.__app=app
self.__pack=package self.__pack=package
def registerClass(self, instance_class=None, meta_type='', def registerClass(self, instance_class=None, meta_type='',
permission=None, constructors=(), permission=None, constructors=(),
icon=None, permissions=None, legacy=(), icon=None, permissions=None, legacy=(),
visibility="Global",interfaces=_marker, visibility="Global",interfaces=_marker,
...@@ -52,7 +52,7 @@ class ProductContext: ...@@ -52,7 +52,7 @@ class ProductContext:
Keyword arguments are used to provide meta data: Keyword arguments are used to provide meta data:
instance_class -- The class of the object that will be created. instance_class -- The class of the object that will be created.
This is not currently used, but may be used in the future to This is not currently used, but may be used in the future to
increase object mobility. increase object mobility.
...@@ -81,7 +81,7 @@ class ProductContext: ...@@ -81,7 +81,7 @@ class ProductContext:
permissions -- Additional permissions to be registered permissions -- Additional permissions to be registered
If not provided, then permissions defined in the If not provided, then permissions defined in the
class will be registered. class will be registered.
legacy -- A list of legacy methods to be added to ObjectManager legacy -- A list of legacy methods to be added to ObjectManager
for backward compatibility for backward compatibility
...@@ -95,7 +95,7 @@ class ProductContext: ...@@ -95,7 +95,7 @@ class ProductContext:
filter is called before showing ObjectManager's Add list, filter is called before showing ObjectManager's Add list,
and before pasting (after object copy or cut), but not and before pasting (after object copy or cut), but not
before calling an object's constructor. before calling an object's constructor.
""" """
app=self.__app app=self.__app
pack=self.__pack pack=self.__pack
...@@ -216,18 +216,18 @@ class ProductContext: ...@@ -216,18 +216,18 @@ class ProductContext:
module=base_class.__module__ module=base_class.__module__
name=base_class.__name__ name=base_class.__name__
key="%s/%s" % (module, name) key="%s/%s" % (module, name)
if module[:9]=='Products.': module=module.split('.')[1] if module[:9]=='Products.': module=module.split('.')[1]
else: module=module.split('.')[0] else: module=module.split('.')[0]
info="%s: %s" % (module, name) info="%s: %s" % (module, name)
Products.meta_class_info[key]=info # meta_type Products.meta_class_info[key]=info # meta_type
Products.meta_classes[key]=Z Products.meta_classes[key]=Z
def registerBaseClass(self, base_class, meta_type=None): def registerBaseClass(self, base_class, meta_type=None):
# #
...@@ -274,7 +274,7 @@ class ProductContext: ...@@ -274,7 +274,7 @@ class ProductContext:
HelpTopics are created for these kind of files HelpTopics are created for these kind of files
.dtml -- DTMLHelpTopic .dtml -- DTMLHelpTopic
.html .htm -- TextHelpTopic .html .htm -- TextHelpTopic
.stx .txt -- STXHelpTopic .stx .txt -- STXHelpTopic
.jpg .png .gif -- ImageHelpTopic .jpg .png .gif -- ImageHelpTopic
.py -- APIHelpTopic .py -- APIHelpTopic
...@@ -333,5 +333,3 @@ class ProductContext: ...@@ -333,5 +333,3 @@ class ProductContext:
continue continue
ht=APIHelpTopic.APIHelpTopic(file, '', os.path.join(path, file)) ht=APIHelpTopic.APIHelpTopic(file, '', os.path.join(path, file))
self.registerHelpTopic(file, ht) self.registerHelpTopic(file, ht)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
############################################################################## ##############################################################################
# #
# 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 diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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