continue action_infos.append(ai.getAction(ec)) else: for i in actions: if not i.get('visible', 1): continue permissions = i.get('permissions', None) if permissions: category = i['category'] if (object is not None and (category.startswith('object') or category.startswith('workflow'))): context = object elif (info['folder'] is not None and category.startswith('folder')): context = info['folder'] else: context = info['portal'] for permission in permissions: allowed = _checkPermission(permission, context) if allowed: break if not allowed: continue action_infos.append(i) return action_infos InitializeClass(ActionsTool)
def rssiFromAPString(self): rssi = self.rssiFromAP() return rssi is None and "Unknown" or "%ddBm" % rssi def rssiString(self): fromAP = str(self.rssiFromAP(default="Unknown")) fromSU = str(self.rssiFromSU(default="Unknown")) return "%s / %s" % (fromAP, fromSU) def txPower(self, default=None): return self.cacheRRDValue('txPower', default) def txPowerString(self): power = self.txPower() return power is None and "Unknown" or "%ddBm" % power def getRRDNames(self): return [ 'rssiFromSU_rssiFromSU', 'rssiFromAP_rssiFromAP', 'txPower_txPower', 'rfInOctets_rfInOctets', 'rfOutOctets_rfOutOctets', 'temperature_temperature', ] InitializeClass(TrangoSU)
if hasattr(aq_base(ob), 'workflow_history'): history = ob.workflow_history if history is not None: has_history = 1 wfh = history.get(wf_id, None) if wfh is not None: wfh = list(wfh) if not wfh: wfh = [] wfh.append(status) if not has_history: ob.workflow_history = PersistentMapping() ob.workflow_history[wf_id] = tuple(wfh) InitializeClass(WorkflowTool) _workflow_factories = {} def addWorkflowFactory(factory, id=None, title=None): # The factory should take one argument, id. if id is None: id = getattr(factory, 'id', '') or getattr(factory, 'meta_type', '') if title is None: title = getattr(factory, 'title', '') key = id if title: key = key + ' (%s)' % title _workflow_factories[key] = factory
'modified', '', '', lineterm="") security.declareProtected(ViewManagementScreens, 'manage_showDiff') manage_showDiff = PageTemplateFile('www/cpsDiff.pt', globals()) manage_options = (PythonScript.manage_options[:1] + ({ 'label': 'Diff', 'action': 'manage_showDiff' }, ) + PythonScript.manage_options[1:]) InitializeClass(CustomizedPythonScript) class FSPythonScript(FSObject, Script): """FSPythonScripts act like Python Scripts but are not directly modifiable from the management interface.""" meta_type = 'Filesystem Script (Python)' _params = _body = '' _v_f = None _proxy_roles = () _owner = None # Unowned manage_options = ( { 'label': 'Customize',
security.declareProtected(View, 'enforceVocabulary') def enforceVocabulary(self): """ """ return self.enforce_vocabulary security.declareProtected(View, 'allowedVocabulary') def allowedVocabulary(self): """ """ return self.allowed_vocabulary InitializeClass(MetadataElementPolicy) DEFAULT_ELEMENT_SPECS = (('Title', 0), ('Description', 0), ('Subject', 1), ('Format', 0), ('Language', 0), ('Rights', 0)) class ElementSpec(SimpleItem): """ Represent all the tool knows about a single metadata element. """ security = ClassSecurityInfo() # # Default values. # is_multi_valued = 0
classImplements(ReferenceWithBrains, IReferenceWithBrains) except TypeError: ReferenceWithBrains.__implements__ = (IReferenceWithBrains, ) # # These proxy methods all make use of a volatile attribute to store their value # The dict maps method names, e.g. 'getSourceBrain', to functions that produce # the value. proxies = { 'getSourceBrain': lambda self: makeBrainAggregate(self, self.sourceUID), 'getTargetBrain': lambda self: makeBrainAggregate(self, self.targetUID), 'getSourceObject': lambda self: Reference.getSourceObject(self), 'getTargetObject': lambda self: Reference.getTargetObject(self), } def makeProxyMethod(key, valueFun): def proxyMethod(self): attr_name = '_v_%s' % key if not shasattr(self, attr_name): setattr(self, attr_name, valueFun(self)) return getattr(self, attr_name) return proxyMethod for key, valueFun in proxies.items(): setattr(ReferenceWithBrains, key, makeProxyMethod(key, valueFun)) # end of class ReferenceWithBrains InitializeClass(ReferenceWithBrains)
if not hasattr(self, '_shortdescription'): self._shortdescription = "" else: return self._shortdescription # Mutator def set_image(self, image): self._image = image # Accessor def get_image(self): if not hasattr(self, '_image'): self._image = "" else: return self._image # Mutator def set_casestudy(self, casestudy): self._casestudy = casestudy # Accessor def get_casestudy(self): if not hasattr(self, '_casestudy'): self._casestudy = "" else: return self._casestudy InitializeClass(CourseSubject) InitializeClass(CourseSubjectVersion)
security.declarePrivate('unrestrictedGetBrain') def unrestrictedGetBrain(self, uid): """See IUniqueIdUnrestrictedQuery. """ return self._getBrain(uid, self.unrestrictedQueryBrain) security.declarePrivate('unrestrictedGetObject') def unrestrictedGetObject(self, uid): """See IUniqueIdUnrestrictedQuery. """ return self.unrestrictedGetBrain(uid).getObject() security.declarePrivate('unrestrictedQueryObject') def unrestrictedQueryObject(self, uid, default=None): """See IUniqueIdUnrestrictedQuery. """ try: return self.unrestrictedGetObject(uid) except UniqueIdError: return default security.declareProtected(ManagePortal, 'manage_queryObject') manage_queryObject = PageTemplateFile('queryUID.pt', _wwwdir) InitializeClass(UniqueIdHandlerTool)
portal_type = meta_type = "MultiGraphReportClass" # Remove this relationship after version 2.1 _relations = ReportClass._relations + ( ('graphDefs', ToManyCont(ToOne, 'Products.ZenModel.GraphDefinition', 'reportClass')), ) security = ClassSecurityInfo() def getReportClass(self): """ Return the class to instantiate for new report classes """ return MultiGraphReportClass security.declareProtected('Manage DMD', 'manage_addMultiGraphReport') def manage_addMultiGraphReport(self, id, REQUEST=None): """Add a MultiGraph report to this object. """ fr = MultiGraphReport(id) self._setObject(id, fr) if REQUEST: audit('UI.Report.Add', fr.id, reportType=getDisplayType(fr)) url = '%s/%s/editMultiGraphReport' % (self.getPrimaryUrlPath(), id) return REQUEST['RESPONSE'].redirect(url) return self._getOb(id) InitializeClass(MultiGraphReportClass)
RESPONSE.setHeader('Last-Modified', rfc1123_date()) RESPONSE.setHeader('Content-Type', 'application/x-zope-edit') def _write_metadata(self, RESPONSE, metadata, length): # Set response content-type so that the browser gets hinted # about what application should handle this. self._set_headers(RESPONSE) # Set response length and write our metadata. The '+1' on the # content-length is the '\n' after the metadata. RESPONSE.setHeader('Content-Length', length + 1) RESPONSE.write(metadata) RESPONSE.write('\n') InitializeClass(ExternalEditor) is_mac_user_agent = re.compile('.*Mac OS X.*|.*Mac_PowerPC.*').match def EditLink(self, object, borrow_lock=0, skip_data=0): """Insert the external editor link to an object if appropriate""" base = Acquisition.aq_base(object) user = getSecurityManager().getUser() editable = (hasattr(base, 'manage_FTPget') or hasattr(base, 'EditableBody') or hasattr(base, 'document_src') or hasattr(base, 'read')) if editable and user.has_permission(ExternalEditorPermission, object): query = {} if is_mac_user_agent(object.REQUEST['HTTP_USER_AGENT']): # Add extension to URL so that the Mac finder can
zcat.addColumn('id') zcat.addColumn('oid') def handleUploadedFile(self, REQUEST): """ Assumes the file to be a mib so we need to create a mib module with its contents File will be available with REQUEST.upload """ filename = REQUEST.upload.filename mibs = REQUEST.upload.read() savedMIBPath = zenPath(_pathToMIB, filename) atomicWrite(savedMIBPath, mibs, raiseException=True, createDir=True) # create the job mypath = self.absolute_url_path().replace('/zport/dmd/Mibs', '') if not mypath: mypath = '/' commandArgs = [ binPath('zenmib'), 'run', savedMIBPath, '--path=%s' % mypath, '--mibdepsdir=%s' % zenPath(_pathToMIB) ] return self.dmd.JobManager.addJob(SubprocessJob, description="Load MIB at %s" % mypath, kwargs=dict(cmd=commandArgs)) InitializeClass(MibOrganizer)
self, REQUEST, ) + args, my_kw) security.declarePublic('propertyLabel') def propertyLabel(self, id): """Return a label for the given property id """ for p in self._properties: if p['id'] == id: return p.get('label', id) return id InitializeClass(SimpleItemWithProperties) # # "Omnibus" factory framework for tools. # class ToolInit: """ Utility class for generating the factories for several tools. """ __name__ = 'toolinit' security = ClassSecurityInfo() security.declareObjectPrivate() # equivalent of __roles__ = () def __init__(self, meta_type, tools, product_name, icon): self.meta_type = meta_type
lines.extend(msg.split('\n')) lines.append('') report = '\n'.join(lines) if isinstance(report, unicode): report = report.encode('latin-1') # BBB: ObjectManager won't allow unicode IDS if isinstance(name, unicode): name = name.encode('UTF-8') file = File(id=name, title='', file=report, content_type='text/plain') self._setObject(name, file) InitializeClass(SetupTool) _PLAINTEXT_DIFF_HEADER = """\ Comparing configurations: '%s' and '%s' %s""" _TOOL_ID = 'setup_tool' addSetupToolForm = PageTemplateFile('toolAdd.zpt', _wwwdir) def addSetupTool(dispatcher, RESPONSE): """ """ dispatcher._setObject(_TOOL_ID, SetupTool(_TOOL_ID))
xml = Rdf.RDF(rss_channel_for_channel(self, lang)) channel = xml[0] items = channel[-1] seq = etree.SubElement(items, '{%s}Seq' % rdf_namespace) for i in l_items: x = etree.SubElement(seq, '{%s}li' % rdf_namespace, resource=i.absolute_url()) if self.hasImage(): image = E.image(E.title(self.title), E.url(self.getImagePath()), E.link(s.absolute_url()), E.description(self.utToUtf8(self.description))) xml.append(image) received_items = ''.join([i.syndicateThis() for i in l_items]) received = '<rdf:RDF %s>%s</rdf:RDF>' % (''.join(header), received_items) xml_received = etree.XML(received, etree.XMLParser(strip_cdata=False)) xml.extend(xml_received) self.REQUEST.RESPONSE.setHeader('content-type', 'text/xml') return etree.tostring(xml, xml_declaration=True, encoding="utf-8") # zmi pages security.declareProtected(view_management_screens, 'manage_properties_html') manage_properties_html = PageTemplateFile('zpt/scriptchannel_properties', globals()) InitializeClass(ScriptChannel)
def getHistoryId(self, obj): """Returns the version history ID of the object. """ verifyPermission(UseVersionControl, obj) obj = unproxied(obj) repo = self._getVersionRepository() return repo.getVersionInfo(obj).history_id security.declarePublic('revertToVersion') def revertToVersion(self, obj, version_id): """Reverts the object to the given version. If make_new_revision, a new revision is created, so that the object's state can progress along a new line without making the user deal with branches, labels, etc. """ verifyPermission(UseVersionControl, obj) obj = unproxied(obj) repo = self._getVersionRepository() # Verify the object is under version control. repo.getVersionInfo(obj) if self.isCheckedOut(obj): # Save the current data. self.checkin(obj, 'Auto-saved') repo.updateResource(obj, version_id) InitializeClass(VersionsTool)
'filename': { DEFAULT: '%(id)s' } } } def _convertTypes(self, val): for type in val: if type['filename'] == type['id']: type['filename'] = _getTypeFilename(type['filename']) return val InitializeClass(TypesToolImportConfigurator) class TypesToolExportConfigurator(ExportConfiguratorBase): security = ClassSecurityInfo() security.declareProtected(ManagePortal, 'listTypeInfo') def listTypeInfo(self): """ Return a list of mappings for each type info in the site. o These mappings are pretty much equivalent to the stock 'factory_type_information' elements used everywhere in the CMF. """
""" TextDiff.py - Text difference between objects Author: Brent Hendricks (C) 2005 Rice University This software is subject to the provisions of the GNU Lesser General Public License Version 2.1 (LGPL). See LICENSE.txt for details. """ from Globals import InitializeClass from FieldDiff import FieldDiff from interfaces.portal_diff import IDifference class TextDiff(FieldDiff): """Text difference""" __implements__ = (IDifference) meta_type = "Lines Diff" def _parseField(self, value): """Parse a field value in preparation for diffing""" # Split the text into a list for diffs return value.split('\n') InitializeClass(TextDiff)
def getHTTPCachingHeaders(self, content, view_method, keywords, time=None): """ Return a list of HTTP caching headers based on 'content', 'view_method', and 'keywords'. """ context = createCPContext(content, view_method, keywords, time=time) for policy_id, policy in self.listPolicies(): headers = policy.getHeaders(context) if headers: return headers return () InitializeClass(CachingPolicyManager) def manage_addCachingPolicyManager(self, REQUEST=None): """ Add a CPM to self. """ id = CachingPolicyManager.id mgr = CachingPolicyManager() self._setObject(id, mgr) if REQUEST is not None: REQUEST['RESPONSE'].redirect( self.absolute_url() + '/manage_main' + '?manage_tabs_message=Caching+Policy+Manager+added.')
# Update state. status[self.state_var] = new_state tool = aq_parent(aq_inner(self)) tool.setStatusOf(self.id, ob, status) # Update role to permission assignments. self.updateRoleMappingsFor(ob) # Execute the "after" script. if tdef is not None and tdef.after_script_name: script = self.scripts[tdef.after_script_name] # Pass lots of info to the script in a single parameter. sci = StateChangeInfo(ob, self, status, tdef, old_sdef, new_sdef, kwargs) script(sci) # May throw an exception. # Fire "after" event notify( AfterTransitionEvent(ob, self, old_sdef, new_sdef, tdef, status, kwargs)) # Return the new state object. if moved_exc is not None: # Propagate the notification that the object has moved. raise moved_exc else: return new_sdef InitializeClass(DCWorkflowDefinition)
}, 'roles': { 'role': { KEY: None } }, 'role': { 'name': { KEY: None } }, 'permissions': { 'permission': { KEY: None, DEFAULT: () } }, 'permission': { 'name': {}, 'role': { KEY: 'roles' }, 'acquire': { CONVERTER: self._convertToBoolean } } } InitializeClass(RolemapConfigurator)
self.value = int(value) self.direction = direction else: self.value = int(value) self.direction = None security.declareProtected(View, 'getCriteriaItems') def getCriteriaItems(self): """ Return a tuple of query elements to be passed to the catalog (used by 'Topic.buildQuery()'). """ if self.value is None: return () elif self.direction is None: return ((self.Field(), self.value), ) else: return ((self.Field(), { 'query': self.value, 'range': self.direction }), ) InitializeClass(SimpleIntCriterion) # Register as a criteria type with the Topic class Topic._criteriaTypes.append(SimpleIntCriterion)
subject=(), description='', contributors=(), effective_date=None, expiration_date=None, format='text/html', language='en-US', rights=''): """ used to be: editMetadata = WorkflowAction(_editMetadata) Need to add check for webDAV locked resource for TTW methods. """ # as per bug #69, we cant assume they use the webdav # locking interface, and fail gracefully if they dont if hasattr(self, 'failIfLocked'): self.failIfLocked() self._editMetadata(title=title, subject=subject, description=description, contributors=contributors, effective_date=effective_date, expiration_date=expiration_date, format=format, language=language, rights=rights) self.reindexObject() InitializeClass(DefaultDublinCoreImpl)
raise "Calendar Type Error", month try: year = int(year) except: raise "Calendar Type Error", year if month == 12: month, year = 1, year + 1 else: month += 1 return DateTime(str(month) + '/1/' + str(year)) security.declarePublic('getBeginAndEndTimes') def getBeginAndEndTimes(self, day, month, year): # Given any day, month and year this method returns 2 DateTime objects # That represent the exact start and the exact end of that particular day. day = str(day) month = str(month) year = str(year) begin = DateTime(month + '/' + day + '/' + year + ' 12:00:00AM') end = DateTime(month + '/' + day + '/' + year + ' 11:59:59PM') return (begin, end) InitializeClass(CalendarTool)
for norma in normas: resultado = {} cod_norma = norma.cod_norma identificador = self.monta_id(cod_norma) urn = self.monta_urn(cod_norma) xml_lexml = self.monta_xml(urn, cod_norma) resultado['tx_metadado_xml'] = xml_lexml #resultado['id_registro_item'] = resultado['name'] #del resultado['name'] #record['sets'] = record['sets'].strip().split(' ') #if resultado['sets'] == [u'']: # resultado['sets'] = [] resultado['cd_status'] = 'N' resultado['id'] = identificador resultado['when_modified'] = norma.timestamp resultado['deleted'] = 0 if norma.ind_excluido == 1: resultado['deleted'] = 1 # resultado['cd_status'] = 'D' yield { 'record': resultado, # 'sets': ['person'], 'metadata': resultado['tx_metadado_xml'], # 'assets':{} } InitializeClass(SAPLTool)
title=_(u"Some List"), value_type=TextLine(title=_(u"Some item")), default=[], required=False ) class FieldContent(SimpleItem): """A Viewable piece of content with fields""" implements(IFieldContent) meta_type = 'Five FieldContent' def __init__(self, id, title): self.id = id self.title = title InitializeClass(FieldContent) def manage_addFieldContent(self, id, title, REQUEST=None): """Add the field content""" id = self._setObject(id, FieldContent(id, title)) return '' class IComplexSchemaContent(Interface): fishtype = TextLine( title=u"Fish type", description=u"The type of fish", default=u"It was a lovely little fish. And it went wherever I did go.", required=False) fish = Object(
_dict['(Default)'] = viewmethod # correct guessed values if we know better if self.content_meta_type in ('Portal File', 'Portal Folder', 'Portal Image'): _dict['(Default)'] = 'index_html' if viewmethod == '(Default)': _dict['view'] = 'index_html' if self.content_meta_type in ('Document', 'News Item'): _dict['gethtml'] = 'source_html' self.setMethodAliases(_dict) return 1 InitializeClass(TypeInformation) class FactoryTypeInformation(TypeInformation): """ Portal content factory. """ implements(ITypeInformation) __implements__ = z2ITypeInformation meta_type = 'Factory-based Type Information' security = ClassSecurityInfo() _properties = (TypeInformation._basic_properties + ( {
if not operator: operator = None self.operator = operator security.declareProtected(View, 'getCriteriaItems') def getCriteriaItems(self): """ Return a tuple of query elements to be passed to the catalog (used by 'Topic.buildQuery()'). """ # filter out empty strings result = [] value = tuple(filter(None, self.value)) if not value: return () result.append((self.field, self.value), ) if self.operator is not None: result.append(('%s_operator' % self.field, self.operator)) return tuple(result) InitializeClass(ListCriterion) # Register as a criteria type with the Topic class Topic._criteriaTypes.append(ListCriterion)
self.default_expr = Expression(default_expr) else: self.default_expr = None g = Guard() if g.changeFromProperties(props or REQUEST): self.info_guard = g else: self.info_guard = None self.for_catalog = bool(for_catalog) self.for_status = bool(for_status) self.update_always = bool(update_always) if REQUEST is not None: return self.manage_properties(REQUEST, 'Properties changed.') InitializeClass(VariableDefinition) class Variables(ContainerTab): """A container for variable definitions""" meta_type = 'Workflow Variables' all_meta_types = ({'name':VariableDefinition.meta_type, 'action':'addVariable', },) _manage_variables = DTMLFile('variables', _dtmldir) def manage_main(self, REQUEST, manage_tabs_message=None): '''
If 'size' is not zero, only the closest 'size' parents will be returned. """ parents = [] current = self while not size or len(parents) < size: parent = current.inReplyTo() assert not parent in parents # sanity check parents.insert(0, parent) if parent.meta_type != self.meta_type: break current = parent return parents InitializeClass(DiscussionItem) class DiscussionItemContainer(Persistent, Implicit, Traversable): """ Store DiscussionItem objects. Discussable content that has DiscussionItems associated with it will have an instance of DiscussionItemContainer injected into it to hold the discussion threads. """ __implements__ = Discussable # for the security machinery to allow traversal #__roles__ = None
device = self.getDevice(dmd) if device: return _findComponent(device, self.component) return None def getDeviceLink(self, dmd=None): if self.link: return self.link if dmd: device = self.getDevice(dmd) if device: return device.getDeviceLink() return None InitializeClass(AvailabilityColl) class CReport(object): "Determine availability by counting the amount of time down" rf.write('Start of CReport\n') def __init__(self, startDate=None, endDate=None, eventClass=Status_Ping, severity=5, device=None, component='', prodState=1000,