rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
_stupid_dest("%s: %s\n" % error[:2])
|
_stupid_dest.write("%s: %s\n" % error[:2])
|
def stupid_log_write(subsystem, severity, summary, detail, error): if severity < 0: return global _stupid_dest if _stupid_dest is None: import os if os.environ.has_key('STUPID_LOG_FILE'): f=os.environ['STUPID_LOG_FILE'] if f: _stupid_dest=open(f,'a') else: import sys _stupid_dest=sys.stderr else: _stupid_dest=_no_stupid_log if _stupid_dest is _no_stupid_log: return _stupid_dest.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) _stupid_dest.flush() if error: try: _stupid_dest(format_exception( error[0], error[1], error[2], trailer='\n', limit=100)) except: _stupid_dest("%s: %s\n" % error[:2])
|
self.headers[n]=value
|
self.headers[name]=value
|
def setHeader(self, name, value): self.headers[n]=value
|
result=self.getUser(id) return result.__of__(self)
|
return self.getUser(id)
|
def getUserById(self, id, default=_marker): """Return the user corresponding to the given id. """ # The connection between getting by ID and by name is not a strong # one try: result=self.getUser(id) return result.__of__(self) # Wrap in our context except: if default is _marker: raise return default
|
('index_html', 'tag', 'view_image_or_file', 'getSize',
|
('index_html', 'view_image_or_file', 'getSize',
|
def manage_addFile(self,id,file='',title='',precondition='', content_type='', REQUEST=None): """Add a new File object. Creates a new File object 'id' with the contents of 'file'""" id, title = cookId(id, title, file) self=self.this() # First, we create the file without data: self._setObject(id, File(id,title,'',content_type, precondition)) # Now we "upload" the data. By doing this in two steps, we # can use a database trick to make the upload more efficient. self._getOb(id).manage_upload(file) if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
|
LOG('Transience', WARNING, ('Transient object container %s max subobjects ' 'reached' % self.getId()) )
|
LOG.warn('Transient object container %s max subobjects ' 'reached' % self.getId())
|
def __setitem__(self, k, v): DEBUG and TLOG('__setitem__: called with key %s, value %s' % (k,v)) if self._timeout_slices: current_ts = getCurrentTimeslice(self._period) else: current_ts = 0 item = self._move_item(k, current_ts, _marker) STRICT and _assert(self._data.has_key(current_ts)) if item is _marker: # the key didnt already exist, this is a new item
|
LOG('Transience', WARNING, err % (callback, '/'.join(path)), error=sys.exc_info() )
|
LOG.warn(err % (callback, '/'.join(path)), exc_info=sys.exc_info())
|
def _getCallback(self, callback): if not callback: return None if type(callback) is type(''): try: method = self.unrestrictedTraverse(callback) except (KeyError, AttributeError): path = self.getPhysicalPath() err = 'No such onAdd/onDelete method %s referenced via %s' LOG('Transience', WARNING, err % (callback, '/'.join(path)), error=sys.exc_info() ) return else: method = callback return method
|
LOG('Transience', WARNING, '%s failed when calling %s in %s' % (name,callback, '/'.join(path)), error=sys.exc_info() )
|
LOG.warn('%s failed when calling %s in %s' % (name,callback, '/'.join(path)), exc_info=sys.exc_info())
|
def _notify(self, item, callback, name): if callable(callback): sm = getSecurityManager() try: user = sm.getUser() try: newSecurityManager(None, nobody) callback(item, self) except: # dont raise, just log path = self.getPhysicalPath() LOG('Transience', WARNING, '%s failed when calling %s in %s' % (name,callback, '/'.join(path)), error=sys.exc_info() ) finally: setSecurityManager(sm) else: err = '%s in %s attempted to call non-callable %s' path = self.getPhysicalPath() LOG('Transience', WARNING, err % (name, '/'.join(path), callback), error=sys.exc_info() )
|
LOG('Transience', WARNING, err % (name, '/'.join(path), callback), error=sys.exc_info() )
|
LOG.warn(err % (name, '/'.join(path), callback), exc_info=sys.exc_info())
|
def _notify(self, item, callback, name): if callable(callback): sm = getSecurityManager() try: user = sm.getUser() try: newSecurityManager(None, nobody) callback(item, self) except: # dont raise, just log path = self.getPhysicalPath() LOG('Transience', WARNING, '%s failed when calling %s in %s' % (name,callback, '/'.join(path)), error=sys.exc_info() ) finally: setSecurityManager(sm) else: err = '%s in %s attempted to call non-callable %s' path = self.getPhysicalPath() LOG('Transience', WARNING, err % (name, '/'.join(path), callback), error=sys.exc_info() )
|
return Globals.Bobobase['roles']
|
return self.validRoles()
|
def roleNames(self):
|
if not headers.has_key('content-type') and self.status == 200: self.setStatus('nocontent')
|
def __str__(self, html_search=regex.compile('<html>',regex.casefold).search, ): if self._wrote: return '' # Streaming output was used.
|
|
clip_data='',REQUEST):
|
clip_data='',REQUEST=None):
|
def manage_delObjects(self,ids=[],submit='',clip_id='', clip_data='',REQUEST):
|
self.parser = None
|
self.parser = self.feed = None
|
def close(self): try: self.parser.close() finally: self.parser = None # nuke circular reference
|
This method will cause this object to get reindexed. Of this
|
This method will cause this object to get reindexed. If this
|
def reindex_all(self, obj=None): """
|
if SUPPORTS_WEBDAV_LOCKS: __implements__ = (WriteLockInterface,)
|
__implements__ = (WriteLockInterface,)
|
def __call__(self, REQUEST, RESPONSE): " " return self.document_src(REQUEST)
|
if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
|
if self.wl_isLocked():
|
def pt_editAction(self, REQUEST, title, text, content_type, expand): """Change the title and document.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError, "File is locked via WebDAV" self.expand=expand self.pt_setTitle(title) self.pt_edit(text, content_type) REQUEST.set('text', self.read()) # May not equal 'text'! REQUEST.set('title', self.title) message = "Saved changes." if getattr(self, '_v_warnings', None): message = ("<strong>Warning:</strong> <i>%s</i>" % '<br>'.join(self._v_warnings)) return self.pt_editForm(manage_tabs_message=message)
|
if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
|
if self.wl_isLocked():
|
def pt_upload(self, REQUEST, file='', charset=None): """Replace the document with the text in file.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): raise ResourceLockedError, "File is locked via WebDAV"
|
if SUPPORTS_WEBDAV_LOCKS: self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
|
self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
|
def PUT(self, REQUEST, RESPONSE): """ Handle HTTP PUT requests """ self.dav__init(REQUEST, RESPONSE) if SUPPORTS_WEBDAV_LOCKS: self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) self.write(REQUEST.get('BODY', '')) RESPONSE.setStatus(204) return RESPONSE
|
if not SUPPORTS_WEBDAV_LOCKS: def wl_isLocked(self): return 0
|
def pt_source_file(self): """Returns a file name to be compiled into the TAL code.""" try: return '/'.join(self.getPhysicalPath()) except: # This page template is being compiled without an # acquisition context, so we don't know where it is. :-( return None
|
|
examples_path = os.path.join(Globals.data_dir, 'Examples.zexp')
|
examples_path = os.path.join(Globals.INSTANCE_HOME, 'import', 'Examples.zexp')
|
def initialize(app): # Initialize the application # Initialize the cache: app.Control_Panel.initialize_cache() # The following items marked b/c are backward compatibility hacks # which make sure that expected system objects are added to the # bobobase. This is required because the bobobase in use may pre- # date the introduction of certain system objects such as those # which provide Lever support. # b/c: Ensure that Control Panel exists. if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().note('Added Control_Panel') get_transaction().commit() # b/c: Ensure that a ProductFolder exists. if not hasattr(app.Control_Panel.aq_base, 'Products'): app.Control_Panel.Products=App.Product.ProductFolder() get_transaction().note('Added Control_Panel.Products') get_transaction().commit() # Ensure that a temp folder exists if not hasattr(app, 'temp_folder'): from Products.TemporaryFolder.TemporaryFolder import \ MountedTemporaryFolder tf = MountedTemporaryFolder('temp_folder','Temporary Folder') app._setObject('temp_folder', tf) get_transaction().note('Added temp_folder') get_transaction().commit() del tf # Ensure that there is a transient container in the temp folder tf = app.temp_folder if not hasattr(tf, 'session_data'): env_has = os.environ.get from Products.Transience.Transience import TransientObjectContainer addnotify = env_has('ZSESSION_ADD_NOTIFY', None) delnotify = env_has('ZSESSION_DEL_NOTIFY', None) default_limit = 1000 limit = env_has('ZSESSION_OBJECT_LIMIT', default_limit) try: limit=int(limit) if limit != default_limit: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_OBJECT_LIMIT-specified max objects ' 'value of %s' % limit)) except ValueError: LOG('Zope Default Object Creation', WARNING, ('Noninteger value %s specified for ZSESSION_OBJECT_LIMIT, ' 'defaulting to %s' % (limit, default_limit))) limit = default_limit if addnotify and app.unrestrictedTraverse(addnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_ADD_NOTIFY' % addnotify)) addnotify=None elif addnotify: LOG('Zope Default Object Creation', INFO, 'using %s as add notification script' % addnotify) if delnotify and app.unrestrictedTraverse(delnotify, None) is None: LOG('Zope Default Object Creation', WARNING, ('failed to use nonexistent "%s" script as ' 'ZSESSION_DEL_NOTIFY' % delnotify)) delnotify=None elif delnotify: LOG('Zope Default Object Creation', INFO, 'using %s as delete notification script' % delnotify) toc = TransientObjectContainer('session_data', 'Session Data Container', addNotification = addnotify, delNotification = delnotify, limit=limit) timeout_spec = env_has('ZSESSION_TIMEOUT_MINS', '') if timeout_spec: try: timeout_spec = int(timeout_spec) except ValueError: LOG('Zope Default Object Creation', WARNING, ('"%s" is an illegal value for ZSESSION_TIMEOUT_MINS, ' 'using default timeout instead.' % timeout_spec)) else: LOG('Zope Default Object Creation', INFO, ('using ZSESSION_TIMEOUT_MINS-specified session timeout ' 'value of %s' % timeout_spec)) toc = TransientObjectContainer('session_data', 'Session Data Container', timeout_mins = timeout_spec, addNotification=addnotify, delNotification = delnotify, limit=limit) tf._setObject('session_data', toc) tf_reserved = getattr(tf, '_reserved_names', ()) if 'session_data' not in tf_reserved: tf._reserved_names = tf_reserved + ('session_data',) get_transaction().note('Added session_data to temp_folder') get_transaction().commit() del toc del addnotify del delnotify del timeout_spec del env_has del tf # Ensure that a browser ID manager exists if not hasattr(app, 'browser_id_manager'): from Products.Sessions.BrowserIdManager import BrowserIdManager bid = BrowserIdManager('browser_id_manager', 'Browser Id Manager') app._setObject('browser_id_manager', bid) get_transaction().note('Added browser_id_manager') get_transaction().commit() del bid # Ensure that a session data manager exists if not hasattr(app, 'session_data_manager'): from Products.Sessions.SessionDataManager import SessionDataManager sdm = SessionDataManager('session_data_manager', title='Session Data Manager', path='/temp_folder/session_data', requestName='SESSION') app._setObject('session_data_manager', sdm) get_transaction().note('Added session_data_manager') get_transaction().commit() del sdm # Ensure that there's an Examples folder with examples. # However, make sure that if the examples have been added already # and then deleted that we don't add them again. if not hasattr(app, 'Examples') and not \ hasattr(app, '_Zope25_examples_have_been_added'): examples_path = os.path.join(Globals.data_dir, 'Examples.zexp') if os.path.isfile(examples_path): app._importObjectFromFile(examples_path, verify=0) app._Zope25_examples_have_been_added=1 get_transaction().note('Added Examples folder') get_transaction().commit() else: LOG('Zope Default Object Creation', INFO, '%s examples import file could not be found.' % examples_path) # b/c: Ensure that Owner role exists. if hasattr(app, '__ac_roles__') and not ('Owner' in app.__ac_roles__): app.__ac_roles__=app.__ac_roles__ + ('Owner',) get_transaction().note('Added Owner role') get_transaction().commit() # ensure the Authenticated role exists. if hasattr(app, '__ac_roles__'): if not 'Authenticated' in app.__ac_roles__: app.__ac_roles__=app.__ac_roles__ + ('Authenticated',) get_transaction().note('Added Authenticated role') get_transaction().commit() # Make sure we have Globals root=app._p_jar.root() if not root.has_key('ZGlobals'): import BTree app._p_jar.root()['ZGlobals']=BTree.BTree() get_transaction().note('Added Globals') get_transaction().commit() # Install the initial user. if hasattr(app, 'acl_users'): users = app.acl_users if hasattr(users, '_createInitialUser'): app.acl_users._createInitialUser() get_transaction().note('Created initial user') get_transaction().commit() install_products(app) install_standards(app) # Note that the code from here on only runs if we are not a ZEO # client, or if we are a ZEO client and we've specified by way # of env variable that we want to force products to load. if (os.environ.get('ZEO_CLIENT') and not os.environ.get('FORCE_PRODUCT_LOAD')): return # Check for dangling pointers (broken zclass dependencies) in the # global class registry. If found, rebuild the registry. Note that # if the check finds problems but fails to successfully rebuild the # registry we abort the transaction so that we don't leave it in an # indeterminate state. did_fixups=0 bad_things=0 try: if app.checkGlobalRegistry(): LOG('Zope', INFO, 'Beginning attempt to rebuild the global ZClass registry.') app.fixupZClassDependencies(rebuild=1) did_fixups=1 LOG('Zope', INFO, 'The global ZClass registry has successfully been rebuilt.') get_transaction().note('Rebuilt global product registry') get_transaction().commit() except: bad_things=1 LOG('Zope', ERROR, 'The attempt to rebuild the registry failed.', error=sys.exc_info()) get_transaction().abort() # Now we need to see if any (disk-based) products were installed # during intialization. If so (and the registry has no errors), # there may still be zclasses dependent on a base class in the # newly installed product that were previously broken and need to # be fixed up. If any really Bad Things happened (dangling pointers # were found in the registry but it couldn't be rebuilt), we don't # try to do anything to avoid making the problem worse. if (not did_fixups) and (not bad_things): # App.Product.initializeProduct will set this if a disk-based # product was added or updated and we are not a ZEO client. if getattr(Globals, '__disk_product_installed__', 0): try: LOG('Zope', INFO, 'New disk product detected, determining '\ 'if we need to fix up any ZClasses.') if app.fixupZClassDependencies(): LOG('Zope', INFO, 'Repaired broken ZClass dependencies.') get_transaction().commit() except: LOG('Zope', ERROR, 'Attempt to fixup ZClass dependencies after detecting ' \ 'an updated disk-based product failed.', error=sys.exc_info()) get_transaction().abort()
|
product_names.remove("PluginIndexes") product_names.insert(0,"PluginIndexes")
|
if "PluginIndexes" in product_names: product_names.remove("PluginIndexes") product_names.insert(0,"PluginIndexes")
|
def import_products(): # Try to import each product, checking for and catching errors. done={} for product_dir in Products.__path__: product_names=os.listdir(product_dir) product_names.sort() # Hack !!! # We must initialize the PluginIndexes first before # all other products (ajung) product_names.remove("PluginIndexes") product_names.insert(0,"PluginIndexes") for product_name in product_names: if done.has_key(product_name): continue done[product_name]=1 import_product(product_dir, product_name)
|
product_names.remove("PluginIndexes") product_names.insert(0,"PluginIndexes")
|
if "PluginIndexes" in product_names: product_names.remove("PluginIndexes") product_names.insert(0,"PluginIndexes")
|
def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products folder_permissions = get_folder_permissions() meta_types=[] done={} get_transaction().note('Prior to product installs') get_transaction().commit() for product_dir in Products.__path__: product_names=os.listdir(product_dir) product_names.sort() # Hack !!! # We must initialize the PluginIndexes first before # all other products (ajung) product_names.remove("PluginIndexes") product_names.insert(0,"PluginIndexes") for product_name in product_names: # For each product, we will import it and try to call the # intialize() method in the product __init__ module. If # the method doesnt exist, we put the old-style information # together and do a default initialization. if done.has_key(product_name): continue done[product_name]=1 install_product(app, product_dir, product_name, meta_types, folder_permissions) Products.meta_types=Products.meta_types+tuple(meta_types) Globals.default__class_init__(Folder.Folder)
|
BUILD_BASE=os.path.join(os.getcwd(), 'build-base')
|
BUILD_BASE=os.path.join(os.getcwd(), 'build-base', 'python-%s.%s' % sys.version_info[:2])
|
def main(): # below assumes this script is in the BASE_DIR/inst directory global PREFIX BASE_DIR=os.path.abspath(os.path.dirname(os.path.dirname(sys.argv[0]))) BUILD_BASE=os.path.join(os.getcwd(), 'build-base') PYTHON=sys.executable MAKEFILE=open(os.path.join(BASE_DIR, 'inst', IN_MAKEFILE)).read() REQUIRE_LF_ENABLED = 1 REQUIRE_ZLIB = 1 REQUIRE_EXPAT = 1 INSTALL_FLAGS = '' DISTUTILS_OPTS = '' try: longopts = ['help', 'ignore-largefile', 'ignore-zlib', 'ignore-expat', 'prefix=', 'build-base=', 'optimize', 'no-compile', 'quiet'] opts, args = getopt.getopt(sys.argv[1:], 'h', longopts) except getopt.GetoptError, v: print v usage() sys.exit(1) for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() if o == '--prefix': PREFIX=os.path.abspath(os.path.expanduser(a)) if o == '--ignore-largefile': REQUIRE_LF_ENABLED=0 if o == '--ignore-zlib': REQUIRE_ZLIB=0 if o == '--ignore-expat': REQUIRE_EXPAT=0 if o == '--optimize': INSTALL_FLAGS = '--optimize=1 --no-compile' if o == '--no-compile': INSTALL_FLAGS = '--no-compile' if o == '--build-base': BUILD_BASE = a if o == '--quiet': DISTUTILS_OPTS = '-q' global QUIET QUIET = 1 if REQUIRE_LF_ENABLED: test_largefile() if REQUIRE_ZLIB: test_zlib() if REQUIRE_EXPAT: test_expat() out(' - Zope top-level binary directory will be %s.' % PREFIX) if INSTALL_FLAGS: out(' - Distutils install flags will be "%s"' % INSTALL_FLAGS) idata = { '<<PYTHON>>':PYTHON, '<<PREFIX>>':PREFIX, '<<BASE_DIR>>':BASE_DIR, '<<BUILD_BASE>>':BUILD_BASE, '<<INSTALL_FLAGS>>':INSTALL_FLAGS, '<<ZOPE_MAJOR_VERSION>>':versions.ZOPE_MAJOR_VERSION, '<<ZOPE_MINOR_VERSION>>':versions.ZOPE_MINOR_VERSION, '<<VERSION_RELEASE_TAG>>':versions.VERSION_RELEASE_TAG, '<<DISTUTILS_OPTS>>':DISTUTILS_OPTS, } for k,v in idata.items(): MAKEFILE = MAKEFILE.replace(k, v) f = open(os.path.join(os.getcwd(), 'makefile'), 'w') f.write(MAKEFILE) out(' - Makefile written.') out('') out(' Next, run %s.' % MAKE_COMMAND) out('')
|
try: return d[key] except KeyError, AttributeError: pass
|
try: return d[key] except (KeyError, AttributeError): pass
|
def __getitem__(self, key): for d in self.dicts: try: return d[key] except KeyError, AttributeError: pass raise KeyError, key
|
if name and name[:1] in '@+':
|
if name and name[:1] in '@+' and name != '+':
|
def unrestrictedTraverse(self, path, default=_marker, restricted=False): """Lookup an object by path.
|
einfo = sys.exc_info() if type(einfo[0])==type(''): errname = einfo[0]
|
t,v = sys.exc_info()[:2] if type(t)==type(''): errname = t
|
def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except: # but an error occurs.. save the info. einfo = sys.exc_info() if type(einfo[0])==type(''): errname = einfo[0] else: errname = einfo[0].__name__
|
errname = einfo[0].__name__
|
errname = t.__name__
|
def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except: # but an error occurs.. save the info. einfo = sys.exc_info() if type(einfo[0])==type(''): errname = einfo[0] else: errname = einfo[0].__name__
|
handler = self.find_handler(einfo[0])
|
handler = self.find_handler(t)
|
def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except: # but an error occurs.. save the info. einfo = sys.exc_info() if type(einfo[0])==type(''): errname = einfo[0] else: errname = einfo[0].__name__
|
ns = namespace(self, error_type=errname, error_value=einfo[1],
|
ns = namespace(self, error_type=errname, error_value=v,
|
def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except: # but an error occurs.. save the info. einfo = sys.exc_info() if type(einfo[0])==type(''): errname = einfo[0] else: errname = einfo[0].__name__
|
doc(person=person)
|
doc(person=person())
|
def testNoImplicitAccess(self): class person: name='Jim'
|
import os
|
def stupid_log_write(subsystem, severity, summary, detail, error): if severity < 0: return global _stupid_dest if _stupid_dest is None: import os if os.environ.has_key('STUPID_LOG_FILE'): f=os.environ['STUPID_LOG_FILE'] if f: _stupid_dest=open(f,'a') else: import sys _stupid_dest=sys.stderr else: _stupid_dest=_no_stupid_log import os if os.environ.has_key('Z_DEBUG_MODE'): import sys sys.stderr.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) sys.stderr.flush() if _stupid_dest is _no_stupid_log: return _stupid_dest.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) _stupid_dest.flush() if error: try: _stupid_dest.write(format_exception( error[0], error[1], error[2], trailer='\n', limit=100)) except: _stupid_dest.write("%s: %s\n" % error[:2])
|
|
else: import sys _stupid_dest=sys.stderr
|
else: _stupid_dest=sys.stderr elif os.environ.get('Z_DEBUG_MODE',0): _stupid_dest=sys.stderr
|
def stupid_log_write(subsystem, severity, summary, detail, error): if severity < 0: return global _stupid_dest if _stupid_dest is None: import os if os.environ.has_key('STUPID_LOG_FILE'): f=os.environ['STUPID_LOG_FILE'] if f: _stupid_dest=open(f,'a') else: import sys _stupid_dest=sys.stderr else: _stupid_dest=_no_stupid_log import os if os.environ.has_key('Z_DEBUG_MODE'): import sys sys.stderr.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) sys.stderr.flush() if _stupid_dest is _no_stupid_log: return _stupid_dest.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) _stupid_dest.flush() if error: try: _stupid_dest.write(format_exception( error[0], error[1], error[2], trailer='\n', limit=100)) except: _stupid_dest.write("%s: %s\n" % error[:2])
|
import os if os.environ.has_key('Z_DEBUG_MODE'): import sys sys.stderr.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) sys.stderr.flush()
|
def stupid_log_write(subsystem, severity, summary, detail, error): if severity < 0: return global _stupid_dest if _stupid_dest is None: import os if os.environ.has_key('STUPID_LOG_FILE'): f=os.environ['STUPID_LOG_FILE'] if f: _stupid_dest=open(f,'a') else: import sys _stupid_dest=sys.stderr else: _stupid_dest=_no_stupid_log import os if os.environ.has_key('Z_DEBUG_MODE'): import sys sys.stderr.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) sys.stderr.flush() if _stupid_dest is _no_stupid_log: return _stupid_dest.write( "------\n" "%s %s %s %s\n%s" % (log_time(), severity_string(severity), subsystem, summary, detail, ) ) _stupid_dest.flush() if error: try: _stupid_dest.write(format_exception( error[0], error[1], error[2], trailer='\n', limit=100)) except: _stupid_dest.write("%s: %s\n" % error[:2])
|
|
def _checkId(self, id, allow_dup=1, _reserved=('propertysheets',)):
|
def _checkId(self, id, allow_dup=0, _reserved=('propertysheets','manage_workspace')):
|
def _checkId(self, id, allow_dup=1, _reserved=('propertysheets',)): if id in _reserved: raise 'Bad Request', 'The id, %s, is reseverd' % id ZClassMethodsSheet.inheritedAttribute('_checkId')( self, id, allow_dup) return id+' '
|
self, id, allow_dup)
|
self, id, 0)
|
def _checkId(self, id, allow_dup=1, _reserved=('propertysheets',)): if id in _reserved: raise 'Bad Request', 'The id, %s, is reseverd' % id ZClassMethodsSheet.inheritedAttribute('_checkId')( self, id, allow_dup) return id+' '
|
data=(headers is None) and file or file.read()
|
if hasattr(file, 'read'): data=file.read() else: data=file
|
def __init__(self, id, title, file, content_type='', precondition=''): self.__name__=id self.title=title self.precondition=precondition headers=hasattr(file, 'headers') and file.headers or None data=(headers is None) and file or file.read() if headers and headers.has_key('content-type') and (not content_type): content_type=headers['content-type'] if not content_type: content_type, enc=mimetypes.guess_type(id) if not content_type: if content_types.find_binary(data) >= 0: content_type='application/octet-stream' else: content_type=content_types.text_type(data) content_type=string.lower(content_type) self.update_data(data, content_type)
|
def positions(self, docid, words):
|
def positions(self, docid, words, obj):
|
def positions(self, docid, words): """Return the positions in the document for the given document id of the word, word.""" id = self.id
|
row = self._data[docid]
|
def positions(self, docid, words): """Return the positions in the document for the given document id of the word, word.""" id = self.id
|
|
doc = str(f(row, id)())
|
doc = str(f(obj, id)())
|
def positions(self, docid, words): """Return the positions in the document for the given document id of the word, word.""" id = self.id
|
doc = str(f(row, id))
|
doc = str(f(obj, id))
|
def positions(self, docid, words): """Return the positions in the document for the given document id of the word, word.""" id = self.id
|
db.SetCacheSize(self._cache_size) db.SetCacheDeactivateAfter(self._cache_age) db.SetVersionCacheSize(self._vcache_size) db.SetVersionCacheDeactivateAfter(self._vcache_age)
|
db.setCacheSize(self._cache_size) db.setCacheDeactivateAfter(self._cache_age) db.setVersionCacheSize(self._vcache_size) db.setVersionCacheDeactivateAfter(self._vcache_age)
|
def initialize_cache(self): try: db=self._p_jar.db() except: # BoboPOS2 Globals.Bobobase._jar.cache.cache_size=self._cache_size Globals.Bobobase._jar.cache.cache_age =self._cache_age else: db.SetCacheSize(self._cache_size) db.SetCacheDeactivateAfter(self._cache_age) db.SetVersionCacheSize(self._vcache_size) db.SetVersionCacheDeactivateAfter(self._vcache_age)
|
options=[] for option in c.manage_options: copy={} copy.update(option) options.append(copy) c.manage_options=tuple(options)
|
if zope_object: options=[] for option in c.manage_options: copy={} copy.update(option) options.append(copy) c.manage_options=tuple(options)
|
def __init__(self, id, title, bases, zope_object=1): """Build a Zope class
|
def pt_macro(self):
|
def pt_macros(self):
|
def pt_macro(self): self._cook_check() return PageTemplate.pt_macro(self)
|
return PageTemplate.pt_macro(self)
|
return PageTemplate.pt_macros(self)
|
def pt_macro(self): self._cook_check() return PageTemplate.pt_macro(self)
|
k=None
|
def sort_sequence(self, sequence):
|
|
if mapping: k=v[sort] else: k=getattr(v, sort) if not basic_type(k): try: k=k() except: pass
|
if multsort: k = [] for sk in sortfields: try: if mapping: akey = v[sk] else: akey = getattr(v, sk) except AttributeError, KeyError: akey = None if not basic_type(akey): try: akey = akey() except: pass k.append(akey) else: try: if mapping: k = v[sort] else: k = getattr(v, sort) except AttributeError, KeyError: k = None if not basic_type(k): try: k = k() except: pass
|
def sort_sequence(self, sequence):
|
basic_type={type(''): 1, type(0): 1, type(0.0): 1, type(()): 1, type([]): 1 }.has_key
|
basic_type={type(''): 1, type(0): 1, type(0.0): 1, type(()): 1, type([]): 1, type(None) : 1 }.has_key
|
def reverse_sequence(self, sequence): s=list(sequence) s.reverse() return s
|
e=e+1
|
def __getitem__(self,index):
|
|
except Unauthorized, vv:
|
except 'Unauthorized', vv:
|
def __getitem__(self,index):
|
continue if skip and not getSecurityManager().checkPermission(skip, v): continue if test is None or test(v): data.append(v) ind=ind+1
|
skip_this = 1 else: skip_this = 0
|
def __getitem__(self,index):
|
do("chown %s %s" % (group, path), 0)
|
do("chown %s %s" % (user, path), 0)
|
def ch(path, user, group, mode=0600): if group: mode=mode+060 do("chgrp %s %s" % (group, path), 0) if user: do("chown %s %s" % (group, path), 0) do("chmod %s %s" % (oct(mode), path), 0)
|
if not hasattr(app.Control_Panel, 'Products'):
|
if not hasattr(app.Control_Panel.aq_base, 'Products'):
|
def open_bobobase(): # Open the application database Bobobase=Globals.Bobobase=Globals.PickleDictionary(Globals.BobobaseName) product_dir=os.path.join(SOFTWARE_HOME,'lib/python/Products') __traceback_info__=sys.path try: app=Bobobase['Application'] except KeyError: app=Application() app._init() Bobobase['Application']=app get_transaction().commit() # The following items marked b/c are backward compatibility hacks # which make sure that expected system objects are added to the # bobobase. This is required because the bobobase in use may pre- # date the introduction of certain system objects such as those # which provide Lever support. # b/c: Ensure that Control Panel exists. if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().commit() # b/c: Ensure that a ProductFolder exists. if not hasattr(app.Control_Panel, 'Products'): app.Control_Panel.Products=App.Product.ProductFolder() get_transaction().commit() # b/c: Ensure that std err msg exists. if not hasattr(app, 'standard_error_message'): import Document Document.manage_addDocument( app, 'standard_error_message', 'Standard Error Message', _standard_error_msg) get_transaction().commit() install_products(app) get_transaction().commit() return Bobobase
|
from types import BooleanType
|
def guarded_getitem(object, index): v = object[index] if getSecurityManager().validate(object, object, index, v): return v raise Unauthorized, 'unauthorized access to element %s' % `i`
|
|
if isinstance(v, StringType):
|
if isinstance(v, str):
|
def complex_marshal(pairs): '''Add request marshalling information to a list of name-value pairs. Names must be strings. Values may be strings, integers, floats, or DateTimes, and they may also be lists or namespaces containing these types. The list is edited in place so that each (name, value) pair becomes a (name, marshal, value) triple. The middle value is the request marshalling string. Integer, float, and DateTime values will have ":int", ":float", or ":date" as their marshal string. Lists will be flattened, and the elements given ":list" in addition to their simple marshal string. Dictionaries will be flattened and marshalled using ":record". ''' i = len(pairs) while i > 0: i = i - 1 k, v = pairs[i] m = '' sublist = None if isinstance(v, StringType): pass elif hasattr(v, 'items'): sublist = [] for sk, sv in v.items(): sm = simple_marshal(sv) sublist.append(('%s.%s' % (k, sk), '%s:record' % sm, sv)) elif isinstance(v, ListType): sublist = [] for sv in v: sm = simple_marshal(sv) sublist.append((k, '%s:list' % sm, sv)) else: m = simple_marshal(v) if sublist is None: pairs[i] = (k, m, v) else: pairs[i:i + 1] = sublist return pairs
|
elif isinstance(v, ListType):
|
elif isinstance(v, list):
|
def complex_marshal(pairs): '''Add request marshalling information to a list of name-value pairs. Names must be strings. Values may be strings, integers, floats, or DateTimes, and they may also be lists or namespaces containing these types. The list is edited in place so that each (name, value) pair becomes a (name, marshal, value) triple. The middle value is the request marshalling string. Integer, float, and DateTime values will have ":int", ":float", or ":date" as their marshal string. Lists will be flattened, and the elements given ":list" in addition to their simple marshal string. Dictionaries will be flattened and marshalled using ":record". ''' i = len(pairs) while i > 0: i = i - 1 k, v = pairs[i] m = '' sublist = None if isinstance(v, StringType): pass elif hasattr(v, 'items'): sublist = [] for sk, sv in v.items(): sm = simple_marshal(sv) sublist.append(('%s.%s' % (k, sk), '%s:record' % sm, sv)) elif isinstance(v, ListType): sublist = [] for sv in v: sm = simple_marshal(sv) sublist.append((k, '%s:list' % sm, sv)) else: m = simple_marshal(v) if sublist is None: pairs[i] = (k, m, v) else: pairs[i:i + 1] = sublist return pairs
|
if isinstance(v, StringType):
|
if isinstance(v, str):
|
def simple_marshal(v): if isinstance(v, StringType): return '' if isinstance(v, BooleanType): return ':boolean' if isinstance(v, IntType): return ':int' if isinstance(v, FloatType): return ':float' if isinstance(v, DateTime): return ':date' return ''
|
if isinstance(v, BooleanType):
|
if isinstance(v, bool):
|
def simple_marshal(v): if isinstance(v, StringType): return '' if isinstance(v, BooleanType): return ':boolean' if isinstance(v, IntType): return ':int' if isinstance(v, FloatType): return ':float' if isinstance(v, DateTime): return ':date' return ''
|
if isinstance(v, IntType):
|
if isinstance(v, int):
|
def simple_marshal(v): if isinstance(v, StringType): return '' if isinstance(v, BooleanType): return ':boolean' if isinstance(v, IntType): return ':int' if isinstance(v, FloatType): return ':float' if isinstance(v, DateTime): return ':date' return ''
|
if isinstance(v, FloatType):
|
if isinstance(v, float):
|
def simple_marshal(v): if isinstance(v, StringType): return '' if isinstance(v, BooleanType): return ':boolean' if isinstance(v, IntType): return ':int' if isinstance(v, FloatType): return ':float' if isinstance(v, DateTime): return ':date' return ''
|
elif os.environ.has_key('BOBO_DEBUG_MODE'): debug_mode=lower(os.environ['BOBO_DEBUG_MODE'])
|
elif (os.environ.has_key('Z_DEBUG_MODE') or os.environ.has_key('BOBO_DEBUG_MODE')): if os.environ.has_key('Z_DEBUG_MODE'): debug_mode=lower(os.environ['Z_DEBUG_MODE']) else: debug_mode=lower(os.environ['BOBO_DEBUG_MODE'])
|
def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ elif os.environ.has_key('BOBO_REALM'): realm=os.environ['BOBO_REALM'] else: realm=module_name # Check for debug mode if hasattr(module,'__bobo_debug_mode__'): debug_mode=not not module.__bobo_debug_mode__ elif os.environ.has_key('BOBO_DEBUG_MODE'): debug_mode=lower(os.environ['BOBO_DEBUG_MODE']) if debug_mode=='y' or debug_mode=='yes': debug_mode=1 else: try: debug_mode=atoi(debug_mode) except: debug_mode=None else: debug_mode=None # Check whether tracebacks should be hidden: if hasattr(module,'__bobo_hide_tracebacks__'): hide_tracebacks=not not module.__bobo_hide_tracebacks__ elif os.environ.has_key('BOBO_HIDE_TRACEBACKS'): hide_tracebacks=lower(os.environ['BOBO_HIDE_TRACEBACKS']) if hide_tracebacks=='y' or hide_tracebacks=='yes': hide_tracebacks=1 else: try: hide_tracebacks=atoi(hide_tracebacks) except: hide_tracebacks=None else: hide_tracebacks=1 # Reset response handling of tracebacks, if necessary: if debug_mode or not hide_tracebacks: def hack_response(): import Response Response._tbopen = '<PRE>' Response._tbclose = '</PRE>' hack_response() if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None # Get request data from outermost environment: if hasattr(module,'__request_data__'): request_params=module.__request_data__ else: request_params=None # Get initial group data: inherited_groups=[] if hasattr(module,'__allow_groups__'): groups=module.__allow_groups__ inherited_groups.append(groups) else: groups=None web_objects=None roles=UNSPECIFIED_ROLES if hasattr(module,'bobo_application'): object=module.bobo_application if hasattr(object,'__allow_groups__'): groups=object.__allow_groups__ inherited_groups.append(groups) else: groups=None if hasattr(object,'__roles__'): roles=object.__roles__ else: if hasattr(module,'web_objects'): web_objects=module.web_objects object=web_objects else: object=module published=web_objects try: doc=module.__doc__ except: if web_objects is not None: doc=' ' else: doc=None info= (bobo_before, bobo_after, request_params, inherited_groups, groups, roles, object, doc, published, realm, module_name, debug_mode) modules[module_name]=modules[module_name+'.cgi']=info return info except: if hasattr(sys, 'exc_info'): t,v,tb=sys.exc_info() else: t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback v=str(v) raise ImportError, (t, v), tb finally: tb=None release()
|
ostream = tempfile.NamedTemporaryFile(suffix='.xml')
|
handle, path = tempfile.mkstemp(suffix='.xml')
|
def test_export_import_as_file_idempotent(self): from OFS.DTMLMethod import DTMLMethod from OFS.XMLExportImport import exportXML from OFS.XMLExportImport import importXML
|
ostream.flush() newobj = importXML(connection, ostream.name)
|
ostream.close() newobj = importXML(connection, path) self.failUnless(isinstance(newobj, DTMLMethod)) self.assertEqual(newobj.read(), dm.read())
|
def test_export_import_as_file_idempotent(self): from OFS.DTMLMethod import DTMLMethod from OFS.XMLExportImport import exportXML from OFS.XMLExportImport import importXML
|
ostream.close()
|
os.remove(path)
|
def test_export_import_as_file_idempotent(self): from OFS.DTMLMethod import DTMLMethod from OFS.XMLExportImport import exportXML from OFS.XMLExportImport import importXML
|
self.failUnless(isinstance(newobj, DTMLMethod)) self.assertEqual(newobj.read(), dm.read())
|
def test_export_import_as_file_idempotent(self): from OFS.DTMLMethod import DTMLMethod from OFS.XMLExportImport import exportXML from OFS.XMLExportImport import importXML
|
|
ostream = tempfile.NamedTemporaryFile(suffix='.xml')
|
handle, path = tempfile.mkstemp(suffix='.xml')
|
def test_OFS_ObjectManager__importObjectFromFile_xml(self): from OFS.DTMLMethod import DTMLMethod from OFS.Folder import Folder from OFS.XMLExportImport import exportXML
|
ostream.flush() sub._importObjectFromFile(ostream.name, 0, 0)
|
ostream.close() sub._importObjectFromFile(path, 0, 0)
|
def test_OFS_ObjectManager__importObjectFromFile_xml(self): from OFS.DTMLMethod import DTMLMethod from OFS.Folder import Folder from OFS.XMLExportImport import exportXML
|
ostream.close()
|
os.remove(path)
|
def test_OFS_ObjectManager__importObjectFromFile_xml(self): from OFS.DTMLMethod import DTMLMethod from OFS.Folder import Folder from OFS.XMLExportImport import exportXML
|
if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">')
|
if level > 3: output(_td_colspan % (level-1)) elif level > 1: output(_td_single * (level-1)) output(_td_single) output('\n') output('<TD WIDTH="16" VALIGN="TOP" NOWRAP>')
|
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=tpUrl() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] if have_arg('reverse'): items=list(items) # Copy the list items.reverse() diff.append(id) sub=None if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s" HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" ALT="-" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s" HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" ALT="+" BORDER=0></A>' % (id, root_url, s, id, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): doc=args['header'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=oid(item) else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): doc=args['footer'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
|
if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n')
|
if level > 2: output(_td_colspan % level) elif level > 0: output(_td_single * level) output(_td_single) output('\n')
|
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=tpUrl() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] if have_arg('reverse'): items=list(items) # Copy the list items.reverse() diff.append(id) sub=None if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s" HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" ALT="-" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s" HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" ALT="+" BORDER=0></A>' % (id, root_url, s, id, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): doc=args['header'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=oid(item) else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): doc=args['footer'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
|
if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1)
|
if level > 3: h=_td_colspan % (level-1) elif level > 1: h=_td_single * (level-1)
|
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=tpUrl() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] if have_arg('reverse'): items=list(items) # Copy the list items.reverse() diff.append(id) sub=None if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s" HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" ALT="-" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s" HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" ALT="+" BORDER=0></A>' % (id, root_url, s, id, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): doc=args['header'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=oid(item) else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): doc=args['footer'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
|
'<TR>%s<TD WIDTH="16"></TD>'
|
'<TR>%s<TD WIDTH="16" NOWRAP></TD>'
|
def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None, simple_type={type(''):0, type(1):0, type(1.0):0}.has_key, ): "Render a tree as a table" have_arg=args.has_key exp=0 if level >= 0: urlattr=args['url'] if urlattr and hasattr(self, urlattr): tpUrl=getattr(self, urlattr) if not simple_type(type(tpUrl)): tpUrl=tpUrl() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 idattr=args['id'] output=data.append items=None if (have_arg('assume_children') and args['assume_children'] and substate is not state): # We should not compute children unless we have to. # See if we've been asked to expand our children. for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break if not exp: items=1 if items is None: validate=md.validate if have_arg('branches') and hasattr(self, args['branches']): if validate is None or not hasattr(self, 'aq_acquire'): items=getattr(self, args['branches']) else: items=self.aq_acquire(args['branches'],validate,md) items=items() elif have_arg('branches_expr'): items=args['branches_expr'](md) if not items and have_arg('leaves'): items=1 if items and items != 1: if validate is not None: unauth=[] index=0 for i in items: try: v=validate(items,items,index,i,md) except: v=0 if not v: unauth.append(index) index=index+1 if unauth: if have_arg('skip_unauthorized') and args['skip_unauthorized']: items=list(items) unauth.reverse() for i in unauth: del items[i] else: raise ValidationError, unauth if have_arg('sort'): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] if have_arg('reverse'): items=list(items) # Copy the list items.reverse() diff.append(id) sub=None if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### script=md['SCRIPT_NAME'] if exp: treeData['tree-item-expanded']=1 output('<A NAME="%s" HREF="%s?tree-c=%s#%s">' '<IMG SRC="%s/p_/mi" ALT="-" BORDER=0></A>' % (id, root_url, s, id, script)) else: output('<A NAME="%s" HREF="%s?tree-e=%s#%s">' '<IMG SRC="%s/p_/pl" ALT="+" BORDER=0></A>' % (id, root_url, s, id, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP" ALIGN="LEFT">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(render_blocks(section, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): doc=args['header'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves if have_arg('leaves'): doc=args['leaves'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) elif have_arg('expand'): doc=args['expand'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) try: output(doc( None,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) finally: md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, idattr): id=getattr(item, idattr) if not simple_type(type(id)): id=id() elif hasattr(item, '_p_oid'): id=oid(item) else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 md._push(InstanceDict(item,md)) try: data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) finally: md._pop() if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): doc=args['footer'] if md.has_key(doc): doc=md.getitem(doc,0) else: doc=None if doc is not None: output(doc( None, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data
|
__implements__ = IZCatalog
|
def manage_addZCatalog(self, id, title, vocab_id=None, # Deprecated REQUEST=None): """Add a ZCatalog object """ id=str(id) title=str(title) c=ZCatalog(id, title, vocab_id, self) self._setObject(id, c) if REQUEST is not None: return self.manage_main(self, REQUEST,update_menu=1)
|
|
lower=string.lower,
|
def zpublisher_exception_hook( published, REQUEST, t, v, traceback, # static StringType=type(''), lower=string.lower, ConflictError=ZODB.POSException.ConflictError, ListType=type([]), ): try: if ((type(t) is StringType and lower(t) in ('unauthorized', 'redirect')) or t is SystemExit): raise if issubclass(t, ConflictError): # now what # First, we need to close the current connection. We'll # do this by releasing the hold on it. There should be # some sane protocol for this, but for now we'll use # brute force: global conflict_errors conflict_errors = conflict_errors + 1 method_name = REQUEST.get('PATH_INFO', '') err = ('ZODB conflict error at %s (%s conflicts since startup ' 'at %s)') LOG(err % (method_name, conflict_errors, startup_time), INFO, '') LOG('Conflict traceback', BLATHER, '', error=sys.exc_info()) raise ZPublisher.Retry(t, v, traceback) if t is ZPublisher.Retry: v.reraise() if (getattr(REQUEST.get('RESPONSE', None), '_error_format', '') !='text/html'): raise if (published is None or published is app or type(published) is ListType): # At least get the top-level object published=app.__bobo_traverse__(REQUEST).__of__( RequestContainer(REQUEST)) get_transaction().begin() # Just to be sure. published=getattr(published, 'im_self', published) while 1: f=getattr(published, 'raise_standardErrorMessage', None) if f is None: published=getattr(published, 'aq_parent', None) if published is None: raise else: break client=published while 1: if getattr(client, 'standard_error_message', None) is not None: break client=getattr(client, 'aq_parent', None) if client is None: raise if REQUEST.get('AUTHENTICATED_USER', None) is None: REQUEST['AUTHENTICATED_USER']=AccessControl.User.nobody f(client, REQUEST, t, v, traceback) finally: traceback=None
|
|
if ((type(t) is StringType and lower(t) in ('unauthorized', 'redirect')) or t is SystemExit): raise if issubclass(t, ConflictError): global conflict_errors conflict_errors = conflict_errors + 1 method_name = REQUEST.get('PATH_INFO', '') err = ('ZODB conflict error at %s (%s conflicts since startup ' 'at %s)') LOG(err % (method_name, conflict_errors, startup_time), INFO, '') LOG('Conflict traceback', BLATHER, '', error=sys.exc_info()) raise ZPublisher.Retry(t, v, traceback) if t is ZPublisher.Retry: v.reraise()
|
if isinstance(t, StringType): if t.lower() in ('unauthorized', 'redirect'): raise else: if t is SystemExit: raise if issubclass(t, ConflictError): global conflict_errors conflict_errors = conflict_errors + 1 method_name = REQUEST.get('PATH_INFO', '') err = ('ZODB conflict error at %s ' '(%s conflicts since startup at %s)') LOG(err % (method_name, conflict_errors, startup_time), INFO, '') LOG('Conflict traceback', BLATHER, '', error=sys.exc_info()) raise ZPublisher.Retry(t, v, traceback) if t is ZPublisher.Retry: v.reraise()
|
def zpublisher_exception_hook( published, REQUEST, t, v, traceback, # static StringType=type(''), lower=string.lower, ConflictError=ZODB.POSException.ConflictError, ListType=type([]), ): try: if ((type(t) is StringType and lower(t) in ('unauthorized', 'redirect')) or t is SystemExit): raise if issubclass(t, ConflictError): # now what # First, we need to close the current connection. We'll # do this by releasing the hold on it. There should be # some sane protocol for this, but for now we'll use # brute force: global conflict_errors conflict_errors = conflict_errors + 1 method_name = REQUEST.get('PATH_INFO', '') err = ('ZODB conflict error at %s (%s conflicts since startup ' 'at %s)') LOG(err % (method_name, conflict_errors, startup_time), INFO, '') LOG('Conflict traceback', BLATHER, '', error=sys.exc_info()) raise ZPublisher.Retry(t, v, traceback) if t is ZPublisher.Retry: v.reraise() if (getattr(REQUEST.get('RESPONSE', None), '_error_format', '') !='text/html'): raise if (published is None or published is app or type(published) is ListType): # At least get the top-level object published=app.__bobo_traverse__(REQUEST).__of__( RequestContainer(REQUEST)) get_transaction().begin() # Just to be sure. published=getattr(published, 'im_self', published) while 1: f=getattr(published, 'raise_standardErrorMessage', None) if f is None: published=getattr(published, 'aq_parent', None) if published is None: raise else: break client=published while 1: if getattr(client, 'standard_error_message', None) is not None: break client=getattr(client, 'aq_parent', None) if client is None: raise if REQUEST.get('AUTHENTICATED_USER', None) is None: REQUEST['AUTHENTICATED_USER']=AccessControl.User.nobody f(client, REQUEST, t, v, traceback) finally: traceback=None
|
install_products()
|
def open_bobobase(): # Open the application database Bobobase=Globals.Bobobase=Globals.PickleDictionary(Globals.BobobaseName) product_dir=os.path.join(SOFTWARE_HOME,'Products') sys.path.append(product_dir) try: app=Bobobase['Application'] except KeyError: app=Application() app._init() Bobobase['Application']=app get_transaction().commit() if not Bobobase.has_key('roles'): Bobobase['roles']=('manage',) get_transaction().commit() # Backward compatibility if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().commit() install_products() return Bobobase
|
|
for product_name in os.listdir(product_dir):
|
product_names=os.listdir(product_dir) product_names.sort() for product_name in product_names:
|
def install_products(): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists app =Globals.Bobobase['Application'] meta_types=list(Folder.Folder.dynamic_meta_types) role_names=list(app.__defined_roles__) for product_name in os.listdir(product_dir): package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): continue product=__import__(product_name) for meta_type in product.meta_types: if product_name=='OFS': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] if (not meta_type.has_key('prefix') and not regex.match('[^a-zA-Z0-9_]', name)): meta_type['prefix']=lower(name) if meta_type.has_key('prefix'): prefix=meta_type['prefix'] def productNames(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']==name: t.append(i['name']) return t setattr(Folder.Folder, "%sNames" % prefix , productNames) def productValues(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']==name: t.append(getattr(self,i['name'])) return t setattr(Folder.Folder, "%sValues" % prefix , productValues) def productItems(self, name=name): t=[] for i in self.objectMap(): if i['meta_type']=='Image': n=i['name'] t.append((n,getattr(self,n))) return t setattr(Folder.Folder, "%sItems" % prefix , productItems) for name,method in product.methods.items(): setattr(Folder.Folder, name, method) # Try to install role names try: for n in product.role_names: if n not in role_names: role_names.append(n) except: pass Folder.Folder.dynamic_meta_types=tuple(meta_types) role_names.sort() role_names=tuple(role_names) if app.__defined_roles__ != role_names: app.__defined_roles__=tuple(role_names)
|
if no_table: tr='<p>' else: tr, _tr = '<tr>', '</p>' row=('%s\n%s\t\t%s' %
|
if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=('%s\n%s\t%s' %
|
def custom_default_report(id, result, action='', no_table=0): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\t</tr>' % string.joinfields( map(lambda c: '\t<th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>' else: tr, _tr = '<tr>', '</p>' row=('%s\n%s\t\t%s' % (tr,string.joinfields( map(lambda c, td=td, _td=_td: '\t\t%s<!--#var %s%s-->%s\n' % (td,urllib.quote(c['name']), c['type']!='s' and ' null=""' or '',_td), columns), delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
|
'\t\t%s<!--
|
'\t%s<!--
|
def custom_default_report(id, result, action='', no_table=0): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\t</tr>' % string.joinfields( map(lambda c: '\t<th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>' else: tr, _tr = '<tr>', '</p>' row=('%s\n%s\t\t%s' % (tr,string.joinfields( map(lambda c, td=td, _td=_td: '\t\t%s<!--#var %s%s-->%s\n' % (td,urllib.quote(c['name']), c['type']!='s' and ' null=""' or '',_td), columns), delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
|
for k, intset in sort_index.items():
|
for k, intset in sort_index._index.items():
|
def _indexedSearch(self, args, sort_index, append, used):
|
if len(args) > 2 or len(args) < 2: raise TypeError, None if len(args) == 2: path_info=args[1]
|
if len(args) < 1 or len(args) > 2: raise TypeError, None elif len(args)==1: args=args[0],'/' path_info=args[1]
|
def main(): import sys, os, getopt, string global repeat_count try: optlist,args=getopt.getopt(sys.argv[1:], 'dtu:p:r:e:s') if len(args) > 2 or len(args) < 2: raise TypeError, None if len(args) == 2: path_info=args[1] except: sys.stderr.write(__doc__) sys.exit(-1) silent=profile=u=debug=timeit=None env={} for opt,val in optlist: if opt=='-d': debug=1 if opt=='-s': silent=1 if opt=='-t': timeit=1 if opt=='-u': u=val elif opt=='-p': profile=val elif opt=='-r': repeat_count=string.atoi(val) elif opt=='-e': opt=string.find(val,'=') if opt <= 0: raise 'Invalid argument to -e', val env[val[:opt]]=val[opt+1:] if (debug or 0)+(timeit or 0)+(profile and 1 or 0) > 1: raise 'Invalid options', 'only one of -p, -t, and -d are allowed' module=args[0] publish(module,path_info,u=u,p=profile,d=debug,t=timeit,e=env,s=silent)
|
menu=HTMLFile('dtml/menu', globals())
|
menu=DTMLFile('dtml/menu', globals())
|
def __call__(self, REQUEST=None, **kw): "Searchable interface" if REQUEST is not None: perms=[] user=REQUEST.AUTHENTICATED_USER for p in self.ac_inherited_permissions(): if user.has_permission(p[0], self): perms.append(p[0]) REQUEST.set('permissions',perms) results=[] for ph in self.helpValues(): results.append(apply(getattr(ph, '__call__'), (REQUEST,) , kw)) return LazyCat(results)
|
'\([^\0- ;,=\"]+\)=\([^\0;-=\"]*\)'
|
'\([^\0- ;,=\"]+\)=\([^\0- ;,\"]*\)'
|
def parse_cookie(text, result=None, qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0;-=\"]*\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), acquire=parse_cookie_lock.acquire, release=parse_cookie_lock.release, ): if result is None: result={} already_have=result.has_key acquire() try: if qparmre.match(text) >= 0: # Match quoted correct cookies name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) elif parmre.match(text) >= 0: # Match evil MSIE cookies ;) name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text finally: release() if not already_have(name): result[name]=value return apply(parse_cookie,(text[l:],result))
|
def parse(self, line):
|
def parse(self, line, _index=-1):
|
def parse(self, line):
|
self._row=line=self._Record(self.parse(line), self._schema, self._names)
|
self._row=line=self._Record( self.parse(line,_index), self._schema, self._names)
|
def __getitem__(self,input_index):
|
return self._Record(self.parse(file.readline()), self._schema, self._names)
|
return self._Record( self.parse(file.readline(), index), self._schema, self._names)
|
def __getitem__(self,input_index):
|
f.write(START_SCRIPT % (varname, varname, sys.executable, varname))
|
f.write(START_SCRIPT % sys.executable)
|
def sh(home, user, group): start=os.path.join(home, 'start') if not os.path.exists(start): print '-'*78 print 'Creating start script, start' f = open(start,'w') f.write(START_SCRIPT % (varname, varname, sys.executable, varname)) ch(start,user,group,0711) f.close() stop=os.path.join(home, 'stop') if not os.path.exists(stop): print '-'*78 print 'Creating stop script, stop' f = open(stop,'w') f.write(STOP_SCRIPT % os.path.join(home,'var','Z2.pid')) ch(stop,user,group,0711) f.close()
|
%s=`cd $reldir; pwd` export %s exec %s $%s/z2.py -D "$@"
|
exec %s $cwd/z2.py -D "$@"
|
def sh(home, user, group): start=os.path.join(home, 'start') if not os.path.exists(start): print '-'*78 print 'Creating start script, start' f = open(start,'w') f.write(START_SCRIPT % (varname, varname, sys.executable, varname)) ch(start,user,group,0711) f.close() stop=os.path.join(home, 'stop') if not os.path.exists(stop): print '-'*78 print 'Creating stop script, stop' f = open(stop,'w') f.write(STOP_SCRIPT % os.path.join(home,'var','Z2.pid')) ch(stop,user,group,0711) f.close()
|
if (options[i].has_key('help') and options[i]['help'] != helps[i]) or \ (not options[i].has_key('help') and helps[i]):
|
if options[i].get('help') != (self.zclass_productid(), helps[i]):
|
def manage_edit(self, actions=[], helps=[], REQUEST=None): "Change view actions" options=self.data() changed=0 if len(actions)!=len(options): raise 'Bad Request', 'wrong number of actions'
|
else:
|
changed=1 elif options[i].has_key('help'):
|
def manage_edit(self, actions=[], helps=[], REQUEST=None): "Change view actions" options=self.data() changed=0 if len(actions)!=len(options): raise 'Bad Request', 'wrong number of actions'
|
if name[:3]=='aq_' and name != 'aq_parent' and name != 'aq_explicit': return 0
|
try: if (name[:3]=='aq_' and name != 'aq_parent' and name != 'aq_explicit'): return 0 except: pass
|
def oldvalidate(self, inst, parent, name, value, md): ################################################################# # Note that this method is not used normally. It is simply a # Python rendition of the validate method implemented in # DocumentTemplate.cDocumentTemplate. The Python version # serves the role of a requirements spec for the C version and # can also be useful (if temporarily renamed to validate) for # debugging. #################################################################
|
"The specified module, <em>%s</em>, couldn't be found.")
|
"The specified module, <em>%s</em>, couldn't be found." % module)
|
def getObject(module, name, reload=0, modules={}): if modules.has_key(module): old=modules[module] if old.has_key(name) and not reload: return old[name] else: old=None if module[-3:]=='.py': p=module[:-3] elif module[-4:]=='.pyp': p=module[:-4] else: p=module p=getPath('Extensions', p, suffixes=('','py','pyp')) if p is None: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be found.") __traceback_info__=p, module if p[-4:]=='.pyp': data=zlib.decompress( rotor.newrotor(d+' shshsh').decrypt(open(p,'rb').read()) ) execsrc=compile(data,module,'exec') else: try: execsrc=open(p) except: raise "Module Error", ( "The specified module, <em>%s</em>, couldn't be opened." % module) m={} exec execsrc in m try: r=m[name] except KeyError: raise 'Invalid Object Name', ( "The specified object, <em>%s</em>, was not found in module, " "<em>%s</em>." % (name, module)) if old: for k, v in m.items(): old[k]=v else: modules[module]=m return r
|
for k, v in list(index.items()):
|
if DEBUG: TLOG('building list of index items') l = list(index.items()) if DEBUG: TLOG('done building list of index items, now iterating over them') tmp = [] for k, v in l:
|
def _clean(self, b, index): for k, v in list(index.items()): if v is b: self.notifyDestruct(index[k][k]) del index[k] b.clear()
|
multiple=1, optional=1)
|
multiple=1, optional=1, op=None)
|
def __init__(self, args): args = parse_params(args, name='', type=None, column=None, multiple=1, optional=1) self.__name__ = name_param(args,'sqlvar') has_key=args.has_key if not has_key('type'): raise ParseError, ('the type attribute is required', 'dtvar') self.type=t=args['type'] if not valid_type(t): raise ParseError, ('invalid type, %s' % t, 'dtvar') if has_key('optional'): self.optional=args['optional'] if has_key('multiple'): self.multiple=args['multiple'] if has_key('column'): self.column=args['column'] else: self.column=self.__name__
|
raise ParseError, ('the type attribute is required', 'dtvar')
|
raise ParseError, ('the type attribute is required', 'sqltest')
|
def __init__(self, args): args = parse_params(args, name='', type=None, column=None, multiple=1, optional=1) self.__name__ = name_param(args,'sqlvar') has_key=args.has_key if not has_key('type'): raise ParseError, ('the type attribute is required', 'dtvar') self.type=t=args['type'] if not valid_type(t): raise ParseError, ('invalid type, %s' % t, 'dtvar') if has_key('optional'): self.optional=args['optional'] if has_key('multiple'): self.multiple=args['multiple'] if has_key('column'): self.column=args['column'] else: self.column=self.__name__
|
raise ParseError, ('invalid type, %s' % t, 'dtvar')
|
raise ParseError, ('invalid type, %s' % t, 'sqltest')
|
def __init__(self, args): args = parse_params(args, name='', type=None, column=None, multiple=1, optional=1) self.__name__ = name_param(args,'sqlvar') has_key=args.has_key if not has_key('type'): raise ParseError, ('the type attribute is required', 'dtvar') self.type=t=args['type'] if not valid_type(t): raise ParseError, ('invalid type, %s' % t, 'dtvar') if has_key('optional'): self.optional=args['optional'] if has_key('multiple'): self.multiple=args['multiple'] if has_key('column'): self.column=args['column'] else: self.column=self.__name__
|
return "%s=%s" % (self.column,vs[0])
|
return "%s %s %s" % (self.column, self.op, vs[0])
|
def render(self, md): name=self.__name__ t=self.type try: v = md[name] except KeyError, key: if str(key)==name and self.optional: return '' raise KeyError, key, sys.exc_traceback if type(v) in (ListType, TupleType): if len(v) > 1 and not self.multiple: raise 'Multiple Values', ( 'multiple values are not allowed for <em>%s</em>' % name) else: v=[v] vs=[] for v in v: if not v and type(v) is StringType and t != 'string': continue if t=='int': try: if type(v) is StringType: atoi(v) else: v=str(int(v)) except: raise ValueError, ( 'Invalid integer value for <em>%s</em>' % name) elif t=='float': if not v and type(v) is StringType: continue try: if type(v) is StringType: atof(v) else: v=str(float(v)) except: raise ValueError, ( 'Invalid floating-point value for <em>%s</em>' % name) else: v=str(v) v=md.getitem('sql_quote__',0)(v) #if find(v,"\'") >= 0: v=join(split(v,"\'"),"''") #v="'%s'" % v vs.append(v)
|
ev = translate(str(v), nl2sp) if ev.find( '<html>') >= 0: ev = 'bobo exception' self.setHeader('bobo-exception-value', ev[:255])
|
ev = 'See the server error log for details' self.setHeader('bobo-exception-value', ev)
|
def exception(self, fatal=0, info=None, absuri_match=re.compile(r'\w+://[\w\.]+').match, tag_search=re.compile('[a-zA-Z]>').search, abort=1 ): if type(info) is type(()) and len(info) == 3: t, v, tb = info else: t, v, tb = sys.exc_info()
|
uri=os.path.join(url, absattr(ob.id))
|
uri=urljoin(url, absattr(ob.id))
|
def apply(self, obj, url=None, depth=0, result=None, top=1): if result is None: result=StringIO() depth=self.depth url=urlfix(self.request['URL'], 'PROPFIND') url=urlbase(url) result.write('<?xml version="1.0" encoding="utf-8"?>\n' \ '<d:multistatus xmlns:d="DAV:">\n') iscol=isDavCollection(obj) if iscol and url[-1] != '/': url=url+'/' result.write('<d:response>\n<d:href>%s</d:href>\n' % safe_quote(url)) if hasattr(aq_base(obj), 'propertysheets'): propsets=obj.propertysheets.values() obsheets=obj.propertysheets else: davprops=DAVProps(obj) propsets=(davprops,) obsheets={'DAV:': davprops} if self.allprop: stats=[] for ps in propsets: if hasattr(aq_base(ps), 'dav__allprop'): stats.append(ps.dav__allprop()) stats=''.join(stats) or '<d:status>200 OK</d:status>\n' result.write(stats) elif self.propname: stats=[] for ps in propsets: if hasattr(aq_base(ps), 'dav__propnames'): stats.append(ps.dav__propnames()) stats=''.join(stats) or '<d:status>200 OK</d:status>\n' result.write(stats) elif self.propnames: rdict={} for name, ns in self.propnames: ps=obsheets.get(ns, None) if ps is not None and hasattr(aq_base(ps), 'dav__propstat'): stat=ps.dav__propstat(name, rdict) else: prop='<n:%s xmlns:n="%s"/>' % (name, ns) code='404 Not Found' if not rdict.has_key(code): rdict[code]=[prop] else: rdict[code].append(prop) keys=rdict.keys() keys.sort() for key in keys: result.write('<d:propstat>\n' \ ' <d:prop>\n' \ ) map(result.write, rdict[key]) result.write(' </d:prop>\n' \ ' <d:status>HTTP/1.1 %s</d:status>\n' \ '</d:propstat>\n' % key ) else: raise BadRequest, 'Invalid request' result.write('</d:response>\n') if depth in ('1', 'infinity') and iscol: for ob in obj.listDAVObjects(): if hasattr(ob,"meta_type"): if ob.meta_type=="Broken Because Product is Gone": continue dflag=hasattr(ob, '_p_changed') and (ob._p_changed == None) if hasattr(ob, '__locknull_resource__'): # Do nothing, a null resource shouldn't show up to DAV if dflag: ob._p_deactivate() elif hasattr(ob, '__dav_resource__'): uri=os.path.join(url, absattr(ob.id)) depth=depth=='infinity' and depth or 0 self.apply(ob, uri, depth, result, top=0) if dflag: ob._p_deactivate() if not top: return result result.write('</d:multistatus>')
|
uri = os.path.join(url, absattr(ob.id))
|
uri = urljoin(url, absattr(ob.id))
|
def apply(self, obj, creator=None, depth='infinity', token=None, result=None, url=None, top=1): """ Apply, built for recursion (so that we may lock subitems of a collection if requested """
|
uri = os.path.join(url, absattr(ob.id))
|
uri = urljoin(url, absattr(ob.id))
|
def apply(self, obj, token, url=None, result=None, top=1): if result is None: result = StringIO() url = urlfix(url, 'UNLOCK') url = urlbase(url) iscol = isDavCollection(obj) if iscol and url[-1] != '/': url = url + '/' errmsg = None
|
uri = os.path.join(url, absattr(ob.id))
|
uri = urljoin(url, absattr(ob.id))
|
def apply(self, obj, token, user, url=None, result=None, top=1): if result is None: result = StringIO() url = urlfix(url, 'DELETE') url = urlbase(url) iscol = isDavCollection(obj) errmsg = None parent = aq_parent(obj)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.