1
2
3
4
5
6
7
8
9
10
11
12
13
14 __doc__="""ZenModelBase
15
16 $Id: ZenModelBase.py,v 1.17 2004/04/23 19:11:58 edahl Exp $"""
17
18 __version__ = "$Revision: 1.17 $"[11:-2]
19
20 import re
21 import time
22
23 import sys
24 from urllib import unquote
25 from cgi import escape
26 from OFS.ObjectManager import checkValidId as globalCheckValidId
27
28 from AccessControl import ClassSecurityInfo, getSecurityManager, Unauthorized
29 from Globals import InitializeClass
30 from Acquisition import aq_base, aq_chain
31
32 from Products.ZenUtils.Utils import zenpathsplit, zenpathjoin
33 from Products.ZenUtils.Utils import createHierarchyObj, getHierarchyObj
34 from Products.ZenUtils.Utils import getObjByPath
35
36 from Products.ZenUtils.Utils import prepId as globalPrepId
37 from Products.ZenWidgets import messaging
38
39 from ZenossSecurity import *
40
41
42
43 iscustprop = re.compile("^c[A-Z]").search
44
46 """
47 All ZenModel Persistent classes inherit from this class. It provides some
48 screen management functionality, and general utility methods.
49 """
50 sub_meta_types = ()
51
52
53 security = ClassSecurityInfo()
54
56 """
57 Invokes the default view.
58 """
59 view = "view"
60 if hasattr(self, "factory_type_information"):
61 view = self.factory_type_information[0]['immediate_view']
62 else:
63 raise NameError('Cannot find default view for "%s"' %
64 '/'.join(self.getPhysicalPath()))
65 return self.restrictedTraverse(view)()
66
67 index_html = None
68
69
70 security.declareProtected(ZEN_VIEW, 'view')
72 '''
73 Returns the default view even if index_html is overridden.
74
75 @permission: ZEN_VIEW
76 '''
77 return self()
78
79
82
83 - def prepId(self, id, subchar='_'):
84 """
85 Clean out an id of illegal characters.
86
87 @type id: string
88 @param subchar: Character to be substituted with illegal characters
89 @type subchar: string
90 @rtype: string
91
92 >>> dmd.Devices.prepId('ab^*cd')
93 'ab__cd'
94 >>> dmd.Devices.prepId('ab^*cd', subchar='Z')
95 'abZZcd'
96 >>> dmd.Devices.prepId('/boot')
97 'boot'
98 >>> dmd.Devices.prepId('/')
99 '-'
100 >>> dmd.Devices.prepId(' mydev ')
101 'mydev'
102 """
103 return globalPrepId(id, subchar)
104
106 """
107 Checks that an id is a valid Zope id. Looks for invalid characters and
108 checks that the id doesn't already exist in this context.
109
110 @type id: string
111 @type prep_id: boolean
112 @rtype: boolean
113
114 >>> dmd.Devices.checkValidId('^*')
115 'The id "^*" contains characters illegal in URLs.'
116 >>> dmd.Devices.checkValidId('Server')
117 'The id "Server" is invalid - it is already in use.'
118 >>> dmd.Devices.checkValidId('ZenTestId')
119 True
120 """
121 new_id = unquote(id)
122 if prep_id: new_id = self.prepId(id)
123 try:
124 globalCheckValidId(self, new_id)
125 return True
126 except:
127 return str(sys.exc_info()[1])
128
129
130 - def getUnusedId(self, relName, baseKey, extensionIter=None):
131 """
132 Return a new id that is not already in use in the relationship. If
133 baseKey is not already in use, return that. Otherwise append values
134 from extensionIter to baseKey until an used key is found. The default
135 extensionIter appends integers starting with 2 and counting up.
136
137 @type relName: string
138 @type baseKey: string
139 @type extensionIter: iterator
140 @rtype: string
141
142 >>> id1 = dmd.Devices.getUnusedId('devices', 'dev')
143 >>> id1
144 'dev'
145 >>> dmd.Devices.createInstance(id1)
146 <Device at /zport/dmd/Devices/devices/dev>
147 >>> id2 = dmd.Devices.getUnusedId('devices', 'dev')
148 >>> id2
149 'dev2'
150 """
151 import itertools
152 if extensionIter is None:
153 extensionIter = itertools.count(2)
154 rel = getattr(self, relName)
155 candidate = baseKey
156 while candidate in rel.objectIds():
157 candidate = self.prepId('%s%s' % (baseKey, extensionIter.next()))
158 return candidate
159
160
162 """
163 DEPRECATED Return an a link to this object with its id as the name.
164
165 @return: An HTML link to this object
166 @rtype: string
167
168 >>> dmd.Devices.getIdLink()
169 '<a href="/zport/dmd/Devices">/</a>'
170 """
171 return self.urlLink()
172
173
175 """
176 Call and return screen specified by zenScreenName value of REQUEST.
177 If zenScreenName is not present call the default screen. This is used
178 in functions that are called from forms to get back to the correct
179 screen with the correct context.
180 """
181 if REQUEST is None or getattr(REQUEST, 'dontRender', False):
182
183
184 return ''
185 screenName = REQUEST.get("zenScreenName", "")
186 if redirect:
187 nurl = "%s/%s" % (self.getPrimaryUrlPath(), screenName)
188 REQUEST['RESPONSE'].redirect(nurl)
189 else:
190 REQUEST['URL'] = "%s/%s" % (self.absolute_url_path(), screenName)
191 screen = getattr(self, screenName, False)
192 if not screen: return self()
193 return screen()
194
195
197 """
198 Return the url for the current screen as defined by zenScreenName.
199 If zenScreenName is not found in the request the request url is used.
200
201 @return: An url to this object
202 @rtype: string
203 """
204 screenName = self.REQUEST.get("zenScreenName", "")
205 if not screenName: return self.REQUEST.URL
206 return self.getPrimaryUrlPath() + "/" + screenName
207
208
209 - def urlLink(self, text=None, url=None, attrs={}):
210 """
211 Return an anchor tag if the user has access to the remote object.
212
213 @param text: the text to place within the anchor tag or string.
214 Defaults to the id of this object.
215 @param url: url for the href. Default is getPrimaryUrlPath
216 @type attrs: dict
217 @param attrs: any other attributes to be place in the in the tag.
218 @return: An HTML link to this object
219 @rtype: string
220 """
221 if not text:
222 text = self.id
223 text = escape(text)
224 if not self.checkRemotePerm("View", self):
225 return text
226 if not url:
227 url = self.getPrimaryUrlPath()
228 if len(attrs):
229 return '<a href="%s" %s>%s</a>' % (url,
230 ' '.join(['%s="%s"' % (x,y) for x,y in attrs.items()]),
231 text)
232 else:
233 return '<a href="%s">%s</a>' % (url, text)
234
235
237 """
238 Return the url to be used in breadcrumbs for this object. normally
239 this is equal to getPrimaryUrlPath. It can be used as a hook to modify
240 the url so that it points towards a different tab then the default.
241
242 @return: A url to this object
243 @rtype: string
244
245 >>> dmd.Devices.getBreadCrumbUrlPath()
246 '/zport/dmd/Devices'
247 >>> rc = dmd.Reports._getOb('Graph Reports')
248 >>> rc.manage_addGraphReport('test').getBreadCrumbUrlPath()
249 '/zport/dmd/Reports/Graph%20Reports/test/editGraphReport'
250 """
251 return self.getPrimaryUrlPath()
252
253
255 """
256 Return the data to create the breadcrumb links for this object.
257
258 This is a list of tuples where the first value is the URL of the bread
259 crumb and the second is the lable.
260
261 @return: List of tuples to create a bread crumbs
262 @rtype: list
263
264 >>> dmd.Devices.Server.breadCrumbs()
265 [('/zport/dmd/Devices', 'Devices'),
266 ('/zport/dmd/Devices/Server', 'Server')]
267 """
268 links = []
269 curDir = self.primaryAq()
270 while curDir.id != terminator:
271 if curDir.meta_type == 'ToManyContRelationship':
272 curDir = curDir.getPrimaryParent()
273 continue
274 if not getattr(aq_base(curDir),"getBreadCrumbUrlPath", False):
275 break
276 url = ""
277 if self.checkRemotePerm("View", curDir):
278 url = curDir.getBreadCrumbUrlPath()
279 links.append((url, curDir.id))
280 curDir = curDir.aq_parent
281 links.reverse()
282 return links
283
284
285 security.declareProtected(ZEN_VIEW, 'getZ')
286 - def getZ(self, zpropname):
287 """
288 Return the value of a zProperty on this object. This method is used to
289 lookup zProperties for a user with a role that doesn't have direct
290 access to an attribute further up the acquisition path.
291
292 @param zpropname: Name of zProperty
293 @type zpropname: string
294 @return: Value of zProperty
295 @permission: ZEN_VIEW
296
297 >>> dmd.Devices.getZ('zSnmpPort')
298 161
299 """
300 return getattr(self, zpropname)
301
302
303 security.declareProtected(ZEN_COMMON, 'checkRemotePerm')
305 """
306 Look to see if the current user has permission on remote object.
307
308 @param permission: Zope permission to be tested. ie "View"
309 @param robject: remote objecct on which test is run. Will test on
310 primary acquisition path.
311 @rtype: boolean
312 @permission: ZEN_COMMON
313 """
314 user = getSecurityManager().getUser()
315 return user.has_permission(permission, robject.primaryAq())
316
317
318
319 security.declareProtected(ZEN_VIEW, 'zentinelTabs')
321 """
322 Return a list of hashes that define the screen tabs for this object.
323
324 Keys in the hash are:
325 - action = the name of the page template for this tab
326 - name = the label used on the tab
327 - permissions = a tuple of permissions to view this template
328
329 @permission: ZEN_VIEW
330
331 >>> dmd.Devices.zentinelTabs('deviceOrganizerStatus')
332 [{'action': 'deviceOrganizerStatus', 'selected': True,
333 'name': 'Classes', 'permissions': ('View',)},
334 {'action': 'viewEvents', 'name': 'Events', 'permissions': ('View',)},
335 {'action': 'zPropertyEdit', 'name': 'zProperties',
336 'permissions': ('View',)},
337 {'action': 'perfConfig', 'name': 'Templates',
338 'permissions': ('Manage DMD',)}]
339 """
340 tabs = []
341 user = getSecurityManager().getUser()
342 actions = self.factory_type_information[0]['actions']
343 for a in actions:
344 def permfilter(p): return user.has_permission(p,self)
345 permok = filter(permfilter, a['permissions'])
346 if not a.get('visible', True) or not permok:
347 continue
348 a = a.copy()
349 if a['action'] == templateName: a['selected'] = True
350 tabs.append(a)
351 return tabs
352
353
354 security.declareProtected(ZEN_MANAGE_DMD, 'zmanage_editProperties')
372
373
374 security.declareProtected(ZEN_VIEW, 'getPrimaryDmdId')
376 """
377 Return the full dmd id of this object for instance /Devices/Server.
378 Everything before dmd is removed. A different rootName can be passed
379 to stop at a different object in the path. If subrel is passed any
380 relationship name in the path to the object will be removed.
381
382 @param rootName: Name of root
383 @type rootName: string
384 @param subrel: Name of relation
385 @type subrel: string
386 @return: Path to object
387 @rtype: string
388 @permission: ZEN_VIEW
389
390 >>> d = dmd.Devices.Server.createInstance('test')
391 >>> d.getPrimaryDmdId()
392 '/Devices/Server/devices/test'
393 >>> d.getPrimaryDmdId('Devices')
394 '/Server/devices/test'
395 >>> d.getPrimaryDmdId('Devices','devices')
396 '/Server/test'
397 """
398 path = list(self.getPrimaryPath())
399 path = path[path.index(rootName)+1:]
400 if subrel: path = filter(lambda x: x != subrel, path)
401 return '/'+'/'.join(path)
402
403
405 """
406 DEPRECATED Build a Zenoss path based on a list or tuple.
407
408 @type path: list or tuple
409
410 >>> dmd.zenpathjoin(('zport', 'dmd', 'Devices', 'Server'))
411 '/zport/dmd/Devices/Server'
412 """
413 return zenpathjoin(path)
414
415
417 """
418 DEPRECATED Split a path on its '/'.
419 """
420 return zenpathsplit(path)
421
422
424 """
425 DEPRECATED this is only seems to be used in Organizer.createOrganizer -
426 Create an object from its path we use relpath to skip down any missing
427 relations in the path and factory is the constructor for this object.
428 """
429 return createHierarchyObj(root, name, factory, relpath, alog)
430
431
433 """
434 DEPRECATED this doesn't seem to be used anywere don't use it!!!
435 """
436 return getHierarchyObj(root, name, relpath)
437
438
440 """
441 DEPRECATED Return the dmd root object with unwraped acquisition path.
442
443 >>> dmd.Devices.Server.getDmd()
444 <DataRoot at /zport/dmd>
445 """
446 for obj in aq_chain(self):
447 if obj.id == 'dmd': return obj
448
449
451 """
452 Return a dmd root organizer such as "Systems". The acquisition path
453 will be cleaned so that it points directly to the root.
454
455 >>> dmd.Devices.Server.getDmdRoot("Systems")
456 <System at /zport/dmd/Systems>
457 """
458 dmd = self.getDmd()
459 return dmd._getOb(name)
460
461
463 """
464 DEPRECATED Return an object from path that starts at dmd.
465
466 >>> dmd.getDmdObj('/Devices/Server')
467 <DeviceClass at /zport/dmd/Devices/Server>
468 """
469 if path.startswith("/"): path = path[1:]
470 return self.getDmd().getObjByPath(path)
471
472
474 """
475 DEPRECATED Return an object from path tat starts at zope root.
476
477 >>> dmd.getZopeObj('/zport/dmd/Devices/Server')
478 <DeviceClass at /zport/dmd/Devices/Server>
479 """
480 return self.getObjByPath(path)
481
482
484 """
485 Return the current time as a string in the format '2007/09/27 14:09:53'.
486
487 @rtype: string
488 """
489 return time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
490
491
493 """
494 Return today's date as a string in the format 'mm/dd/yyyy'.
495
496 @rtype: string
497 """
498 return time.strftime("%m/%d/%Y", time.localtime())
499
500
502 """
503 Return yesterday's date as a string in the format 'mm/dd/yyyy'.
504
505 @rtype: string
506 """
507 yesterday = time.time() - 24*3600
508 return time.strftime("%m/%d/%Y", time.localtime(yesterday))
509
510
524
525
526 security.declareProtected('Delete objects', 'manage_deleteObjects')
528 """
529 Delete objects by id from this object and return to the current
530 template as defined by callZenScreen. Uses ObjectManager._delObject to
531 remove the object.
532
533 @permission: ZEN_VIEW
534 """
535 for id in ids: self._delObject(id)
536 if REQUEST:
537 return self.callZenScreen(REQUEST)
538
539
541 """
542 List custom properties that are defined at root node. Custom properties
543 start with a lower "c" followed by a uppercase character.
544 """
545 return self.zenPropertyIds(pfilt=iscustprop)
546
547
549 """
550 Return custom property definitions.
551
552 @rtype: [{'id':'cName','label':'Name', 'type':'string'},]
553 """
554 return self.zenPropertyMap(pfilt=iscustprop)
555
556
558 """
559 List custom property definitions that are visible using
560 custPropertyMap::
561
562 @rtype: [{'id':'cName','label':'Name', 'type':'string'},]
563 """
564 return [ p for p in self.zenPropertyMap(pfilt=iscustprop) \
565 if p.get('visible', True) ]
566
567
568 security.declareProtected(ZEN_MANAGE_DMD, 'saveCustProperties')
576
577
579 """
580 Lookup and object by its path. Basically does a Zope unrestricted
581 traverse on the path given.
582
583 @type path: list or string /zport/dmd/Devices
584
585 >>> dmd.getObjByPath(('zport','dmd','Devices'))
586 <DeviceClass at /zport/dmd/Devices>
587 >>> dmd.getObjByPath(('Devices','Server'))
588 <DeviceClass at /zport/dmd/Devices/Server>
589 >>> dmd.getObjByPath('/zport/dmd/Devices/Server')
590 <DeviceClass at /zport/dmd/Devices/Server>
591 >>> dmd.getObjByPath('Devices/Server')
592 <DeviceClass at /zport/dmd/Devices/Server>
593 """
594 return getObjByPath(self, path)
595
596
598 """
599 Check to see if a name is local to our current context or if it comes
600 from our acquisition chain.
601
602 @rtype: boolean
603
604 >>> dmd.isLocalName('Devices')
605 True
606 >>> dmd.Devices.Server.isLocalName('Devices')
607 False
608 """
609 v = getattr(aq_base(self), name, '__ZENMARKER__')
610 return v != '__ZENMARKER__'
611
612 security.declareProtected(ZEN_VIEW, 'helpLink')
614 """
615 DEPRECATED Return a link to the objects help file.
616
617 @permission: ZEN_VIEW
618 """
619 path = self.__class__.__module__.split('.')
620 className = path[-1].replace('Class','')
621 product = path[-2]
622
623 path = ("", "Control_Panel", "Products", product, "Help",
624 "%s.stx"%className)
625
626
627 app = self.getPhysicalRoot()
628 try:
629 app.restrictedTraverse(path)
630 except (KeyError, Unauthorized):
631 return ""
632
633 url = "/HelpSys?help_url="+ "/".join(path)
634
635 return """<a class="tabletitle" href="%s" \
636 onClick="window.open('%s','zope_help','width=600,height=500, \
637 menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes'); \
638 return false;" onMouseOver="window.status='Open online help'; \
639 return true;" onMouseOut="window.status=''; return true;">Help!</a>
640 """ % (url, url)
641
642
643 security.declareProtected(ZEN_VIEW, 'getIconPath')
645 """
646 Return the icon associated with this object. The icon path is defined
647 in the zProperty zIcon.
648
649 @return: Path to icon
650 @rtype: string
651 @permission: ZEN_VIEW
652
653 >>> d = dmd.Devices.Server.createInstance('test')
654 >>> d.getIconPath()
655 '/zport/dmd/img/icons/server.png'
656 """
657 try:
658 return self.primaryAq().zIcon
659 except AttributeError:
660 return '/zport/dmd/img/icons/noicon.png'
661
662
664 """
665 Return hasattr(aq_base(self), attr)
666 This is a convenience function for use in templates, where it's not
667 so easy to make a similar call directly.
668 hasattr itself will swallow exceptions, so we don't want to use that.
669 We also need to allow for values of None, so something like
670 getattr(aq_base(self, attr, None) doesn't really tell us anything.
671 Testing __dict__ is not a good choice because it doesn't allow
672 for properties (and I believe __getitem__ calls.)
673 So while this looks pretty attrocious, it might be the most sane
674 solution.
675 """
676 base = aq_base(self)
677 return getattr(base, attr, True) == getattr(base, attr, False)
678
679
680 InitializeClass(ZenModelBase)
681