RESPONSE.setHeader('Content-Length', self.size) return result data = self.data if isinstance(data, binary_type): RESPONSE.setBase(None) return data while data is not None: RESPONSE.write(data.data) data = data.next return b'' InitializeClass(File) manage_addImageForm = DTMLFile( 'dtml/imageAdd', globals(), Kind='Image', kind='image', ) def manage_addImage(self, id, file, title='', precondition='', content_type='',
class Script(SimpleItem, BindingsUI): """Web-callable script mixin """ security = ClassSecurityInfo() index_html = None __code__ = None __defaults__ = () _Bindings_ns_class = TemplateDict security.declareProtected( view_management_screens, # NOQA: D001 'ZScriptHTML_tryForm') ZScriptHTML_tryForm = DTMLFile('dtml/scriptTry', globals()) def ZScriptHTML_tryAction(self, REQUEST, argvars): """Apply the test parameters. """ vv = [] for argvar in argvars: if argvar.value: vv.append("%s=%s" % (quote(argvar.name), quote(argvar.value))) raise Redirect("%s?%s" % (REQUEST['URL1'], '&'.join(vv))) from .Signature import _setFuncSignature InitializeClass(Script)
def __bobo_traverse__(self, request, name): '''Traversing away''' if name[:1] != '/': return getattr(self, name) parents = request.PARENTS parents.pop() # I don't belong there if len(name) > 1: request.setVirtualRoot(name) else: request.setVirtualRoot([]) return parents.pop() # He'll get put back on InitializeClass(VirtualHostMonster) def manage_addVirtualHostMonster(self, id=None, REQUEST=None, **ignored): """ """ container = self.this() vhm = VirtualHostMonster() container._setObject(vhm.getId(), vhm) if REQUEST is not None: goto = '%s/manage_main' % self.absolute_url() qs = 'manage_tabs_message=Virtual+Host+Monster+added.' REQUEST['RESPONSE'].redirect('%s?%s' % (goto, qs)) constructors = (('manage_addVirtualHostMonster',
security = ClassSecurityInfo() security.declareObjectProtected(view_management_screens) PUT = document_src = Acquired index_html = None def __before_publishing_traverse__(self, ob, request): if getattr(request, '_hacked_path', 0): request._hacked_path = 0 def __call__(self, REQUEST, RESPONSE): " " return self.document_src(REQUEST) InitializeClass(Src) class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable, Traversable, PropertyManager): "Zope wrapper for Page Template using TAL, TALES, and METAL" meta_type = 'Page Template' zmi_icon = 'far fa-file-code' output_encoding = 'utf-8' # provide default for old instances __code__ = FuncCode((), 0) __defaults__ = None _default_bindings = {'name_subpath': 'traverse_subpath'} _default_content_fn = os.path.join(package_home(globals()), 'www',
title='Insufficient Privileges', message=('You do not possess the %s permission in the ' 'context of the container into which you are ' 'pasting, thus you are not able to perform ' 'this operation.' % mt_permission), action='manage_main')) else: raise CopyError( MessageDialog( title='Not Supported', message=('The object <em>%s</em> does not support this ' 'operation.' % escape(absattr(object.id))), action='manage_main')) InitializeClass(CopyContainer) class CopySource(Base): """Interface for objects which allow themselves to be copied.""" implements(ICopySource) # declare a dummy permission for Copy or Move here that we check # in cb_isCopyable. security = ClassSecurityInfo() security.setPermissionDefault(copy_or_move, ('Anonymous', 'Manager')) def _canCopy(self, op=0): """Called to make sure this object is copyable.
initializeObjectFromSchemata(self.context, iterSchemata(self.context), self._message, self._encoding) def write(self, data): if self._closed: raise ValueError("File is closed") self._written += len(data) self._parser.feed(data) def writelines(self, sequence): for item in sequence: self.write(item) def truncate(self, size=None): if (size is None and self._written != 0) and size != 0: raise NotImplementedError( "The 'size' argument to truncate() must be 0 - partial " "truncation is not supported") if self._closed: raise ValueError("File is closed") self._parser = FeedParser() self._written = 0 def flush(self): pass InitializeClass(DAVResourceMixin) InitializeClass(DAVCollectionMixin) InitializeClass(FolderDataResource)
# # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo from OFS.SimpleItem import Item from Persistence import Persistent class Draft(Persistent, Item): "Draft objects" meta_type = 'Zope Draft' security = ClassSecurityInfo() def __init__(self, id, baseid, PATH_INFO): self.id = id def icon(self): return 'p_/broken' InitializeClass(Draft)
return result def tpValues(self): # Return a list of subobjects, used by tree tag. r = [] if hasattr(aq_base(self), 'tree_ids'): tree_ids = self.tree_ids try: tree_ids = list(tree_ids) except TypeError: pass if hasattr(tree_ids, 'sort'): tree_ids.sort() for id in tree_ids: if hasattr(self, id): r.append(self._getOb(id)) else: # this part is different from the ObjectManager code r = [obj for obj in self.objectValues() if getattr(obj, 'isPrincipiaFolderish', False)] r = sort(r, ((self._default_sort_key, 'cmp', 'asc'), )) if self._default_sort_reverse: r.reverse() return r def getIdsSubset(self, objects): return [obj['id'] for obj in objects] InitializeClass(OrderSupport)
script = script[:-1] path=path.split('/')[:-1] if script: path = [script] + path if not path: return '' script='' last=path[-1] del path[-1] for p in path: script="%s/%s" % (script, quote(p)) out.append('<a href="%s/manage_workspace">%s</a>' % (script, p)) out.append(last) return '/'.join(out) InitializeClass(Tabs) class Navigation(Base): """Basic navigation UI support""" implements(INavigation) security = ClassSecurityInfo() security.declareProtected(view_management_screens, 'manage') manage =DTMLFile('dtml/manage', globals()) security.declareProtected(view_management_screens, 'manage_menu') manage_menu =DTMLFile('dtml/menu', globals())
if elem in ignored or ignore_re.match(elem): path_elems.remove(elem) skinpath = ','.join(path_elems) if test: self.testSkinPath(skinpath) sels[str(skinname)] = skinpath if make_default: self.default_skin = skinname @security.protected(AccessContentsInformation) def getDiff(self, item_one_path, item_two_path, reverse=0): """ Return a diff between one and two. """ if not reverse: item_one = self.unrestrictedTraverse(item_one_path) item_two = self.unrestrictedTraverse(item_two_path) else: item_one = self.unrestrictedTraverse(item_two_path) item_two = self.unrestrictedTraverse(item_one_path) res = unified_diff(item_one.read().splitlines(), item_two.read().splitlines(), item_one_path, item_two_path, '', '', lineterm='') return res InitializeClass(SkinsTool) registerToolInterface('portal_skins', ISkinsTool)
class DeviceReportClass(ReportClass): portal_type = meta_type = "DeviceReportClass" security = ClassSecurityInfo() def getReportClass(self): ''' Return the class to instantiate for new report classes ''' return DeviceReportClass security.declareProtected('Manage DMD', 'manage_addDeviceReport') @deprecated def manage_addDeviceReport(self, id, REQUEST=None): """Add a report to this object. """ from Products.ZenModel.DeviceReport import DeviceReport fr = DeviceReport(id) self._setObject(id, fr) fr = self._getOb(id) if REQUEST: audit('UI.Report.Add', fr.id, reportType=getDisplayType(fr)) url = '%s/%s/editDeviceReport' % (self.getPrimaryUrlPath(), id) return REQUEST['RESPONSE'].redirect(url) return fr InitializeClass(DeviceReportClass)
self.connect(s) return self._v_database_connection raise BadRequest, ('''The database connection is not connected''') def connect(self, s): self.manage_close_connection() DB = self.factory() try: try: self._v_database_connection = DB(s) except: t, v, tb = sys.exc_info() raise BadRequest, ( '<strong>Error connecting to DB.</strong><br>\n' '<!--\n%s\n%s\n-->\n' % (t, v)), tb finally: tb = None self._v_connected = DateTime() return self def sql_quote__(self, v): if string.find(v, "\'") >= 0: v = string.join(string.split(v, "\'"), "''") if string.find(v, "\x00") >= 0: v = string.join(string.split(v, "\x00"), "") return "'%s'" % v InitializeClass(Connection)
def __class_init__(self): InitializeClass(self)
def getPhysicalRoot(self): return self def getPhysicalPath(self): # Get the physical path of the object. # # Returns a path (an immutable sequence of strings) that can be used to # access this object again later, for example in a copy/paste # operation. getPhysicalRoot() and getPhysicalPath() are designed to # operate together. # # We're at the base of the path. return ('', ) InitializeClass(Application) def initialize(app): initializer = AppInitializer(app) initializer.initialize() class AppInitializer: """ Initialize an Application object (called at startup) """ def __init__(self, app): self.app = (app, ) def getApp(self): # this is probably necessary, but avoid acquisition anyway return self.app[0]
getSize = get_size def PrincipiaSearchSource(self): "Support for searching - the document's contents are searched." return "%s\n%s" % (self._params, self._body) def document_src(self, REQUEST=None, RESPONSE=None): """Return unprocessed document source.""" if RESPONSE is not None: RESPONSE.setHeader('Content-Type', 'text/plain') return self.read() InitializeClass(PythonScript) class PythonScriptTracebackSupplement: """Implementation of ITracebackSupplement""" def __init__(self, script, line=0): self.object = script # If line is set to -1, it means to use tb_lineno. self.line = line _first_indent = re.compile('(?m)^ *(?! |$)') _nonempty_line = re.compile('(?m)^(.*\S.*)$') _nice_bind_names = { 'context': 'name_context',
temperature = temperatureCelsius def temperatureFahrenheit(self, default=None): """ Return the current temperature in degrees fahrenheit """ tempC = self.temperatureCelsius(default) if tempC is not None and not isnan(tempC): tempF = tempC * 9 / 5 + 32.0 return long(tempF) return None def temperatureCelsiusString(self): """ Return the current temperature in degrees celsius as a string """ tempC = self.temperature() return tempC is None and "unknown" or "%dC" % (tempC,) temperatureString = temperatureCelsiusString def temperatureFahrenheitString(self): """ Return the current temperature in degrees fahrenheit as a string """ tempF = self.temperatureFahrenheit() return tempF is None and "unknown" or "%dF" % (tempF,) InitializeClass(TemperatureSensor)
If there isn't a next older one returns the next newer one. """ if selector is None: selector = 0 else: selector = int(selector) storage = getToolByName(self, 'portal_historiesstorage') savedSelector = selector while selector: selector -= 1 data = storage.retrieve(history_id, selector, substitute=False) if data.isValid(): return data selector = savedSelector while True: selector += 1 try: data = storage.retrieve(history_id, selector, substitute=False) except storage.StorageRetrieveError: break if data.isValid(): return data return default InitializeClass(KeepLastNVersionsTool)
self.__enabled = enabled and 1 or 0 if REQUEST is not None: return self.ZCacheable_manage( self, REQUEST, management_view='Cache', manage_tabs_message='Cache settings changed.') security.declareProtected(ViewManagementScreensPermission, 'ZCacheable_configHTML') def ZCacheable_configHTML(self): '''Override to provide configuration of caching behavior that can only be specific to the cacheable object. ''' return '' InitializeClass(Cacheable) def findCacheables(ob, manager_id, require_assoc, subfolders, meta_types, rval, path): ''' Used by the CacheManager UI. Recursive. Similar to the Zope "Find" function. Finds all Cacheable objects in a hierarchy. ''' try: if meta_types: subobs = ob.objectValues(meta_types) else: subobs = ob.objectValues() sm = getSecurityManager()
# Force all subs to acquire ownership! for object in self.objectValues(): try: s = object._p_changed except: s = 0 try: object._deleteOwnershipAfterAdd() except: pass if s is None: object._p_deactivate() InitializeClass(Owned) class EmergencyUserCannotOwn(Exception): "The emergency user cannot own anything" class EditUnowned(Exception): "Can't edit unowned executables" def absattr(attr): if callable(attr): return attr() return attr
from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo from Acquisition import Implicit from OFS.role import RoleManager from OFS.SimpleItem import Item from Persistence import Persistent class Permission(RoleManager, Persistent, Implicit, Item ): """Model Permission meta-data """ meta_type = 'Zope Permission' icon = 'p_/Permission_icon' index_html = None security = ClassSecurityInfo() manage_options=( RoleManager.manage_options + Item.manage_options ) def __init__(self, id, title, name): self.id=id self.title=title self.name=name InitializeClass(Permission)
if ifhdr.find(tok) > -1: token = tok cmd = DeleteCollection() result = cmd.apply(self, token, sm, REQUEST['URL']) if result: # There were conflicts, so we need to report them RESPONSE.setStatus(207) RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"') RESPONSE.setBody(result) else: # There were no conflicts, so we can go ahead and delete # ajung: additional check if we really could delete the collection # (Collector #2196) if parent.manage_delObjects([name], REQUEST=None) is None: RESPONSE.setStatus(204) else: RESPONSE.setStatus(403) return RESPONSE @security.protected(webdav_access) def listDAVObjects(self): objectValues = getattr(self, 'objectValues', None) if objectValues is not None: return objectValues() return [] InitializeClass(Collection)
guarded_getitem = None def __str__(self): return self.read() def __getstate__(self, _special=('_v_', '_p_')): # Waaa, we need _v_ behavior but we may not subclass Persistent d = {} for k, v in self.__dict__.items(): if k[:3] in _special: continue d[k] = v return d InitializeClass(String) class FileMixin(object): # Mix-in class to abstract certain file-related attributes edited_source = '' security = ClassSecurityInfo() def __init__(self, file_name='', mapping=None, __name__='', **vars): """Create a document template based on a named file. The optional parameter, 'mapping', may be used to provide a mapping object containing defaults for values to be inserted. """ self.raw = file_name
""" Provide roles during Authentication from local roles assignments made on the root object. """ meta_type = 'Local Role Plugin' zmi_icon = 'fas fa-user-tag' security = ClassSecurityInfo() def __init__(self, id, title=None): self._setId(id) self.title = title # # IRolesPlugin implementation # @security.private def getRolesForPrincipal(self, principal, request=None): """ See IRolesPlugin. """ local_roles = getattr(self.getPhysicalRoot(), '__ac_local_roles__', None) if local_roles is None: return None return local_roles.get(principal.getId()) classImplements(LocalRolePlugin, ILocalRolePlugin, IRolesPlugin) InitializeClass(LocalRolePlugin)
ps = self.propertysheets if hasattr(ps, 'props'): ps.props.manage_changeProperties(props) def title(self): site = queryUtility(ISiteRoot) if site is None: # fallback return aq_parent(aq_inner(self)).title return site.title def smtp_server(self): return getUtility(IMailHost).smtp_host InitializeClass(PropertiesTool) @implementer(ISimpleItemWithProperties) class SimpleItemWithProperties(PropertyManager, SimpleItem): """ A common base class for objects with configurable properties in a fixed schema. """ def __init__(self, id, title=''): self.id = id self.title = title meta_type = 'Plone Property Sheet' manage_options = (PropertyManager.manage_options +
raise except: logger.error( "Exception was thrown while updating " "role mappings", exc_info=True) if not swallow_errors: raise logger.info("Your Plone instance is now up-to-date.") if dry_run: logger.info("Dry run selected, transaction aborted") transaction.abort() return stream.getvalue() finally: logger.removeHandler(handler) gslogger.removeHandler(handler) upgrade = postonly(upgrade) def registerUpgradePath(oldversion, newversion, function): """ Basic register func """ pass InitializeClass(MigrationTool) registerToolInterface('portal_migration', IMigrationTool)
if not removed: message = 'Role+%s+alread+removed+from+all+principals' % role_id else: message = 'Role+%s+removed+from+%s' % (role_id, '+'.join(removed)) if RESPONSE is not None: RESPONSE.redirect('%s/manage_roles?role_id=%s&assign=1' '&manage_tabs_message=%s' % (self.absolute_url(), role_id, message)) classImplements(ZODBRoleManager, IZODBRoleManager, IRolesPlugin, IRoleEnumerationPlugin, IRoleAssignerPlugin) InitializeClass(ZODBRoleManager) class _ZODBRoleFilter: def __init__(self, id=None, **kw): self._filter_ids = id def __call__(self, role_info): if self._filter_ids: key = 'id' else: return 1 # ???: try using 'kw'
full_path=full_path, text=text) return result def getEditingViewlet(self, obj): if hasattr(self, 'portal_url'): icon_base_url = self.portal_url() elif hasattr(self, 'REQUEST'): icon_base_url = self.REQUEST['BASEPATH1'] else: icon_base_url = '/' text = obj.renderInline() return self._render_editing(obj, text, icon_base_url) InitializeClass(PackSlot) class PackSlotCollection(SlotCollection): """ """ meta_type = 'Pack Slot Collection' def Title(self): ''' Just in case we get indexed anyway.''' return '' InitializeClass(PackSlotCollection) class PackTitleCollection(PortalFolderBase): """ """ meta_type = 'Pack Title Collection'
unions. They provide meta-data about their input parameters and result data. For more information, see the searchable-object interface specification. - Containment Database methods support URL traversal to access and invoke methods on individual record objects. For example, suppose you had an 'employees' database method that took a single argument 'employee_id'. Suppose that employees had a 'service_record' method (defined in a record class or acquired from a folder). The 'service_record' method could be accessed with a URL like:: employees/employee_id/1234/service_record """ meta_type = 'Z SQL Method' security = ClassSecurityInfo() security.declareProtected(change_database_methods, 'manage') security.declareProtected(change_database_methods, 'manage_main') manage = manage_main = DTMLFile('dtml/edit', globals()) manage_main._setName('manage_main') InitializeClass(SQL)
@security.private def sniffRequestType(self, request): found = None for iface, func in _sniffers: if func(request): found = iface if found is not None: return found classImplements(RequestTypeSniffer, IRequestTypeSnifferPlugin, IRequestTypeSniffer) InitializeClass(RequestTypeSniffer) # Most of the sniffing code below has been inspired by # similar tests found in BaseRequest, HTTPRequest and ZServer def webdavSniffer(request): dav_src = request.get('WEBDAV_SOURCE_PORT', None) method = request.get('REQUEST_METHOD', 'GET').upper() path_info = request.get('PATH_INFO', '') if dav_src: return True if request.maybe_webdav_client and method not in ('GET', 'POST'): return True
from os.path import dirname import App from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo from App.ImageFile import ImageFile class misc_(object): "Miscellaneous product information" security = ClassSecurityInfo() security.declareObjectPublic() InitializeClass(misc_) class p_(object): "Shared system information" security = ClassSecurityInfo() security.declareObjectPublic() app_dir = dirname(App.__file__) zopelogo_png = ImageFile('www/zopelogo.png', app_dir) InitializeClass(p_) class Misc_(object):