Package Products :: Package ZenRelations :: Module ZItem |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenRelations.ZItem

      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  import marshal, re, sys, time
     14
     15  import Globals, Acquisition
     16  import App
     17  import App.Management
     18  import AccessControl
     19  import AccessControl.Role, AccessControl.Owned, App.Common
     20  from ExtensionClass import Base
     21  from ComputedAttribute import ComputedAttribute
     22  from AccessControl import getSecurityManager, Unauthorized
     23  from AccessControl.ZopeSecurityPolicy import getRoles
     24  from Acquisition import aq_base, aq_parent, aq_inner
     25  from DocumentTemplate.html_quote import html_quote
     26  from DocumentTemplate.ustr import ustr
     27  from zExceptions.ExceptionFormatter import format_exception
     28  from zExceptions import Redirect
     29
     30  from OFS.CopySupport import CopySource
     31  from OFS.Traversable import Traversable
     32
     33  from Products.ZenUtils.Utils import unused
     34
     35
     36  HTML=Globals.HTML
     37
     38  import logging
     39  logger = logging.getLogger()
     40
     41 -class ZItem(Base, CopySource, App.Management.Tabs, Traversable,
     42             AccessControl.Owned.Owned,
     43             ):
     44
     45
     46      """A common base class for simple, non-container objects."""
     47
     48      isPrincipiaFolderish=0
     49      isTopLevelPrincipiaApplicationObject=0
     50
     51      # Direct use of the 'id' attribute is deprecated - use getId()
     52      id=''
     53
     54      getId__roles__=None
     55 -    def getId(self):
     56          """Return the id of the object as a string.
     57
     58          This method should be used in preference to accessing an id attribute
     59          of an object directly. The getId method is public.
     60          """
     61          name=getattr(self, 'id', None)
     62          if callable(name):
     63              return name()
     64          if name is not None:
     65              return name
     66          if hasattr(self, '__name__'):
     67              return self.__name__
     68          raise AttributeError, 'This object has no id'
     69
     70      # Alias id to __name__, which will make tracebacks a good bit nicer:
     71      __name__=ComputedAttribute(lambda self: self.getId())
     72
     73      # Name, relative to SOFTWARE_URL of icon used to display item
     74      # in folder listings.
     75      icon=''
     76
     77      # Meta type used for selecting all objects of a given type.
     78      meta_type='simple item'
     79
     80      # Default title.
     81      title=''
     82
     83      # Default propertysheet info:
     84      __propsets__=()
     85
     86      manage_options=(
     87          AccessControl.Owned.Owned.manage_options
     88          )
     89
     90      # Attributes that must be acquired
     91      REQUEST=Acquisition.Acquired
     92
     93      # Allow (reluctantly) access to unprotected attributes
     94      __allow_access_to_unprotected_subobjects__=1
     95
     96 -    def title_or_id(self):
     97          """Return the title if it is not blank and the id otherwise.
     98          """
     99          title=self.title
    100          if callable(title):
    101              title=title()
    102          if title: return title
    103          return self.getId()
    104
    105 -    def titleOrId(self):
    106          """Return the title if it is not blank and the id otherwise
    107          """
    108          return self.title_or_id()
    109
    110 -    def title_and_id(self):
    111          """Return the title if it is not blank and the id otherwise.
    112
    113          If the title is not blank, then the id is included in parens.
    114          """
    115          title=self.title
    116          if callable(title):
    117              title=title()
    118          id = self.getId()
    119          return title and ("%s (%s)" % (title,id)) or id
    120
    121 -    def this(self):
    122          # Handy way to talk to ourselves in document templates.
    123          return self
    124
    125 -    def tpURL(self):
    126          # My URL as used by tree tag
    127          return self.getId()
    128
    129 -    def tpValues(self):
    130          # My sub-objects as used by the tree tag
    131          return ()
    132
    133      _manage_editedDialog=Globals.DTMLFile('dtml/editedDialog', globals())
    134 -    def manage_editedDialog(self, REQUEST, **args):
    135          return apply(self._manage_editedDialog,(self, REQUEST), args)
    136
    137      """
    138      def raise_standardErrorMessage(
    139          self, client=None, REQUEST={},
    140          error_type=None, error_value=None, tb=None,
    141          error_tb=None, error_message='',
    142          tagSearch=re.compile(r'[a-zA-Z]>').search,
    143          error_log_url=''):
    144
    145          try:
    146              if error_type  is None: error_type =sys.exc_info()[0]
    147              if error_value is None: error_value=sys.exc_info()[1]
    148
    149              # allow for a few different traceback options
    150              if tb is None and error_tb is None:
    151                  tb=sys.exc_info()[2]
    152              if type(tb) is not type('') and (error_tb is None):
    153                  error_tb = pretty_tb(error_type, error_value, tb)
    154              elif type(tb) is type('') and not error_tb:
    155                  error_tb = tb
    156
    157              # turn error_type into a string
    158              if hasattr(error_type, '__name__'):
    159                  error_type=error_type.__name__
    160
    161              if hasattr(self, '_v_eek'):
    162                  # Stop if there is recursion.
    163                  raise error_type, error_value, tb
    164              self._v_eek=1
    165
    166              if str(error_type).lower() in ('redirect',):
    167                  raise error_type, error_value, tb
    168
    169              if not error_message:
    170                  try:
    171                      s = ustr(error_value)
    172                  except:
    173                      s = error_value
    174                  try:
    175                      match = tagSearch(s)
    176                  except TypeError:
    177                      match = None
    178                  if match is not None:
    179                      error_message=error_value
    180
    181              if client is None: client=self
    182              if not REQUEST: REQUEST=self.aq_acquire('REQUEST')
    183
    184              try:
    185                  if hasattr(client, 'standard_error_message'):
    186                      s=client.standard_error_message
    187                  else:
    188                      client = client.aq_parent
    189                      s=client.standard_error_message
    190                  kwargs = {'error_type': error_type,
    191                            'error_value': error_value,
    192                            'error_tb': error_tb,
    193                            'error_traceback': error_tb,
    194                            'error_message': error_message,
    195                            'error_log_url': error_log_url}
    196
    197                  if getattr(aq_base(s),'isDocTemp',0):
    198                      v = s(client, REQUEST, **kwargs)
    199                  elif callable(s):
    200                      v = s(**kwargs)
    201                  else:
    202                      __pychecker__='self="s"'
    203                      v = HTML.__call__(s, client, REQUEST, **kwargs)
    204              except:
    205                  logger.error(
    206                      'Exception while rendering an error message',
    207                      exc_info=True
    208                      )
    209                  try:
    210                      strv = str(error_value)
    211                  except:
    212                      strv = ('<unprintable %s object>' %
    213                              str(type(error_value).__name__))
    214                  v = strv + (
    215                      (" (Also, the following error occurred while attempting "
    216                       "to render the standard error message, please see the "
    217                       "event log for full details: %s)")%(
    218                      html_quote(sys.exc_info()[1]),
    219                      ))
    220              raise error_type, v, tb
    221          finally:
    222              if hasattr(self, '_v_eek'): del self._v_eek
    223              tb=None
    224      """
    225
    226 -    def manage(self, URL1):
    227          """
    228          """
    229          raise Redirect, "%s/manage_main" % URL1
    230
    231      # This keeps simple items from acquiring their parents
    232      # objectValues, etc., when used in simple tree tags.
    233 -    def objectValues(self, spec=None):
    234          unused(spec)
    235          return ()
    236      objectIds=objectItems=objectValues
    237
    238      # FTP support methods
    239
    240 -    def manage_FTPstat(self,REQUEST):
    241          """Psuedo stat, used by FTP for directory listings.
    242          """
    243          from AccessControl.User import nobody
    244          mode=0100000
    245
    246          if (hasattr(aq_base(self),'manage_FTPget')):
    247              try:
    248                  if getSecurityManager().validate(
    249                      None, self, 'manage_FTPget', self.manage_FTPget):
    250                      mode=mode | 0440
    251              except Unauthorized:
    252                  pass
    253
    254              if nobody.allowed(
    255                  self.manage_FTPget,
    256                  getRoles(self, 'manage_FTPget', self.manage_FTPget, ()),
    257                  ):
    258                  mode=mode | 0004
    259
    260          # check write permissions
    261          if hasattr(aq_base(self),'PUT'):
    262              try:
    263                  if getSecurityManager().validate(None, self, 'PUT', self.PUT):
    264                      mode=mode | 0220
    265              except Unauthorized:
    266                  pass
    267
    268              if nobody.allowed(
    269                  self.PUT,
    270                  getRoles(self, 'PUT', self.PUT, ()),
    271                  ):
    272                  mode=mode | 0002
    273
    274          # get size
    275          if hasattr(aq_base(self), 'get_size'):
    276              size=self.get_size()
    277          elif hasattr(aq_base(self),'manage_FTPget'):
    278              size=len(self.manage_FTPget())
    279          else:
    280              size=0
    281          # get modification time
    282          if hasattr(aq_base(self), 'bobobase_modification_time'):
    283              mtime=self.bobobase_modification_time().timeTime()
    284          else:
    285              mtime=time.time()
    286          # get owner and group
    287          owner=group='Zope'
    288          if hasattr(aq_base(self), 'get_local_roles'):
    289              for user, roles in self.get_local_roles():
    290                  if 'Owner' in roles:
    291                      owner=user
    292                      break
    293          return marshal.dumps((mode,0,0,1,owner,group,size,mtime,mtime,mtime))
    294
    295 -    def manage_FTPlist(self,REQUEST):
    296          """Directory listing for FTP.
    297
    298          In the case of non-Foldoid objects, the listing should contain one
    299          object, the object itself.
    300          """
    301          # check to see if we are being acquiring or not
    302          ob=self
    303          while 1:
    304              if App.Common.is_acquired(ob):
    305                  raise ValueError('FTP List not supported on acquired objects')
    306              if not hasattr(ob,'aq_parent'):
    307                  break
    308              ob=ob.aq_parent
    309
    310          stat=marshal.loads(self.manage_FTPstat(REQUEST))
    311          id = self.getId()
    312          return marshal.dumps((id,stat))
    313
    314 -    def __len__(self):
    315          return 1
    316
    317 -    def __repr__(self):
    318          """Show the physical path of the object and its context if available.
    319          """
    320          try:
    321              path = '/'.join(self.getPhysicalPath())
    322          except:
    323              return Base.__repr__(self)
    324          context_path = None
    325          context = aq_parent(self)
    326          container = aq_parent(aq_inner(self))
    327          if aq_base(context) is not aq_base(container):
    328              try:
    329                  context_path = '/'.join(context.getPhysicalPath())
    330              except:
    331                  context_path = None
    332          res = '<%s' % self.__class__.__name__
    333          res += ' at %s' % path
    334          if context_path:
    335              res += ' used for %s' % context_path
    336          res += '>'
    337          return res
    338
    339 -def pretty_tb(t, v, tb, as_html=1):
    340      tb = format_exception(t, v, tb, as_html=as_html)
    341      tb = '\n'.join(tb)
    342      return tb
    343
    344  #from OFS.SimpleItem import SimpleItem
    345  #ZItem = SimpleItem
    346