Commit 341cbf11 authored by Tres Seaver's avatar Tres Seaver

Further import / PEP8 cleanups:

o All 'from Globals import...' lines now removed in favor of imports
  from the original location.

o All valid 'import Globals' now bear comments documenting their purpose
  (to read or set shared data).

o All unit tests are passing.  Some functional tests now fail (in addition
  to those failing on the trunk), due to dependencies on import-time
  side effects, now cleared up.  These need to be visited, of course.
parent 29c8317c
......@@ -41,9 +41,8 @@
import sys
from logging import getLogger
import Acquisition
from AccessControl.ImplPython import _what_not_even_god_should_do
from Acquisition import Implicit
LOG = getLogger('SecurityInfo')
......@@ -57,7 +56,7 @@ ACCESS_PUBLIC = None
_marker = []
class SecurityInfo(Acquisition.Implicit):
class SecurityInfo(Implicit):
"""Encapsulate security information."""
__security_info__ = 1
......@@ -312,5 +311,5 @@ def allow_class(Class):
sec.declareObjectPublic()
sec.setDefaultAccess(1)
sec.apply(Class)
from Globals import InitializeClass
from App.class_init import default__class_init__ as InitializeClass
InitializeClass(Class)
......@@ -15,15 +15,15 @@
# $Id$
import os, sys, unittest
import unittest
import ZODB
import SecurityBase
from AccessControl.SecurityInfo import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.User import nobody
from AccessControl.securitySuite import SecurityBase
from OFS.Folder import Folder
from OFS.SimpleItem import SimpleItem
from AccessControl import ClassSecurityInfo,getSecurityManager
from AccessControl.User import nobody
import Globals
from App.class_init import default__class_init__ as InitializeClass
# let's define some permissions first
......@@ -79,7 +79,7 @@ class TestObject(SimpleItem):
security.setPermissionDefault(MAGIC_PERMISSION1, ("Manager","Owner"))
security.setPermissionDefault(MAGIC_PERMISSION2, ("TestRole",))
Globals.InitializeClass(TestObject)
InitializeClass(TestObject)
##############################################################################
......@@ -99,7 +99,7 @@ class TestFolder(Folder):
security = ClassSecurityInfo()
Globals.InitializeClass(TestFolder)
InitializeClass(TestFolder)
##############################################################################
......
......@@ -28,7 +28,6 @@ class ClassSecurityInfoTests(unittest.TestCase):
# Test setting default roles for permissions.
#import Globals # XXX: avoiding import cycle
from App.class_init import default__class_init__
from ExtensionClass import Base
......
......@@ -247,7 +247,7 @@ class DebugManager(Fake, Item, Implicit):
'rc': n[1][0]}, rd)
def dbconnections(self):
import Globals
import Globals # for data
return Globals.DB.connectionDebugInfo()
......
......@@ -95,23 +95,23 @@ class CacheManager:
# BoboPOS 2
def cache_mean_age(self):
import Globals
import Globals # for data
return Globals.Bobobase._jar.cache.cache_mean_age/60.0
# BoboPOS 2
def cache_mean_deal(self):
import Globals
import Globals # for data
return Globals.Bobobase._jar.cache.cache_mean_deal*60
# BoboPOS 2
def cache_mean_deac(self):
import Globals
import Globals # for data
return Globals.Bobobase._jar.cache.cache_mean_deac*60
# BoboPOS 2
def cache_last_gc_time(self):
import Globals
t=Globals.Bobobase._jar.cache.cache_last_gc_time
import Globals # for data
t = Globals.Bobobase._jar.cache.cache_last_gc_time
return time.asctime(time.localtime(t))
def manage_full_sweep(self,value,REQUEST):
......
......@@ -34,7 +34,7 @@ class ImageFile(Explicit):
security = ClassSecurityInfo()
def __init__(self,path,_prefix=None):
import Globals
import Globals # for data
if _prefix is None:
_prefix=getConfiguration().softwarehome
elif type(_prefix) is not type(''):
......
......@@ -38,7 +38,7 @@ class PersistentUtil:
def locked_in_version(self):
"""Was the object modified in any version?
"""
import Globals
import Globals # for data
jar=self._p_jar
oid=self._p_oid
if jar is None or oid is None: return None
......
......@@ -242,7 +242,7 @@ class Product(Folder, PermissionManager):
def manage_refresh(self, REQUEST, manage_tabs_message=None):
"""Displays the refresh management screen.
"""
import Globals
import Globals # for data
from App.RefreshFuncs import getLastRefreshException
from App.RefreshFuncs import isAutoRefreshEnabled
from App.RefreshFuncs import getDependentProducts
......@@ -400,7 +400,7 @@ class CompressedInputFile:
def initializeProduct(productp, name, home, app):
# Initialize a levered product
import Globals
import Globals # to set data
products = app.Control_Panel.Products
fver = ''
......
......@@ -15,14 +15,14 @@ Functions for refreshing products.
$Id$
'''
import os, sys
from logging import getLogger
import os
import sys
from time import time
from traceback import format_exception
from logging import getLogger
import transaction
import Products
from ExtensionClass import Base
from Globals import PersistentMapping
from Persistence import PersistentMapping
LOG = getLogger('RefreshFuncs')
global_classes_timestamp = 0
......@@ -32,9 +32,14 @@ _marker = [] # create a new marker object.
refresh_exc_info = {}
class dummyClass: pass
class dummyClass2 (Base): pass
def dummyFunc(): pass
class dummyClass:
pass
class dummyClass2(Base):
pass
def dummyFunc():
pass
ClassTypes = (type(dummyClass), type(dummyClass2))
ModuleType = type(sys)
......@@ -207,6 +212,7 @@ def getLastRefreshException(productid):
# Functions for quickly scanning the dates of product modules.
def tryFindProductDirectory(productid):
import Products
path_join = os.path.join
isdir = os.path.isdir
exists = os.path.exists
......@@ -316,6 +322,7 @@ def finishAutoRefresh(jar, productids):
def autoRefresh(jar):
# Must be called before there are any changes made
# by the connection to the database!
import transaction
auto_refresh_ids = checkAutoRefresh(jar)
if auto_refresh_ids:
finishAutoRefresh(jar, auto_refresh_ids)
......
......@@ -62,16 +62,13 @@ def setConfiguration(cfg):
os.environ["SOFTWARE_HOME"] = cfg.softwarehome
os.environ["ZOPE_HOME"] = cfg.zopehome
if "Globals" in sys.modules:
# XXX We *really* want to avoid this if Globals hasn't already
# been imported, due to circular imports. ;-(
import Globals
Globals.data_dir = cfg.clienthome
# Globals does not export CLIENT_HOME
Globals.INSTANCE_HOME = cfg.instancehome
Globals.SOFTWARE_HOME = cfg.softwarehome
Globals.ZOPE_HOME = cfg.zopehome
Globals.DevelopmentMode = cfg.debug_mode
import Globals # to set data
Globals.data_dir = cfg.clienthome
# Globals does not export CLIENT_HOME
Globals.INSTANCE_HOME = cfg.instancehome
Globals.SOFTWARE_HOME = cfg.softwarehome
Globals.ZOPE_HOME = cfg.zopehome
Globals.DevelopmentMode = cfg.debug_mode
class DefaultConfiguration:
"""
......
......@@ -56,7 +56,7 @@ class SetConfigTests(unittest.TestCase):
def testClientHomeLegacySources(self):
import os
import App.FindHomes
import Globals
import Globals # for data
import __builtin__
self.setconfig(clienthome='foo')
self.assertEqual(os.environ.get('CLIENT_HOME'), 'foo')
......@@ -67,7 +67,7 @@ class SetConfigTests(unittest.TestCase):
def testInstanceHomeLegacySources(self):
import os
import App.FindHomes
import Globals
import Globals # for data
import __builtin__
self.setconfig(instancehome='foo')
self.assertEqual(os.environ.get('INSTANCE_HOME'), 'foo')
......@@ -78,7 +78,7 @@ class SetConfigTests(unittest.TestCase):
def testSoftwareHomeLegacySources(self):
import os
import App.FindHomes
import Globals
import Globals # for data
import __builtin__
self.setconfig(softwarehome='foo')
self.assertEqual(os.environ.get('SOFTWARE_HOME'), 'foo')
......@@ -89,7 +89,7 @@ class SetConfigTests(unittest.TestCase):
def testZopeHomeLegacySources(self):
import os
import App.FindHomes
import Globals
import Globals # for data
import __builtin__
self.setconfig(zopehome='foo')
self.assertEqual(os.environ.get('ZOPE_HOME'), 'foo')
......@@ -98,7 +98,7 @@ class SetConfigTests(unittest.TestCase):
self.assertEqual(Globals.ZOPE_HOME, 'foo')
def testDebugModeLegacySources(self):
import Globals
import Globals # for data
self.setconfig(debug_mode=True)
self.assertEqual(Globals.DevelopmentMode, True)
self.setconfig(debug_mode=False)
......
......@@ -15,13 +15,19 @@
__version__='$Revision: 1.12 $'[11:-2]
import sys, re
import Globals, Acquisition
import re
import sys
from Acquisition import Implicit
from App.class_init import default__class_init__
from App.Dialogs import MessageDialog
from App.special_dtml import HTML
from Persistence import Persistent
from zope.structuredtext.html import HTMLWithImages
from zope.structuredtext.document import DocumentWithImages
class HelpBase(Acquisition.Implicit):
class HelpBase(Implicit):
""" """
def __bobo_traverse__(self, REQUEST, name=None):
# A sneaky trick - we cant really _have_ an index_html
......@@ -35,7 +41,7 @@ class HelpBase(Acquisition.Implicit):
return 1
class object(Acquisition.Implicit):
class object(Implicit):
def __init__(self, name, ob, op=None):
self._name=name
self._obj_=ob
......@@ -373,15 +379,15 @@ class methodobject(object):
_classtypes=(type(Globals.HTML),
type(Globals.Persistent),
_classtypes=(type(HTML),
type(Persistent),
)
_methodtypes=(type([].sort),
type(Globals.default__class_init__),
type(Globals.HTML.manage_edit),
type(Globals.HTML.__changed__),
type(Globals.MessageDialog.manage_edit),
type(default__class_init__),
type(HTML.manage_edit),
type(HTML.__changed__),
type(MessageDialog.manage_edit),
)
def is_module(ob):
......
......@@ -14,16 +14,16 @@
__version__='$Revision: 1.10 $'[11:-2]
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
import sys, Globals
from HelpUtil import HelpBase, classobject
from HelpUtil import is_class, is_module
from Globals import DTMLFile
import sys
from urllib import quote
from AccessControl.SecurityInfo import ClassSecurityInfo
from App.class_init import default__class_init__ as InitializeClass
from App.special_dtml import DTMLFile
from HelpSys.HelpUtil import classobject
from HelpSys.HelpUtil import HelpBase
from HelpSys.HelpUtil import is_class
from HelpSys.HelpUtil import is_module
class ObjectItem(HelpBase, classobject):
......
......@@ -549,10 +549,12 @@ class AppInitializer:
app = self.getApp()
if app._getInitializerFlag('virtual_hosting'):
return
if not app.objectIds('Virtual Host Monster') and not hasattr(app, 'virtual_hosting'):
from Products.SiteAccess.VirtualHostMonster import VirtualHostMonster
vhm=VirtualHostMonster()
vhm.id='virtual_hosting'
if (not app.objectIds('Virtual Host Monster') and
not hasattr(app, 'virtual_hosting')):
from Products.SiteAccess.VirtualHostMonster \
import VirtualHostMonster
vhm = VirtualHostMonster()
vhm.id = 'virtual_hosting'
vhm.addToContainer(app)
app._setInitializerFlag('virtual_hosting')
self.commit('Added virtual_hosting')
......
......@@ -19,7 +19,6 @@
$Id$
"""
import Globals
class Moniker:
"""An object moniker is an intelligent reference to a
......
......@@ -25,9 +25,6 @@ import re
import sys
import warnings
import App.Common
import App.FactoryDispatcher, Products
import App.Management, Acquisition
from AccessControl import ClassSecurityInfo
from AccessControl.Permissions import view_management_screens
from AccessControl.Permissions import access_contents_information
......@@ -37,13 +34,15 @@ from AccessControl.Permissions import import_export_objects
from AccessControl import getSecurityManager
from AccessControl.ZopeSecurityPolicy import getRoles
from Acquisition import aq_base
from Acquisition import Implicit
from App.class_init import default__class_init__ as InitializeClass
from App.Common import is_acquired
from App.config import getConfiguration
from App.Dialogs import MessageDialog
from App.FactoryDispatcher import ProductDispatcher
from App.Management import Navigation
from App.Management import Tabs
from App.special_dtml import DTMLFile
from Globals import REPLACEABLE
from Globals import NOT_REPLACEABLE
from Globals import UNIQUE
from Persistence import Persistent
from webdav.Collection import Collection
from webdav.Lockable import ResourceLockedError
......@@ -52,27 +51,28 @@ from zExceptions import BadRequest
from ZODB.POSException import ConflictError
from zope.interface import implements
from zope.component.interfaces import ComponentLookupError
import CopySupport
from interfaces import IObjectManager
from Traversable import Traversable
from zope.event import notify
from zope.app.container.contained import ObjectAddedEvent
from zope.app.container.contained import ObjectRemovedEvent
from zope.app.container.contained import notifyContainerModified
from zope.app.container.interfaces import IContainer
from zope.interface import implements
from OFS.CopySupport import CopyContainer
from OFS.interfaces import IObjectManager
from OFS.Traversable import Traversable
from OFS.event import ObjectWillBeAddedEvent
from OFS.event import ObjectWillBeRemovedEvent
import OFS.subscribers
from OFS.subscribers import compatibilityCall
from OFS.XMLExportImport import importXML
from OFS.XMLExportImport import exportXML
from OFS.XMLExportImport import magic
# the name BadRequestException is relied upon by 3rd-party code
BadRequestException = BadRequest
import XMLExportImport
customImporters={
XMLExportImport.magic: XMLExportImport.importXML,
}
customImporters={magic: importXML,
}
bad_id=re.compile(r'[^a-zA-Z0-9-_~,.$\(\)# @]').search
......@@ -82,6 +82,7 @@ def checkValidId(self, id, allow_dup=0):
# only check that the id string contains no illegal chars;
# check_valid_id() will be called again later with allow_dup
# set to false before the object is added.
import Globals # for data
if not id or not isinstance(id, str):
if isinstance(id, unicode):
......@@ -103,15 +104,15 @@ def checkValidId(self, id, allow_dup=0):
if obj is not None:
# An object by the given id exists either in this
# ObjectManager or in the acquisition path.
flags = getattr(obj, '__replaceable__', NOT_REPLACEABLE)
flags = getattr(obj, '__replaceable__', Globals.NOT_REPLACEABLE)
if hasattr(aq_base(self), id):
# The object is located in this ObjectManager.
if not flags & REPLACEABLE:
if not flags & Globals.REPLACEABLE:
raise BadRequest, (
'The id "%s" is invalid - it is already in use.' % id)
# else the object is replaceable even if the UNIQUE
# flag is set.
elif flags & UNIQUE:
elif flags & Globals.UNIQUE:
raise BadRequest, ('The id "%s" is reserved.' % id)
if id == 'REQUEST':
raise BadRequest, 'REQUEST is a reserved name.'
......@@ -133,15 +134,14 @@ class BreakoutException(Exception):
_marker=[]
class ObjectManager(
CopySupport.CopyContainer,
App.Management.Navigation,
App.Management.Tabs,
Acquisition.Implicit,
Persistent,
Collection,
Traversable,
):
class ObjectManager(CopyContainer,
Navigation,
Tabs,
Implicit,
Persistent,
Collection,
Traversable,
):
"""Generic object manager
......@@ -210,6 +210,7 @@ class ObjectManager(
def all_meta_types(self, interfaces=None):
# A list of products registered elsewhere
import Products
external_candidates = []
# Look at _product_meta_types, if there is one
......@@ -261,6 +262,7 @@ class ObjectManager(
return meta_types
def _subobject_permissions(self):
import Products
Products_permissions = getattr(Products, '__ac_permissions__', ())
return (Products_permissions +
self.aq_acquire('_getProductRegistryData')('ac_permissions')
......@@ -359,7 +361,7 @@ class ObjectManager(
notify(ObjectAddedEvent(ob, self, id))
notifyContainerModified(self)
OFS.subscribers.compatibilityCall('manage_afterAdd', ob, ob, self)
compatibilityCall('manage_afterAdd', ob, ob, self)
return id
......@@ -385,7 +387,7 @@ class ObjectManager(
"""
ob = self._getOb(id)
OFS.subscribers.compatibilityCall('manage_beforeDelete', ob, ob, self)
compatibilityCall('manage_beforeDelete', ob, ob, self)
if not suppress_events:
notify(ObjectWillBeRemovedEvent(ob, self, id))
......@@ -503,7 +505,7 @@ class ObjectManager(
return vals
manage_addProduct=App.FactoryDispatcher.ProductDispatcher()
manage_addProduct = ProductDispatcher()
security.declareProtected(delete_objects, 'manage_delObjects')
def manage_delObjects(self, ids=[], REQUEST=None):
......@@ -577,8 +579,10 @@ class ObjectManager(
if download:
f=StringIO()
if toxml: XMLExportImport.exportXML(ob._p_jar, ob._p_oid, f)
else: ob._p_jar.exportFile(ob._p_oid, f)
if toxml:
exportXML(ob._p_jar, ob._p_oid, f)
else:
ob._p_jar.exportFile(ob._p_oid, f)
if RESPONSE is not None:
RESPONSE.setHeader('Content-type','application/data')
RESPONSE.setHeader('Content-Disposition',
......@@ -588,7 +592,7 @@ class ObjectManager(
cfg = getConfiguration()
f = os.path.join(cfg.clienthome, '%s.%s' % (id, suffix))
if toxml:
XMLExportImport.exportXML(ob._p_jar, ob._p_oid, f)
exportXML(ob._p_jar, ob._p_oid, f)
else:
ob._p_jar.exportFile(ob._p_oid, f)
......@@ -673,7 +677,7 @@ class ObjectManager(
# check to see if we are being acquiring or not
ob=self
while 1:
if App.Common.is_acquired(ob):
if is_acquired(ob):
raise ValueError('FTP List not supported on acquired objects')
if not hasattr(ob,'aq_parent'):
break
......
......@@ -36,7 +36,6 @@ from App.Extensions import getPath
from App.Extensions import FuncCode
from App.special_dtml import DTMLFile
from App.special_dtml import HTML
import Globals # for data
from OFS.SimpleItem import Item
from OFS.SimpleItem import pretty_tb
from Persistence import Persistent
......@@ -174,30 +173,21 @@ class ExternalMethod(Item, Persistent, Explicit,
self._v_f=self.getFunction(1)
self._v_last_read=ts
if Globals.DevelopmentMode:
# In development mode we do an automatic reload
# if the module code changed
def getFuncDefaults(self):
def getFuncDefaults(self):
import Globals # for data
if Globals.DevelopmentMode:
self.reloadIfChanged()
if not hasattr(self, '_v_func_defaults'):
self._v_f = self.getFunction()
return self._v_func_defaults
if not hasattr(self, '_v_func_defaults'):
self._v_f = self.getFunction()
return self._v_func_defaults
def getFuncCode(self):
def getFuncCode(self):
import Globals # for data
if Globals.DevelopmentMode:
self.reloadIfChanged()
if not hasattr(self, '_v_func_code'):
self._v_f = self.getFunction()
return self._v_func_code
else:
def getFuncDefaults(self):
if not hasattr(self, '_v_func_defaults'):
self._v_f = self.getFunction()
return self._v_func_defaults
def getFuncCode(self):
if not hasattr(self, '_v_func_code'):
self._v_f = self.getFunction()
return self._v_func_code
if not hasattr(self, '_v_func_code'):
self._v_f = self.getFunction()
return self._v_func_code
security.declareProtected(View, '__call__')
def __call__(self, *args, **kw):
......@@ -218,6 +208,7 @@ class ExternalMethod(Item, Persistent, Explicit,
In this case, the URL parent of the object is supplied as the
first argument.
"""
import Globals # for data
filePath = self.filepath()
if filePath==None:
......
......@@ -20,12 +20,13 @@ the widget's sub-editform.
$Id$
"""
import zope.app.form.browser.objectwidget
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass as initializeClass
from App.class_init import default__class_init__ as InitializeClass
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.app.form.browser.objectwidget import ObjectWidget as OWBase
from zope.app.form.browser.objectwidget import ObjectWidgetView as OWVBase
class ObjectWidgetView(zope.app.form.browser.objectwidget.ObjectWidgetView):
class ObjectWidgetView(OWVBase):
security = ClassSecurityInfo()
security.declareObjectPublic()
......@@ -33,7 +34,7 @@ class ObjectWidgetView(zope.app.form.browser.objectwidget.ObjectWidgetView):
initializeClass(ObjectWidgetView)
class ObjectWidgetClass(zope.app.form.browser.objectwidget.ObjectWidget):
class ObjectWidgetClass(OWBase):
def setRenderedValue(self, value):
"""Slightly more robust re-implementation this method."""
......
......@@ -15,14 +15,14 @@
$Id$
"""
from App.class_init import default__class_init__ as InitializeClass
from OFS.SimpleItem import SimpleItem
from Globals import InitializeClass
from Products.Five.form.objectwidget import ObjectWidget
from zope.i18nmessageid import MessageFactory
from zope.interface import implements, Interface
from zope.schema import TextLine, Text, Object, Int, List
from zope.app.form import CustomWidgetFactory
from Products.Five.form.objectwidget import ObjectWidget
_ = MessageFactory('formtest')
......
......@@ -15,12 +15,15 @@
$Id$
"""
from App.class_init import default__class_init__ as InitializeClass
from OFS.SimpleItem import SimpleItem
from Globals import InitializeClass
from zope.interface import implements, Interface
from zope.schema import ASCIILine, TextLine, List
from zope.i18nmessageid import MessageFactory
from zope.interface import implements
from zope.interface import Interface
from zope.schema import ASCIILine
from zope.schema import List
from zope.schema import TextLine
_ = MessageFactory('formtest')
......
......@@ -15,17 +15,18 @@
$Id$
"""
import Acquisition
from AccessControl import ClassSecurityInfo
from AccessControl.SecurityInfo import ClassSecurityInfo
from Acquisition import Explicit
from App.class_init import default__class_init__ as InitializeClass
from OFS.SimpleItem import SimpleItem
from Globals import InitializeClass
from zope.interface import Interface, implements
from zope.interface import implements
from zope.interface import Interface
class IFancyContent(Interface):
pass
class FancyAttribute(Acquisition.Explicit):
class FancyAttribute(Explicit):
"""Doc test fanatics"""
def __init__(self, name):
......
......@@ -15,11 +15,12 @@
$Id$
"""
from AccessControl.SecurityInfo import ClassSecurityInfo
from App.class_init import default__class_init__ as InitializeClass
from OFS.SimpleItem import SimpleItem
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from zope.interface import Interface, implements
from zope.interface import implements
from zope.interface import Interface
class ISimpleContent(Interface):
pass
......
......@@ -10,51 +10,58 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
from AccessControl.SecurityInfo import ClassSecurityInfo
import AccessControl.User
from AccessControl.User import UserFolder
from App.class_init import default__class_init__ as InitializeClass
from App.special_dtml import HTMLFile
from Acquisition import Implicit
from OFS import SimpleItem
from OFS.SimpleItem import Item
from Persistence import Persistent
manage_addPrincipiaDraftForm = HTMLFile('dtml/draftAdd',globals())
def manage_addPrincipiaDraft(self, id, baseid, PATH_INFO, REQUEST=None):
"Add a draft object"
self._setObject(id, Draft(id, baseid, PATH_INFO))
if REQUEST is not None: return self.manage_main(self,REQUEST)
if REQUEST is not None:
return self.manage_main(self,REQUEST)
class Draft(Persistent, Implicit, SimpleItem.Item):
class Draft(Persistent, Implicit, Item):
"Daft objects"
_refid=''
_version='/version'
meta_type='Zope Draft'
_refid = ''
_version = '/version'
meta_type = 'Zope Draft'
security = ClassSecurityInfo()
def __init__(self, id, baseid, PATH_INFO):
self.id=id
self._refid=baseid
version=PATH_INFO
l=version.rfind('/')
if l >= 0: version=version[:l]
self._version="%s/%s" % (version, id)
self.users__draft__=uf=AccessControl.User.UserFolder()
self.__allow_groups__=uf
self.id = id
self._refid = baseid
version = PATH_INFO
l = version.rfind('/')
if l >= 0:
version = version[:l]
self._version = "%s/%s" % (version, id)
self.users__draft__ = uf = UserFolder()
self.__allow_groups__ = uf
def icon(self):
try: return getattr(self.aq_parent.aq_base,self._refid).icon
except: return 'p_/broken'
try:
return getattr(self.aq_parent.aq_base,self._refid).icon
except:
return 'p_/broken'
def manage_options(self):
try: return getattr(self.aq_parent.aq_base,self._refid).manage_options
except: return ()
try:
return getattr(self.aq_parent.aq_base,self._refid).manage_options
except:
return ()
def title(self):
return 'draft of '+self._refid
def title_and_id(self):
nonempty=self.nonempty()
nonempty = self.nonempty()
if nonempty:
return ('draft of %s (%s)'
'</a> <a href="%s/users__draft__/manage_main">[Users]'
......@@ -77,7 +84,8 @@ class Draft(Persistent, Implicit, SimpleItem.Item):
return versionbase.get(self._version)
def _bobo_traverse__(self, REQUEST, name):
if name[-9:]=='__draft__': return getattr(self, name)
if name[-9:] == '__draft__':
return getattr(self, name)
try:
......@@ -90,16 +98,19 @@ class Draft(Persistent, Implicit, SimpleItem.Item):
# ZODB 3
jar = db.open(self._version)
cleanup = Cleanup(jar)
REQUEST[Cleanup]=cleanup
REQUEST[Cleanup] = cleanup
dself=getdraft(self, jar)
dself = getdraft(self, jar)
ref=getattr(dself.aq_parent.aq_base,dself._refid).aq_base.__of__(dself)
if hasattr(ref, name): return dself, ref, getattr(ref, name)
ref = getattr(dself.aq_parent.aq_base,dself._refid
).aq_base.__of__(dself)
if hasattr(ref, name):
return dself, ref, getattr(ref, name)
return getattr(self, name)
def nonempty(self):
try: db=self._p_jar.db()
try:
db = self._p_jar.db()
except:
# BoboPOS 2
vb = self._getVersionBase()
......@@ -116,16 +127,18 @@ class Draft(Persistent, Implicit, SimpleItem.Item):
'manage_Save__draft__')
def manage_Save__draft__(self, remark, REQUEST=None):
"""Make version changes permanent"""
try: db=self._p_jar.db()
try:
db = self._p_jar.db()
except:
# BoboPOS 2
vb = self._getVersionBase()
vb.commit(remark)
else:
# ZODB 3
s=self._version
d=self._p_jar.getVersion()
if d==s: d=''
s = self._version
d = self._p_jar.getVersion()
if d == s:
d = ''
db.commitVersion(s, d)
if REQUEST:
......@@ -135,7 +148,8 @@ class Draft(Persistent, Implicit, SimpleItem.Item):
'manage_Discard__draft__')
def manage_Discard__draft__(self, REQUEST=None):
'Discard changes made during the version'
try: db=self._p_jar.db()
try:
db = self._p_jar.db()
except:
# BoboPOS 2
vb = self._getVersionBase()
......@@ -148,11 +162,11 @@ class Draft(Persistent, Implicit, SimpleItem.Item):
REQUEST['RESPONSE'].redirect(REQUEST['URL2']+'/manage_main')
def manage_afterClone(self, item):
self._version=''
self._version = ''
def manage_afterAdd(self, item, container):
if not self._version:
self._version=self.absolute_url(1)
self._version = self.absolute_url(1)
def manage_beforeDelete(self, item, container):
if self.nonempty():
......@@ -168,7 +182,8 @@ def getdraft(ob, jar):
if hasattr(ob,'aq_parent'):
return getdraft(ob.aq_self, jar).__of__(getdraft(ob.aq_parent, jar))
if hasattr(ob,'_p_oid'): ob=jar[ob._p_oid]
if hasattr(ob,'_p_oid'):
ob = jar[ob._p_oid]
return ob
......
......@@ -113,7 +113,8 @@ class Version(Persistent,Implicit,RoleManager,Item):
'alt': self.meta_type, 'title': self.meta_type},
{'path': 'misc_/PageTemplates/exclamation.gif',
'alt': 'Deprecated object',
'title': 'Version objects are deprecated and should not be used anyore.'},)
'title': 'Version objects are deprecated '
'and should not be used anyore.'},)
security.declareProtected(change_versions, 'manage_edit')
def manage_edit(self, title, REQUEST=None):
......@@ -128,7 +129,7 @@ class Version(Persistent,Implicit,RoleManager,Item):
def enter(self, REQUEST, RESPONSE):
"""Begin working in a version.
"""
import Globals
import Globals # for data
RESPONSE.setCookie(
Globals.VersionNameName, self.cookie,
path=(REQUEST['BASEPATH1'] or '/'),
......@@ -148,7 +149,7 @@ class Version(Persistent,Implicit,RoleManager,Item):
def leave(self, REQUEST, RESPONSE):
"""Temporarily stop working in a version
"""
import Globals
import Globals # for data
RESPONSE.setCookie(
Globals.VersionNameName,'No longer active',
expires="Mon, 25-Jan-1999 23:59:59 GMT",
......@@ -234,14 +235,16 @@ class Version(Persistent,Implicit,RoleManager,Item):
self.cookie='/'.join(self.getPhysicalPath())
def manage_beforeDelete(self, item, container):
import Globals
import Globals # for data
if self.nonempty():
raise VersionException(
'Attempt to %sdelete a non-empty version.<br />' %
((self is not item) and 'indirectly ' or ''))
try: REQUEST=self.REQUEST
except: pass
try:
REQUEST=self.REQUEST
except:
pass
else:
v=self.cookie
if REQUEST.get(Globals.VersionNameName, '') == v:
......
......@@ -57,8 +57,7 @@ class PageTemplateFile(SimpleItem, Script, PageTemplate, Traversable):
func_code = FuncCode((), 0)
_v_last_read = 0
# needed by App.class_init.default__class_init__, often imported
# using the alias Globals.InitializeClass
# needed by App.class_init.default__class_init__
_need__name__ = 1
_default_bindings = {'name_subpath': 'traverse_subpath'}
......@@ -141,7 +140,7 @@ class PageTemplateFile(SimpleItem, Script, PageTemplate, Traversable):
return self.__name__ # Don't reveal filesystem paths
def _cook_check(self):
import Globals
import Globals # for data
if self._v_last_read and not Globals.DevelopmentMode:
return
__traceback_info__ = self.filename
......
......@@ -38,7 +38,6 @@ from App.special_dtml import DTMLFile
from Persistence import Persistent
from persistent import TimeStamp
from OFS.SimpleItem import Item
from OFS.ObjectManager import UNIQUE
from ZPublisher.BeforeTraverse import registerBeforeTraverse
from ZPublisher.BeforeTraverse import unregisterBeforeTraverse
from ZPublisher.BeforeTraverse import queryBeforeTraverse
......
import Zope2
from ZPublisher.BeforeTraverse import NameCaller, rewriteBeforeTraverse
from Products.SiteAccess.AccessRule import AccessRule
import transaction
def updata(self):
"""Convert SiteAccess objects from 1.x to 2.x"""
_cvt_btr(self.REQUEST['PARENTS'][-1])
from Globals import MessageDialog
from App.Dialogs import MessageDialog
return MessageDialog(title='Update Complete', message='Update Complete!',
action='./manage_main')
def _cvt_btr(app):
from ZPublisher.BeforeTraverse import NameCaller
from ZPublisher.BeforeTraverse import rewriteBeforeTraverse
from Products.SiteAccess.AccessRule import AccessRule
stack = [app]
while stack:
o = stack.pop()
......@@ -31,6 +29,8 @@ def _cvt_btr(app):
rewriteBeforeTraverse(o, btr)
if __name__ == '__main__':
import Zope2
import transaction
print "Converting SiteAccess objects from 1.x to 2.x ..."
app = Zope2.app()
_cvt_btr(app)
......
......@@ -12,39 +12,38 @@
# FOR A PARTICULAR PURPOSE
#
############################################################################
import os
import sys
import ZODB
import Globals
from ZODB import FileStorage, DB
import Globals # for data
from ZODB import DB
from ZODB import FileStorage
import transaction
import Products.Sessions.BrowserIdManager
import Products.Sessions.SessionDataManager
import Products.TemporaryFolder.TemporaryFolder
import os.path
import sys
from Products.Sessions.BrowserIdManager import BrowserIdManager
from Products.Sessions.SessionDataManager import SessionDataManager
from Products.TemporaryFolder.TemporaryFolder import MountedTemporaryFolder
fs = FileStorage.FileStorage(os.path.join(Globals.data_dir,'Data.fs.in'))
db = DB(fs)
conn = db.open()
root = conn.root()
app = root['Application']
print "Patching Data.fs.in"
tf = Products.TemporaryFolder.TemporaryFolder.MountedTemporaryFolder('temp_folder','Temporary Folder')
bid = Products.Sessions.BrowserIdManager.BrowserIdManager('browser_id_manager',
'Browser Id Manager')
sdm = Products.Sessions.SessionDataManager.SessionDataManager('session_data_manager',
title='Session Data Manager', path='/temp_folder/transient_container',
automatic=0)
tf = MountedTemporaryFolder('temp_folder','Temporary Folder')
app._setObject('temp_folder', tf)
bid = BrowserIdManager('browser_id_manager', 'Browser Id Manager')
app._setObject('browser_id_manager', bid)
sdm = r.SessionDataManager('session_data_manager',
title='Session Data Manager',
path='/temp_folder/transient_container',
automatic=0)
app._setObject('session_data_manager', sdm)
app._p_changed = 1
transaction.commit()
......@@ -13,23 +13,25 @@
__version__='$Revision$'[11:-2]
#from Globals import InitializeClass
from App.class_init import default__class_init__ as InitializeClass
from AccessControl import ClassSecurityInfo
from AccessControl import getSecurityManager
import re
import string
from AccessControl.SecurityInfo import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.Permissions import view_management_screens
from AccessControl.PermissionRole import _what_not_even_god_should_do
from AccessControl.ZopeGuards import guarded_getattr
from Acquisition import aq_parent
from Acquisition import aq_inner
from App.class_init import default__class_init__ as InitializeClass
from Persistence import Persistent
from Acquisition import aq_parent, aq_inner
from string import join, strip
import re
defaultBindings = {'name_context': 'context',
'name_container': 'container',
'name_m_self': 'script',
'name_ns': '',
'name_subpath': 'traverse_subpath'}
'name_subpath': 'traverse_subpath',
}
_marker = [] # Create a new marker
......@@ -56,7 +58,7 @@ class NameAssignments:
_isLegalName = self._isLegalName
for name, expr in self._exprs:
if mapping.has_key(name):
assigned_name = strip(mapping[name])
assigned_name = string.strip(mapping[name])
if not assigned_name:
continue
if not _isLegalName(assigned_name):
......@@ -102,7 +104,7 @@ class NameAssignments:
for assigned_name in assigned_names:
text.append('if kw.has_key("%s"):\n' % assigned_name)
text.append(' del kw["%s"]\n' % assigned_name)
codetext = join(text, '')
codetext = string.join(text, '')
return (compile(codetext, '<string>', 'exec'), len(assigned_names))
def _createCodeBlockForMapping(self):
......@@ -118,7 +120,7 @@ class NameAssignments:
assigned_name = asgns[name]
assigned_names.append(assigned_name)
exprtext.append('"%s":%s,' % (assigned_name, expr))
text = '{%s}' % join(exprtext, '')
text = '{%s}' % string.join(exprtext, '')
return self._generateCodeBlock(text, assigned_names)
def _createCodeBlockForTuple(self, argNames):
......@@ -144,7 +146,7 @@ class NameAssignments:
if passedLastBoundArg:
# Found last of bound args.
break
text = '(%s)' % join(exprtext, '')
text = '(%s)' % string.join(exprtext, '')
return self._generateCodeBlock(text, assigned_names)
......
......@@ -15,35 +15,39 @@ __doc__='''Generic Database Connection Support
$Id$'''
__version__='$Revision: 1.39 $'[11:-2]
from cgi import escape
from cStringIO import StringIO
from logging import getLogger
import Globals, OFS.SimpleItem, AccessControl.Role, Acquisition, sys
from DateTime import DateTime
from App.Dialogs import MessageDialog
from Globals import DTMLFile
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
import string
import sys
from AccessControl.Permissions import view_management_screens
from AccessControl.Permissions import change_database_connections
from AccessControl.Permissions import test_database_connections
from AccessControl.Permissions import open_close_database_connection
from string import find, join, split
from Aqueduct import custom_default_report
from cStringIO import StringIO
from Results import Results
from cgi import escape
import DocumentTemplate, RDB
from AccessControl.Role import RoleManager
from AccessControl.SecurityInfo import ClassSecurityInfo
from Acquisition import Implicit
from App.class_init import default__class_init__ as InitializeClass
from App.Dialogs import MessageDialog
from App.special_dtml import DTMLFile
from DateTime.DateTime import DateTime
from DocumentTemplate import HTML
from OFS.SimpleItem import Item
from Persistence import Persistent
from zExceptions import BadRequest
from Aqueduct import custom_default_report
import RDB
from Results import Results
LOG = getLogger('ZRDB.Connection')
class Connection(
Globals.Persistent,
AccessControl.Role.RoleManager,
OFS.SimpleItem.Item,
Acquisition.Implicit,
):
class Connection(Persistent,
RoleManager,
Item,
Implicit,
):
security = ClassSecurityInfo()
......@@ -54,8 +58,8 @@ class Connection(
{'label':'Properties', 'action':'manage_properties'},
{'label':'Test', 'action':'manage_testForm'},
)
+AccessControl.Role.RoleManager.manage_options
+OFS.SimpleItem.Item.manage_options
+ RoleManager.manage_options
+ Item.manage_options
)
_v_connected=''
......@@ -135,14 +139,14 @@ class Connection(
else:
r='This statement returned no results.'
report=DocumentTemplate.HTML(
report = HTML(
'<html><body bgcolor="#ffffff" link="#000099" vlink="#555555">\n'
'<dtml-var name="manage_tabs">\n<hr>\n%s\n\n'
'<hr><h4>SQL Used:</strong><br>\n<pre>\n%s\n</pre>\n<hr>\n'
'</body></html>'
% (r, query))
report=apply(report,(self,REQUEST),{self.id:result})
report = apply(report,(self,REQUEST),{self.id:result})
return report
......@@ -199,7 +203,8 @@ class Connection(
return self
def sql_quote__(self, v):
if find(v,"\'") >= 0: v=join(split(v,"\'"),"''")
if string.find(v,"\'") >= 0:
v = string.join(string.split(v,"\'"),"''")
return "'%s'" % v
InitializeClass(Connection)
......@@ -91,8 +91,8 @@ _exec('import ZODB')
import ZODB
_write('.')
_exec('import Globals')
import Globals
#_exec('import Globals')
#import Globals
_exec('import OFS.SimpleItem')
import OFS.SimpleItem
_exec('import OFS.ObjectManager')
......@@ -166,6 +166,7 @@ def installProduct(name, quiet=0):
def _installProduct(name, quiet=0):
'''Installs a Zope product.'''
from App.class_init import default__class_init__ as InitializeClass
start = time.time()
meta_types = []
if _patched and not _installedProducts.has_key(name):
......@@ -178,7 +179,7 @@ def _installProduct(name, quiet=0):
get_folder_permissions(), raise_exc=1)
_installedProducts[product_name] = 1
Products.meta_types = Products.meta_types + tuple(meta_types)
Globals.InitializeClass(Folder)
InitializeClass(Folder)
if not quiet: _print('done (%.3fs)\n' % (time.time() - start))
break
else:
......
......@@ -20,16 +20,18 @@ information about XML-RPC and Zope.
"""
import re
import sys, types
from HTTPResponse import HTTPResponse
import sys
import types
import xmlrpclib
from zExceptions import Unauthorized
from ZODB.POSException import ConflictError
from ZPublisher.HTTPResponse import HTTPResponse
# Make DateTime.DateTime marshallable via XML-RPC
# http://www.zope.org/Collectors/Zope/2109
from DateTime import DateTime
from DateTime.DateTime import DateTime
WRAPPERS = xmlrpclib.WRAPPERS + (DateTime,)
def dump_instance(self, value, write):
......@@ -167,8 +169,8 @@ class Response:
remove = [r"<[^<>]*>", r"&[A-Za-z]+;"]
for pat in remove:
vstr = re.sub(pat, " ", vstr)
from Globals import DevelopmentMode
if DevelopmentMode:
import Globals # for data
if Globals.DevelopmentMode:
from traceback import format_exception
value = '\n' + ''.join(format_exception(t, vstr, tb))
else:
......
......@@ -14,13 +14,19 @@
$Id$
"""
import sys, cgi, urllib, cgi
from Tree import encodeExpansion, decodeExpansion, TreeMaker
from SimpleTree import SimpleTreeMaker
from Batch import Batch
from Products.ZCatalog.Lazy import Lazy
import cgi
import sys
import urllib
from AccessControl import getSecurityManager
from DateTime import DateTime
from DateTime.DateTime import DateTime
from Products.ZCatalog.Lazy import Lazy
from ZTUtils.Batch import Batch
from ZTUtils.SimpleTree import SimpleTreeMaker
from ZTUtils.Tree import decodeExpansion
from ZTUtils.Tree import encodeExpansion
from ZTUtils.Tree import TreeMaker
try:
from AccessControl.ZopeGuards import guarded_getitem
......@@ -32,7 +38,7 @@ except ImportError:
return v
raise Unauthorized, 'unauthorized access to element %s' % `i`
else:
from AccessControl import Unauthorized
from AccessControl.unauthorized import Unauthorized
class LazyFilter(Lazy):
......
......@@ -30,7 +30,6 @@ import transaction
import AccessControl.User
import App.FindHomes
import ExtensionClass
import Globals
import imp
import logging
import OFS.Application
......@@ -49,6 +48,7 @@ startup_time = asctime()
def startup():
from App.PersistentExtra import patchPersistent
import Globals # to set / fetch data
patchPersistent()
global app
......@@ -95,7 +95,7 @@ def startup():
Zope2.DB = DB
# Hook for providing multiple transaction object manager undo support:
Globals.UndoManager=DB
Globals.UndoManager = DB
Globals.opened.append(DB)
import ClassFactory
......@@ -133,6 +133,7 @@ def startup():
def validated_hook(request, user):
import Globals # to fetch data
newSecurityManager(request, user)
version = request.get(Globals.VersionNameName, '')
if version:
......@@ -148,7 +149,6 @@ def validated_hook(request, user):
raise Unauthorized, "You don't have permission to enter versions."
class RequestContainer(ExtensionClass.Base):
def __init__(self,r): self.REQUEST=r
......
......@@ -38,7 +38,7 @@ started = False
def stuff_Globals():
# Stuff BBB names into the Globals module
import Globals
import Globals # to set data
import TreeDisplay
Globals.TreeDisplay = TreeDisplay
......@@ -86,7 +86,7 @@ def start_zope(cfg, debug_handler):
# Don't allow any code to call start_zope() twice.
return
stuff_Globals()
stuff_Globals() # XXX should this be optional?
starter = get_starter()
starter.setConfiguration(cfg)
......@@ -198,7 +198,7 @@ class ZopeStarter:
logger.error(msg)
def setupPublisher(self):
import Globals
import Globals # to set data
import ZPublisher.HTTPRequest
import ZPublisher.Publish
Globals.DevelopmentMode = self.cfg.debug_mode
......
......@@ -46,8 +46,8 @@ def _setenv(name, value):
def debug_mode(value):
value and _setenv('Z_DEBUG_MODE', '1')
import Globals
Globals.DevelopmentMode = not not value
import Globals # to set value
Globals.DevelopmentMode = boolean(value)
return value
def locale(value):
......
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