meta_type = self.meta_type, # This is a little sneaky: we add self to the # FactoryDispatcher under the name "toolinit". # manage_addTool() can then grab it. constructors = (manage_addToolForm, manage_addTool, self,), icon = self.icon ) for tool in self.tools: tool.__factory_meta_type__ = self.meta_type tool.icon = 'misc_/%s/%s' % (self.product_name, self.icon) Globals.InitializeClass( ToolInit ) def manage_addToolForm(self, REQUEST): ''' Shows the add tool form. ''' # self is a FactoryDispatcher. toolinit = self.toolinit tl = [] for tool in toolinit.tools: tl.append(tool.meta_type) return addInstanceForm(addInstanceForm, self, REQUEST, factory_action='manage_addTool', factory_meta_type=toolinit.meta_type, factory_product_name=toolinit.product_name, factory_icon=toolinit.icon,
raise ValueError, 'Not a valid permission name:' + p self.permissions = self.permissions + (p, ) if REQUEST is not None: return self.manage_permissions( REQUEST, manage_tabs_message='Permission added.') security.declareProtected(ManagePortal, 'delManagedPermissions') def delManagedPermissions(self, ps, REQUEST=None): ''' ''' if ps: l = list(self.permissions) for p in ps: l.remove(p) self.permissions = tuple(l) if REQUEST is not None: return self.manage_permissions( REQUEST, manage_tabs_message='Permission(s) removed.') security.declareProtected(ManagePortal, 'getPossiblePermissions') def getPossiblePermissions(self): ''' ''' # possible_permissions is in AccessControl.Role.RoleManager. return list(self.possible_permissions()) Globals.InitializeClass(WorkflowUIMixin)
self.invokeFactory( type_name='Folder', id=id ) else: # call it getattr( self, action )( id=id ) ob = self._getOb( id ) ob.setTitle( title ) try: ob.reindexObject() except AttributeError: pass if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1) Globals.InitializeClass(PortalFolder) class ContentFilter: """ Represent a predicate against a content object's metadata. """ MARKER = [] filterSubject = [] def __init__( self , Title=MARKER , Creator=MARKER , Subject=MARKER , Description=MARKER , created=MARKER
proptype = proptype.strip() propvstr = propvstr.strip() converter = get_converter(proptype, lambda x: x) propvalue = converter(propvstr) # Should be safe since we're loading from # the filesystem. setattr(self, propname, propvalue) map.append({ 'id': propname, 'type': proptype, 'mode': '', 'default_value': propvalue, }) except: raise ValueError, ('Error processing line %s of %s:\n%s' % (lino, fp, line)) self._properties = tuple(map) if Globals.DevelopmentMode: # Provide an opportunity to update the properties. def __of__(self, parent): self = Acquisition.ImplicitAcquisitionWrapper(self, parent) self._updateFromFS() return self Globals.InitializeClass(FSPropertiesObject) registerFileExtension('props', FSPropertiesObject) registerMetaType('Properties Object', FSPropertiesObject)
m = members[id] # Return a wrapper with self as containment and # the user as context. return m.__of__(self).__of__(u) security.declarePrivate('registerMemberData') def registerMemberData(self, m, id): ''' Adds the given member data to the _members dict. This is done as late as possible to avoid side effect transactions and to reduce the necessary number of entries. ''' self._members[id] = m Globals.InitializeClass(MemberDataTool) class MemberData (SimpleItem): security = ClassSecurityInfo() def __init__(self, tool, id): self.id = id # Make a temporary reference to the tool. # The reference will be removed by notifyModified(). self._tool = tool security.declarePrivate('notifyModified') def notifyModified(self): # Links self to parent for full persistence. tool = getattr(self, '_tool', None)
finally: security.removeContext(self) return result # Copy over more methods security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = ZopeSimplate.manage_FTPget security.declareProtected(View, 'get_size') get_size = ZopeSimplate.get_size getSize = get_size security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = ZopeSimplate.PrincipiaSearchSource security.declareProtected(ViewManagementScreens, 'document_src') document_src = ZopeSimplate.document_src simplate_getContext = ZopeSimplate.simplate_getContext ZScriptHTML_tryParams = ZopeSimplate.ZScriptHTML_tryParams Globals.InitializeClass(FSSimplate) registerFileExtension('smpt', FSSimplate) registerFileExtension('smpl', FSSimplate) registerFileExtension('spt', FSSimplate) registerMetaType('Simplate', FSSimplate) registerIcon(FSSimplate, 'www/fssimplate.png', globals())
# Copy over more methods security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = ZopePageTemplate.manage_FTPget.im_func security.declareProtected(View, 'get_size') get_size = ZopePageTemplate.get_size.im_func getSize = get_size security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource.im_func security.declareProtected(ViewManagementScreens, 'document_src') document_src = ZopePageTemplate.document_src.im_func pt_getContext = ZopePageTemplate.pt_getContext.im_func ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams.im_func source_dot_xml = Src() setattr(FSPageTemplate, 'source.xml', FSPageTemplate.source_dot_xml) setattr(FSPageTemplate, 'source.html', FSPageTemplate.source_dot_xml) Globals.InitializeClass(FSPageTemplate) registerFileExtension('pt', FSPageTemplate) registerFileExtension('zpt', FSPageTemplate) registerFileExtension('html', FSPageTemplate) registerFileExtension('htm', FSPageTemplate) registerMetaType('Page Template', FSPageTemplate)
return ''.join([object.view() for object in self.objectValues('SimpleEmbed')]) return '' security.declarePrivate('classUpgrader') def classUpgrader(self): "upgrade this class" self.removeOldAttributes() self.fixupObservation() security.declarePrivate('removeOldAttributes') def removeOldAttributes(self): "remove attributes that are no longer needed" self.delObjects(['editDTML', 'viewDTML', 'CreationAssistantString']) removeOldAttributes = utility.upgradeLimit(removeOldAttributes, 141) security.declarePrivate('fixupObservation') def fixupObservation(self): "fix the observation stuff" try: object = self.getCompoundDoc().restrictedTraverse(self.path) except KeyError: object = None if object is not None: object.observerAttached(self) if object.inuse == []: self.delObjects(self.objectIds('SimpleEmbed')) fixupObservation = utility.upgradeLimit(fixupObservation, 141) Globals.InitializeClass(MultiSimpleEmbed) import register register.registerClass(MultiSimpleEmbed)
import com.parsers class ControlComHelp(ControlBase): "Input text class" meta_type = "ControlComHelp" security = ClassSecurityInfo() control_title = 'Help' security.declareProtected('View management screens', 'edit') def edit(self, *args, **kw): "Inline edit short object" seq = [ com.javascript, com.css, com.detection, com.html, com.form, com.catalog, com.parsers ] seq = [(pydoc.html.document(mod), mod.__name__) for mod in seq] temp = [ com.javascript.document_ready( [com.javascript.tabs_init('control_help')]) ] temp.append('<div class="">') temp.append(com.javascript.tabs_html_data('control_help', seq)) temp.append('</div>') return ''.join(temp) Globals.InitializeClass(ControlComHelp)
self.manage_advanced(max_rows, max_cache, cache_time, class_name, class_file, connection_hook=connection_hook, direct=direct) # do we need to do anything on reparse? if Globals.DevelopmentMode: # Provide an opportunity to update the properties. def __of__(self, parent): try: self = ImplicitAcquisitionWrapper(self, parent) self._updateFromFS() return self except: import sys LOG('FS Z SQL Method', ERROR, 'Error during __of__', error=sys.exc_info()) raise Globals.InitializeClass(FSZSQLMethod) registerFileExtension('zsql', FSZSQLMethod) registerMetaType('Z SQL Method', FSZSQLMethod)
def asHTML(self): ''' Called when this object is the index_html for a folder. ''' view = self.view if getattr(aq_base(view), 'isDocTemp', 0): return apply(view, (self, self.REQUEST)) else: return view() # Overridden methods to support cataloging items that might # be stored in attributes unknown to the content object, such # as the DiscussionItemContainer "talkback" security.declareProtected(AccessContentsInformation, 'objectItems') def objectItems(self): """ since "talkback" is the only opaque item on content right now i will return that. should be replaces with a list of tuples for every opaque item! """ talkback = getattr(self, 'talkback', None) if talkback is not None: return ((talkback.id, talkback), ) else: return [] Globals.InitializeClass(PortalContent)
return event.render(name=display) elif formattedString: lookup = { 'url': event.absolute_url_path(), 'title_or_id': event.title_or_id(), 'title': event.title(), 'id': event.getId() } return formattedString % lookup elif self.renderScript: script = self.getCompoundDocContainer().restrictedTraverse( self.renderScript, None) if script is not None: return script(event) return '<br><a href="%(url)s">%(title_or_id)s</a>' % { 'url': event.absolute_url_path(), 'title_or_id': event.title_or_id() } security.declarePrivate('PrincipiaSearchSource') def PrincipiaSearchSource(self): "This is the basic search function" #ERROR: Do no currently index this object becuse it causes changes saved to break return '' Globals.InitializeClass(EventCalendar) import register register.registerClass(EventCalendar)
for entry in self._getLog(): if entry['id'] == id: return entry.copy() return None security.declareProtected(use_error_logging, 'getLogEntryAsText') def getLogEntryAsText(self, id, RESPONSE=None): """Returns the specified log entry. Makes a copy to prevent changes. Returns None if not found. """ entry = self.getLogEntryById(id) if entry is None: return 'Log entry not found or expired' if RESPONSE is not None: RESPONSE.setHeader('Content-Type', 'text/plain') return entry['tb_text'] Globals.InitializeClass(SiteErrorLog) def manage_addErrorLog(dispatcher, RESPONSE=None): """Add a site error log to a container.""" log = SiteErrorLog() dispatcher._setObject(log.id, log) if RESPONSE is not None: RESPONSE.redirect(dispatcher.DestinationURL() + '/manage_main?manage_tabs_message=Error+Log+Added.')
security.declarePrivate('render_multiple') def render_multiple(self, name, key, value, containers, format, lookup): "draw the multiple selection rendering control" values = self.classConfig[key]['values'] size = self.classConfig[key].get('size', None) lookup['form'] = self.multiselect(seq = values, name = key, selected = value, size=size, containers=containers) return format % lookup security.declarePrivate('render_radio') def render_radio(self, name, key, value, containers, format, lookup): "draw the radio rendering control" lookup['form'] = self.true_false(key, value, 0, containers=containers) return format % lookup security.declarePrivate('render_file') def render_file(self, name, key, value, containers, format, lookup): "draw the file rendering control" lookup['form'] = self.input_file(key, utility.renderNoneAsString(value), containers=containers) return format % lookup security.declarePrivate('render_path') def render_path(self, name, key, value, containers, format, lookup): "draw the path rendering control" lookup['form'] = self.input_text(key, value, containers=containers) href = self.getHref(value) if href: lookup['form'] = '%s %s' % (lookup['form'], href) return format % lookup Globals.InitializeClass(MixConfigObject)
_editableAttributes = ('value', ) def __init__(self, id, field): self.id = id self.field = field self.value = '' security.declareProtected(TopicPermissions.ChangeTopics, 'getEditForm') def getEditForm(self): " Return the skinned name of the edit form " return 'ssc_edit' security.declareProtected(TopicPermissions.ChangeTopics, 'edit') def edit(self, value): """ Update the value we are to match up against """ self.value = str(value) security.declareProtected(CMFCorePermissions.View, 'getCriteriaItems') def getCriteriaItems(self): """ Return a sequence of criteria items, used by Topic.buildQuery """ return self.value is not '' and ((self.field, self.value), ) or () Globals.InitializeClass(SimpleStringCriterion) # Register as a criteria type with the Topic class Topic._criteriaTypes.append(SimpleStringCriterion)
########################################################################### from commonradio import CommonRadio #For Security control and init from AccessControl import ClassSecurityInfo import Globals class CheckBox(CommonRadio): "CheckBox class" security = ClassSecurityInfo() meta_type = "CheckBox" data = 0 actionYes = '' actionNo = '' security.declareProtected('View management screens', 'edit') def edit(self, *args, **kw): "Inline edit short object" return self.radio_box('data', self.data, enableDefault=1) Globals.InitializeClass(CheckBox) import register register.registerClass(CheckBox)
ve = self.var_exprs if REQUEST is not None: for id in ve.keys(): fname = 'varexpr_%s' % id val = REQUEST[fname] expr = None if val: expr = Expression(str(REQUEST[fname])) ve[id] = expr return self.manage_variables(REQUEST, 'Variables changed.') Globals.InitializeClass(TransitionDefinition) class Transitions(ContainerTab): """A container for transition definitions""" meta_type = 'Workflow Transitions' security = ClassSecurityInfo() security.declareObjectProtected(ManagePortal) all_meta_types = ({ 'name': TransitionDefinition.meta_type, 'action': 'addTransition', }, )
"CMF 2.3; please mark the root object with " "'ISiteRoot' instead.", DeprecationWarning, stacklevel=2) return ob ob = aq_parent(ob) return None def getDateTime(self): date = self._date if not date: date = self._date = DateTime() return date Globals.InitializeClass(StateChangeInfo) def createExprContext(sci): ''' An expression context provides names for TALES expressions. ''' ob = sci.object wf = sci.workflow container = aq_parent(aq_inner(ob)) data = { 'here': ob, 'object': ob, 'container': container, 'folder': container, 'nothing': None,
# Installation and removal of traversal hooks. def manage_beforeDelete(self, item, container): if item is self: handle = self.meta_type + '/' + self.getId() BeforeTraverse.unregisterBeforeTraverse(container, handle) def manage_afterAdd(self, item, container): if item is self: handle = self.meta_type + '/' + self.getId() container = container.this() nc = BeforeTraverse.NameCaller(self.getId()) BeforeTraverse.registerBeforeTraverse(container, nc, handle) Globals.InitializeClass(CookieCrumbler) class ResponseCleanup: def __init__(self, resp): self.resp = resp def __del__(self): # Free the references. # # No errors of any sort may propagate, and we don't care *what* # they are, even to log them. try: del self.resp.unauthorized except: pass
temp.append(self.drawAlternateDropDown(documents)) if loadText is None: loadText = 'Load Document' if enableLoadButton: temp.append(self.submitChanges(loadText)) return ''.join(temp) security.declarePrivate('drawPrimaryDropDown') def drawPrimaryDropDown(self, docs): "draw the primary drop down" js = 'onchange="submit()"' seq = [(name, name) for (name, i) in docs] seq.insert(0, ('', 'Load Document')) return self.option_select(seq, 'selectedDocument', dataType='list:ignore_empty', events=js) security.declarePrivate('drawAlternateDropDown') def drawAlternateDropDown(self, docs): "draw the alternate drop down" return '' Globals.InitializeClass(ObjectCompoundController) import register register.registerClass(ObjectCompoundController)
security.declareProtected(TopicPermissions.ChangeTopics, 'edit') def edit(self, value, direction=''): """ Update the value we match against. """ if type(value) == type('') and (not string.strip(value)): # An empty string was passed in, which evals to None self.value = self.direction = None else: self.value = int(value) self.direction = direction security.declareProtected(CMFCorePermissions.View, 'getCriteriaItems') def getCriteriaItems(self): """ Used by Topic.buildQuery() """ if self.value is None: return () result = ((self.Field(), self.value), ) if self.direction is not None: result = result + ( ('%s_usage' % self.Field(), 'range:%s' % self.direction), ) return result Globals.InitializeClass(SimpleIntCriterion) # Register as a criteria type with the Topic class Topic._criteriaTypes.append(SimpleIntCriterion)
'''<p>The Order Catalog will be auto created do not create anything else in the Order Location folder with the name you want this catalog to have.</p>''') temp.append( "<p>Total Price Calculation MUST be enabled if you want to use a CreditCardManager on the orders.</p>" ) temp.append( '<p>Enable Total Price Calculation:%s</p>' % self.true_false('totalPriceEnabled', self.totalPriceEnabled, 0)) temp.append('<p>Enable Freight:%s</p>' % self.true_false('freightEnabled', self.freightEnabled, 0)) temp.append(self.editSingleConfig('orderOkayAddScript')) temp.append(self.editSingleConfig('runInSecureMode')) temp.append(self.editSingleConfig('viewerRole')) return ''.join(temp) security.declarePrivate('instance') instance = (('SessionManagerConfig', ('create', 'SessionManagerConfig')), ('FreightOrderListing', ('create', 'FreightOrderListing'))) security.declarePrivate('PrincipiaSearchSource') def PrincipiaSearchSource(self): "Return what can be search which is nothing" return '' Globals.InitializeClass(SessionCart) import register register.registerClass(SessionCart)
pt = self._getPortalTypeName() return tool.getTypeInfo(pt) # Can return None. # Support for dynamic icons security.declarePublic('getIcon') def getIcon(self, relative_to_portal=0): """ Using this method allows the content class creator to grab icons on the fly instead of using a fixed attribute on the class. """ ti = self.getTypeInfo() if ti is not None: icon = quote(ti.getIcon()) if icon: if relative_to_portal: return icon else: # Need the full path to the icon. portal_url = getPortal(self).absolute_url(relative=1) return portal_url + '/' + icon return 'misc_/OFSP/dtmldoc.gif' security.declarePublic('icon') icon = getIcon # For the ZMI and the catalog. Globals.InitializeClass(DynamicType)
''' ks = [] for key in keys: key = strip(str(key)) if key: ks.append(key) self._cache_namespace_keys = tuple(ks) if REQUEST is not None: return self.ZCacheable_manage(self, REQUEST) # Zope 2.3.x way: def validate(self, inst, parent, name, value, md=None): return getSecurityManager().validate(inst, parent, name, value) security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = DTMLMethod.manage_FTPget.im_func security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = DTMLMethod.PrincipiaSearchSource.im_func security.declareProtected(ViewManagementScreens, 'document_src') document_src = DTMLMethod.document_src.im_func security.declareProtected(ViewManagementScreens, 'manage_haveProxy') manage_haveProxy = DTMLMethod.manage_haveProxy.im_func Globals.InitializeClass(FSDTMLMethod) registerFileExtension('dtml', FSDTMLMethod) registerMetaType('DTML Method', FSDTMLMethod)
if info is not None: info = info.getContents(_dirreg) if info is None: data = {} objects = () else: data, objects = info s = DirectoryViewSurrogate(self, data, objects) res = s.__of__(parent) return res def getId(self): return self.id Globals.InitializeClass(DirectoryView) class DirectoryViewSurrogate(Folder): meta_type = 'Filesystem Directory View' all_meta_types = () _isDirectoryView = 1 security = ClassSecurityInfo() def __init__(self, real, data, objects): d = self.__dict__ d.update(data) d.update(real.__dict__) d['_real'] = real
ob = self wftool = getToolByName(self, 'portal_workflow', None) # XXX None ? if wftool is not None: wf_ids = wftool.getChainFor(ob) states = {} chain = [] for wf_id in wf_ids: wf = wftool.getWorkflowById(wf_id) if wf is not None: # XXX a standard API would be nice if hasattr(wf, 'getReviewStateOf'): # Default Workflow state = wf.getReviewStateOf(ob) elif hasattr(wf, '_getWorkflowStateOf'): # DCWorkflow state = wf._getWorkflowStateOf(ob, id_only=1) else: state = '(Unknown)' states[wf_id] = state chain.append(wf_id) return self._manage_workflowsTab( REQUEST, chain=chain, states=states, management_view='Workflows', manage_tabs_message=manage_tabs_message) Globals.InitializeClass(CMFCatalogAware)
element = stack.pop() # Append rule to the list if isinstance(element, ErrorTranslationRule): rules.append(element) # Check if it could be a container that holds more rules try: new = element.objectValues() stack.extend(new) except AttributeError: pass rules.sort(lambda x,y: cmp(x.getPriority(), y.getPriority())) return rules Globals.InitializeClass(ErrorTranslator) manage_addErrorTranslationRule = Globals.HTMLFile('dtml/ErrorTranslationRuleAdd', globals()) def createErrorTranslationRule(context, id, REQUEST=None): """A factory for creating a new translation rule.""" context._setObject(id, ErrorTranslationRule(id, REQUEST)) if REQUEST is not None: return context.manage_main(context, REQUEST) class ErrorTranslationRule(SimpleItem.SimpleItem): __implements__ = IErrorTranslator.IErrorTranslationRule security = AccessControl.ClassSecurityInfo() meta_type = "Error Translation Rule"
field = self.Field() value = self.value # Negate the value for 'old' days if self.daterange == 'old': value = -value date = DateTime() + value operation = self.operation if operation == 'within_day': range = (date.earliestTime(), date.latestTime()) result.append((field, range)) result.append(('%s_usage' % field, 'range:min:max')) else: result.append((field, date)) result.append( ('%s_usage' % field, 'range:%s' % self.operation)) return result Globals.InitializeClass(FriendlyDateCriterion) # Register as a criteria type with the Topic class Topic._criteriaTypes.append(FriendlyDateCriterion)
if cookie != mskin: resp = req.RESPONSE expires = (DateTime('GMT') + 365).rfc822() resp.setCookie(self.request_varname, mskin, path='/', expires=expires) # Ensure updateSkinCookie() doesn't try again # within this request. req.cookies[self.request_varname] = mskin req[self.request_varname] = mskin return 1 return 0 security.declareProtected(ManagePortal, 'addSkinSelection') def addSkinSelection(self, skinname, skinpath, test=0, make_default=0): ''' Adds a skin selection. ''' sels = self._getSelections() skinpath = str(skinpath) if test: self.testSkinPath(skinpath) sels[str(skinname)] = skinpath if make_default: self.default_skin = skinname Globals.InitializeClass(SkinsTool)
security.declarePrivate('getAvailableSessionManagers') def getAvailableSessionManagers(self): "Return a list of all the available session managers" return [ '/'.join(i.getPhysicalPath()) for i in self.superValues('Session Data Manager') ] security.declarePrivate('getDefaultSessionManager') def getDefaultSessionManager(self): "Get the first one we have worse case return a blank string" managers = self.getAvailableSessionManagers() if len(managers): return managers[0] return "" security.declarePrivate('delayedInstance') delayedInstance = (('sessionManager', ('call', 'getDefaultSessionManager')), ) security.declarePrivate('getSessionManager') def getSessionManager(self): "get the session manager object" return self.unrestrictedTraverse(self.sessionManager, None) Globals.InitializeClass(BaseSessionManager)