Exemplo n.º 1
0
    def _addFileFromRequest(self,REQUEST,log=''):
        """Add and link a new File or Image object, depending on file's filename
        suffix. Returns a tuple containing the new id, content type &
        size, or (None,None,None).
        """
        # ensure we have a suitable file, id and title
        file, title = REQUEST.file, str(REQUEST.get('title',''))
        id, title = OFS.Image.cookId('', title, file)
        if not id: return None
        folder = self.uploadFolder()
        try: checkValidId(folder,id,allow_dup=1)
        except BadRequest:
            id, ext = os.path.splitext(id)
            id = self.canonicalIdFrom(id)
            id = id + ext
        # create the file or image object, unless it already exists
        # XXX should use CMF/Plone content types when appropriate
        if not (self.folderContains(folder,id) and
                folder[id].meta_type in ('File','Image')): #'Portal File','Portal Image')):
            if guess_content_type(file.filename)[0][0:5] == 'image':
#                 if self.inCMF():
#                     #from Products.ATContentTypes import ATFile, ATImage
#                     #folder.create(ATImage) ...
#                 else:
                id = folder._setObject(id, OFS.Image.Image(id,title,''))
            else:
#                 if self.inCMF():
#                 else:
                id = folder._setObject(id, OFS.Image.File(id,title,''))
        # adding the data after creation is more efficient, reportedly
        ob = folder._getOb(id)
        ob.manage_upload(file)
        # and link/inline it
        self._addFileOrImageToPage(id,ob.content_type,ob.getSize(),log,REQUEST)
        return id
Exemplo n.º 2
0
 def addClass(self, contextUid, id):
     context = self._getObject(contextUid)
     _class = self._classFactory(contextUid)(id)
     relationship = getattr(context, self._classRelationship)
     checkValidId(relationship, id)
     relationship._setObject(id, _class)
     return '%s/%s/%s' % (contextUid, self._classRelationship, id)
Exemplo n.º 3
0
 def utValidateId(self, p_id=''):
     """."""
     try:
         checkValidId(self, p_id)
     except Exception, error:
         if str(error) != "('Empty or invalid id specified', '')":
             return [str(error)]
Exemplo n.º 4
0
 def utValidateId(self, p_id=''):
     """."""
     try:
         checkValidId(self, p_id)
     except Exception, error:
         if str(error) != "('Empty or invalid id specified', '')":
             return [str(error)]
Exemplo n.º 5
0
 def addClass(self, contextUid, id):
     context = self._getObject(contextUid)
     _class = self._classFactory(contextUid)(id)
     relationship = getattr(context, self._classRelationship)
     checkValidId(relationship, id)
     relationship._setObject(id, _class)
     return '%s/%s/%s' % (contextUid, self._classRelationship, id)
    def process(self, device, results, log):
        # data format expected in results
        # DisplayName=Software1;InstallDate=19700101;Vendor=Microsoft Corporation|
        # DisplayName=Software2;InstallDate=19700102;Vendor=Microsoft Corporation|
        log.info(
            "Modeler %s processing data for device %s",
            self.name(), device.id)

        rm = self.relMap()

        software_results = results.get('software')
        if not software_results:
            return rm

        software_results = ''.join(software_results.stdout).split('|')

        # Registry Software formatting
        for sw in software_results:
            softwareDict = {}
            for keyvalues in sw.split(';'):
                try:
                    key, value = keyvalues.split('=')
                except ValueError:
                    continue
                value = str(value.strip())
                try:
                    if key == "Vendor":
                        checkValidId(None, value, allow_dup=False)
                except BadRequest:
                    value = str()
                softwareDict[key] = value

            keys = ['DisplayName', 'Vendor', 'InstallDate']
            # malformed data line
            if set(keys).difference(set(softwareDict.keys())):
                continue
            # skip over empty entries
            if softwareDict['DisplayName'] == '':
                continue
            om = self.objectMap()
            om.id = self.eliminate_underscores(self.prepId(softwareDict['DisplayName'])).strip()
            vendor = softwareDict['Vendor'].strip() if softwareDict['Vendor'].strip() != '' else 'Unknown'

            om.setProductKey = MultiArgs(om.id, vendor)

            if any(om.setProductKey.args == x.setProductKey.args for x in rm.maps):
                # https://jira.zenoss.com/browse/ZPS-1245
                # Do not report duplicate software, even if Windows reports it
                continue

            try:
                installDate = DateTime(softwareDict['InstallDate'])
                om.setInstallDate = '{0} 00:00:00'.format(installDate.Date())
            except (SyntaxError, TimeError):
                # Date is unreadable or empty, ok to leave blank
                pass
            rm.append(om)

        return rm
def id(form, name, container):
    id = form.request.get(name, '').strip()
    putils = getToolByName(form.context, 'plone_utils')
    id = generate_id(putils.normalizeString(id), container.objectIds())
    try:
        checkValidId(container, id)
    except:
        form.errors[name] = _(u'Invalid workflow name. Please try another.')
    return id
Exemplo n.º 8
0
 def _check_id(self, id, container):
     if container.check_id(id, 1, container) is not None:
         return False
     try:
         checkValidId(container, id)
         return True
     except:
         pass
     return False
Exemplo n.º 9
0
 def checkValidId(self, id):
     """
     Is this a valid id for this container?
     """
     try:
         checkValidId(self, id)
     except:
         raise
     else:
         return True
Exemplo n.º 10
0
 def checkValidId(self, id):
     """
     Is this a valid id for this container?
     """
     try:
         checkValidId(self, id)
     except:
         raise
     else:
         return True
Exemplo n.º 11
0
    def process(self, device, results, log):
        # data format expected in results
        # DisplayName=Software1;InstallDate=19700101;Vendor=Microsoft Corporation|
        # DisplayName=Software2;InstallDate=19700102;Vendor=Microsoft Corporation|
        log.info("Modeler %s processing data for device %s", self.name(),
                 device.id)

        rm = self.relMap()

        software_results = results.get('software')
        if not software_results:
            return rm

        software_results = ''.join(software_results.stdout).split('|')

        # Registry Software formatting
        for sw in software_results:
            softwareDict = {}
            for keyvalues in sw.split(';'):
                try:
                    key, value = keyvalues.split('=')
                except ValueError:
                    continue
                try:
                    if key == "Vendor":
                        checkValidId(None, value, allow_dup=False)
                except BadRequest:
                    value = str()
                softwareDict[key] = value

            keys = ['DisplayName', 'Vendor', 'InstallDate']
            # malformed data line
            if set(keys).difference(set(softwareDict.keys())):
                continue
            # skip over empty entries
            if softwareDict['DisplayName'] == '':
                continue
            om = self.objectMap()
            om.id = self.eliminate_underscores(
                self.prepId(softwareDict['DisplayName'])).strip()
            vendor = softwareDict['Vendor'].strip(
            ) if softwareDict['Vendor'].strip() != '' else 'Unknown'

            om.setProductKey = MultiArgs(om.id, vendor)

            try:
                installDate = DateTime(softwareDict['InstallDate'])
                om.setInstallDate = '{0} 00:00:00'.format(installDate.Date())
            except (SyntaxError, TimeError):
                # Date is unreadable or empty, ok to leave blank
                pass
            rm.append(om)

        return rm
def id(form, name, container):
    elt_id = form.request.get(name, '').strip()
    putils = getToolByName(form.context, 'plone_utils')
    elt_id = generate_id(putils.normalizeString(unicode(elt_id, encoding='utf-8')),
                         container.objectIds())
    try:
        checkValidId(container, elt_id)
    except:
        form.errors[name] = translate(_(u'Invalid name. Please try another.'),
                                      context=form.request)

    return elt_id
Exemplo n.º 13
0
 def valid_id(self, container, id):
     if id in ('path', 'id', 'start'):
         return False
     try:
         checkValidId(container, id, False)
         obj = getattr(self, id, None)
         if obj is not None:
             if id not in container.objectIds():
                 return False
     except Exception:
         return False
     return True
Exemplo n.º 14
0
def id(form, name, container):
    elt_id = form.request.get(name, '').strip()
    putils = getToolByName(form.context, 'plone_utils')
    elt_id = generate_id(
        putils.normalizeString(unicode(elt_id, encoding='utf-8')),
        container.objectIds())
    try:
        checkValidId(container, elt_id)
    except:
        form.errors[name] = translate(_(u'Invalid name. Please try another.'),
                                      context=form.request)

    return elt_id
Exemplo n.º 15
0
 def _create_id(self, container, subinst):
         id = startid = queryUtility(IIDNormalizer).normalize(getattr(subinst, 'title', 'subcontent'))
         id = startid = id and id or 'subcontent'
         ok = False
         counter = 0
         while(not ok):
             try:
                 checkValidId(container, id)
                 ok = True
             except BadRequest:
                 counter += 1
                 id = '%s_%s' % (startid,counter)
         return id
Exemplo n.º 16
0
 def getId(self, context):
     id = normalizeString(self.id, context)
     if context.check_id(id, 1, context) is None:
         try:
             checkValidId(context, id)
             return id
         except:
             pass
     new_id = id + '-%s'
     i = 1
     while not context.check_id(new_id % i, 1, context) is None:
         i += 1
     return new_id % i
Exemplo n.º 17
0
 def _add(self, obj):
     """add an object to one side of a ToManyContRelationship.
     """
     id = obj.id
     if self._objects.has_key(id):
         raise RelationshipExistsError
     v = checkValidId(self, id)
     if v is not None: id = v
     self._objects[id] = aq_base(obj)
     obj = aq_base(obj).__of__(self)
Exemplo n.º 18
0
 def _add(self,obj):
     """add an object to one side of a ToManyContRelationship.
     """
     id = obj.id
     if self._objects.has_key(id):
         raise RelationshipExistsError
     v=checkValidId(self, id)
     if v is not None: id=v
     self._objects[id] = aq_base(obj)
     obj = aq_base(obj).__of__(self)
Exemplo n.º 19
0
 def checkName(self, identifier, content, file=None, interface=None):
     try:
         checkValidId(self.container, str(identifier))
     except BadRequest as error:
         raise ContentError(error.args[0], self.container)
     return True
Exemplo n.º 20
0
    def _validate(self):
        """ test if the given id is valid, returning a status code
            about its validity or reason of invalidity
        """
        folder = self._context
        maybe_id = self._maybe_id
        allow_dup = self._allow_dup
        if self._valid_id.match(maybe_id) is None:
            return self.CONTAINS_BAD_CHARS
        if maybe_id.endswith('__'):
            # ugly, but Zope explicitely checks this ...
            return self.RESERVED_POSTFIX
        prefixing = maybe_id.split('_')
        if (len(prefixing) > 1) and (prefixing[0] in self._reserved_prefixes):
            return self.RESERVED_PREFIX

        if maybe_id in self._reserved_ids:
            return self.RESERVED

        if self._interface is not None:
            for interface, prefixes in \
                    list(self._reserved_ids_for_interface.items()):
                if self._interface.isOrExtends(interface):
                    if maybe_id in prefixes:
                        return self.RESERVED_FOR_CONTENT

        attr = getattr(aq_inner(folder), maybe_id, _marker)
        if attr is not _marker:
            if ISilvaObject.providedBy(attr):
                # there is a silva object with the same id
                if allow_dup: return self.OK
                attr = getattr(folder.aq_base, maybe_id, _marker)
                if attr is _marker:
                    # shadowing a content object is ok (hopefully)
                    return self.OK
                if IAsset.providedBy(attr):
                    return self.IN_USE_ASSET
                # else it must be a content object (?)
                return self.IN_USE_CONTENT

            # check if object with this id is acquired; if not, it cannot be
            # allowed
            attr2 = getattr(folder.aq_base, maybe_id, _marker)
            if attr2 is not _marker:
                #either it is an attribute/method (self.RESERVED)
                #or it is an object within the container (self.IN_USE_ZOPE)
                if maybe_id in folder.objectIds():
                    return self.IN_USE_ZOPE
                else:
                    return self.RESERVED

            # object using wanted id is acquried
            # now it may be a Zope object, which is allowed (for now)
            # or it is an attribute (which is disallowed)
            if not hasattr(attr, 'meta_type'):
                # not a zope object (guessing ...)
                return self.RESERVED
        try:
            # Call Zope verification function
            checkValidId(folder, str(maybe_id), allow_dup)
        except BadRequest:
            return self.CONTAINS_BAD_CHARS

        return self.OK
Exemplo n.º 21
0
    def _validate(self):
        """ test if the given id is valid, returning a status code
            about its validity or reason of invalidity
        """
        folder = self._context
        maybe_id = self._maybe_id
        allow_dup = self._allow_dup
        if self._valid_id.match(maybe_id) is None:
            return self.CONTAINS_BAD_CHARS
        if maybe_id.endswith('__'):
            # ugly, but Zope explicitely checks this ...
            return self.RESERVED_POSTFIX
        prefixing = maybe_id.split('_')
        if (len(prefixing) >1) and (prefixing[0] in self._reserved_prefixes):
            return self.RESERVED_PREFIX

        if maybe_id in self._reserved_ids:
            return self.RESERVED

        if self._interface is not None:
            for interface, prefixes in \
                    self._reserved_ids_for_interface.items():
                if self._interface.isOrExtends(interface):
                    if maybe_id in prefixes:
                        return self.RESERVED_FOR_CONTENT

        attr = getattr(aq_inner(folder), maybe_id, _marker)
        if attr is not _marker:
            if ISilvaObject.providedBy(attr):
                # there is a silva object with the same id
                if allow_dup: return self.OK
                attr = getattr(folder.aq_base, maybe_id, _marker)
                if attr is _marker:
                    # shadowing a content object is ok (hopefully)
                    return self.OK
                if IAsset.providedBy(attr):
                    return self.IN_USE_ASSET
                # else it must be a content object (?)
                return self.IN_USE_CONTENT

            # check if object with this id is acquired; if not, it cannot be
            # allowed
            attr2 = getattr(folder.aq_base, maybe_id, _marker)
            if attr2 is not _marker:
                #either it is an attribute/method (self.RESERVED)
                #or it is an object within the container (self.IN_USE_ZOPE)
                if maybe_id in folder.objectIds():
                    return self.IN_USE_ZOPE
                else:
                    return self.RESERVED

            # object using wanted id is acquried
            # now it may be a Zope object, which is allowed (for now)
            # or it is an attribute (which is disallowed)
            if not hasattr(attr, 'meta_type'):
                # not a zope object (guessing ...)
                return self.RESERVED
        try:
            # Call Zope verification function
            checkValidId(folder, str(maybe_id), allow_dup)
        except BadRequest:
            return self.CONTAINS_BAD_CHARS

        return self.OK
Exemplo n.º 22
0
 def checkName(self, identifier, content, file=None, interface=None):
     try:
         checkValidId(self.container, str(identifier))
     except BadRequest as error:
         raise ContentError(error.args[0], self.container)
     return True
Exemplo n.º 23
0
 def _checkId(self, new_id):
     """This method gets called from the new manage_renameObject which
     seems to be a bug in the Zope code. We add it until the problem is
     fixed.
     """
     checkValidId(self, new_id)
Exemplo n.º 24
0
 def _callFUT(self, container, id, allow_dup=_marker):
     from OFS.ObjectManager import checkValidId
     if allow_dup is _marker:
         return checkValidId(container, id)
     return checkValidId(container, id, allow_dup)
Exemplo n.º 25
0
 def _callFUT(self, container, id, allow_dup=_marker):
     from OFS.ObjectManager import checkValidId
     if allow_dup is _marker:
         return checkValidId(container, id)
     return checkValidId(container, id, allow_dup)
Exemplo n.º 26
0
 def _checkId(self, new_id):
     """This method gets called from the new manage_renameObject which
     seems to be a bug in the Zope code. We add it until the problem is
     fixed.
     """
     checkValidId(self, new_id)