Package Products :: Package ZenModel :: Module UserSettings |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenModel.UserSettings

       1  ###########################################################################
       2  #
       3  # This program is part of Zenoss Core, an open source monitoring platform.
       4  # Copyright (C) 2007, Zenoss Inc.
       5  #
       6  # This program is free software; you can redistribute it and/or modify it
       7  # under the terms of the GNU General Public License version 2 or (at your
       8  # option) any later version as published by the Free Software Foundation.
       9  #
      10  # For complete information please visit: http://www.zenoss.com/oss/
      11  #
      12  ###########################################################################
      13
      14  from DateTime import DateTime
      15  from random import choice
      16  from email.MIMEText import MIMEText
      17  import socket
      18  import logging
      19  log = logging.getLogger("zen.UserSettings")
      20
      21  from Globals import DTMLFile
      22  from Globals import InitializeClass
      23  from AccessControl import ClassSecurityInfo
      24  from AccessControl import getSecurityManager
      25  from Acquisition import aq_base
      26  from Products.PluggableAuthService import interfaces
      27  from Products.PluggableAuthService.PluggableAuthService \
      28      import _SWALLOWABLE_PLUGIN_EXCEPTIONS
      29  from zExceptions import Unauthorized
      30
      31  from Products.ZenEvents.ActionRule import ActionRule
      32  from Products.ZenEvents.CustomEventView import CustomEventView
      33  from Products.ZenRelations.RelSchema import *
      34  from Products.ZenUtils import Time
      35  from Products.ZenUtils.Utils import unused, prepId
      36  from Products.ZenUtils.guid.interfaces import IGUIDManager
      37  from Products.ZenUtils import DotNetCommunication
      38  from Products.ZenUtils.guid.interfaces import IGloballyIdentifiable
      39  from Products.ZenWidgets import messaging
      40  from Products.ZenModel.interfaces import IProvidesEmailAddresses, IProvidesPagerAddresses
      41  from Products.ZenMessaging.actions import sendUserAction
      42  from Products.ZenMessaging.actions.constants import ActionTargetType, ActionName
      43  from Products.Zuul.decorators import deprecated
      44
      45  from ZenossSecurity import *
      46  from ZenModelRM import ZenModelRM
      47  from Products.ZenUtils import Utils
      48  from zope.interface import implements
      49
      50
      51 -class LocalAndLDAPUserEntries(Exception): pass
      52
      53  UserSettingsId = "ZenUsers"
      54
      55 -def manage_addUserSettingsManager(context, REQUEST=None):
      56      """Create user settings manager."""
      57      ufm = UserSettingsManager(UserSettingsId)
      58      context._setObject(ufm.getId(), ufm)
      59      if REQUEST is not None:
      60          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
      61
      62
      63 -def rolefilter(r): return r not in ("Anonymous", "Authenticated", "Owner")
      64
      65
      66 -class UserSettingsManager(ZenModelRM):
      67      """Manage zenoss user folders.
      68      """
      69      security = ClassSecurityInfo()
      70
      71      meta_type = "UserSettingsManager"
      72
      73      #zPrimaryBasePath = ("", "zport")
      74
      75      sub_meta_types = ("UserSettings",)
      76
      77      factory_type_information = (
      78          {
      79              'id'             : 'UserSettingsManager',
      80              'meta_type'      : 'UserSettingsManager',
      81              'description'    : """Base class for all devices""",
      82              'icon'           : 'UserSettingsManager.gif',
      83              'product'        : 'ZenModel',
      84              'factory'        : 'manage_addUserSettingsManager',
      85              'immediate_view' : 'manageUserFolder',
      86              'actions'        :
      87           (
      88                  { 'id'            : 'settings'
      89                  , 'name'          : 'Settings'
      90                  , 'action'        : '../editSettings'
      91                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
      92                  },
      93                  { 'id'            : 'manage'
      94                  , 'name'          : 'Commands'
      95                  , 'action'        : '../dataRootManage'
      96                  , 'permissions'   : (ZEN_MANAGE_DMD,)
      97                  },
      98                  { 'id'            : 'users'
      99                  , 'name'          : 'Users'
     100                  , 'action'        : 'manageUserFolder'
     101                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     102                  },
     103                  { 'id'            : 'packs'
     104                  , 'name'          : 'ZenPacks'
     105                  , 'action'        : '../ZenPackManager/viewZenPacks'
     106                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     107                  },
     108                  { 'id'            : 'jobs'
     109                  , 'name'          : 'Jobs'
     110                  , 'action'        : '../joblist'
     111                  , 'permissions'   : ( "Manage DMD", )
     112                  },
     113                  #{ 'id'            : 'menus'
     114                  #, 'name'          : 'Menus'
     115                  #, 'action'        : '../editMenus'
     116                  #, 'permissions'   : ( ZEN_MANAGE_DMD, )
     117                  #},
     118                  { 'id'            : 'portlets'
     119                  , 'name'          : 'Portlets'
     120                  , 'action'        : '../editPortletPerms'
     121                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     122                  },
     123                  { 'id'            : 'daemons'
     124                  , 'name'          : 'Daemons'
     125                  , 'action'        : '../../About/zenossInfo'
     126                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     127                  },
     128                  { 'id'            : 'versions'
     129                  , 'name'          : 'Versions'
     130                  , 'action'        : '../../About/zenossVersions'
     131                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     132                  },
     133                  { 'id'            : 'backups'
     134                  , 'name'          : 'Backups'
     135                  , 'action'        : '../backupInfo'
     136                  , 'permissions'   : ( ZEN_MANAGE_DMD, )
     137                  },
     138                  { 'id'            : 'eventConfig'
     139                  , 'name'          : 'Events'
     140                  , 'action'        : 'eventConfig'
     141                  , 'permissions'   : ( "Manage DMD", )
     142                  },
     143             )
     144           },
     145          )
     146
     147
     148 -    def getAllUserSettings(self):
     149          """Return list user settings objects.
     150          """
     151          # This code used to filter out the admin user.
     152          # See ticket #1615 for why it no longer does.
     153          users = self.objectValues(spec="UserSettings")
     154          users.sort(lambda a,b:cmp(a.id, b.id))
     155          return users
     156
     157 -    def getAllGroupSettings(self):
     158          """Return list user settings objects.
     159          """
     160          groups = self.objectValues(spec="GroupSettings")
     161          groups.sort(lambda a,b:cmp(a.id, b.id))
     162          return groups
     163
     164 -    def getAllUserSettingsNames(self, filtNames=()):
     165          """Return list of all zenoss usernames.
     166          """
     167          filt = lambda x: x not in filtNames
     168          return [ u.id for u in self.getAllUserSettings() if filt(u.id) ]
     169
     170 -    def getAllGroupSettingsNames(self, filtNames=()):
     171          """Return list of all zenoss usernames.
     172          """
     173          filt = lambda x: x not in filtNames
     174          return [ g.id for g in self.getAllGroupSettings() if filt(g.id) ]
     175
     176 -    def getUsers(self):
     177          """Return list of Users wrapped in their settings folder.
     178          """
     179          users = []
     180          for uset in self.objectValues(spec="UserSettings"):
     181              user = self.acl_users.getUser(uset.id)
     182              if user: users.append(user.__of__(uset))
     183          return users
     184
     185
     186 -    def getUser(self, userid=None):
     187          """Return a user object.  If userid is not passed return current user.
     188          """
     189          if userid is None:
     190              user = getSecurityManager().getUser()
     191          else:
     192              user = self.acl_users.getUser(userid)
     193          if user: return user.__of__(self.acl_users)
     194
     195
     196 -    def getAllActionRules(self):
     197          for u in self.getAllUserSettings() + self.getAllGroupSettings():
     198              for ar in u.getActionRules():
     199                  yield ar
     200
     201 -    def getUserSettings(self, userid=None):
     202          """Return a user folder.  If userid is not passed return current user.
     203          """
     204          user=None
     205          if userid is None:
     206              user = getSecurityManager().getUser()
     207              userid = user.getId()
     208          if not userid: raise Unauthorized
     209          folder = self._getOb(userid,None)
     210          if not folder and userid:
     211              userid = str(userid)
     212              ufolder = UserSettings(userid)
     213              self._setObject(ufolder.getId(), ufolder)
     214              folder = self._getOb(userid)
     215              if not user:
     216                  user = self.getUser(userid)
     217              if user:
     218                  # Load default values from our auth backend
     219                  psheets = user.listPropertysheets()
     220                  psheets.reverse() # Because first sheet should have priority
     221                  for ps in map(lambda ps: user.getPropertysheet(ps), psheets):
     222                      props = {}
     223                      for id in ps.propertyIds():
     224                          props[id] = ps.getProperty(id)
     225                      ufolder.updatePropsFromDict(props)
     226                  folder.changeOwnership(user)
     227                  folder.manage_setLocalRoles(userid, ("Owner",))
     228          return folder
     229
     230
     231 -    def getGroupSettings(self, groupid):
     232          groupid = prepId(groupid)
     233          if not self._getOb(groupid, False):
     234              gfolder = GroupSettings(groupid)
     235              self._setObject(gfolder.getId(), gfolder)
     236          return self._getOb(groupid)
     237
     238
     239 -    def setDashboardState(self, userid=None, REQUEST=None):
     240          """ Store a user's portlets and layout. If userid is not passed
     241              set the state for the current user.
     242          """
     243          user = self.getUserSettings(userid)
     244          posted = Utils.extractPostContent(REQUEST)
     245          if posted:
     246              user.dashboardState = posted
     247              if sendUserAction and REQUEST:
     248                  sendUserAction(ActionTargetType.Dashboard, ActionName.Edit,
     249                                 username=userid)
     250          return True
     251
     252 -    def getUserSettingsUrl(self, userid=None):
     253          """Return the url to the current user's folder.
     254          """
     255          uf = self.getUserSettings(userid)
     256          if uf: return uf.getPrimaryUrlPath()
     257          return ""
     258
     259
     260      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addUser')
     261 -    def manage_addUser(self, userid, password=None,roles=("ZenUser",),
     262                      REQUEST=None,**kw):
     263          """
     264          Add a Zenoss user to the system and set the user's default properties.
     265
     266          @parameter userid: username to add
     267          @parameter password: password for the username
     268          @parameter roles: tuple of role names
     269          @parameter REQUEST: Zope object containing details about this request
     270          """
     271          if not userid: return
     272
     273          userid= userid.strip()
     274
     275          illegal_usernames= [ 'user', ]
     276
     277          user_name= userid.lower()
     278          if user_name in illegal_usernames:
     279              if REQUEST:
     280                  messaging.IMessageSender(self).sendToBrowser(
     281                      'Error',
     282                      'The username "%s" is reserved.' % userid,
     283                      priority=messaging.WARNING
     284                  )
     285                  return self.callZenScreen(REQUEST)
     286              else:
     287                  return None
     288
     289          if password is None:
     290              password = self.generatePassword()
     291
     292          self.acl_users._doAddUser(userid,password,roles,"")
     293          self.acl_users.ZCacheable_invalidate()
     294          user = self.acl_users.getUser(userid)
     295          ufolder = self.getUserSettings(userid)
     296          if REQUEST: kw = REQUEST.form
     297          ufolder.updatePropsFromDict(kw)
     298
     299          if REQUEST:
     300              messaging.IMessageSender(self).sendToBrowser(
     301                  'User Added',
     302                  'User "%s" has been created.' % userid
     303              )
     304              if sendUserAction:
     305                  # don't send password
     306                  sendUserAction(ActionTargetType.User, ActionName.Add,
     307                                 username=userid, roles=roles)
     308              return self.callZenScreen(REQUEST)
     309          else:
     310              return user
     311
     312
     313 -    def generatePassword(self):
     314          """ Generate a valid password.
     315          """
     316          # we don't use these to avoid typos: OQ0Il1
     317          chars = 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
     318          return ''.join(choice(chars) for i in range(6))
     319
     320
     321 -    def authenticateCredentials(self, login, password):
     322          """
     323          Authenticates a given set of credentials against all configured
     324          authentication plugins. Returns True for successful authentication and
     325          False otherwise.
     326          """
     327          if login == 'admin':
     328              acl_users = self.getPhysicalRoot().acl_users
     329          else:
     330              acl_users = self.acl_users
     331
     332          try:
     333              authenticators = acl_users.plugins.listPlugins(
     334                  interfaces.plugins.IAuthenticationPlugin)
     335          except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
     336              authenticators = ()
     337
     338          # try each authenticator until a non-None user_id is returned
     339          for authenticator_id, auth in authenticators:
     340              try:
     341                  uid_and_info = auth.authenticateCredentials(
     342                      {'login':login, 'password':password})
     343
     344                  if isinstance(uid_and_info, tuple):
     345                      # make sure tuple has enough values to unpack
     346                      user_id, info = (uid_and_info + (None,None))[:2]
     347
     348                      # return if authentication was a success
     349                      if user_id is not None:
     350                          return True
     351
     352              except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
     353                  pass
     354
     355          # indicate no successful authentications
     356          return False
     357
     358
     359      security.declareProtected(ZEN_MANAGE_DMD, 'manage_changeUser')
     360 -    def manage_changeUser(self, userid, password=None, sndpassword=None,
     361                            roles=None, domains=None, REQUEST=None, **kw):
     362          """Change a zenoss users settings.
     363          """
     364          user = self.acl_users.getUser(userid)
     365          if not user:
     366              if REQUEST:
     367                  messaging.IMessageSender(self).sendToBrowser(
     368                      'Error',
     369                      'User "%s" was not found.' % userid,
     370                      priority=messaging.WARNING
     371                  )
     372                  return self.callZenScreen(REQUEST)
     373              else:
     374                  return
     375          if password and password != sndpassword:
     376              if REQUEST:
     377                  messaging.IMessageSender(self).sendToBrowser(
     378                      'Error',
     379                      "Passwords didn't match. No change.",
     380                      priority=messaging.WARNING
     381                  )
     382                  return self.callZenScreen(REQUEST)
     383              else:
     384                  raise ValueError("passwords don't match")
     385          if sendUserAction and REQUEST:
     386              # TODO: Record all the non-password values.
     387              #updates = dict((k,v) for k,v in kw.items() if 'password' not in k.lower())
     388              updates = {}
     389              if password: updates['password'] = '****'
     390              if roles: updates['roles': roles]
     391              if domains: updates['domains': domains]
     392          if password is None: password = user._getPassword()
     393          if roles is None: roles = user.roles
     394          if domains is None: domains = user.domains
     395          self.acl_users._doChangeUser(userid,password,roles,domains)
     396          self.acl_users.ZCacheable_invalidate()
     397          ufolder = self.getUserSettings(userid)
     398          ufolder.updatePropsFromDict(kw)
     399          if REQUEST:
     400              messaging.IMessageSender(self).sendToBrowser(
     401                  'Settings Saved',
     402                  Time.SaveMessage()
     403              )
     404              if sendUserAction:
     405                  sendUserAction(ActionTargetType.User, ActionName.Edit,
     406                                 username=userid, extra=updates)
     407              return self.callZenScreen(REQUEST)
     408          else:
     409              return user
     410
     411
     412      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteUsers')
     413 -    def manage_deleteUsers(self, userids=(), REQUEST=None):
     414          """Delete a list of zenoss users from the system.
     415          """
     416          # get a list of plugins that can add manage users and then call the
     417          # appropriate methods
     418          #
     419          # XXX this needs to be reviewed when new plugins are added, such as the
     420          # LDAP plugin
     421          if 'admin' in userids:
     422              messaging.IMessageSender(self).sendToBrowser(
     423                  'Error',
     424                  "Cannot delete admin user. No users were deleted.",
     425                  messaging.WARNING
     426              )
     427              return self.callZenScreen(REQUEST)
     428
     429          ifaces = [interfaces.plugins.IUserAdderPlugin]
     430          getPlugins = self.acl_users.plugins.listPlugins
     431          plugins = [ getPlugins(x)[0][1] for x in ifaces ]
     432          for userid in userids:
     433              try:
     434                  for plugin in plugins:
     435                      plugin.removeUser(userid)
     436                  self.acl_users.ZCacheable_invalidate()
     437              except KeyError:
     438                  # this means that there's no user in the acl_users, but that
     439                  # Zenoss still sees the user; we want to pass on this exception
     440                  # so that Zenoss can clean up
     441                  pass
     442              if getattr(aq_base(self), userid, False):
     443                  us = self._getOb(userid)
     444                  us.removeAdminRoles()
     445                  for ar in us.adminRoles():
     446                      ar.userSetting.removeRelation()
     447                      mobj = ar.managedObject().primaryAq()
     448                      mobj.adminRoles._delObject(ar.id)
     449                  self._delObject(userid)
     450
     451          if REQUEST:
     452              messaging.IMessageSender(self).sendToBrowser(
     453                  'Users Deleted',
     454                  "Users were deleted: %s." % (', '.join(userids))
     455              )
     456              if sendUserAction:
     457                  for userid in userids:
     458                      sendUserAction(ActionTargetType.User, ActionName.Delete,
     459                                     username=userid)
     460              return self.callZenScreen(REQUEST)
     461
     462
     463      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addGroup')
     464 -    def manage_addGroup(self, groupid, REQUEST=None):
     465          """Add a zenoss group to the system and set its default properties.
     466          """
     467          if not groupid: return
     468          groupid = prepId(groupid)
     469          try:
     470              self.acl_users.groupManager.addGroup(groupid)
     471              self.acl_users.ZCacheable_invalidate()
     472          except KeyError: pass
     473          self.getGroupSettings(groupid)
     474          if REQUEST:
     475              messaging.IMessageSender(self).sendToBrowser(
     476                  'Group Added',
     477                  'Group "%s" has been created.' % groupid
     478              )
     479              if sendUserAction:
     480                  sendUserAction(ActionTargetType.Group, ActionName.Add,
     481                                 group=groupid)
     482              return self.callZenScreen(REQUEST)
     483
     484
     485      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteGroups')
     486 -    def manage_deleteGroups(self, groupids=(), REQUEST=None):
     487          """ Delete a zenoss group from the system
     488          """
     489          gm = self.acl_users.groupManager
     490          if isinstance(groupids, basestring):
     491              groupids = [groupids]
     492          for groupid in groupids:
     493              if self._getOb(groupid):
     494                  group = self._getOb(groupid)
     495                  group.removeAdminRoles()
     496                  self._delObject(groupid)
     497              try:
     498                  gm.removeGroup(groupid)
     499                  self.acl_users.ZCacheable_invalidate()
     500              except KeyError: pass
     501          if REQUEST:
     502              messaging.IMessageSender(self).sendToBrowser(
     503                  'Groups Deleted',
     504                  "Groups were deleted: %s." % (', '.join(groupids))
     505              )
     506              if sendUserAction:
     507                  for groupid in groupids:
     508                      sendUserAction(ActionTargetType.Group, ActionName.Delete,
     509                                     group=groupid)
     510              return self.callZenScreen(REQUEST)
     511
     512
     513      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addUsersToGroups')
     514 -    def manage_addUsersToGroups(self, userids=(), groupids=(), REQUEST=None):
     515          """ Add users to a group
     516          """
     517          if isinstance(userids, basestring):
     518              userids = [userids]
     519          if isinstance(groupids, basestring):
     520              groupids = [groupids]
     521          for groupid in groupids:
     522              self._getOb(groupid).manage_addUsersToGroup(userids)
     523          if REQUEST:
     524              if not groupids:
     525                  messaging.IMessageSender(self).sendToBrowser(
     526                      'Error',
     527                      'No groups were selected.',
     528                      priority=messaging.WARNING
     529                  )
     530              else:
     531                  messaging.IMessageSender(self).sendToBrowser(
     532                      'Groups Modified',
     533                      'Users %s were added to group %s.' % (
     534                          ', '.join(userids), ', '.join(groupids))
     535                  )
     536              if sendUserAction:
     537                  for userid in userids:
     538                      for groupid in groupids:
     539                          sendUserAction(ActionTargetType.User, 'AddToGroup',
     540                                         username=userid, group=groupid)
     541              return self.callZenScreen(REQUEST)
     542
     543
     544      security.declareProtected(ZEN_MANAGE_DMD, 'manage_emailTestAdmin')
     545 -    def manage_emailTestAdmin(self, userid, REQUEST=None):
     546          ''' Do email test for given user
     547          '''
     548          userSettings = self.getUserSettings(userid)
     549          msg = userSettings.manage_emailTest()
     550          if msg:
     551              messaging.IMessageSender(self).sendToBrowser('Email Test', msg)
     552          if REQUEST:
     553              return self.callZenScreen(REQUEST)
     554
     555
     556      security.declareProtected(ZEN_MANAGE_DMD, 'manage_pagerTestAdmin')
     557 -    def manage_pagerTestAdmin(self, userid, REQUEST=None):
     558          ''' Do pager test for given user
     559          '''
     560          userSettings = self.getUserSettings(userid)
     561          msg = userSettings.manage_pagerTest()
     562          if msg:
     563              messaging.IMessageSender(self).sendToBrowser('Pager Test', msg)
     564          if REQUEST:
     565              return self.callZenScreen(REQUEST)
     566
     567
     568 -    def cleanUserFolders(self):
     569          """Delete orphaned user folders.
     570          """
     571          userfolders = self._getOb(UserSettingsId)
     572          userids = self.acl_users.getUserNames()
     573          for fid in userfolders.objectIds():
     574              if fid not in userids:
     575                  userfolders._delObject(fid)
     576          self.acl_users.ZCacheable_invalidate()
     577
     578
     579 -    def getAllRoles(self):
     580          """Get list of all roles without Anonymous and Authenticated.
     581          """
     582          return filter(rolefilter, self.valid_roles())
     583
     584
     585 -    def exportXmlHook(self,ofile, ignorerels):
     586          map(lambda x: x.exportXml(ofile, ignorerels), self.getAllUserSettings())
     587
     588
     589
     590 -def manage_addUserSettings(context, id, title = None, REQUEST = None):
     591      """make a device class"""
     592      dc = UserSettings(id, title)
     593      context._setObject(id, dc)
     594      if REQUEST:
     595          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     596
     597
     598  addUserSettings = DTMLFile('dtml/addUserSettings',globals())
     599
     600
     601 -class UserSettings(ZenModelRM):
     602      """zenoss user folder has users preferences.
     603      """
     604      implements(IProvidesEmailAddresses, IProvidesPagerAddresses, IGloballyIdentifiable)
     605
     606      meta_type = "UserSettings"
     607
     608      sub_meta_types = ("ActionRule",)
     609
     610      email = ""
     611      pager = ""
     612      defaultPageSize = 40
     613      defaultEventPageSize = 30
     614      defaultAdminRole = "ZenUser"
     615      defaultAdminLevel = 1
     616      oncallStart = 0
     617      oncallEnd = 0
     618      escalationMinutes = 0
     619      dashboardState = ''
     620      netMapStartObject = ''
     621      eventConsoleRefresh = True
     622      zenossNetUser = ''
     623      zenossNetPassword = ''
     624
     625      _properties = ZenModelRM._properties + (
     626          {'id':'email', 'type':'string', 'mode':'w'},
     627          {'id':'pager', 'type':'string', 'mode':'w'},
     628          {'id':'defaultPageSize', 'type':'int', 'mode':'w'},
     629          {'id':'defaultEventPageSize', 'type':'int', 'mode':'w'},
     630          {'id':'defaultAdminRole', 'type':'string', 'mode':'w'},
     631          {'id':'defaultAdminLevel', 'type':'int', 'mode':'w'},
     632          {'id':'oncallStart', 'type':'int', 'mode':'w'},
     633          {'id':'oncallEnd', 'type':'int', 'mode':'w'},
     634          {'id':'escalationMinutes', 'type':'int', 'mode':'w'},
     635          {'id':'dashboardState', 'type':'string', 'mode':'w'},
     636          {'id':'netMapStartObject', 'type':'string', 'mode':'w'},
     637          {'id':'eventConsoleRefresh', 'type':'boolean', 'mode':'w'},
     638          {'id':'zenossNetUser', 'type':'string', 'mode':'w'},
     639          {'id':'zenossNetPassword', 'type':'string', 'mode':'w'},
     640      )
     641
     642
     643      _relations =  (
     644          ("adminRoles", ToMany(ToOne, "Products.ZenModel.AdministrativeRole",
     645                                "userSetting")),
     646          ("messages", ToManyCont(ToOne,
     647              "Products.ZenWidgets.PersistentMessage.PersistentMessage",
     648              "messageQueue")),
     649      )
     650
     651      # Screen action bindings (and tab definitions)
     652      factory_type_information = (
     653          {
     654              'immediate_view' : 'editUserSettings',
     655              'actions'        :
     656              (
     657                  {'name'         : 'Edit',
     658                  'action'        : 'editUserSettings',
     659                  'permissions'   : (ZEN_CHANGE_SETTINGS,),
     660                  },
     661                  {'name'         : 'Administered Objects',
     662                  'action'        : 'administeredDevices',
     663                  'permissions'   : (ZEN_CHANGE_ADMIN_OBJECTS,)
     664                  },
     665              )
     666           },
     667          )
     668
     669      security = ClassSecurityInfo()
     670
     671 -    def hasNoGlobalRoles(self):
     672          """This user doesn't have global roles. Used to limit access
     673          """
     674          return self.id != 'admin' and len(self.getUserRoles()) == 0
     675
     676 -    def getUserRoles(self):
     677          """Get current roles for this user.
     678          """
     679          user = self.getUser(self.id)
     680          if user:
     681              # This call will create GroupSettings objects for any externally-
     682              # sourced groups.
     683              self.getAllAdminRoles()
     684              return filter(rolefilter, user.getRoles())
     685          return []
     686
     687
     688 -    def getUserGroupSettingsNames(self):
     689          """Return group settings objects for user
     690          """
     691          user = self.getUser(self.id)
     692          if user:
     693              return self.acl_users._getGroupsForPrincipal(user)
     694          return ()
     695
     696
     697      security.declareProtected(ZEN_CHANGE_SETTINGS, 'updatePropsFromDict')
     698 -    def updatePropsFromDict(self, propdict):
     699          props = self.propertyIds()
     700          for k, v in propdict.items():
     701              if k in props: setattr(self,k,v)
     702
     703
     704 -    def iseditable(self):
     705          """Can the current user edit this settings object.
     706          """
     707          currentUser = getSecurityManager().getUser()
     708
     709          # Managers can edit any users' settings.
     710          if currentUser.has_role("Manager"):
     711              return True
     712
     713          # thisUser can be None if the plugin that created it is inactive.
     714          thisUser = self.acl_users.getUser(self.id)
     715          if thisUser is None:
     716              return False
     717
     718          # ZenManagers can edit any users' settings except for Managers.
     719          if currentUser.has_role("ZenManager") \
     720              and not thisUser.has_role("Manager"):
     721              return True
     722
     723          # Users can edit their own settings.
     724          if thisUser.getUserName() == currentUser.getUserName():
     725              return True
     726
     727          return False
     728
     729      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_resetPassword')
     730 -    def manage_resetPassword(self):
     731          """
     732          Reset a password.
     733          """
     734          email = self.email.strip()
     735          if not email:
     736              messaging.IMessageSender(self).sendToBrowser(
     737                  'Password Reset Failed',
     738                  'Cannot send password reset email; user has no'+
     739                  ' email address.',
     740                  priority=messaging.WARNING
     741              )
     742              return self.callZenScreen(self.REQUEST)
     743
     744          newpw = self.generatePassword()
     745          body = """
     746          Your Zenoss password has been reset at %s's request.
     747
     748          Your new password is: %s
     749          """ % (self.getUser().getId(), newpw)
     750          msg = MIMEText(body)
     751          msg['Subject'] = 'Zenoss Password Reset Request'
     752          msg['From'] = self.dmd.getEmailFrom()
     753          msg['To'] = email
     754          msg['Date'] = DateTime().rfc822()
     755          result, errorMsg = Utils.sendEmail(msg, self.dmd.smtpHost,
     756                              self.dmd.smtpPort,
     757                              self.dmd.smtpUseTLS, self.dmd.smtpUser,
     758                              self.dmd.smtpPass)
     759          if result:
     760              userManager = self.acl_users.userManager
     761              try:
     762                  userManager.updateUserPassword(self.id, newpw)
     763              except KeyError:
     764                  self.getPhysicalRoot().acl_users.userManager.updateUserPassword(
     765                                  self.id, newpw)
     766              messaging.IMessageSender(self).sendToBrowser(
     767                  'Password reset',
     768                  'An email with a new password has been sent.'
     769              )
     770              if sendUserAction:
     771                  sendUserAction(ActionTargetType.User,
     772                                 'ResetPassword',
     773                                 username=self.id)
     774              loggedInUser = self.REQUEST['AUTHENTICATED_USER']
     775              # we only want to log out the user if it's *their* password
     776              # they've changed, not, for example, if the admin user is
     777              # changing another user's password
     778              if loggedInUser.getUserName() == self.id:
     779                  self.acl_users.logout(self.REQUEST)
     780          else:
     781              messaging.IMessageSender(self).sendToBrowser(
     782                  'Password reset failed',
     783                  'Unable to send password reset email: %s' % errorMsg,
     784                  priority=messaging.WARNING
     785              )
     786          return self.callZenScreen(self.REQUEST)
     787
     788
     789      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_editUserSettings')
     790 -    def manage_editUserSettings(self, oldpassword=None, password=None,
     791                                  sndpassword=None, roles=None, groups=None,
     792                                  domains=None, REQUEST=None, **kw):
     793          """Update user settings.
     794          """
     795          # get the user object; return if no user
     796          user = self.acl_users.getUser(self.id)
     797          if not user:
     798              user = self.getPhysicalRoot().acl_users.getUser(self.id)
     799          if not user:
     800              if REQUEST:
     801                  messaging.IMessageSender(self).sendToBrowser(
     802                      'Error',
     803                      'User %s not found.' % self.id,
     804                      priority=messaging.WARNING
     805                  )
     806                  return self.callZenScreen(REQUEST)
     807              else:
     808                  return
     809
     810          # Verify existing password
     811          curuser = self.getUser().getId()
     812          if not oldpassword or not self.ZenUsers.authenticateCredentials(
     813              curuser, oldpassword):
     814              if REQUEST:
     815                  messaging.IMessageSender(self).sendToBrowser(
     816                      'Error',
     817                      'Confirmation password is empty or invalid. Please'+
     818                      ' confirm your password for security reasons.',
     819                      priority=messaging.WARNING
     820                  )
     821                  return self.callZenScreen(REQUEST)
     822              else:
     823                  raise ValueError("Current password is incorrect.")
     824
     825          # update role info
     826          roleManager = self.acl_users.roleManager
     827          origRoles = filter(rolefilter, user.getRoles())
     828
     829          if not self.has_role('Manager') and roles and 'Manager' in roles:
     830              if REQUEST:
     831                  messaging.IMessageSender(self).sendToBrowser(
     832                      'Error',
     833                      'Only Managers can make more Managers.',
     834                      priority=messaging.WARNING
     835                  )
     836                  return self.callZenScreen(REQUEST)
     837              else:
     838                  return
     839
     840          if not self.has_role('Manager') and origRoles and \
     841              'Manager' in origRoles:
     842
     843              if REQUEST:
     844                  messaging.IMessageSender(self).sendToBrowser(
     845                      'Error',
     846                      'Only Managers can modify other Managers.',
     847                      priority=messaging.WARNING
     848                  )
     849                  return self.callZenScreen(REQUEST)
     850              else:
     851                  return
     852
     853          # if there's a change, then we need to update
     854          # TODO: Record all the non-password values.
     855          #updates = dict((k,v) for k,v in kw.items() if 'password' not in k.lower())
     856          updates = {}
     857          if roles != origRoles and self.isManager():
     858              from sets import Set as set
     859              # get roles to remove and then remove them
     860              removeRoles = list(set(origRoles).difference(set(roles)))
     861              for role in removeRoles:
     862                  try:
     863                      roleManager.removeRoleFromPrincipal(role, self.id)
     864                  except KeyError:
     865                      # User doesn't actually have that role; ignore
     866                      pass
     867              # get roles to add and then add them
     868              addRoles = list(set(roles).difference(set(origRoles)))
     869              for role in addRoles:
     870                  roleManager.assignRoleToPrincipal(role, self.id)
     871              updates['roles'] = roles
     872
     873          # update group info
     874          groupManager = self.acl_users.groupManager
     875          origGroups = groupManager.getGroupsForPrincipal(user)
     876          # if there's a change, then we need to update
     877          if groups != origGroups and self.isManager():
     878              # can we use the built-in set?
     879              try:
     880                  set()
     881              except NameError:
     882                  from sets import Set as set
     883              # get groups to remove and then remove them
     884              removeGroups = set(origGroups).difference(set(groups))
     885              for groupid in removeGroups:
     886                  groupManager.removePrincipalFromGroup(user.getId(), groupid)
     887              # get groups to add and then add them
     888              addGroups = set(groups).difference(set(origGroups))
     889              for groupid in addGroups:
     890                  try:
     891                      groupManager.addPrincipalToGroup(user.getId(), groupid)
     892                  except KeyError:
     893                      # This can occur if the group came from an external source.
     894                      pass
     895              updates['groups'] = groups
     896
     897          # we're not managing domains right now
     898          if domains:
     899              msg = 'Zenoss does not currently manage domains for users.'
     900              raise NotImplementedError(msg)
     901
     902          # update Zenoss user folder settings
     903          if REQUEST:
     904              kw = REQUEST.form
     905          self.manage_changeProperties(**kw)
     906
     907          # update password info
     908          if self.id=='admin':
     909              userManager = self.getPhysicalRoot().acl_users.userManager
     910          else:
     911              userManager = self.acl_users.userManager
     912          if password:
     913              if password.find(':') >= 0:
     914                  if REQUEST:
     915                      messaging.IMessageSender(self).sendToBrowser(
     916                          'Error',
     917                          'Passwords cannot contain a ":". Password not updated.',
     918                          priority=messaging.WARNING
     919                      )
     920                      return self.callZenScreen(REQUEST)
     921                  else:
     922                      raise ValueError("Passwords cannot contain a ':' ")
     923              elif password != sndpassword:
     924                  if REQUEST:
     925                      messaging.IMessageSender(self).sendToBrowser(
     926                          'Error',
     927                          'Passwords did not match. Password not updated.',
     928                          priority=messaging.WARNING
     929                      )
     930                      return self.callZenScreen(REQUEST)
     931                  else:
     932                      raise ValueError("Passwords don't match")
     933              else:
     934                  try:
     935                      userManager.updateUserPassword(self.id, password)
     936                      updates['password'] = '****'
     937                  except KeyError:
     938                      self.getPhysicalRoot().acl_users.userManager.updateUserPassword(
     939                                      self.id, password)
     940                  if REQUEST:
     941                      loggedInUser = REQUEST['AUTHENTICATED_USER']
     942                      # we only want to log out the user if it's *their* passowrd
     943                      # they've changed, not, for example, if the admin user is
     944                      # changing another user's password
     945                      if loggedInUser.getUserName() == self.id:
     946                          self.acl_users.logout(REQUEST)
     947
     948          self.acl_users.ZCacheable_invalidate()
     949
     950          # finish up
     951          if REQUEST:
     952              messaging.IMessageSender(self).sendToBrowser(
     953                  'Settings Saved',
     954                  Time.SaveMessage()
     955              )
     956              if sendUserAction:
     957                  sendUserAction(ActionTargetType.User, ActionName.Edit,
     958                                 username=self.id, extra=updates)
     959              return self.callZenScreen(REQUEST)
     960          else:
     961              return user
     962
     963      security.declareProtected(ZEN_CHANGE_ALERTING_RULES, 'manage_addActionRule')
     964      @deprecated
     965 -    def manage_addActionRule(self, id=None, REQUEST=None):
     966          """Add an action rule to this object.
     967          """
     968          if id:
     969              ar = ActionRule(id)
     970              self._setObject(id, ar)
     971              ar = self._getOb(id)
     972              user = getSecurityManager().getUser()   # current user
     973              userid = user.getId()
     974              if userid != self.id:            # if we are not the current user
     975                  userid = self.id
     976                  user = self.getUser(userid)
     977                  ar.changeOwnership(user)     # make us the owner of it
     978                  ar.manage_setLocalRoles(userid, ("Owner",))
     979          if REQUEST:
     980              return self.callZenScreen(REQUEST)
     981
     982 -    def getActionRules(self):
     983          return self.objectValues(spec=ActionRule.meta_type)
     984
     985      security.declareProtected(ZEN_CHANGE_EVENT_VIEWS,
     986          'manage_addCustomEventView')
     987      @deprecated
     988 -    def manage_addCustomEventView(self, id=None, REQUEST=None):
     989          """Add a custom event view to this object.
     990          """
     991          if id:
     992              ar = CustomEventView(id)
     993              self._setObject(id, ar)
     994              ar = self._getOb(id)
     995              user = getSecurityManager().getUser()
     996              userid = user.getId()
     997              if userid != self.id:
     998                  userid = self.id
     999                  user = self.getUser(userid)
    1000                  ar.changeOwnership(user)
    1001                  ar.manage_setLocalRoles(userid, ("Owner",))
    1002          if REQUEST:
    1003              return self.callZenScreen(REQUEST)
    1004
    1005
    1006      security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
    1007          'manage_addAdministrativeRole')
    1008 -    def manage_addAdministrativeRole(self, name=None, type='device', role=None,
    1009                                       guid=None, uid=None, REQUEST=None):
    1010          "Add a Admin Role to the passed object"
    1011          unused(role)
    1012          mobj = None
    1013          if guid or uid:
    1014              # look up our object by either guid or uid
    1015              if guid:
    1016                  manager = IGUIDManager(self.dmd)
    1017                  mobj = manager.getObject(guid)
    1018              elif uid:
    1019                  mobj = self.unrestrictedTraverse(uid)
    1020          else:
    1021              # use magic to look up our object
    1022              if not name:
    1023                  name = REQUEST.deviceName
    1024              if type == 'device':
    1025                  mobj =self.getDmdRoot("Devices").findDevice(name)
    1026              else:
    1027                  try:
    1028                      root = type.capitalize()+'s'
    1029                      if type == "deviceClass":
    1030                          mobj = self.getDmdRoot("Devices").getOrganizer(name)
    1031                      else:
    1032                          mobj = self.getDmdRoot(root).getOrganizer(name)
    1033                  except KeyError: pass
    1034          if not mobj:
    1035              if REQUEST:
    1036                  messaging.IMessageSender(self).sendToBrowser(
    1037                      'Error',
    1038                      "%s %s not found"%(type.capitalize(),name),
    1039                      priority=messaging.WARNING
    1040                  )
    1041                  return self.callZenScreen(REQUEST)
    1042              else: return
    1043          roleNames = [ r.id for r in mobj.adminRoles() ]
    1044          if self.id in roleNames:
    1045              if REQUEST:
    1046                  messaging.IMessageSender(self).sendToBrowser(
    1047                      'Error',
    1048                      (("Administrative Role for %s %s "
    1049                       "for user %s already exists.") % (type, name, self.id)),
    1050                      priority=messaging.WARNING
    1051                  )
    1052                  return self.callZenScreen(REQUEST)
    1053              else: return
    1054          mobj.manage_addAdministrativeRole(self.id)
    1055          if REQUEST:
    1056              messaging.IMessageSender(self).sendToBrowser(
    1057                  'Role Added',
    1058                  ("Administrative Role for %s %s for user %s added" %
    1059                      (type, name, self.id))
    1060              )
    1061              if sendUserAction:
    1062                  type_ = mobj.meta_type
    1063                  sendUserAction(ActionTargetType.User, 'AddAdministrativeRole',
    1064                                 username=self.id,
    1065                                 extra={type_:mobj.getPrimaryId()})
    1066              return self.callZenScreen(REQUEST)
    1067
    1068
    1069      security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
    1070          'manage_editAdministrativeRoles')
    1071 -    def manage_editAdministrativeRoles(self, ids=(), role=(),
    1072                                          level=(), REQUEST=None):
    1073          """Edit list of admin roles.
    1074          """
    1075          if isinstance(ids, basestring):
    1076              ids = [ids]
    1077              level = [level]
    1078              role = [role]
    1079          else:
    1080              ids = list(ids)
    1081          for ar in self.adminRoles():
    1082              mobj = ar.managedObject()
    1083              try: i = ids.index(mobj.managedObjectName())
    1084              except ValueError: continue
    1085              mobj = mobj.primaryAq()
    1086              mobj.manage_editAdministrativeRoles(self.id, role[i], level[i])
    1087              if sendUserAction and REQUEST:
    1088                  type_ = mobj.meta_type
    1089                  sendUserAction(ActionTargetType.User, 'EditAdministrativeRole',
    1090                                 username=self.id,
    1091                                 extra={type_:mobj.getPrimaryId()},
    1092                                 role=role[i], level=level[i])
    1093          if REQUEST:
    1094              if ids:
    1095                  messaging.IMessageSender(self).sendToBrowser(
    1096                      'Roles Updated',
    1097                      "Administrative roles were updated."
    1098                  )
    1099              return self.callZenScreen(REQUEST)
    1100
    1101
    1102      security.declareProtected(ZEN_CHANGE_ADMIN_OBJECTS,
    1103          'manage_deleteAdministrativeRole')
    1104 -    def manage_deleteAdministrativeRole(self, delids=(), REQUEST=None):
    1105          "Delete admin roles of objects."
    1106          if isinstance(delids, basestring):
    1107              delids = [delids]
    1108          for ar in self.adminRoles():
    1109              mobj = ar.managedObject()
    1110              if mobj.managedObjectName() not in delids: continue
    1111              mobj = mobj.primaryAq()
    1112              mobj.manage_deleteAdministrativeRole(self.id)
    1113              if sendUserAction and REQUEST:
    1114                  type_ = mobj.meta_type
    1115                  sendUserAction(ActionTargetType.User, 'DeleteAdministrativeRole',
    1116                                 username=self.id,
    1117                                 extra={type_:mobj.getPrimaryId()})
    1118          if REQUEST:
    1119              if delids:
    1120                  messaging.IMessageSender(self).sendToBrowser(
    1121                      'Roles Deleted',
    1122                      "Administrative roles were deleted."
    1123                  )
    1124              return self.callZenScreen(REQUEST)
    1125
    1126
    1127      security.declareProtected(ZEN_CHANGE_SETTINGS, 'getAllAdminRoles')
    1128 -    def getAllAdminRoles(self):
    1129          """Return all admin roles for this user and its groups
    1130          """
    1131          ars = self.adminRoles()
    1132          for group in self.getUser().getGroups():
    1133              gs = self.getGroupSettings(group)
    1134              ars.extend(gs.adminRoles())
    1135          return ars
    1136
    1137
    1138      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_emailTest')
    1139 -    def manage_emailTest(self, REQUEST=None):
    1140          ''' Send a test email to the given userid.
    1141          '''
    1142          destSettings = self.getUserSettings(self.getId())
    1143          destAddresses = destSettings.getEmailAddresses()
    1144          msg = None
    1145          if destAddresses:
    1146              fqdn = socket.getfqdn()
    1147              thisUser = self.getUser()
    1148              srcId = thisUser.getId()
    1149              self.getUserSettings(srcId)
    1150              srcAddress = self.dmd.getEmailFrom()
    1151              # Read body from file probably
    1152              body = ('This is a test message sent by %s' % srcId +
    1153                      ' from the Zenoss installation on %s.' % fqdn)
    1154              emsg = MIMEText(body)
    1155              emsg['Subject'] = 'Zenoss Email Test'
    1156              emsg['From'] = srcAddress
    1157              emsg['To'] = ', '.join(destAddresses)
    1158              emsg['Date'] = DateTime().rfc822()
    1159              result, errorMsg = Utils.sendEmail(emsg, self.dmd.smtpHost,
    1160                                  self.dmd.smtpPort,
    1161                                  self.dmd.smtpUseTLS, self.dmd.smtpUser,
    1162                                  self.dmd.smtpPass)
    1163              if result:
    1164                  msg = 'Test email sent to %s' % ', '.join(destAddresses)
    1165              else:
    1166                  msg = 'Test failed: %s' % errorMsg
    1167          else:
    1168              msg = 'Test email not sent, user has no email address.'
    1169          if REQUEST:
    1170              messaging.IMessageSender(self).sendToBrowser(
    1171                  'Email Test',
    1172                  msg.replace("'", "\\'")
    1173              )
    1174              return self.callZenScreen(REQUEST)
    1175          else:
    1176              return msg
    1177
    1178
    1179      security.declareProtected(ZEN_CHANGE_SETTINGS, 'manage_pagerTest')
    1180 -    def manage_pagerTest(self, REQUEST=None):
    1181          ''' Send a test page
    1182          '''
    1183          destSettings = self.getUserSettings(self.getId())
    1184          destPagers = [ x.strip() for x in
    1185              (destSettings.getPagerAddresses() or []) ]
    1186          msg = None
    1187          fqdn = socket.getfqdn()
    1188          srcId = self.getUser().getId()
    1189          testMsg = ('Test sent by %s' % srcId +
    1190                  ' from the Zenoss installation on %s.' % fqdn)
    1191          for destPager in destPagers:
    1192              result, errorMsg = Utils.sendPage(destPager, testMsg,
    1193                                      self.dmd.pageCommand)
    1194              if result:
    1195                  msg = 'Test page sent to %s' % ', '.join(destPagers)
    1196              else:
    1197                  msg = 'Test failed: %s' % errorMsg
    1198                  break
    1199          if not destPagers:
    1200              msg = 'Test page not sent, user has no pager number.'
    1201          if REQUEST:
    1202              messaging.IMessageSender(self).sendToBrowser(
    1203                  'Pager Test', msg)
    1204              return self.callZenScreen(REQUEST)
    1205          else:
    1206              return msg
    1207
    1208 -    def exportXmlHook(self, ofile, ignorerels):
    1209          """patch to export all user configuration
    1210          """
    1211          for o in self.objectValues():
    1212              if hasattr(aq_base(o), 'exportXml'):
    1213                  o.exportXml(ofile, ignorerels)
    1214
    1215 -    def getPagerAddresses(self):
    1216          if self.pager.strip():
    1217              return [self.pager.strip()]
    1218          return []
    1219
    1220 -    def getEmailAddresses(self):
    1221          if self.email.strip():
    1222              return [self.email]
    1223          return []
    1224
    1225 -    def isLoggedInUser(self):
    1226          loggedinUser = self.ZenUsers.getUserSettings()
    1227          return loggedinUser.id == self.id
    1228
    1229 -    def getDotNetSession(self):
    1230          """
    1231          Use the Zenoss.net credentials associated with this user to log in to a
    1232          Zenoss.net session.
    1233          """
    1234          session = DotNetCommunication.getDotNetSession(
    1235                                          self.zenossNetUser,
    1236                                          self.zenossNetPassword)
    1237          return session
    1238
    1239 -    def removeAdminRoles(self):
    1240          """
    1241          Call before deleting a user or group this will
    1242          remove this user/group from the list of admin objects for
    1243          everything that the object adminstered before. This
    1244          prevents broken relationships
    1245          """
    1246          for role in self.getAllAdminRoles():
    1247              obj = role.managedObject().primaryAq()
    1248              obj.manage_deleteAdministrativeRole(self.id)
    1249
    1250 -class GroupSettings(UserSettings):
    1251      implements(IProvidesEmailAddresses, IProvidesPagerAddresses)
    1252      meta_type = 'GroupSettings'
    1253
    1254      factory_type_information = (
    1255          {
    1256              'immediate_view' : 'editGroupSettings',
    1257              'actions'        :
    1258              (
    1259                  {'name'         : 'Edit',
    1260                  'action'        : 'editGroupSettings',
    1261                  'permissions'   : (ZEN_CHANGE_SETTINGS,),
    1262                  },
    1263                  {'name'         : 'Administered Objects',
    1264                  'action'        : 'administeredDevices',
    1265                  'permissions'   : (ZEN_CHANGE_ADMIN_OBJECTS,)
    1266                  },
    1267              )
    1268           },
    1269          )
    1270
    1271      security = ClassSecurityInfo()
    1272
    1273 -    def _getG(self):
    1274          return self.zport.acl_users.groupManager
    1275
    1276
    1277 -    def hasNoGlobalRoles(self):
    1278          """This is a group we never have roles. This is set to false so that
    1279          fuctionality that would normally be taken away for a restricted user is
    1280          left in.
    1281          """
    1282          return False
    1283
    1284
    1285      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addUsersToGroup')
    1286 -    def manage_addUsersToGroup( self, userids, REQUEST=None ):
    1287          """ Add user to this group
    1288          """
    1289          if isinstance(userids, basestring):
    1290              userids = [userids]
    1291          for userid in userids:
    1292              self._getG().addPrincipalToGroup( userid, self.id )
    1293              if sendUserAction and REQUEST:
    1294                  sendUserAction(ActionTargetType.User, 'AddToGroup',
    1295                                 username=userid,
    1296                                 group=self.id)
    1297          if REQUEST:
    1298              messaging.IMessageSender(self).sendToBrowser(
    1299                  'Users Added',
    1300                  'Added %s to Group %s' % (','.join(userids), self.id)
    1301              )
    1302              return self.callZenScreen(REQUEST)
    1303
    1304      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteUserFromGroup')
    1305 -    def manage_deleteUserFromGroup( self, userid ):
    1306          self._getG().removePrincipalFromGroup( userid, self.id )
    1307
    1308      security.declareProtected(ZEN_MANAGE_DMD, 'manage_deleteUsersFromGroup')
    1309 -    def manage_deleteUsersFromGroup(self, userids=(), REQUEST=None ):
    1310          """ Delete users from this group
    1311          """
    1312          for userid in userids:
    1313              self.manage_deleteUserFromGroup(userid)
    1314              if sendUserAction and REQUEST:
    1315                  sendUserAction(ActionTargetType.User, 'RemoveFromGroup',
    1316                                 username=userid,
    1317                                 group=self.id)
    1318          if REQUEST:
    1319              messaging.IMessageSender(self).sendToBrowser(
    1320                  'Users Removed',
    1321                  'Deleted users from Group %s' % self.id
    1322              )
    1323              return self.callZenScreen(REQUEST)
    1324
    1325 -    def getMemberUserSettings(self):
    1326          return [ self.getUserSettings(u[0])
    1327           for u in self._getG().listAssignedPrincipals(self.id) ]
    1328
    1329 -    def getMemberUserIds(self):
    1330          """
    1331          Returns a list of user ids that are members of this group.
    1332          """
    1333          # We must using reverse mapping of all users to their groups rather
    1334          # than going directly to the group's assigned principals because
    1335          # some group backends don't support listAssignedPrincipals.
    1336          return [ u.id for u in self.ZenUsers.getAllUserSettings()
    1337              if self.id in u.getUserGroupSettingsNames() ]
    1338
    1339 -    def printUsers(self):
    1340          try:
    1341              userIds = self.getMemberUserIds()
    1342          except LocalAndLDAPUserEntries, ex:
    1343              return str(ex)
    1344
    1345          return ", ".join(userIds)
    1346
    1347 -    def getEmailAddresses(self):
    1348          try:
    1349              userIds = self.getMemberUserIds()
    1350          except LocalAndLDAPUserEntries, ex:
    1351              return []
    1352
    1353          result = []
    1354          for username in userIds:
    1355              result.extend(self.getUserSettings(username).getEmailAddresses())
    1356          return result
    1357
    1358 -    def getPagerAddresses(self):
    1359          try:
    1360              userIds = self.getMemberUserIds()
    1361          except LocalAndLDAPUserEntries, ex:
    1362              return []
    1363
    1364          result = []
    1365          for username in userIds:
    1366              result.extend(self.getUserSettings(username).getPagerAddresses())
    1367          return result
    1368
    1369
    1370  InitializeClass(UserSettingsManager)
    1371  InitializeClass(UserSettings)
    1372