コード例 #1
0
    def getSetter(self, obj, indexName):
        """Gets the setter function for the field based on the index name.

        Returns None if it can't get the function
        """
        fieldName = self.fieldNameForIndex(indexName)
        field = None
        if IComment.providedBy(obj):
            #Discussion
            field = getattr(obj, 'getField', None)
        else:
            #Archetype
            field = getattr(aq_base(obj), 'getField', None)
        # Archetypes:
        if field:
            fieldObj = field(fieldName) or field(fieldName.lower())
            if not fieldObj and fieldName.startswith('get'):
                fieldName = fieldName.lstrip('get_')
                fieldName = fieldName[0].lower() + fieldName[1:]
                fieldObj = obj.getField(fieldName)
            if fieldObj is not None:
                return fieldObj.getMutator(obj)
            return None
        # DefaultDublinCoreImpl:
        setterName = 'set' + indexName
        if getattr(aq_base(obj), setterName, None) is not None:
            return getattr(obj, setterName)
        # Dexterity
        if IDexterityContent.providedBy(obj):
            if fieldName.startswith('get'):
                fieldName = fieldName.lstrip('get_')
                fieldName = fieldName[0].lower() + fieldName[1:]
            return lambda value: setattr(obj, fieldName, value)

        return None
コード例 #2
0
ファイル: test_resolver.py プロジェクト: upiq/uu.retrieval
 def test_mock_UID_index(self):
     mock = self._content(id='mock3', items=ALL_ITEMS)
     uid = IUUID(mock)
     r = self.catalog.unrestrictedSearchResults({'UID': uid})
     assert len(r) > 0
     o = r[0]._unrestrictedGetObject()
     assert aq_base(o) is aq_base(mock)
コード例 #3
0
    def _getFieldValues(self, obj):
        """Finds the specified field values and returns them if
        they contain file objects which are too large.  Specifically,
        it returns an iterator of tuples containing the type of storage,
        the field name, and the value stored"""
        max_size  = self.max_size

        # Search for fields stored via AnnotationStorage
        annotations = getattr(obj, '__annotations__', None)
        if annotations is not None:
            annotation_names = (ANNOTATION_PREFIX + name for name in
                                                              self.field_names)
            for name in annotation_names:
                val = annotations.get(name, None)
                # Skip linked Pdata chains too long for the pickler
                if hasattr(aq_base(val), 'getSize') and callable(val.getSize):
                    try:
                        size = val.getSize()
                    except (TypeError,AttributeError):
                        size = None
                    if isinstance(size, (int, long)) and size >= max_size:
                        yield 'annotation', name, val

        # Search for fields stored via AttributeStorage
        for name in self.field_names:
            val = getattr(obj, name, None)
            # Skip linked Pdata chains too long for the pickler
            if hasattr(aq_base(val), 'getSize') and callable(val.getSize):
                size = val.getSize()
                if isinstance(size, (int, long)) and size >= max_size:
                    yield 'attribute', name, val
コード例 #4
0
    def computeDiff(self, ob1, ob2, id1=None, id2=None):
        """Compute the differences between two objects and return the
        results as a list.  Each object in the list will implement the
        IDifference interface"""

        # Try to get the portal type from obj1 first.  If that fails, use obj2
        pt_name = ''
        try:
            pt_name = aq_base(ob1).portal_type
        except AttributeError:
            try:
                pt_name = aq_base(ob2).portal_type
            except AttributeError:
                pass

        diff_map = self._pt_diffs.get(pt_name, {})

        diffs = []
        for field, klass_name in diff_map.items():
            klass = self._difftypes[klass_name]
            f_diff = klass(ob1, ob2, field, id1=id1, id2=id2)
            # handle compound diff types
            if hasattr(f_diff, '__getitem__'):
                diffs.extend(f_diff)
            else:
                diffs.append(f_diff)
        return diffs
コード例 #5
0
ファイル: test_PortalContent.py プロジェクト: goschtl/zope
    def test_CopyPasteSetsOwnership(self):
        # Copy/pasting a File should set new ownership including local roles
        from OFS.Folder import Folder

        acl_users = self.acl_users
        folder1 = self.site._setObject('folder1', Folder('folder1'))
        folder2 = self.site._setObject('folder2', Folder('folder2'))

        newSecurityManager(None, acl_users.user_foo)
        content = self._initContent(folder1, 'content')
        content.manage_setLocalRoles(acl_users.user_foo.getId(), ['Owner'])

        newSecurityManager(None, acl_users.all_powerful_Oz)
        cb = folder1.manage_copyObjects(['content'])
        folder2.manage_pasteObjects(cb)

        # Now test executable ownership and "owner" local role
        # "member" should have both.
        moved = folder2._getOb('content')
        self.assertEqual(aq_base(moved.getOwner()),
                         aq_base(acl_users.all_powerful_Oz))

        local_roles = moved.get_local_roles()
        self.assertEqual(len(local_roles), 1)
        userid, roles = local_roles[0]
        self.assertEqual(userid, acl_users.all_powerful_Oz.getId())
        self.assertEqual(len(roles), 1)
        self.assertEqual(roles[0], 'Owner')
コード例 #6
0
ファイル: test_components.py プロジェクト: goschtl/zope
    def _verifyImport(self, obj):
        util = queryUtility(IDummyInterface, name=u'foo')
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())

        util = queryUtility(IDummyInterface)
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())

        util = queryUtility(IDummyInterface, name='dummy tool name')
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())
        self.assertEqual(util.meta_type, 'dummy tool')

        # make sure we can get the tool by normal means
        tool = getattr(self.app, 'dummy_tool')
        self.assertEqual(tool.meta_type, 'dummy tool')
        self.assertEquals(repr(aq_base(util)), repr(aq_base(tool)))

        util = queryUtility(IDummyInterface, name='dummy tool name2')
        self.failUnless(IDummyInterface.providedBy(util))
        self.failUnless(util.verify())
        self.assertEqual(util.meta_type, 'dummy tool2')

        # make sure we can get the tool by normal means
        tool = getattr(self.folder, 'dummy_tool2')
        self.assertEqual(tool.meta_type, 'dummy tool2')
        self.assertEquals(repr(aq_base(util)), repr(aq_base(tool)))
コード例 #7
0
ファイル: CMFCatalogAware.py プロジェクト: c0ns0le/zenoss-4
    def opaqueItems(self):
        """
            Return opaque items (subelements that are contained
            using something that is not an ObjectManager).
        """
        items = []

        # Call 'talkback' knowing that it is an opaque item.
        # This will remain here as long as the discussion item does
        # not implement ICallableOpaqueItem (backwards compatibility).
        if hasattr(aq_base(self), 'talkback'):
            talkback = self.talkback
            if talkback is not None:
                items.append((talkback.id, talkback))

        # Other opaque items than 'talkback' may have callable
        # manage_after* and manage_before* hooks.
        # Loop over all attributes and add those to 'items'
        # implementing 'ICallableOpaqueItem'.
        self_base = aq_base(self)
        for name in self_base.__dict__.keys():
            obj = getattr(self, name)
            if ICallableOpaqueItem.providedBy(obj):
                items.append((obj.getId(), obj))

        return tuple(items)
コード例 #8
0
    def __iter__(self):
        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]
            propertieskey = self.propertieskey(*item.keys())[0]

            if not pathkey or not propertieskey or \
               propertieskey not in item:   # not enough info
                yield item; continue

            obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None)
            if obj is None:                 # path doesn't exist
                yield item; continue

            if IBaseObject.providedBy(obj):
                if getattr(aq_base(obj), '_delProperty', False):
                    for prop in item[propertieskey]:
                        if getattr(aq_base(obj), prop[0], None) is not None:
                            # if object have a attribute equal to property, do nothing
                            continue
                        try:
                            if obj.hasProperty(prop[0]):
                                obj._updateProperty(prop[0], prop[1])
                            else:
                                obj._setProperty(prop[0], prop[1], prop[2])
                        except ConflictError:
                            raise
                        except Exception, e:
                            raise Exception('Failed to set property %s type %s to %s at object %s. ERROR: %s' % \
                                                        (prop[0], prop[1], prop[2], str(obj), str(e)))

            yield item
コード例 #9
0
ファイル: TypesTool.py プロジェクト: c0ns0le/zenoss-4
 def getTypeInfo( self, contentType ):
     """
         Return an instance which implements the
         TypeInformation interface, corresponding to
         the specified 'contentType'.  If contentType is actually
         an object, rather than a string, attempt to look up
         the appropriate type info using its portal_type.
     """
     if not isinstance(contentType, basestring):
         if hasattr(aq_base(contentType), 'getPortalTypeName'):
             contentType = contentType.getPortalTypeName()
             if contentType is None:
                 return None
         else:
             return None
     ob = getattr( self, contentType, None )
     if ITypeInformation.providedBy(ob):
         return ob
     if getattr(aq_base(ob), '_isTypeInformation', 0):
         # BBB
         warn("The '_isTypeInformation' marker attribute is deprecated, "
              "and will be removed in CMF 2.3.  Please mark the instance "
              "with the 'ITypeInformation' interface instead.",
              DeprecationWarning, stacklevel=2)
         return ob
     else:
         return None
コード例 #10
0
    def getProperty(self, id, default=None):
        """PAS-specific method to fetch a group's properties. Looks
        through the ordered property sheets.
        """
        group = self.getGroup()
        sheets = getattr(group, 'getOrderedPropertySheets', lambda: [])()

        # If we made this far, we found a PAS and some property sheets.
        for sheet in sheets:
            if sheet.hasProperty(id):
                # Return the first one that has the property.
                return sheet.getProperty(id)
        # we won't always have PlonePAS groups, due to acquisition,
        # nor are guaranteed property sheets
        # Couldn't find the property in the property sheets. Try to
        # delegate back to the base implementation.

        tool = self.getTool()
        base = aq_base( self )

        # Then, check the user object, the tool, and attrs of myself for a
        # value:
        user_value = getattr( aq_base(self.getGroup()), id, _marker )
        tool_value = tool.getProperty( id, _marker )
        value = getattr( base, id, _marker )
        
        # Take the first of the above that is filled out:
        for v in [user_value, tool_value, value]:
            if v is not _marker:
                return v
        
        return default
コード例 #11
0
ファイル: WorkflowTool.py プロジェクト: goschtl/zope
    def _recursiveUpdateRoleMappings(self, ob, wfs):

        """ Update roles-permission mappings recursively, and
            reindex special index.
        """
        # Returns a count of updated objects.
        count = 0
        wf_ids = self.getChainFor(ob)
        if wf_ids:
            changed = 0
            for wf_id in wf_ids:
                wf = wfs.get(wf_id, None)
                if wf is not None:
                    did = wf.updateRoleMappingsFor(ob)
                    if did:
                        changed = 1
            if changed:
                count = count + 1
                if hasattr(aq_base(ob), 'reindexObject'):
                    # Reindex security-related indexes
                    try:
                        ob.reindexObject(idxs=['allowedRolesAndUsers'])
                    except TypeError:
                        # Catch attempts to reindex portal_catalog.
                        pass
        if hasattr(aq_base(ob), 'objectItems'):
            obs = ob.objectItems()
            if obs:
                for k, v in obs:
                    changed = getattr(v, '_p_changed', 0)
                    count = count + self._recursiveUpdateRoleMappings(v, wfs)
                    if changed is None:
                        # Re-ghostify.
                        v._p_deactivate()
        return count
コード例 #12
0
ファイル: Resource.py プロジェクト: nacho22martin/tesis
    def HEAD(self, REQUEST, RESPONSE):
        """Retrieve resource information without a response body."""
        self.dav__init(REQUEST, RESPONSE)

        content_type=None
        if hasattr(self, 'content_type'):
            content_type=absattr(self.content_type)
        if content_type is None:
            url=urlfix(REQUEST['URL'], 'HEAD')
            name=unquote(filter(None, url.split( '/')[-1]))
            content_type, encoding=mimetypes.guess_type(name)
        if content_type is None:
            if hasattr(self, 'default_content_type'):
                content_type=absattr(self.default_content_type)
        if content_type is None:
            content_type = 'application/octet-stream'
        RESPONSE.setHeader('Content-Type', content_type.lower())

        if hasattr(aq_base(self), 'get_size'):
            RESPONSE.setHeader('Content-Length', absattr(self.get_size))
        if hasattr(self, '_p_mtime'):
            mtime=rfc1123_date(self._p_mtime)
            RESPONSE.setHeader('Last-Modified', mtime)
        if hasattr(aq_base(self), 'http__etag'):
            etag = self.http__etag(readonly=1)
            if etag:
                RESPONSE.setHeader('Etag', etag)
        RESPONSE.setStatus(200)
        return RESPONSE
コード例 #13
0
def change_styled_page_class_to_custom_class(context, logger=None):
    """Method to get all styled pages and change their class from Dexterity's
    default to a customized version.
    """

    logger = _get_logger(logger)
    catalog = getToolByName(context, 'portal_catalog')
    results = catalog(portal_type='tn.plonestyledpage.styled_page')

    for brain in results:
        obj = brain.getObject()
        if isinstance(obj, Item) and not isinstance(obj, StyledPage):
            container = aq_parent(obj)

            id = obj.getId()
            path = brain.getPath()
            base = aq_base(obj)

            container._delObject(id)
            aq_base(obj).__class__ = StyledPage
            container._setObject(id, base)
            logger.info('Changed class of %s' % path)

    setup = getToolByName(context, 'portal_setup')
    setup.runImportStepFromProfile('profile-plone.app.intid:default',
                                   'intid-register-content')
コード例 #14
0
ファイル: IdValidator.py プロジェクト: CGTIC/Plone_SP
    def __call__(self, id, instance, *args, **kwargs):
        try:
            # try to use the check_id script of CMFPlone
            check_id = aq_get(instance, 'check_id', None, 1)
            if check_id is None:
                raise AttributeError('check_id script not found')
            return check_id(id, required=kwargs.get('required', 0)) or 1
        except AttributeError:
            # space test
            if ' ' in id:
                msg =  _(u'Spaces are not allowed in ids')
                return recursiveTranslate(msg, **kwargs)

            # in parent test
            parent = aq_parent(aq_inner(instance))
            # If the id is given to a different object already
            if id in parent.objectIds() and getattr(aq_base(parent), id) is not aq_base(instance):
                msg = _(u'Id $id is already in use',
                        mapping = {'id': safe_unicode(id)})
                return recursiveTranslate(msg, **kwargs)

            # objet manager test
            # XXX: This is f***ed
            try:
                ObjectManager.checkValidId(self, id, allow_dup=1)
            except BadRequest, m:
                return str(m)
            return 1
コード例 #15
0
ファイル: DiscussionItem.py プロジェクト: goschtl/zope
 def manage_beforeDelete(self, item, container):
     """
         Remove the contained items from the catalog.
     """
     if aq_base(container) is not aq_base(self):
         for obj in self.objectValues():
             obj.__of__( self ).manage_beforeDelete( item, container )
コード例 #16
0
ファイル: StagingTool.py プロジェクト: goschtl/zope
    def _updateReferences(self, proxy, container_map, to_stages):
        """Internal: creates and updates references.
        """
        # Note that version control is not used when staging
        # reference objects.
        ref = getProxyReference(proxy)
        object_map = self._getObjectStages(proxy)
        ref_id = ref.getId()
        for stage_name, ob in object_map.items():
            if stage_name in to_stages:
                if ob is not None:
                    # There is an object at the reference target.
                    if type(aq_base(ob)) is not type(aq_base(proxy)):
                        p = '/'.join(ob.getPhysicalPath())
                        raise StagingError(
                            'The object "%s", which is not a reference, '
                            'is in the way.' % p)
                    # Delete the reference.
                    container = container_map[stage_name]
                    container._delObject(ref_id)

                # Copy the reference from the source stage.
                container = container_map.get(stage_name, None)
                if container is None:
                    # This can happen if a site doesn't yet exist on
                    # the stage.
                    p = '/'.join(proxy.getPhysicalPath())
                    raise StagingError(
                        'The container for "%s" does not exist on "%s"'
                        % (p, stage_name))
                # Duplicate the reference.
                ob = cloneByPickle(aq_base(ref))
                container._setObject(ob.getId(), ob)
コード例 #17
0
    def test_add_comment(self):
        # Create a conversation. In this case we doesn't assign it to an
        # object, as we just want to check the Conversation object API.
        conversation = IConversation(self.portal.doc1)

        # Add a comment. Note: in real life, we always create comments via the
        # factory to allow different factories to be swapped in

        comment = createObject('plone.Comment')
        comment.text = 'Comment text'

        new_id = conversation.addComment(comment)

        # Check that the conversation methods return the correct data
        self.assertTrue(isinstance(comment.comment_id, long))
        self.assertTrue(IComment.providedBy(conversation[new_id]))
        self.assertEqual(
            aq_base(conversation[new_id].__parent__),
            aq_base(conversation)
        )
        self.assertEqual(new_id, comment.comment_id)
        self.assertEqual(len(list(conversation.getComments())), 1)
        self.assertEqual(len(tuple(conversation.getThreads())), 1)
        self.assertEqual(conversation.total_comments(), 1)
        self.assertTrue(
            conversation.last_comment_date - datetime.utcnow() <
            timedelta(seconds=1)
        )
コード例 #18
0
ファイル: scaling.py プロジェクト: naro/plone.namedfile
 def create(self, fieldname, direction='thumbnail', height=None, width=None, **parameters):
     """ factory for image scales, see `IImageScaleStorage.scale` """
     orig_value = getattr(self.context, fieldname)
     if orig_value is None:
         return
     if height is None and width is None:
         _, format = orig_value.contentType.split('/', 1)
         return None, format, (orig_value._width, orig_value._height)
     if hasattr(aq_base(orig_value), 'open'):
         orig_data = orig_value.open()
     else:
         orig_data = getattr(aq_base(orig_value), 'data', orig_value)
     if not orig_data:
         return
     try:
         result = scaleImage(orig_data, direction=direction, height=height, width=width, **parameters)
     except (ConflictError, KeyboardInterrupt):
         raise
     except Exception:
         exception('could not scale "%r" of %r',
             orig_value, self.context.absolute_url())
         return
     if result is not None:
         data, format, dimensions = result
         mimetype = 'image/%s' % format.lower()
         value = orig_value.__class__(data, contentType=mimetype, filename=orig_value.filename)
         value.fieldname = fieldname
         return value, format, dimensions
コード例 #19
0
ファイル: ZCTextIndex.py プロジェクト: wpjunior/proled
    def getLexicon(self):
        """Get the lexicon for this index
        """
        if hasattr(aq_base(self), 'lexicon'):
            # Fix up old ZCTextIndexes by removing direct lexicon ref
            # and changing it to an ID
            lexicon = getattr(aq_parent(aq_inner(self)), self.lexicon.getId())
            self.lexicon_id = lexicon.getId()
            del self.lexicon

        if getattr(aq_base(self), 'lexicon_path', None):
            # Fix up slightly less old ZCTextIndexes by removing
            # the physical path and changing it to an ID.
            # There's no need to use a physical path, which otherwise
            # makes it difficult to move or rename ZCatalogs.
            self.lexicon_id = self.lexicon_path[-1]
            del self.lexicon_path

        try:
            return self._v_lexicon
        except AttributeError:
            lexicon = getattr(aq_parent(aq_inner(self)), self.lexicon_id)
            if not (ILexicon.providedBy(lexicon) or
                    z2ILexicon.isImplementedBy(lexicon)):
                raise TypeError('Object "%s" is not a ZCTextIndex Lexicon'
                                % repr(lexicon))
            self._v_lexicon = lexicon
            return lexicon
コード例 #20
0
    def test_hasUID(self):
        doc = makeContent(self.folder,
                          portal_type='DDocument',
                          title='Foo')

        self.assertTrue(hasattr(aq_base(doc), UUID_ATTR))
        self.assertTrue(getattr(aq_base(doc), UUID_ATTR, None))
コード例 #21
0
ファイル: ZenTableManager.py プロジェクト: c0ns0le/zenoss-4
    def sortObjects(self, objects, request):
        """Sort objects.
        """
        def dictAwareSort(objects, field, rule, sence):
            if not objects:
                return objects
            class Wrapper:
                def __init__(self, field, cargo):
                    if callable(field): field = field()
                    #make sorting case-insensitive 
                    if isinstance(field, basestring): field = field.lower()
                    self.field = field
                    self.cargo = cargo
            if isinstance(objects[0], dict):
                objects = [Wrapper(o.get(field, ''), o) for o in objects]
            else:
                objects = [Wrapper(getattr(o, field, ''), o) for o in objects]
            objects = sort(objects, (('field', rule, sence),))
            return [w.cargo for w in objects]

        if (getattr(aq_base(request), 'sortedHeader', False)
            and getattr(aq_base(request),"sortedSence", False)):
            sortedHeader = request.sortedHeader
            sortedSence = request.sortedSence
            sortRule = getattr(aq_base(request), "sortRule", "cmp")
            objects = dictAwareSort(objects, sortedHeader, sortRule, sortedSence)
        return objects
コード例 #22
0
ファイル: test_tool.py プロジェクト: dtgit/dtedu
    def test_required_tools_with_replacement( self ):

        from Products.GenericSetup.tool import TOOLSET_XML
        from Products.GenericSetup.tool import importToolset

        site = self._initSite()

        mandatory = AnotherDummyTool()
        mandatory._setId( 'mandatory' )
        site._setObject( 'mandatory', mandatory )

        obligatory = AnotherDummyTool()
        obligatory._setId( 'obligatory' )
        site._setObject( 'obligatory', obligatory )

        self.assertEqual( len( site.objectIds() ), 3 )

        context = DummyImportContext( site, tool=site.setup_tool )
        context._files[ TOOLSET_XML ] = _REQUIRED_TOOLSET_XML

        importToolset( context )

        self.assertEqual( len( site.objectIds() ), 3 )

        self.failIf( aq_base( site._getOb( 'mandatory' ) ) is mandatory )
        self.failUnless( isinstance( aq_base( site._getOb( 'mandatory' ) )
                                   , DummyTool ) )

        self.failIf( aq_base( site._getOb( 'obligatory' ) ) is obligatory )
        self.failUnless( isinstance( aq_base( site._getOb( 'obligatory' ) )
                                   , DummyTool ) )
コード例 #23
0
ファイル: test_tool.py プロジェクト: goschtl/zope
    def test_required_tools_no_replacement( self ):

        from Products.CMFSetup.tool import TOOLSET_XML
        from Products.CMFSetup.tool import importToolset

        site = self._initSite()

        mandatory = DummyTool()
        mandatory._setId( 'mandatory' )
        site._setObject( 'mandatory', mandatory )

        obligatory = DummyTool()
        obligatory._setId( 'obligatory' )
        site._setObject( 'obligatory', obligatory )

        self.assertEqual( len( site.objectIds() ), 3 )

        context = DummyImportContext( site )
        context._files[ TOOLSET_XML ] = _REQUIRED_TOOLSET_XML

        importToolset( context )

        self.assertEqual( len( site.objectIds() ), 3 )
        self.failUnless( aq_base( site._getOb( 'mandatory' ) ) is mandatory )
        self.failUnless( aq_base( site._getOb( 'obligatory' ) ) is obligatory )
コード例 #24
0
    def migrate_properties(self):
        """Migrates zope properties

        Removes the old (if exists) and adds a new
        """
        if not hasattr(aq_base(self.new), '_delProperty'):
            # no properties available
            return None

        for prop_d in self._properties:
            id = prop_d['id']
            value = prop_d['value']
            typ = prop_d['type']
            __traceback_info__ = (self.new, id, value, typ)
            if self.new.hasProperty(id):
                self.new._delProperty(id)

            # continue if the object already has this attribute
            if getattr(aq_base(self.new), id, _marker) is not _marker:
                continue
            try:
                self.new.manage_addProperty(id, value, typ)
            except ConflictError:
                raise
            except:
                LOG.error('Failed to set property %s type %s to %s '
                          'at object %s' % (id, typ, value, self.new),
                          exc_info=True)
コード例 #25
0
ファイル: setup.py プロジェクト: plone/Products.PloneTestCase
 def run(self):
     self.app = self._app()
     try:
         uf = self.app.acl_users
         if uf.getUserById(portal_owner) is None:
             # Add portal owner
             uf.userFolderAddUser(portal_owner, default_password,
                                  ['Manager'], [])
         if not hasattr(aq_base(self.app), self.id):
             # Add site
             self._login(uf, portal_owner)
             self._optimize()
             self._setupPackages()
             self._setupPloneSite()
             self._setupRegistries()
         if hasattr(aq_base(self.app), self.id):
             # Configure site
             self._login(uf, portal_owner)
             self._placefulSetUp()
             self._setupProfiles()
             self._setupProducts()
             # Pre-create default memberarea to speed up the tests
             if self.with_default_memberarea:
                 self._setupHomeFolder()
     finally:
         self._abort()
         self._placefulTearDown()
         self._close()
         self._logout()
コード例 #26
0
ファイル: testMembershipTool.py プロジェクト: dtgit/dtedu
 def testCreateMemberarea(self):
     # CMF 1.5 requires user2 to be logged in!
     self.login('user2')
     members = self.membership.getMembersFolder()
     self.failIf(hasattr(aq_base(members), 'user2'))
     self.membership.createMemberArea('user2')
     self.failUnless(hasattr(aq_base(members), 'user2'))
コード例 #27
0
ファイル: testMembershipTool.py プロジェクト: dtgit/dtedu
 def testCreateMemberareaIfDisabled(self):
     # This should work even if the flag is off
     self.membership.setMemberareaCreationFlag() # toggle
     members = self.membership.getMembersFolder()
     self.failIf(hasattr(aq_base(members), 'user2'))
     self.membership.createMemberarea('user2')
     self.failUnless(hasattr(aq_base(members), 'user2'))
コード例 #28
0
ファイル: utility.py プロジェクト: domruf/Products.TinyMCE
    def getContentType(self, object=None, field=None, fieldname=None):
        context = aq_base(object)
        if context is not None and IBaseObject.providedBy(context):
            # support Archetypes fields
            if field is not None:
                pass
            elif fieldname is not None:
                field = context.getField(fieldname) or getattr(context, fieldname, None)
            else:
                field = context.getPrimaryField()
            if field and hasattr(aq_base(field), 'getContentType'):
                return field.getContentType(context)
        elif IRichText.providedBy(field):
            # support plone.app.textfield RichTextValues

            # First try to get a stored value and check its mimetype.
            mimetype = None
            if context is not None:
                value = getattr(context, fieldname, None)
                mimetype = getattr(value, 'mimeType', None)

            # Fall back to the field's default mimetype
            if mimetype is None:
                mimetype = field.default_mime_type
            return mimetype
        elif context is not None and fieldname is not None and '.widgets.' in fieldname:
            # We don't have the field object but we can at least try
            # to get the mimetype from an attribute on the object
            fieldname = fieldname.split('.widgets.')[-1]
            field = getattr(context, fieldname, None)
            mimetype = getattr(field, 'mimeType', None)
            if mimetype is not None:
                return mimetype
        return 'text/html'
コード例 #29
0
    def test_copy_paste_sets_ownership(self):
        # Copy/pasting a File should set new ownership including local roles
        # borrowed from CMFCore tests

        # First, create a new manager user
        uf = self.portal.acl_users
        uf._doAddUser('manager1', 'secret', ['Manager'], [])
        member = uf.getUser(default_user).__of__(uf)
        manager1 = uf.getUser('manager1').__of__(uf)
        member_area = self.portal.Members[TEST_USER_ID]

        # Switch to the manager user context and plant a content item into
        # the member user's member area
        self.login('manager1')
        member_area.invokeFactory('DDocument', id='test_file')

        # Switch to "member" context now and try to copy and paste the
        # content item created by "manager1"
        self.login(default_user)
        cb = member_area.manage_copyObjects(['test_file'])
        member_area.manage_pasteObjects(cb)

        # Now test executable ownership and "owner" local role
        # "member" should have both.
        file_ob = member_area.copy_of_test_file
        self.assertEqual(aq_base(file_ob.getOwner().getId()),
                         aq_base(member).getId())
        self.assertTrue('Owner' in
                        file_ob.get_local_roles_for_userid(TEST_USER_ID))
コード例 #30
0
ファイル: test_tool.py プロジェクト: dtgit/dtedu
    def test_required_tools_missing_acquired_nofail( self ):

        from Products.GenericSetup.tool import TOOLSET_XML
        from Products.GenericSetup.tool import importToolset

        site = self._initSite()
        parent_site = Folder()

        mandatory = AnotherDummyTool()
        mandatory._setId( 'mandatory' )
        parent_site._setObject( 'mandatory', mandatory )

        obligatory = AnotherDummyTool()
        obligatory._setId( 'obligatory' )
        parent_site._setObject( 'obligatory', obligatory )

        site = site.__of__(parent_site)

        # acquiring subobjects of a different class during import
        # should not prevent new objects from being created if they
        # don't exist in the site

        context = DummyImportContext( site, tool=site.setup_tool )
        context._files[ TOOLSET_XML ] = _REQUIRED_TOOLSET_XML

        importToolset( context )

        self.failIf( aq_base( site._getOb( 'mandatory' ) ) is mandatory )
        self.failUnless( isinstance( aq_base( site._getOb( 'mandatory' ) )
                                   , DummyTool ) )

        self.failIf( aq_base( site._getOb( 'obligatory' ) ) is obligatory )
        self.failUnless( isinstance( aq_base( site._getOb( 'obligatory' ) )
                                   , DummyTool ) )
コード例 #31
0
ファイル: components.py プロジェクト: bendavis78/zope
    def _initUtilities(self, node):
        site = self._getSite()
        blacklist = self._constructBlacklist()

        current_utilities = self.context.registeredUtilities()

        for child in node.childNodes:
            if child.nodeName != 'utility':
                continue

            provided = child.getAttribute('interface')
            if provided in blacklist:
                continue

            provided = _resolveDottedName(provided)
            name = unicode(str(child.getAttribute('name')))

            component = child.getAttribute('component')
            component = component and _resolveDottedName(component) or None

            factory = child.getAttribute('factory')
            factory = factory and _resolveDottedName(factory) or None

            if child.hasAttribute('remove'):
                if self.context.queryUtility(provided, name) is not None:
                    ofs_id = self._ofs_id(child)
                    if ofs_id in self.context.objectIds():
                        self.context._delObject(ofs_id, suppress_events=True)
                    self.context.unregisterUtility(provided=provided, name=name)
                continue

            if component and factory:
                raise ValueError, "Can not specify both a factory and a " \
                                  "component in a utility registration."


            obj_path = child.getAttribute('object')
            if not component and not factory and obj_path is not None:
                # Support for registering the site itself
                if obj_path in ('', '/'):
                    obj = site
                else:
                    # BBB: filter out path segments, we did claim to support
                    # nested paths once
                    id_ = [p for p in obj_path.split('/') if p][0]
                    obj = getattr(site, id_, None)

                if obj is not None:
                    self.context.registerUtility(aq_base(obj), provided, name)
                else:
                    # Log an error, object not found
                    self._logger.warning("The object %s was not found, while "
                                         "trying to register an utility. The "
                                         "provided object definition was %s. "
                                         "The site used was: %s"
                                         % (repr(obj), obj_path, repr(site)))
            elif component:
                self.context.registerUtility(component, provided, name)
            elif factory:
                current = [ utility for utility in current_utilities
                                    if utility.provided==provided and
                                       utility.name==name ]

                if current and getattr(current[0], "factory", None)==factory:
                    continue

                obj = factory()
                ofs_id = self._ofs_id(child)
                if ofs_id not in self.context.objectIds():
                    self.context._setObject(ofs_id, aq_base(obj),
                        set_owner=False, suppress_events=True)
                try:
                    getter = self.context.get
                except AttributeError:
                    getter = self.context._getOb # BBB: Zope <= 2.10.x
                obj = getter(ofs_id)
                obj.__name__ = ofs_id
                obj.__parent__ = aq_base(self.context)
                self.context.registerUtility(aq_base(obj), provided, name)
            else:
                self._logger.warning("Invalid utility registration for "
                                     "interface %s" % provided)
コード例 #32
0
 def migrate_allowDiscussion(self):
     """migrate allow discussion bit."""
     if (getattr(aq_base(self.new), 'isDiscussable', _marker) is not _marker
             and hasattr(self, 'isDiscussable')):
         self.new.isDiscussable(self.isDiscussable)
コード例 #33
0
 def beforeChange_allowDiscussion(self):
     """load allow discussion bit."""
     self._checkLoadAttr('isDiscussable')
     if (getattr(aq_base(self.old), 'allowDiscussion', _marker)
             is not _marker):
         self.isDiscussable = self.old.allowDiscussion()
コード例 #34
0
    def _checkConsistency(self, fixit=0):
        """Constraint API.
    """
        # Check useless cells
        to_delete_set = set()
        error_list = []

        def addError(error_message):
            if fixit:
                error_message += ' (fixed)'
            error = (self.getRelativeUrl(), 'XMLMatrix inconsistency', 102,
                     error_message)

            error_list.append(error)

        # We make sure first that there is an index
        if getattr(aq_base(self), 'index', None) is None:
            self.index = PersistentMapping()
        # We will check each cell of the matrix the matrix

        # XXX This code assumes the following predicate:
        #   each subobject of an XMLMatrix is either a Cell that needs
        #   consistency checking OR ( is not a Cell, and has an id that is
        #   not like "(\w+_)+(\d+_)*\d+" )
        # But Documents inheriting XMLMatrix can have unrelated, non-cell
        # subobjects, possibly with id looking like some_id_2. If it ever happens,
        # an error will be wrongly raised.
        for obj in self.objectValues():
            object_id = obj.getId()
            # obect_id is equal to something like 'something_quantity_3_2'
            # So we need to check for every object.id if the value
            # looks like good or not. We split the name
            # check each key in index
            # First we make sure this is a cell
            object_id_split = object_id.split('_')

            base_id = None
            cell_coordinate_list = []
            while object_id_split:
                coordinate = None
                try:
                    coordinate = int(object_id_split[-1])
                except ValueError:
                    # The last item is not a coordinate, object_id_split hence
                    # only contains the base_id elements
                    base_id = '_'.join(object_id_split)
                    break
                else:
                    cell_coordinate_list.insert(0, coordinate)
                    # the last item is a coordinate not part of base_id
                    object_id_split.pop()

            current_dimension = len(cell_coordinate_list)
            if current_dimension > 0 and base_id is not None:
                if not self.index.has_key(base_id):
                    # The matrix does not have this base_id
                    addError("There is no index for base_id %s" % base_id)
                    to_delete_set.add(object_id)
                    continue

                # Check empty indices.
                empty_list = []
                base_item = self.index[base_id]
                for key, value in base_item.iteritems():
                    if value is None or len(value) == 0:
                        addError(
                            "There is no id for the %dth axis of base_id %s" %
                            (key, base_id))
                        empty_list.append(key)
                if fixit:
                    for i in empty_list:
                        del base_item[key]

                len_id = len(base_item)
                if current_dimension != len_id:
                    addError("Dimension of cell is %s but should be %s" %
                             (current_dimension, len_id))
                    to_delete_set.add(object_id)
                else:
                    for i, coordinate in enumerate(cell_coordinate_list):
                        if coordinate not in base_item[i].values():
                            addError("Cell %s is out of bound" % object_id)
                            to_delete_set.add(object_id)
                            break

        if fixit and len(to_delete_set) > 0:
            self.manage_delObjects(list(to_delete_set))

        return error_list
コード例 #35
0
 def getMatrixList(self):
     """Return possible base_id values
 """
     if getattr(aq_base(self), 'index', None) is None:
         return ()
     return self.index.keys()
コード例 #36
0
    def _renameCellRange(self, *kw, **kwd):
        """Rename a range for a matrix, this method can also handle a change in
    the size of a matrix
    """
        base_id = kwd.get('base_id', 'cell')

        if getattr(aq_base(self), 'index', None) is None:
            self.index = PersistentMapping()

        # Return if previous range is the same
        current_range = self.getCellRange(base_id=base_id) or []
        if current_range == list(kw):  # kw is a tuple
            LOG('XMLMatrix', 0,
                'return form _setCellRange - no need to change range')
            return

        current_len = len(current_range)
        new_len = len(kw)
        len_delta = new_len - current_len

        # We must make sure the base_id exists
        # in the event of a matrix creation for example
        if not self.index.has_key(base_id):
            # Create an index for this base_id
            self.index[base_id] = PersistentMapping()

        cell_id_list = []
        for cell_id in self.getCellIdList(base_id=base_id):
            if self.get(cell_id) is not None:
                cell_id_list.append(cell_id)

        # First, delete all cells which are out of range.
        size_list = map(len, kw)
        if len_delta < 0:
            size_list.extend([1] * (-len_delta))

        def is_in_range(cell_id):
            for i, index in enumerate(cell_id[len(base_id) + 1:].split('_')):
                if int(index) >= size_list[i]:
                    self._delObject(cell_id)
                    return False
            return True

        cell_id_list = filter(is_in_range, cell_id_list)

        # Secondly, rename coordinates. This does not change cell ids.
        for i in range(max(new_len, current_len)):
            if i >= new_len:
                del self.index[base_id][i]
            else:
                if i >= current_len:
                    self.index[base_id][i] = PersistentMapping()
                for place in self.index[base_id][i].keys():
                    if place not in kw[i]:
                        del self.index[base_id][i][place]

                for j, place in enumerate(kw[i]):
                    self.index[base_id][i][place] = j

        # Lastly, rename ids and catalog/uncatalog everything.
        if len_delta > 0:
            # Need to move, say, base_1_2 -> base_1_2_0
            appended_id = '_0' * len_delta
            for old_id in cell_id_list:
                cell = self.get(old_id)
                if cell is not None:
                    new_id = old_id + appended_id
                    self._delObject(old_id)
                    cell.isIndexable = ConstantGetter('isIndexable',
                                                      value=False)
                    cell.id = new_id
                    self._setObject(new_id, aq_base(cell))
                    cell.isIndexable = ConstantGetter('isIndexable',
                                                      value=True)
                    cell.reindexObject()
                    #cell.unindexObject(path='%s/%s' % (self.getUrl(), old_id))
        elif len_delta < 0:
            # Need to move, say, base_1_2_0 -> base_1_2
            removed_id_len = 2 * (-len_delta)
            for old_id in cell_id_list:
                cell = self.get(old_id)
                if cell is not None:
                    new_id = old_id[:-removed_id_len]
                    self._delObject(old_id)
                    cell.isIndexable = ConstantGetter('isIndexable',
                                                      value=False)
                    cell.id = new_id
                    self._setObject(new_id, aq_base(cell))
                    cell.isIndexable = ConstantGetter('isIndexable',
                                                      value=True)
                    cell.reindexObject()
コード例 #37
0
    def test_local_utility_installed(self):
        portal = self.layer['portal']

        registry = getUtility(IRegistry)
        self.assertTrue(aq_base(registry) is aq_base(portal.portal_registry))
コード例 #38
0
ファイル: UbercartTest.py プロジェクト: zamananjum0/erp5
    def getDeliveryOrganisation(self, *args, **kw):
        if not kw.has_key('organisation_id'):
            raise ValueError, "No parameter organisation_id passed to getOrganisation, got %s / %s" % (
                args, kw)
        organisation_id = kw["organisation_id"]
        # retrieve the organisation inside the test module
        org_list = self.context.getPortalObject(
        ).ubercart_test_module.searchFolder(
            id=organisation_id,
            validation_state="validated",
            portal_type="Ubercart Test Delivery Person")
        organisation_list = organisation_gid_list = []
        for organisation in org_list:
            organisation = organisation.getObject()
            org_id = getattr(aq_base(organisation), "company", "")
            country = getattr(aq_base(organisation), "country", "")
            if org_id in [None, "None"]:
                org_id = ""
            if country in [None, "None"]:
                country = ""
            gid = "%s %s" % (org_id, country)
            if org_id != "" and gid.replace(
                    " ", "") != "" and gid not in organisation_gid_list:
                organisation_list.append(organisation)
                organisation_gid_list.append(gid)

        if len(organisation_list) < 1:
            raise KeyError(organisation_id)
        else:
            organisation = organisation_list[0]
        root = self.generateResultHeader()
        # Data part
        organisation_id = getattr(aq_base(organisation), "company", "")
        if organisation_id != "":
            # we got an organisation inside the person
            organisation_element = etree.SubElement(root, "object")
            for prop in [
                    "company", "id", "email", "street", "zip", "city",
                    "country", "country_name"
            ]:
                if prop == "company":
                    value = getattr(aq_base(organisation), prop, "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "delivery_company")
                elif prop == "email":
                    value = getattr(aq_base(organisation), prop, "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "primary_email")
                elif prop == "country_name":
                    value = getattr(aq_base(organisation), "country", "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "country")
                elif prop == "street":
                    value = getattr(aq_base(organisation), "street", "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "delivery_street1")
                else:
                    value = getattr(aq_base(organisation), prop, "")
                    if prop == "id":
                        prop_xml = etree.SubElement(organisation_element, prop)
                    else:
                        prop_xml = etree.SubElement(organisation_element,
                                                    "delivery_%s" % prop)
                if isinstance(value, str):
                    prop_xml.text = value.decode('utf-8')
                else:
                    prop_xml.text = str(value)

        xml = etree.tostring(root, pretty_print=True)
        #person_xml = etree.tostring(person, pretty_print=True)
        #self.validateXMLScheme(product_xml, "Person.xsd")
        return "", xml
コード例 #39
0
ファイル: surveys.py プロジェクト: EU-OSHA/Euphorie
 def __getitem__(self, key):
     country = self.request.client[key]
     if not IClientCountry.providedBy(country):
         raise KeyError(key)
     return aq_base(country).__of__(self)
コード例 #40
0
ファイル: contact.py プロジェクト: aialves/Bika-LIMS-1
    def __call__(self):

        if self.request.form.has_key("submitted"):

            def error(field, message):
                if field:
                    message = "%s: %s" % (field, message)
                self.context.plone_utils.addPortalMessage(message, 'error')
                return self.template()

            form = self.request.form
            contact = self.context

            password = safe_unicode(form.get('password', '')).encode('utf-8')
            username = safe_unicode(form.get('username', '')).encode('utf-8')
            confirm = form.get('confirm', '')
            email = safe_unicode(form.get('email', '')).encode('utf-8')

            if not username:
                return error('username',
                             PMF("Input is required but not given."))

            if not email:
                return error('email', PMF("Input is required but not given."))

            reg_tool = self.context.portal_registration
            properties = self.context.portal_properties.site_properties

            ##            if properties.validate_email:
            ##                password = reg_tool.generatePassword()
            ##            else:
            if password != confirm:
                return error('password', PMF("Passwords do not match."))

            if not password:
                return error('password',
                             PMF("Input is required but not given."))

            if not confirm:
                return error('password', PMF("Passwords do not match."))

            if len(password) < 5:
                return error('password',
                             PMF("Passwords must contain at least 5 letters."))

            try:
                reg_tool.addMember(username,
                                   password,
                                   properties={
                                       'username': username,
                                       'email': email,
                                       'fullname': username
                                   })
            except ValueError, msg:
                return error(None, msg)

            contact.setUsername(username)
            contact.setEmailAddress(email)

            # If we're being created in a Client context, then give
            # the contact an Owner local role on client.
            if contact.aq_parent.portal_type == 'Client':
                contact.aq_parent.manage_setLocalRoles(username, [
                    'Owner',
                ])
                if hasattr(aq_base(contact.aq_parent),
                           'reindexObjectSecurity'):
                    contact.aq_parent.reindexObjectSecurity()

                # add user to Clients group
                group = self.context.portal_groups.getGroupById('Clients')
                group.addMember(username)

            # Additional groups for LabContact users.
            # not required (not available for client Contact)
            if 'groups' in self.request and self.request['groups']:
                groups = self.request['groups']
                if not type(groups) in (list, tuple):
                    groups = [
                        groups,
                    ]
                for group in groups:
                    group = self.portal_groups.getGroupById(group)
                    group.addMember(username)

            contact.reindexObject()

            if properties.validate_email or self.request.get('mail_me', 0):
                try:
                    reg_tool.registeredNotify(username)
                except:
                    import transaction
                    transaction.abort()
                    return error(None, PMF("SMTP server disconnected."))

            message = PMF("Member registered.")
            self.context.plone_utils.addPortalMessage(message, 'info')
            return self.template()
コード例 #41
0
ファイル: test_PortalFolder.py プロジェクト: bendavis78/zope
 def _validate(a, c, n, v, *args, **kw):
     return aq_base(v) is not aq_base(a_file)
コード例 #42
0
ファイル: UbercartTest.py プロジェクト: zamananjum0/erp5
    def getDeliveryOrganisationList(self, *args, **kw):
        org_list = self.context.getPortalObject(
        ).ubercart_test_module.searchFolder(
            portal_type="Ubercart Test Delivery Person",
            validation_state="validated")
        root = self.generateResultHeader()
        # must put date into organisation_list
        organisation_list = []
        organisation_gid_list = []
        for organisation in org_list:
            organisation = organisation.getObject()
            org_id = getattr(aq_base(organisation), "company", "")
            country = getattr(aq_base(organisation), "country", "")
            if org_id in [None, "None"]:
                org_id = ""
            if country in [None, "None"]:
                country = ""
            gid = "%s %s" % (org_id, country)
            if org_id != "" and gid.replace(
                    " ", "") != "" and gid not in organisation_gid_list:
                organisation_list.append(organisation)
                organisation_gid_list.append(gid)

        for organisation in organisation_list:
            organisation_id = getattr(aq_base(organisation), "company", "")
            # we got an organisation inside the person
            organisation_element = etree.SubElement(root, "object")
            for prop in [
                    "company", "id", "email", "street", "zip", "city",
                    "country", "country_name"
            ]:
                if prop == "company":
                    value = getattr(aq_base(organisation), prop, "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "delivery_company")
                elif prop == "email":
                    value = getattr(aq_base(organisation), prop, "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "primary_email")
                elif prop == "country_name":
                    value = getattr(aq_base(organisation), "country", "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "country")
                elif prop == "street":
                    value = getattr(aq_base(organisation), "street", "")
                    prop_xml = etree.SubElement(organisation_element,
                                                "delivery_street1")
                else:
                    value = getattr(aq_base(organisation), prop, "")
                    if prop == "id":
                        prop_xml = etree.SubElement(organisation_element, prop)
                    else:
                        prop_xml = etree.SubElement(organisation_element,
                                                    "delivery_%s" % prop)
                if isinstance(value, str):
                    prop_xml.text = value.decode('utf-8')
                else:
                    prop_xml.text = str(value)

        xml = etree.tostring(root, pretty_print=True)
        #persons_xml = etree.tostring(root, pretty_print=True)
        #self.validateXMLScheme(persons_xml, "PersonList.xsd")
        return "", xml
コード例 #43
0
    def unrestrictedTraverse(self, path, default=_marker, restricted=False):
        """Lookup an object by path.

        path -- The path to the object. May be a sequence of strings or a slash
        separated string. If the path begins with an empty path element
        (i.e., an empty string or a slash) then the lookup is performed
        from the application root. Otherwise, the lookup is relative to
        self. Two dots (..) as a path element indicates an upward traversal
        to the acquisition parent.

        default -- If provided, this is the value returned if the path cannot
        be traversed for any reason (i.e., no object exists at that path or
        the object is inaccessible).

        restricted -- If false (default) then no security checking is
        performed. If true, then all of the objects along the path are
        validated with the security machinery. Usually invoked using
        restrictedTraverse().
        """
        if not path:
            return self

        if isinstance(path, str):
            # Unicode paths are not allowed
            path = path.split('/')
        else:
            path = list(path)

        REQUEST = {'TraversalRequestNameStack': path}
        path.reverse()
        path_pop = path.pop

        if len(path) > 1 and not path[0]:
            # Remove trailing slash
            path_pop(0)

        if restricted:
            validate = getSecurityManager().validate

        if not path[-1]:
            # If the path starts with an empty string, go to the root first.
            path_pop()
            obj = self.getPhysicalRoot()
            if restricted:
                validate(None, None, None, obj)  # may raise Unauthorized
        else:
            obj = self

        # import time ordering problem
        if bbb.HAS_ZSERVER:
            from webdav.NullResource import NullResource
        else:
            NullResource = bbb.NullResource

        resource = _marker
        try:
            while path:
                name = path_pop()
                __traceback_info__ = path, name

                if name[0] == '_':
                    # Never allowed in a URL.
                    raise NotFound(name)

                if name == '..':
                    next = aq_parent(obj)
                    if next is not None:
                        if restricted and not validate(obj, obj, name, next):
                            raise Unauthorized(name)
                        obj = next
                        continue

                bobo_traverse = getattr(obj, '__bobo_traverse__', None)
                try:
                    if (name and name[:1] in '@+' and name != '+' and
                            nsParse(name)[1]):
                        # Process URI segment parameters.
                        ns, nm = nsParse(name)
                        try:
                            next = namespaceLookup(
                                ns, nm, obj, aq_acquire(self, 'REQUEST'))
                            if IAcquirer.providedBy(next):
                                next = next.__of__(obj)
                            if restricted and not validate(
                                    obj, obj, name, next):
                                raise Unauthorized(name)
                        except LocationError:
                            raise AttributeError(name)

                    else:
                        next = UseTraversalDefault  # indicator
                        try:
                            if bobo_traverse is not None:
                                next = bobo_traverse(REQUEST, name)
                                if restricted:
                                    if aq_base(next) is not next:
                                        # The object is wrapped, so the
                                        # acquisition context is the container.
                                        container = aq_parent(aq_inner(next))
                                    elif getattr(next, '__self__',
                                                 None) is not None:
                                        # Bound method, the bound instance
                                        # is the container
                                        container = next.__self__
                                    elif getattr(
                                            aq_base(obj),
                                            name, _marker) is next:
                                        # Unwrapped direct attribute of the
                                        # object so object is the container
                                        container = obj
                                    else:
                                        # Can't determine container
                                        container = None
                                    # If next is a simple unwrapped property,
                                    # its parentage is indeterminate, but it
                                    # may have been acquired safely. In this
                                    # case validate will raise an error, and
                                    # we can explicitly check that our value
                                    # was acquired safely.
                                    try:
                                        ok = validate(
                                            obj, container, name, next)
                                    except Unauthorized:
                                        ok = False
                                    if not ok:
                                        if (container is not None or
                                            guarded_getattr(obj, name, _marker)
                                                is not next):
                                            raise Unauthorized(name)
                        except UseTraversalDefault:
                            # behave as if there had been no
                            # '__bobo_traverse__'
                            bobo_traverse = None
                        if next is UseTraversalDefault:
                            if getattr(
                                    aq_base(obj),
                                    name, _marker) is not _marker:
                                if restricted:
                                    next = guarded_getattr(obj, name)
                                else:
                                    next = getattr(obj, name)
                            else:
                                try:
                                    next = obj[name]
                                    # The item lookup may return a
                                    # NullResource, if this is the case we
                                    # save it and return it if all other
                                    # lookups fail.
                                    if (NullResource is not None and
                                            isinstance(next, NullResource)):
                                        resource = next
                                        raise KeyError(name)
                                except (AttributeError, TypeError):
                                    # Raise NotFound for easier debugging
                                    # instead of AttributeError: __getitem__
                                    # or TypeError: not subscriptable
                                    raise NotFound(name)
                                if restricted and not validate(
                                        obj, obj, None, next):
                                    raise Unauthorized(name)

                except (AttributeError, NotFound, KeyError) as e:
                    # Try to look for a view
                    next = queryMultiAdapter(
                        (obj, aq_acquire(self, 'REQUEST')),
                        Interface, name)

                    if next is not None:
                        if IAcquirer.providedBy(next):
                            next = next.__of__(obj)
                        if restricted and not validate(obj, obj, name, next):
                            raise Unauthorized(name)
                    elif bobo_traverse is not None:
                        # Attribute lookup should not be done after
                        # __bobo_traverse__:
                        raise e
                    else:
                        # No view, try acquired attributes
                        try:
                            if restricted:
                                next = guarded_getattr(obj, name, _marker)
                            else:
                                next = getattr(obj, name, _marker)
                        except AttributeError:
                            raise e
                        if next is _marker:
                            # If we have a NullResource from earlier use it.
                            next = resource
                            if next is _marker:
                                # Nothing found re-raise error
                                raise e

                obj = next

            return obj

        except ConflictError:
            raise
        except Exception:
            if default is not _marker:
                return default
            else:
                raise
コード例 #44
0
    def ZopeFindAndApply(self,
                         obj,
                         obj_ids=None,
                         obj_metatypes=None,
                         obj_searchterm=None,
                         obj_expr=None,
                         obj_mtime=None,
                         obj_mspec=None,
                         obj_permission=None,
                         obj_roles=None,
                         search_sub=0,
                         REQUEST=None,
                         result=None,
                         pre='',
                         apply_func=None,
                         apply_path=''):
        """Zope Find interface and apply."""

        if result is None:
            result = []

            if obj_metatypes and 'all' in obj_metatypes:
                obj_metatypes = None

            if obj_mtime and isinstance(obj_mtime, str):
                obj_mtime = DateTime(obj_mtime).timeTime()

            if obj_permission:
                obj_permission = getPermissionIdentifier(obj_permission)

            if obj_roles and isinstance(obj_roles, str):
                obj_roles = [obj_roles]

            if obj_expr:
                # Setup expr machinations
                md = td()
                obj_expr = (Eval(obj_expr), md, md._push, md._pop)

        base = aq_base(obj)

        if not hasattr(base, 'objectItems'):
            return result
        try:
            items = obj.objectItems()
        except Exception:
            return result

        try:
            add_result = result.append
        except Exception:
            raise AttributeError(repr(result))

        for id, ob in items:
            if pre:
                p = "%s/%s" % (pre, id)
            else:
                p = id

            dflag = 0
            if hasattr(ob, '_p_changed') and (ob._p_changed is None):
                dflag = 1

            bs = aq_base(ob)
            if obj_searchterm:
                if isinstance(obj_searchterm, TaintedString):
                    obj_searchterm = str(obj_searchterm)
                    if six.PY3 and not isinstance(obj_searchterm, str):
                        obj_searchterm = obj_searchterm.decode(
                            default_encoding)
                if hasattr(ob, 'PrincipiaSearchSource'):
                    pss = ob.PrincipiaSearchSource()
                    if six.PY3 and not isinstance(pss, str):
                        try:
                            pss = pss.decode(default_encoding)
                        except UnicodeDecodeError:
                            pss = ''
                if hasattr(ob, 'SearchableText'):
                    st = ob.SearchableText()
                    if six.PY3 and not isinstance(st, str):
                        try:
                            st = st.decode(default_encoding)
                        except UnicodeDecodeError:
                            st = ''
            else:
                pss = st = ''

            if ((not obj_ids or absattr(bs.getId()) in obj_ids) and
                (not obj_metatypes or
                 (hasattr(bs, 'meta_type') and bs.meta_type in obj_metatypes))
                    and
                (not obj_searchterm or (hasattr(ob, 'PrincipiaSearchSource')
                                        and obj_searchterm in pss) or
                 (hasattr(ob, 'SearchableText') and obj_searchterm in st))
                    and (not obj_expr or expr_match(ob, obj_expr)) and
                (not obj_mtime or mtime_match(ob, obj_mtime, obj_mspec))
                    and ((not obj_permission or not obj_roles)
                         or role_match(ob, obj_permission, obj_roles))):

                if apply_func:
                    apply_func(ob, (apply_path + '/' + p))
                else:
                    add_result((p, ob))
                    dflag = 0

            if search_sub and hasattr(bs, 'objectItems'):
                self.ZopeFindAndApply(ob, obj_ids, obj_metatypes,
                                      obj_searchterm, obj_expr, obj_mtime,
                                      obj_mspec, obj_permission, obj_roles,
                                      search_sub, REQUEST, result, p,
                                      apply_func, apply_path)
            if dflag:
                ob._p_deactivate()

        return result
コード例 #45
0
 def test_initial_md5_attribute(self):
     test_podtemplate = aq_base(self.test_podtemplate)
     self.assertTrue(hasattr(test_podtemplate, 'initial_md5'))
コード例 #46
0
 def root_is_portal(self):
     root = self.getNavRoot()
     return aq_base(root) is aq_base(self.urltool.getPortalObject())
コード例 #47
0
    def ZopeFindAndApply(self,
                         obj,
                         obj_ids=None,
                         obj_metatypes=None,
                         obj_searchterm=None,
                         obj_expr=None,
                         obj_mtime=None,
                         obj_mspec=None,
                         obj_permission=None,
                         obj_roles=None,
                         search_sub=0,
                         REQUEST=None,
                         result=None,
                         pre='',
                         apply_func=None,
                         apply_path=''):
        """Zope Find interface and apply

        This is a *great* hack.  Zope find just doesn't do what we
        need here; the ability to apply a method to all the objects
        *as they're found* and the need to pass the object's path into
        that method.
        """

        if result is None:
            result = []

            if obj_metatypes and 'all' in obj_metatypes:
                obj_metatypes = None

            if obj_mtime and isinstance(obj_mtime, str):
                obj_mtime = DateTime(obj_mtime).timeTime()

            if obj_permission:
                obj_permission = p_name(obj_permission)

            if obj_roles and isinstance(obj_roles, str):
                obj_roles = [obj_roles]

            if obj_expr:
                # Setup expr machinations
                md = td()
                obj_expr = (Eval(obj_expr), md, md._push, md._pop)

        base = aq_base(obj)

        if not hasattr(base, 'objectItems'):
            return result
        try:
            items = obj.objectItems()
        except Exception:
            return result

        try:
            add_result = result.append
        except Exception:
            raise AttributeError(repr(result))

        for id, ob in items:
            if pre:
                p = "%s/%s" % (pre, id)
            else:
                p = id

            dflag = 0
            if hasattr(ob, '_p_changed') and (ob._p_changed == None):
                dflag = 1

            bs = aq_base(ob)

            if ((not obj_ids or absattr(bs.id) in obj_ids) and
                (not obj_metatypes or
                 (hasattr(bs, 'meta_type') and bs.meta_type in obj_metatypes))
                    and
                (not obj_searchterm or
                 (hasattr(ob, 'PrincipiaSearchSource')
                  and ob.PrincipiaSearchSource().find(obj_searchterm) >= 0))
                    and (not obj_expr or expr_match(ob, obj_expr)) and
                (not obj_mtime or mtime_match(ob, obj_mtime, obj_mspec))
                    and ((not obj_permission or not obj_roles)
                         or role_match(ob, obj_permission, obj_roles))):
                if apply_func:
                    apply_func(ob, (apply_path + '/' + p))
                else:
                    add_result((p, ob))
                    dflag = 0

            if search_sub and hasattr(bs, 'objectItems'):
                self.ZopeFindAndApply(ob, obj_ids, obj_metatypes,
                                      obj_searchterm, obj_expr, obj_mtime,
                                      obj_mspec, obj_permission, obj_roles,
                                      search_sub, REQUEST, result, p,
                                      apply_func, apply_path)
            if dflag:
                ob._p_deactivate()

        return result
コード例 #48
0
 def test_enabled_attribute(self):
     test_podtemplate = aq_base(self.test_podtemplate)
     self.assertTrue(hasattr(test_podtemplate, 'enabled'))
コード例 #49
0
def get_widget_form(widget):
    form = getattr(widget, 'form', None)
    if getattr(aq_base(form), 'parentForm', None) is not None:
        form = form.parentForm
    return form
コード例 #50
0
 def test_odt_file_attribute(self):
     test_podtemplate = aq_base(self.test_podtemplate)
     self.assertTrue(hasattr(test_podtemplate, 'odt_file'))
コード例 #51
0
ファイル: dummy.py プロジェクト: bendavis78/zope
 def _delObject(self, id):
     object = self._getOb(id)
     if hasattr(aq_base(object), 'manage_beforeDelete'):
         object.manage_beforeDelete(object, self)
     self._delOb(id)
コード例 #52
0
 def valid_property_id(self, id):
     if not id or id[:1]=='_' or (id[:3]=='aq_') \
        or (' ' in id) or hasattr(aq_base(self), id) or escape(id) != id:
         return 0
     return 1
コード例 #53
0
ファイル: PortalFolder.py プロジェクト: bendavis78/zope
    def __init__( self
                , Title=MARKER
                , Creator=MARKER
                , Subject=MARKER
                , Description=MARKER
                , created=MARKER
                , created_usage='range:min'
                , modified=MARKER
                , modified_usage='range:min'
                , Type=MARKER
                , portal_type=MARKER
                , **Ignored
                ):

        self.predicates = []
        self.description = []

        if Title is not self.MARKER:
            self.predicates.append( lambda x, pat=re.compile( Title ):
                                      pat.search( x.Title() ) )
            self.description.append( 'Title: %s' % Title )

        if Creator and Creator is not self.MARKER:
            self.filterCreator = Creator
            self.predicates.append( lambda x, creator=self.filterCreator:
                                    creator in x.listCreators() )
            self.description.append( 'Creator: %s' % Creator )

        if Subject and Subject is not self.MARKER:
            self.filterSubject = Subject
            self.predicates.append( self.hasSubject )
            self.description.append( 'Subject: %s' % ', '.join(Subject) )

        if Description is not self.MARKER:
            self.predicates.append( lambda x, pat=re.compile( Description ):
                                      pat.search( x.Description() ) )
            self.description.append( 'Description: %s' % Description )

        if created is not self.MARKER:
            if created_usage == 'range:min':
                self.predicates.append( lambda x, cd=created:
                                          cd <= x.created() )
                self.description.append( 'Created since: %s' % created )
            if created_usage == 'range:max':
                self.predicates.append( lambda x, cd=created:
                                          cd >= x.created() )
                self.description.append( 'Created before: %s' % created )

        if modified is not self.MARKER:
            if modified_usage == 'range:min':
                self.predicates.append( lambda x, md=modified:
                                          md <= x.modified() )
                self.description.append( 'Modified since: %s' % modified )
            if modified_usage == 'range:max':
                self.predicates.append( lambda x, md=modified:
                                          md >= x.modified() )
                self.description.append( 'Modified before: %s' % modified )

        if Type:
            if type( Type ) == type( '' ):
                Type = [ Type ]
            self.predicates.append( lambda x, Type=Type:
                                      x.Type() in Type )
            self.description.append( 'Type: %s' % ', '.join(Type) )

        if portal_type and portal_type is not self.MARKER:
            if type(portal_type) is type(''):
                portal_type = [portal_type]
            self.predicates.append( lambda x, pt=portal_type:
                                    hasattr(aq_base(x), 'getPortalTypeName')
                                    and x.getPortalTypeName() in pt )
            self.description.append( 'Portal Type: %s'
                                     % ', '.join(portal_type) )
コード例 #54
0
 def available(self):
     context = aq_base(self.context)
     return bool(getattr(context, self.field, None))
コード例 #55
0
 def unset(self, name, instance, **kwargs):
     try:
         delattr(aq_base(instance), name)
     except AttributeError:
         pass
     instance._p_changed = 1
コード例 #56
0
ファイル: dummy.py プロジェクト: bendavis78/zope
 def _setObject(self, id, object):
     self._setOb(id, object)
     object = self._getOb(id)
     if hasattr(aq_base(object), 'manage_afterAdd'):
         object.manage_afterAdd(object, self)
     return object
コード例 #57
0
ファイル: userfolder.py プロジェクト: ehfeng/AccessControl
 def _isTop(self):
     try:
         parent = aq_base(aq_parent(self))
         return parent.isTopLevelPrincipiaApplicationObject
     except:
         return 0
コード例 #58
0
ファイル: PortalFolder.py プロジェクト: bendavis78/zope
    def _verifyObjectPaste(self, object, validate_src=1):
        # This assists the version in OFS.CopySupport.
        # It enables the clipboard to function correctly
        # with objects created by a multi-factory.
        securityChecksDone = False
        sm = getSecurityManager()
        parent = aq_parent(aq_inner(object))
        object_id = object.getId()
        mt = getattr(object, '__factory_meta_type__', None)
        meta_types = getattr(self, 'all_meta_types', None)

        if mt is not None and meta_types is not None:
            method_name=None
            permission_name = None

            if callable(meta_types):
                meta_types = meta_types()

            for d in meta_types:

                if d['name']==mt:
                    method_name=d['action']
                    permission_name = d.get('permission', None)
                    break

            if permission_name is not None:

                if not sm.checkPermission(permission_name,self):
                    raise AccessControl_Unauthorized, method_name

                if validate_src:

                    if not sm.validate(None, parent, None, object):
                        raise AccessControl_Unauthorized, object_id

                if validate_src > 1:
                    if not sm.checkPermission(DeleteObjects, parent):
                        raise AccessControl_Unauthorized

                # validation succeeded
                securityChecksDone = 1

            #
            # Old validation for objects that may not have registered
            # themselves in the proper fashion.
            #
            elif method_name is not None:

                meth = self.unrestrictedTraverse(method_name)

                factory = getattr(meth, 'im_self', None)

                if factory is None:
                    factory = aq_parent(aq_inner(meth))

                if not sm.validate(None, factory, None, meth):
                    raise AccessControl_Unauthorized, method_name

                # Ensure the user is allowed to access the object on the
                # clipboard.
                if validate_src:

                    if not sm.validate(None, parent, None, object):
                        raise AccessControl_Unauthorized, object_id

                if validate_src > 1: # moving
                    if not sm.checkPermission(DeleteObjects, parent):
                        raise AccessControl_Unauthorized

                securityChecksDone = 1

        # Call OFS' _verifyObjectPaste if necessary
        if not securityChecksDone:
            PortalFolder.inheritedAttribute(
                '_verifyObjectPaste')(self, object, validate_src)

        # Finally, check allowed content types
        if hasattr(aq_base(object), 'getPortalTypeName'):

            type_name = object.getPortalTypeName()

            if type_name is not None:

                pt = getToolByName(self, 'portal_types')
                myType = pt.getTypeInfo(self)

                if myType is not None and not myType.allowType(type_name):
                    raise ValueError('Disallowed subobject type: %s'
                                        % type_name)
コード例 #59
0
 def talkback(self):
     aliased = self._target
     if not hasattr(aq_base(aliased), 'talkback'):
         raise AttributeError('talkback')
     # may legitimately raise an attribute error
     return aq_base(aliased.talkback).__of__(self)
コード例 #60
0
 def set(self, name, instance, value, **kwargs):
     # Remove acquisition wrappers
     value = aq_base(value)
     setattr(aq_base(instance), name, value)
     instance._p_changed = 1