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 security = ClassSecurityInfo()
text_format=text_format) self._setObject(id, o) class NewsItem(Document): """ A News Item """ __implements__ = Document.__implements__ # redundant, but explicit meta_type = 'News Item' text_format = 'html' security = ClassSecurityInfo() security.declareProtected(ModifyPortalContent, 'edit') def edit(self, text, description=None, text_format=None): """ Edit the News Item """ if text_format is None: text_format = getattr(self, 'text_format', 'html') if description is not None: self.setDescription(description) Document.edit(self, text_format, text) InitializeClass(NewsItem)
domains=None): """ Edit a user's properties and security settings o Checks should be done before this method is called using testPropertiesValidity and testPasswordValidity """ mtool = getToolByName(self, 'portal_membership') member = mtool.getMemberById(member_id) member.setMemberProperties(properties) member.setSecurityProfile(password, roles, domains) return member InitializeClass(RegistrationTool) # See URL: http://www.zopelabs.com/cookbook/1033402597 # Python 2.1 compatibility try: True except NameError: True = 1 False = 0 _TESTS = ((re.compile("^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$"), True, "Failed a"), (re.compile("^[^0-9a-zA-Z]|[^0-9a-zA-Z]$"), False, "Failed b"), (re.compile("([0-9a-zA-Z]{1})\@."), True, "Failed c"), (re.compile(".\@([0-9a-zA-Z]{1})"), True, "Failed d"),
""" """ return self.getFormsTool().getContent({'here': self}, 'case_study_index') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html') def edit_html(self, REQUEST=None, RESPONSE=None): """ """ if self.hasVersion(): obj = self.version else: obj = self return self.getFormsTool().getContent({'here': obj}, 'case_study_edit') InitializeClass(NyCaseStudy) manage_addNyCaseStudy_html = PageTemplateFile('zpt/case_study_manage_add', globals()) manage_addNyCaseStudy_html.kind = config['meta_type'] manage_addNyCaseStudy_html.action = 'addNyCaseStudy' config.update({ 'constructors': (manage_addNyCaseStudy_html, addNyCaseStudy), 'folder_constructors': [ # NyFolder.manage_addNyCaseStudy_html = manage_addNyCaseStudy_html ('manage_addNyCaseStudy_html', manage_addNyCaseStudy_html), ('case_study_add_html', case_study_add_html), ('addNyCaseStudy', addNyCaseStudy), ('import_case_study_item', importNyCaseStudy), ],
hdrlist = self.getMetadataHeaders() if self.Format() == 'text/html': hdrtext = '' for name, content in hdrlist: if lower(name) == 'title': continue else: hdrtext = '%s\n <meta name="%s" content="%s" />' % ( hdrtext, name, content) bodytext = self._htmlsrc % { 'title': self.Title(), 'metatags': hdrtext, 'body': self.text, } else: hdrtext = join(map(lambda x: '%s: %s' % (x[0], x[1]), hdrlist), '\n') bodytext = '%s\n\n%s' % (hdrtext, self.text) return bodytext security.declareProtected(CMFCorePermissions.View, 'get_size') def get_size(self): """ Used for FTP and apparently the ZMI now too """ return len(self.manage_FTPget()) InitializeClass(Document)
"""Test the specified object to determine if the change set will apply without errors""" value = _getValue(ob, self.field) if not self.same and value != self.oldValue: raise MergeError("Conflict Error during merge", self.field, value, self.oldValue) def applyChanges(self, ob): """Update the specified object with the difference""" # Simplistic update self.testChanges(ob) if not self.same: setattr(ob, self.field, self.newValue) def htmlDiff(self): """Return a revised xml document""" from Stream import ListStream from DiffExecutor import XMLDiffExecutor from xml.dom.ext import Print from Products.CNXMLDocument import XMLService diff = XMLDiffExecutor(self.oldValue, self.newValue) diff.execute() strm = ListStream() Print(diff.getRevisedDocument().getDocumentRoot(), stream=strm) # ignore <?xml ..> return strm.read()[38:] InitializeClass(XmlDiff)
) #**************** _relations = Device._relations + ( ('printermibtray', ToManyCont(ToOne, 'ZenPacks.TwoNMS.PrinterMIB.PrinterTray', 'printermibprinter')), ('printermibsupply', ToManyCont(ToOne, 'ZenPacks.TwoNMS.PrinterMIB.PrinterSupply', 'printermibprinter')), ('printermibtoner', ToManyCont(ToOne, 'ZenPacks.TwoNMS.PrinterMIB.PrinterToner', 'printermibprinter'))) factory_type_information = deepcopy(Device.factory_type_information) # keep this section if you need an extra menu item in left side menu of zenoss 3 # factory_type_information[0]['actions'] += ( # { 'id' : 'BridgeInt' # , 'name' : 'Bridge Interfaces' # , 'action' : 'BridgeDeviceDetail' # , 'permissions' : (ZEN_VIEW, ) }, # ) def __init__(self, *args, **kw): Device.__init__(self, *args, **kw) self.buildRelations() InitializeClass(Printer)
def _convertDateTime(self, value): if value is None: return value if type(value) == type(''): dt_obj = DateTime(value) value = dt_obj.millis() / 1000 / 60 # flatten to minutes if isinstance(value, DateTime): value = value.millis() / 1000 / 60 # flatten to minutes result = int(value) if isinstance(result, long): # this won't work (Python 2.3) raise OverflowError('%s is not within the range of dates allowed' 'by a DateRangeIndex' % value) return result InitializeClass(DateRangeIndex) manage_addDateRangeIndexForm = DTMLFile('addDateRangeIndex', _dtmldir) def manage_addDateRangeIndex(self, id, extra=None, REQUEST=None, RESPONSE=None, URL3=None): """ Add a date range index to the catalog, using the incredibly icky double-indirection-which-hides-NOTHING. """ return self.manage_addIndex(id, 'DateRangeIndex', extra, REQUEST, RESPONSE,
adminNewsEditCMS = DTMLFile('dtml/manage_editAdminNewsCMS', globals()) checkActive = DTMLFile('dtml/manage_adminNewscheckActive', globals()) delete = DTMLFile('dtml/manage_deleteAdminNews', globals()) #Constructor pages. Only used when the product is added to a folder. def manage_addAdminNewsAction(self, id, title='', data='', author='', active=0, tags='', created=DateTime().strftime('%Y/%m/%d'), RESPONSE=None): "Add a Blend Admin News to a folder" id = id.lower() id = id.lstrip() id = id.rstrip() id = id.replace(' ', '_') self._setObject(id, AdminNews(id, title, data, author, active, tags, created)) RESPONSE.redirect('../../../adminNews_html') manage_addAdminNews = DTMLFile('dtml/manage_addAdminNews', globals()) InitializeClass(AdminNews)
'name': 'Modifications', 'action': 'viewHistory', 'permissions': (ZEN_VIEW_MODIFICATIONS, ) }, ) }, ) def reservedSize(self): return self.volumeReservedSize or 0 def reservedSizeString(self): return convToUnits(self.reservedSize(), divby=1024) def provisionedSize(self): return self.volumeProvisionedSize or 0 def provisionedSizeString(self): return convToUnits(self.provisionedSize(), divby=1024) def isThinProvisioned(self): if (self.thinProvisioned == 1): return "true" else: return "false" # def getRRDNames(self): # return ['Volume_Occupancy'] InitializeClass(DellEqualLogicVolume)
#def monitored(self): # return True titleOrId = name = viewName # this allows editable fields in the Details pane isUserCreatedFlag = True def isUserCreated(self): return self.isUserCreatedFlag # define additional panes in the component section (dropdown menu) factory_type_information = ({ 'id': 'PrinterTray', 'meta_type': 'PrinterTray', 'description': """PrinterMIB PrinterTray component""", 'actions': ({ 'id': 'viewHistory', 'name': 'Modifications', 'action': 'viewHistory', 'permissions': (ZEN_VIEW, ) }, ) }, ) InitializeClass(PrinterTray)
##################################################### # Constructor functions, only used when adding class # to objectManager def manage_addCache(self, REQUEST=None): "Add tool instance to parent ObjectManager" id = cache.id self._setObject(id, cache(id)) if REQUEST is not None: return self.manage_main(self, REQUEST) cache_constructors = (manage_addCache,) def manage_addNoCache(self, REQUEST=None): "Add tool instance to parent ObjectManager" id = nocache.id self._setObject(id, nocache(id)) if REQUEST is not None: return self.manage_main(self, REQUEST) nocache_constructors = (manage_addNoCache,) def generateCacheKey(searchhash): """Returns actual key used in cache dictionary, from API 'searchhash' string. Allows optimization of key for underlying storage method. """ return md5.md5(searchhash).digest() InitializeClass(cache)
"Only two historical revision can be compared<p>") serial=apply(pack, ('>HHHH',)+tuple(map(int, keys[-1].split('.')))) rev1=historicalRevision(self, serial) if len(keys)==2: serial=apply(pack, ('>HHHH',)+tuple(map(int, keys[0].split('.')))) rev2=historicalRevision(self, serial) else: rev2=self return self.manage_historyCompare(rev1, rev2, REQUEST) InitializeClass(Historical) def dump(tag, x, lo, hi, r): r1=[] r2=[] for i in xrange(lo, hi): r1.append(tag) r2.append(x[i]) r.append("<tr>\n" "<td><pre>\n%s\n</pre></td>\n" "<td><pre>\n%s\n</pre></td>\n" "</tr>\n" % ('\n'.join(r1), escape('\n'.join(r2)))) def replace(x, xlo, xhi, y, ylo, yhi, r):
from OFS.SimpleItem import SimpleItem from Products.Naaya.tests.NaayaFunctionalTestCase import NaayaFunctionalTestCase from Products.NaayaCore.managers.utils import make_id, slugify class Parent(object): def __init__(self, *args): for arg in args: setattr(self, arg, True) def _getOb(self, id, alt): return getattr(self, id, alt) InitializeClass(Parent) class make_id_TestCase(NaayaFunctionalTestCase): """ TestCase for the make_id function """ def afterSetUp(self): pass def beforeTearDown(self): pass def test_by_id(self): self.parent = Parent('contact', 'contact-1', 'contact-3') id = make_id(self.parent, id='contact', title='bogus', prefix='bogus') self.assertEqual(id, 'contact-2')
security.declarePublic('isDiscussionAllowedFor') def isDiscussionAllowedFor(self, content): """ Get boolean indicating whether discussion is allowed for content. """ if hasattr(aq_base(content), 'allow_discussion'): return bool(content.allow_discussion) typeInfo = content.getTypeInfo() if typeInfo: return bool(typeInfo.allowDiscussion()) return False # # Utility methods # security.declarePrivate('_createDiscussionFor') def _createDiscussionFor(self, content): """ Create DiscussionItemContainer for content, if allowed. """ if not self.isDiscussionAllowedFor(content): raise DiscussionNotAllowed content.talkback = DiscussionItemContainer() return content.talkback InitializeClass(DiscussionTool) registerToolInterface('portal_discussion', IDiscussionTool)
"id": "path", "label": "Target Path", "type": "string", "mode": "w", }) # the initialize method. def __init__(self, id, title, path): """ the constructor. """ self.id = id self.title = title self.path = path # implements the challenge method. def challenge(self, request, response): """ Returns True if it fired, False otherwise """ response.redirect(self.path, lock=1) return True # make sure it implements the IChallengePlugin classImplements(RedirectChallenge, IChallengePlugin) InitializeClass(RedirectChallenge)
def getNextMonth(self, month, year): """ Get a DateTime object for one month after the given year/month """ month = int(month) year = int(year) if month == 12: month, year = 1, year + 1 else: month += 1 return DateTime(year, month, 1) security.declarePublic('getBeginAndEndTimes') def getBeginAndEndTimes(self, day, month, year): """ Get two DateTime objects representing the beginning and end of the given day """ day = int(day) month = int(month) year = int(year) begin = DateTime('%d/%02d/%02d 00:00:00' % (year, month, day)) end = DateTime('%d/%02d/%02d 23:59:59' % (year, month, day)) return (begin, end) InitializeClass(CalendarTool)
RESPONSE.redirect(self.absolute_url() + '/manage_workspace?manage_tabs_message=%s' % msg) security.declareProtected(view_management_screens, 'getVersion') def getVersion(self): """ return version.txt """ return open(os.path.join(os.path.dirname(__file__), 'version.txt')).read() manage_workspace = PageTemplateFile('pt/info', globals(), __name__='manage_workspace') InitializeClass(SAWrapper) def manage_addSAWrapper(self, id, title, RESPONSE=None): """ create a new SAWrapper instance """ wrapper = SAWrapper(id, title) self._setObject(id, wrapper.__of__(self)) if RESPONSE: RESPONSE.redirect(wrapper.absolute_url() + '/manage_workspace') else: return wrapper manage_addSAWrapperForm = PageTemplateFile('pt/addSAWrapperForm', globals(),
except: self.setSessionErrors(['Error while delete data.']) if REQUEST: REQUEST.RESPONSE.redirect('reportquestionnaires_html') def getQuestionsLocation(self): if hasattr(self, PDF_FILENAME): return self else: return None security.declareProtected(view, 'chaptercomments_html') def chaptercomments_html(self, REQUEST=None, RESPONSE=None): """ """ return self.getFormsTool().getContent({'here': self}, 'chapter_comments') InitializeClass(NyReportChapter) manage_addNyReportChapter_html = PageTemplateFile( 'zpt/reportchapter_manage_add', globals()) manage_addNyReportChapter_html.kind = METATYPE_OBJECT manage_addNyReportChapter_html.action = 'addNyReportChapter' config.update({ 'constructors': (manage_addNyReportChapter_html, addNyReportChapter), 'folder_constructors': [ # NyFolder.manage_addNyReportChapter_html = manage_addNyReportChapter_html ('manage_addNyReportChapter_html', manage_addNyReportChapter_html), ('reportchapter_add_html', reportchapter_add_html), ('addNyReportChapter', addNyReportChapter), (config['import_string'], importNyReportChapter), ],
name=permission_names[i] p=class_permissions[i] if p and (p not in perms): __traceback_info__=perms, p, i raise ValueError, 'Invalid class permission' if name not in property_sheet_permissions: continue setattr(ips, pname(name), pname(p)) if REQUEST is not None: return self.manage_security( self, REQUEST, manage_tabs_message='The permission mapping has been updated') InitializeClass(ZCommonSheet) property_sheet_permissions=( # 'Access contents information', 'Manage properties', ) class ZInstanceSheet(OFS.PropertySheets.FixedSchema, OFS.PropertySheets.View, ): "Waaa this is too hard" security = ClassSecurityInfo() security.declareObjectProtected(access_contents_information)
# site pages security.declareProtected(view, 'index_html') def index_html(self, REQUEST=None, RESPONSE=None): """ """ return self.getFormsTool().getContent({'here': self}, 'eduproduct_index') security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html') def edit_html(self, REQUEST=None, RESPONSE=None): """ """ return self.getFormsTool().getContent({'here': self}, 'eduproduct_edit') InitializeClass(NyEduProduct) def on_install_eduproduct(site): portal_portlets = site.getPortletsTool() for tree_data in skel.ref_trees: tree_id = tree_data['id'] if tree_id in portal_portlets.objectIds(): continue tree_title = tree_data['title'] portal_portlets.manage_addRefTree(tree_id, tree_title) tree_ob = portal_portlets[tree_id] for tree_item in tree_data['items']:
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 method not in ('GET', 'POST'): return True
# specified in the IRoleAssignerPlugin interface, so this is bad. security.declareProtected(ManageUsers, 'addRole') def addRole(self, role_id, title='', description=''): """ We do not manage roles. """ raise AttributeError classImplements( Plugin, IAuthenticationPlugin, IUserEnumerationPlugin, # IUserAdderPlugin, IUserManagement, # IDeleteCapability, IPasswordSetCapability, # IRolesPlugin, # IRoleAssignerPlugin, # IAssignRoleCapability, IPropertiesPlugin, IUpdatePlugin, IMutablePropertiesPlugin, # IGroupsPlugin, # IGroupEnumerationPlugin, # IGroupIntrospection, # IGroupManagement ) InitializeClass(Plugin)
view = __call__ index_html = None # This special value informs ZPublisher to use __call__ security.declareProtected(View, 'Creator') def Creator(self): """ Return the ID of our owner. """ owner = self.getOwner() if hasattr(owner, 'getId'): return owner.getId() return 'No owner' # We derive from CMFCatalogAware first, so we are cataloged too. InitializeClass(SkinnedFolder) def addSkinnedFolder(self, id, title='', description='', REQUEST=None): """ """ sf = SkinnedFolder(id, title) sf.description = description self._setObject(id, sf) sf = self._getOb(id) if REQUEST is not None: REQUEST['RESPONSE'].redirect(sf.absolute_url() + '/manage_main')
def _crackArgs(self, predicate): """ Crack apart the "edit args" from predicate. """ cracker = self._KNOWN_PREDICATE_TYPES.get(predicate.PREDICATE_TYPE) if cracker is not None: return cracker(predicate) return () # XXX: raise? security.declarePrivate('_getExportTemplate') def _getExportTemplate(self): return PageTemplateFile('ctrExport.xml', _xmldir) InitializeClass(ContentTypeRegistryExportConfigurator) class ContentTypeRegistryImportConfigurator(ImportConfiguratorBase): def _getImportMapping(self): return { 'content-type-registry': { 'predicate': { KEY: 'predicates', DEFAULT: () } }, 'predicate': { 'predicate_id': {}, 'remove': {}, 'predicate_type': {},
if obj is None: when = syUpdateBase return when.HTML4() syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: when = syInfo.syUpdateBase return when.HTML4() else: return 'Syndication is not Allowed' def getMaxItems(self, obj=None): """ Return the max_items to be displayed in the syndication """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is not Allowed' if obj is None: return self.max_items syInfo = getattr(obj, 'syndication_information', None) if syInfo is not None: return syInfo.max_items else: return 'Syndication is not Allowed' InitializeClass(SyndicationTool)
security.declareProtected(CMFCorePermissions.View, 'getCriterion') def getCriterion(self, criterion_id): """ Get the criterion object. """ try: return self._getOb('crit__%s' % criterion_id) except AttributeError: return self._getOb(criterion_id) security.declareProtected(TopicPermissions.AddTopics, 'addSubtopic') def addSubtopic(self, id): """ Add a new subtopic. """ try: tool = getToolByName(self, 'portal_types') except: self._setOb(id, Topic(id)) else: topictype = tool.getTypeInfo(self) topictype.constructInstance(self, id) return self._getOb(id) # Intialize the Topic class, setting up security. InitializeClass(Topic)
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
isUserCreatedFlag = True def isUserCreated(self): """ Returns the value of isUserCreated. True adds SAVE & CANCEL buttons to Details menu """ return self.isUserCreatedFlag def viewName(self): """Pretty version human readable version of this object""" # return str( self.bankNumber ) return self.id # use viewName as titleOrId because that method is used to display a human # readable version of the object in the breadcrumbs titleOrId = name = viewName def device(self): return self.ApcPduDevBan() def monitored(self): """ Dummy """ return True InitializeClass(ApcPduBank)