Esempio n. 1
0
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass
            implements(IXMLRPCPresentation)


        # Register the simple traverser so we can traverse without @@
        from zope.publisher.interfaces.xmlrpc import IXMLRPCPublisher
        from zope.publisher.interfaces.xmlrpc import IXMLRPCRequest
        from zope.app.publication.traversers import SimpleComponentTraverser
        ztapi.provideView(Interface, IXMLRPCRequest, IXMLRPCPublisher, '',
                          SimpleComponentTraverser)

        r = self._createRequest('/@@spam', pub)
        ztapi.provideView(I, IXMLRPCRequest, Interface, 'spam', V)
        ob2 = pub.traverseName(r, ob, '@@spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
        
        ob2 = pub.traverseName(r, ob, 'spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
Esempio n. 2
0
    def retract(self, principal=None):
        if principal is None:
            principal = getPrincipal()

        if not self.isRetractable(principal):
            raise DraftException('Cannot retract content.')

        container = queryMultiAdapter((principal, self), IDraftContainer)
        if container is None:
            raise DraftException('Cannot find draft container.')

        content = self.context

        origName = content.__name__
        oldContainer = content.__parent__

        newName = INameChooser(container).chooseName(u'', content)

        container[newName] = removeAllProxies(content)
        del removeAllProxies(oldContainer)[origName]

        draft = container[newName]
        event.notify(ObjectRetractedEvent(content, draft))

        return draft
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass

            implements(ISOAPPresentation)

        # Register the simple traverser so we can traverse without @@
        from z3c.soap.interfaces import ISOAPPublisher, ISOAPRequest
        from zope.app.publication.traversers import SimpleComponentTraverser

        ztapi.provideView(Interface, ISOAPRequest, ISOAPPublisher, "", SimpleComponentTraverser)

        r = self._createRequest("/@@spam", pub)
        ztapi.provideView(I, ISOAPRequest, Interface, "spam", V)
        ob2 = pub.traverseName(r, ob, "@@spam")
        self.assertEqual(removeAllProxies(ob2).__class__, V)

        ob2 = pub.traverseName(r, ob, "spam")
        self.assertEqual(removeAllProxies(ob2).__class__, V)
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass
            implements(IXMLRPCView)


        # Register the simple traverser so we can traverse without @@
        component.provideAdapter(SimpleComponentTraverser,
                                 (Interface, IXMLRPCRequest),
                                 IXMLRPCPublisher)

        r = self._createRequest('/@@spam', pub)
        component.provideAdapter(V, (I, IXMLRPCRequest), Interface,
                                 name='spam')
        ob2 = pub.traverseName(r, ob, '@@spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)

        ob2 = pub.traverseName(r, ob, 'spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
Esempio n. 5
0
def commentRemoved(comment, ev):
    comment = removeAllProxies(comment)
    catalog = removeAllProxies(getCatalog())
    try:
        catalog.unindex_doc(getUtility(IIntIds).getId(comment))
    except KeyError:
        pass
Esempio n. 6
0
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass

            implements(IXMLRPCPresentation)

        # Register the simple traverser so we can traverse without @@
        ztapi.provideView(Interface, IXMLRPCRequest, IXMLRPCPublisher, '',
                          SimpleComponentTraverser)

        r = self._createRequest('/@@spam', pub)
        ztapi.provideView(I, IXMLRPCRequest, Interface, 'spam', V)
        ob2 = pub.traverseName(r, ob, '@@spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)

        ob2 = pub.traverseName(r, ob, 'spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
Esempio n. 7
0
    def __call__(self):
        context = self.context
        removeAllProxies(context)._v_currentRevision = -1

        rendered = super(WorkingRevision, self).__call__()

        removeAllProxies(context)._v_currentRevision = None

        return rendered
Esempio n. 8
0
def getMailInDestination(context):
    annotation = IAnnotations(removeAllProxies(context))

    destination = annotation.get(KEY)
    if destination is None:
        destination = MailInAwareDestination(removeAllProxies(context))
        annotation[KEY] = destination

    return destination
Esempio n. 9
0
 def generateMessageId(self, post, salt=None):
     ids = getUtility(IIntIds)
     post = ids.getId(removeAllProxies(post))
     if salt:
         if not isinstance(salt, basestring):
             salt = str(ids.getId(removeAllProxies(salt)))
         return '<*****@*****.**>'%(post, salt)
     else:
         return '<*****@*****.**>'%post
Esempio n. 10
0
    def getContent(self):
        content = self.wizard.getContent()
        data = removeAllProxies(content.getFieldData())

        for schema in (removeAllProxies(content).__schema__, IField):
            for name in getFieldNames(schema):
                field = schema[name].bind(content)
                data[name] = field.get(content)

        return data
Esempio n. 11
0
    def __call__(self):
        revid = int(self.context.__name__)
        content = self.context.__parent__.__parent__

        if checkPermission('zojax.ModifyContent', content):
            removeAllProxies(content).setRevision(revid)
            IStatusMessage(self.request).add(
                _('Revision has been activated.'))

        self.redirect('../')
Esempio n. 12
0
    def install(self):
        ws = self.space.get(self.name)

        if not IMessagesWorkspace.providedBy(ws):
            ws = MessagesWorkspace(self.space.principalId)
            event.notify(ObjectCreatedEvent(ws))
            removeAllProxies(self.space)[self.name] = ws
            ws.__name__ = self.name
            ws.__parent__ = removeAllProxies(self.space)

        return ws
Esempio n. 13
0
def getEvaluations(context):
    """Adapt an ``IHaveEvaluations`` object to ``IEvaluations``."""
    annotations = IAnnotations(removeAllProxies(context))
    try:
        return annotations[EVALUATIONS_KEY]
    except KeyError:
        evaluations = Evaluations()
        annotations[EVALUATIONS_KEY] = evaluations
        location.locate(evaluations, removeAllProxies(context),
                        '++evaluations++')
        return evaluations
Esempio n. 14
0
    def getEntries(self, columns=True):
        """Return info objects for all modules and classes in the
        associated apidoc container.

        """
        if (not hasattr(self.context, "apidoc")
                or not hasattr(self.context.apidoc, "items")):
            return None
        entries = []
        for name, obj in self.context.apidoc.items():
            entry = {
                'name': name,
                'obj': obj,
                'path': getPythonPath(removeAllProxies(obj)),
                'url': u'',
                'doc': None,
                'ispackage': False,
                'ismodule': False,
                'isinterface': False,
                'isclass': False,
                'isfunction': False,
                'istextfile': False,
                'iszcmlfile': False,
                'signature': None
            }
            entry['url'] = "%s/%s" % (self.context.path.replace('.',
                                                                '/'), name)
            if hasattr(obj, "getDocString"):
                entry['doc'] = self.getDocHeading(obj.getDocString())
            elif hasattr(obj, "getDoc") and isinstance(removeAllProxies(obj),
                                                       InterfaceClass):
                entry['doc'] = self.getDocHeading(obj.getDoc())
            if isinstance(obj, Class):
                entry['isclass'] = True
            elif isinstance(obj, TextFile):
                entry['istextfile'] = True
            elif isinstance(obj, ZCMLFile):
                entry['iszcmlfile'] = True
            elif isinstance(obj, Function):
                entry['isfunction'] = True
                if hasattr(obj, 'getSignature'):
                    entry['signature'] = obj.getSignature()
            elif (isinstance(obj, Module)
                  and os.path.basename(obj.getFileName())
                  in ['__init.py__', '__init__.pyc', '__init__.pyo']):
                entry['ispackage'] = True
            elif isinstance(obj, Module):
                entry['ismodule'] = True
            elif isinstance(obj, InterfaceClass):
                entry['isinterface'] = True
            entries.append(entry)

        entries.sort(lambda x, y: cmp(x['name'], y['name']))
        return entries
Esempio n. 15
0
    def search(self, object=None, contexts=(),
               sort_on='date', sort_order='reverse',
               noSecurityChecks=False, **kw):

        ids = getUtility(IIntIds)

        query = dict(kw)

        # records for object
        if type(object) is not type({}) and object is not None:
            oid = ids.queryId(removeAllProxies(object))
            if oid is None:
                return ResultSet(IFBTree(), getUtility(IActivity))

            query['object'] = {'any_of': (oid,)}

        # context
        if not contexts:
            contexts = (getSite(),)

        c = []
        for context in contexts:
            id = ids.queryId(removeAllProxies(context))
            if id is not None:
                c.append(id)

        query['contexts'] = {'any_of': c}

        # security
        if not noSecurityChecks:
            request = getRequest()
            if request is not None:
                users = listAllowedRoles(request.principal, getSite())
                if 'zope.Anonymous' not in users:
                    users.append('zope.Anonymous')

                query['allowedUsers'] = {'any_of': users}

        # apply searh terms
        results = self.apply(query)
        if results is None:
            results = IFBTree()

        # sort result by index
        if sort_on and sort_on in self:
            sortable = ISortable(self[sort_on], None)
            if sortable is not None:
                results = sortable.sort(results)

        if sort_order == 'reverse':
            return ReverseResultSet(results, getUtility(IActivity))
        else:
            return ResultSet(results, getUtility(IActivity))
Esempio n. 16
0
    def __init__(self, record, default=None):
        values = []
        ids = getUtility(IIntIds)

        context = removeAllProxies(record.object)
        while context is not None:
            values.append(ids.queryId(context))

            context = removeAllProxies(
                getattr(context, '__parent__', None))

        self.value = values
Esempio n. 17
0
    def completeTask(self):
        results = getUtility(ICatalog).searchResults(
            type={'any_of': ('project.task',),},
            projectTaskState = {'any_of': (1,)},
            projectTaskMilestone = {'any_of': (getUtility(IIntIds).getId(self),)},
            searchContext = self.__parent__.__parent__)

        for task in results:
            removeAllProxies(task).completeTask()
            event.notify(ObjectModifiedEvent(task))

        self.state = 2
        event.notify(StateChangedEvent(self, 2))
Esempio n. 18
0
    def search(self, content=None,
               contexts=(), sort_on='date', sort_order='reverse', types=(), approved=()):
        ids = getUtility(IIntIds)
        indexes = list(self.values())

        query = {}

        # comments for content
        if content:
            query['content'] = {'any_of':(ids.getId(removeAllProxies(content)),)}

        # context
        if contexts:
            c = []
            for context in contexts:
                id = ids.queryId(removeAllProxies(context))
                if id is not None:
                    c.append(id)

            query['contexts'] = {'any_of': c}

        # content type
        if types:
            query['type'] = {'any_of': types}

        # security
        users = listAllowedRoles(getRequest().principal, getSite())
        if 'zope.Anonymous' not in users:
            users.append('zope.Anonymous')

        query['access'] = {'any_of': users}

        # comments approved
        if approved:
            query['approved'] = {'any_of': approved}

        # apply searh terms
        results = self.apply(query)
        if results is None:
            results = IFBTree()

        # sort result by index
        if sort_on and sort_on in self:
            sortable = ISortable(self[sort_on], None)
            if sortable is not None:
                results = sortable.sort(results)

        if sort_order == 'reverse':
            return ReverseResultSet(results, ids)
        else:
            return ResultSet(results, ids)
Esempio n. 19
0
    def update(self):
        if 'ADD' in self.request:
            for interface in self.getIntrospector().getMarkerInterfaceNames():
                if "add_%s" % interface in self.request:
                    ob = self.context
                    interface = getInterface(ob, interface)
                    directlyProvides(removeAllProxies(ob), directlyProvidedBy(ob), interface)

        if 'REMOVE' in self.request:
            for interface in self.getIntrospector().getDirectlyProvidedNames():
                if "rem_%s" % interface in self.request:
                    ob = self.context
                    interface = getInterface(ob, interface)
                    directlyProvides(removeAllProxies(ob), directlyProvidedBy(ob)-interface)
Esempio n. 20
0
    def __call__(self):
        revid = int(self.context.__name__)
        content = self.context.__parent__.__parent__

        self.revid = revid
        self.content = content

        removeAllProxies(content)._v_currentRevision = revid

        rendered = super(ContentRevision, self).__call__()

        removeAllProxies(content)._v_currentRevision = None

        return rendered
Esempio n. 21
0
    def publishTraverse(self, request, name):
        view = queryMultiAdapter((self.context, request), name=name)
        if view is not None:
            return view

        tasks = self.context.__parent__.__parent__.get('tasks')
        if tasks is not None:
            task = tasks.get(name)
            if task is not None:
                id = getUtility(IIntIds).getId(removeAllProxies(self.context))
                if task.milestone == id:
                    return LocationProxy(
                        removeAllProxies(task), self.context, name)

        raise NotFound(self.context, name, request)
Esempio n. 22
0
 def getValuePng(self, params=None):
     """get Picture"""
     self.request.response.setHeader('Content-Type', 'image/png')
     obj = removeAllProxies(self.context)
     targetPic = str("/tmp/%s%s.png" % \
                     (str(obj.objectID), params['nameext']))
     if 1:  ##fileage > 60:
         myDisplayString1 = "bit"
         myDisplayString2 = "bit"
         rrdFile = "/home/markus/tmp/%s.rrd" % str(obj.objectID)
         rrdtool.graph(
            targetPic,
            "DEF:avg0=%s:ds1:AVERAGE" % (rrdFile),
            "DEF:max0=%s:ds1:MAX" % (rrdFile),
            "CDEF:avg=avg0,%f,*" % (1.0),
            "CDEF:max=max0,%f,*" % (1.0),
            "--start=%d" % params['starttime'],
            "--end=%d" % params['endtime'],
            "--width=540",
            "--height=120",
            "--vertical-label=%s" %myDisplayString1,
            'GPRINT:avg:AVERAGE:avg\: %%lf %s' %myDisplayString2,
            'GPRINT:max:MAX:max\: %%lf %s' %myDisplayString2,
            "AREA:avg#7DD0BC:\"average\"",
            "LINE1:max#008263:\"max\"",
            "--imgformat=PNG",
            "--imginfo=<IMG SRC=\"/img/%s\" WIDTH=\"%lu\" " \
            "HEIGHT=\"%lu\" ALT=\"Demo\">")
     pic = open(targetPic, "r")
     picMem = pic.read()
     pic.close()
     return picMem
Esempio n. 23
0
    def handleSend(self, action):
        request = self.request
        data, errors = self.extractData()

        if errors:
            IStatusMessage(request).add(self.formErrorsMessage, 'error')
        else:
            message = data['message']
            members = self.context.members
            getPrincipal = getUtility(IAuthentication).getPrincipal
            invitations = getUtility(IInvitations)
            group = removeAllProxies(self.context)

            for pid in request.get('principal.users', ()):
                try:
                    principal = getPrincipal(pid)
                except PrincipalLookupError:
                    continue

                if not invitations.catalog.search(
                    group, type = {'any_of': ('invitation.member',)},
                    principal = {'any_of': (pid,)}):
                    removeSecurityProxy(members).invite(pid, message)

            IStatusMessage(request).add(_(u'Invitations have been sent.'))
            self.redirect('.')
Esempio n. 24
0
    def search(self, object=None, **kw):  # , contexts=()

        ids = getUtility(IIntIds)

        query = dict(kw)

        # records for object
        if object is not None:
            if type(object) is not type({}):
                oid = ids.queryId(removeAllProxies(object))
                if oid is None:
                    return ResultSet(IFBTree(), getUtility(IAcknowledgements))

                query['object'] = {'any_of': (oid, )}
            else:
                query['object'] = object

        # context
        # if not contexts:
        #     contexts = (getSite(),)

        # c = []
        # for context in contexts:
        #     id = ids.queryId(removeAllProxies(context))
        #     if id is not None:
        #         c.append(id)

        # query['contexts'] = {'any_of': c}

        return ResultSet(self.apply(query), getUtility(IAcknowledgements))
Esempio n. 25
0
    def _prepareViews(self):
        views = {IBrowserRequest: [], IXMLRPCRequest: [], IHTTPRequest: [],
                 IFTPRequest: [], None: []}
        type_map = {IBrowserRequest: 'Browser', IXMLRPCRequest: 'XMLRPC',
                    IHTTPRequest: 'HTTP', IFTPRequest: 'FTP', None: 'Other'}
        level_map = {'generic': component.GENERIC_INTERFACE_LEVEL,
                     'extended': component.EXTENDED_INTERFACE_LEVEL,
                     'specific': component.SPECIFIC_INTERFACE_LEVEL}

        iface = removeAllProxies(self.context)

        for reg in presentation.getViews(iface):
            type = presentation.getPresentationType(reg.required[-1])

            views[(type in views) and type or None].append(reg)


        sort_function = lambda x, y: cmp(x['name'], y['name'])

        for type, sel_views in views.items():
            for level, qualifier in level_map.items():
                regs = tuple(component.filterAdapterRegistrations(
                    sel_views, iface, level=qualifier))
                infos = [presentation.getViewInfoDictionary(reg)
                         for reg in regs]
                infos.sort()
                setattr(self, level+type_map[type]+'Views', infos)
Esempio n. 26
0
 def __init__(self, obj):
     self._obj = removeAllProxies(obj)
     self._connection = self._obj._p_jar
     self._storage = self._connection._storage
     self._oid = self._obj._p_oid
     self._history = None
     self._by_tid = {}
Esempio n. 27
0
def getEvaluationsTodo(context):
    """List of Content objects"""
    retSet = set([])
    my_catalog = zapi.getUtility(ICatalog)
    if hasattr(context, "requirements"):
        requirements = removeAllProxies(context.requirements)
        if requirements is not None:
            for requirement in requirements:
                if type(requirement) is unicode:
                    res = my_catalog.searchResults(oid_index=requirement)
                else:
                    res = my_catalog.searchResults(
                        oid_index=requirement.objectID)
                if len(res) > 0:
                    startReq = iter(res).next()
                    allObjReqs = []
                    allTmpObjReqs = getRequirementList(startReq)
                    for req in allTmpObjReqs:
                        #                        if req.validAsFirst and len(req) > 0:
                        if len(req) > 0:
                            pass
                        else:
                            allObjReqs.append(req)
                    allObjEvaluations = getEvaluationsDone(context)
                    alreadyCheckedReqs = [
                        ev[0] for ev in allObjEvaluations.items()
                    ]
                    retSet = retSet.union(
                        set(allObjReqs).difference(alreadyCheckedReqs))
    retList = list(retSet)
    retList.sort()
    return retList
Esempio n. 28
0
 def getStateDict(self):
     """get the object state in form of a dict
     """
     overviewNum = 0  # 0: ok, 1: warn, 2: error
     warnList = []
     errorList = []
     retDict = {}
     obj = removeAllProxies(self.context)
     owfs = obj.workflows
     wfrd = owfs['dev_nagios1'].workflowRelevantData
     if wfrd.state == "offline":
         if overviewNum < 1:
             overviewNum = 1
         mesg = _(u'Warning: ')
         mesg += _(u"'device is offline'")
         warnList.append(mesg)
     if wfrd.state == "notification1":
         if overviewNum < 2:
             overviewNum = 2
         mesg = _(u'Error: ')
         mesg += _(u"'device is in notification1'")
         warnList.append(mesg)
     retDict['overview'] = ('ok', 'warn', 'error')[overviewNum]
     retDict['warnings'] = warnList
     retDict['errors'] = errorList
     if overviewNum == 0:
         return None
     return retDict
Esempio n. 29
0
 def triggerEventCrossbarEvent(self, str_time, str_mode):
     from zope.proxy import removeAllProxies
     obj = removeAllProxies(self.context)
     obj.__setattr__("lastEventCrossbar", str_time)
     globalEventCrossbarUtility.receiveEventCrossbar(self.request,
                                                     str_time,
                                                     str_mode)
Esempio n. 30
0
def taskAttributesConfig(context):
    while not IProject.providedBy(context):
        context = context.__parent__
        if context is None:
            return

    return removeAllProxies(context.get('tasks'))
Esempio n. 31
0
    def installUtility(self):
        sm = getSiteManager()

        if 'auth' in sm:
            pau = sm[u'auth']
            sm.registerUtility(pau, IAuthentication)
            return

        portal = getSite()
        if IContainmentRoot.providedBy(portal):
            prefix = u''
        else:
            id = getUtility(IIntIds).queryId(removeAllProxies(portal))
            if not id:
                id = u''
            prefix = u'%s.'%id

        # PluggableAuthentication
        pau = PluggableAuthentication(prefix)
        event.notify(ObjectCreatedEvent(pau))
        sm[u'auth'] = pau
        sm.registerUtility(pau, IAuthentication)

        # Credentials Plugin
        factory = getUtility(ICredentialsPluginFactory, 'default.credentials')
        factory.install()
        factory.activate()
Esempio n. 32
0
def milestoneModified(milestone, ev):
    if milestone.state == 1:
        name = u'project.milestone.active'
    else:
        name = u'project.milestone.completed'

    IObjectPermissionsMapsManager(removeAllProxies(milestone)).set((name,))
Esempio n. 33
0
 def getProvidedAdapters(self):
     """Get adapters where this interface is provided."""
     # Must remove security and location proxies, so that we have access to
     # the API methods and class representation.
     regs = component.getProvidedAdapters(removeAllProxies(self.context))
     return [component.getAdapterInfoDictionary(reg)
             for reg in regs]
Esempio n. 34
0
 def getUtilities(self):
     """Return all utilities that provide this interface."""
     # Must remove security and location proxies, so that we have access to
     # the API methods and class representation.
     regs = component.getUtilities(removeAllProxies(self.context))
     return [component.getUtilityInfoDictionary(reg)
             for reg in regs]
Esempio n. 35
0
 def getWFMCs(self):
     """
     return list of Workflows of this object
     """
     obj = removeAllProxies(self.context)
     owfs = obj.workflows
     return owfs
Esempio n. 36
0
    def update(self):
        uid = getUtility(IIntIds).getId(removeAllProxies(self.context))
        ws = self.context.__parent__.__parent__

        self.news = Batch(
            ws.news(categories=(uid,)),
            size=ws.pageSize, request=self.request)
Esempio n. 37
0
 def triggerCronEvent(self, str_time, str_mode):
     print "AdmUtilCronRpcMethods.triggerCronEvent(%s, %s)" % \
           (str_time, str_mode)
     from zope.proxy import removeAllProxies
     obj = removeAllProxies(self.context)
     obj.__setattr__("lastCron", str_time)
     globalCronUtility.receiveCron(self.request, str_time, str_mode)
Esempio n. 38
0
    def update(self):
        super(PreviewsCatalogBuildView, self).update()
        request = self.request
        context = removeAllProxies(self.context)

        filefield_objects = self.catalog\
            .searchResults(type={'any_of': self.f2c_mapping.keys()}) #,
                           #sort_on='modified', sort_order='reverse')

        if 'form.button.build' in request:
            for obj in filefield_objects:
                self.previewForObject(obj)

            IStatusMessage(request).add(
                _('Previews catalog has been builded.'))

        elif 'form.button.build_selected' in request:
            for id in request.get('form.checkbox.id', ()):
                obj = self.int_ids.queryObject(int(id))
                self.previewForObject(obj)

            IStatusMessage(request).add(
                _('Previews for selected files has been builded.'))

        #results = [o for o in filefield_objects if self.previewsNotExists(o)]
        #self.batch = Batch(results, size=20, context=context, request=request)
        self.batch = Batch(filefield_objects,
                           size=20, context=context, request=request)
Esempio n. 39
0
    def __BBB_old_getComponent(self, path):
        service_manager = zapi.getSiteManager(self)

        # Get the root and unproxy it
        if path.startswith("/"):
            # Absolute path
            root = removeAllProxies(zapi.getRoot(service_manager))
            component = zapi.traverse(root, path)
        else:
            # Relative path.
            ancestor = self.__parent__.__parent__
            component = zapi.traverse(ancestor, path)

        if self.permission:
            if type(component) is Proxy:
                # There should be at most one security Proxy around an object.
                # So, if we're going to add a new security proxy, we need to
                # remove any existing one.
                component = removeSecurityProxy(component)

            interface = self.getInterface()

            checker = InterfaceChecker(interface, self.permission)

            component = Proxy(component, checker)

        return component
Esempio n. 40
0
    def update(self):
        super(AttachView, self).update()

        id = getUtility(IIntIds).queryId(removeAllProxies(self.context))

        self.url = '%s/@@content.attachment/%s/'%(
            absoluteURL(getSite(), self.request), id)
Esempio n. 41
0
    def search(self, object=None, **kw):  # , contexts=()

        ids = getUtility(IIntIds)

        query = dict(kw)

        # records for object
        if object is not None:
            if type(object) is not type({}):
                oid = ids.queryId(removeAllProxies(object))
                if oid is None:
                    return ResultSet(IFBTree(), getUtility(IAcknowledgements))

                query["object"] = {"any_of": (oid,)}
            else:
                query["object"] = object

        # context
        # if not contexts:
        #     contexts = (getSite(),)

        # c = []
        # for context in contexts:
        #     id = ids.queryId(removeAllProxies(context))
        #     if id is not None:
        #         c.append(id)

        # query['contexts'] = {'any_of': c}

        return ResultSet(self.apply(query), getUtility(IAcknowledgements))
Esempio n. 42
0
    def collectViewlets(self):
        indirect = list(
            zope.component.getAdapters(
                (self.context, self.request, self.view, self),
                zope.viewlet.interfaces.IViewlet))
        adapted = [(v, IViewlet(a, None)) for (v, a) in indirect]

        result = dict(adapted)

        direct = list(
            zope.component.getAdapters(
                (self.context, self.request, self.view, self), IViewlet))
        result.update(dict(direct))

        # XXX: This is also a workaround Zope's bug - if an adapter
        #      has a specified a permission and returns None, instead
        #      of being filtered by getAdapters it returns a security
        #      proxied located instance of None.
        for name in list(result):
            if removeAllProxies(result[name]) is None:
                del result[name]

        for name, viewlet in result.items():
            unproxied = zope.security.proxy.removeSecurityProxy(viewlet)
            if unproxied.__name__ != name:
                unproxied.__name__ = name

        viewlets = dict(self.filterViewlets(result.items()))
        return viewlets
Esempio n. 43
0
 def renderComment(self):
     source = zope.component.createObject(
         self.context.source_type, 
         self.context.comment)
     renderer = zope.component.getMultiAdapter(
         (removeAllProxies(source), self.request),
         IHTMLRenderer, name = u'')
     return renderer.render(limit = self.limit)
 def testTraverseNameSiteManager(self):
     pub = self.klass(self.db)
     class C(object):
         def getSiteManager(self):
             return SimpleObject(1)
     ob = C()
     r = self._createRequest('/++etc++site',pub)
     ob2 = pub.traverseName(r, ob, '++etc++site')
     self.assertEqual(removeAllProxies(ob2).v, 1)
Esempio n. 45
0
 def default(self, o, **settings):
     if proxy.isProxy(o, JSONEncoderSettingsProxy):
         o, settings = proxy.getProxiedObject(o), o.__json_settings__
     if proxy.isProxy(o):
         o = proxy.removeAllProxies(o)
         return o
     adapter = self.adapters.lookup_adapter(providedBy(o))
     if adapter is None:
         raise TypeError("%r is not JSON serializable" % o)
     return adapter(o, **settings)
Esempio n. 46
0
    def acknowledge(self, value):
        context = removeAllProxies(self.context)

        if value is None or not value:
            if IContentAcknowledgementAware.providedBy(context):
                interface.noLongerProvides(context,
                                           IContentAcknowledgementAware)
        else:
            if not IContentAcknowledgementAware.providedBy(context):
                interface.alsoProvides(context, IContentAcknowledgementAware)
Esempio n. 47
0
    def getIndexes(self):
        names = []

        for index in self.values():
            names.append(removeAllProxies(index.__name__))
            yield index

        for name, indexFactory in getAdapters((self, ), ICatalogIndexFactory):
            if name not in names:
                yield self.createIndex(name, indexFactory)
Esempio n. 48
0
def mapply(obj, positional=(), request={}):
    __traceback_info__ = obj

    # we need deep access for introspection. Waaa.
    unwrapped = removeAllProxies(obj)

    unwrapped, wrapperCount = unwrapMethod(unwrapped)

    code = getattr(unwrapped, '__code__', None)
    if code is None:
        code = unwrapped.func_code
    defaults = getattr(unwrapped, '__defaults__', None)
    if defaults is None:
        defaults = getattr(unwrapped, 'func_defaults', None)
    names = code.co_varnames[wrapperCount:code.co_argcount]

    nargs = len(names)
    if not positional:
        args = []
    else:
        args = list(positional)
        if len(args) > nargs:
            given = len(args)
            if wrapperCount:
                given += wrapperCount
            raise TypeError(
                '%s() takes at most %d argument%s(%d given)' %
                (getattr(unwrapped, '__name__', repr(obj)), code.co_argcount,
                 (code.co_argcount > 1 and 's ' or ' '), given))

    get = request.get
    nrequired = len(names)
    if defaults:
        nrequired -= len(defaults)

    for index in range(len(args), nargs):
        name = names[index]
        v = get(name, _marker)
        if v is _marker:
            if name == 'REQUEST':
                v = request
            elif index < nrequired:
                raise TypeError(
                    'Missing argument to %s(): %s' %
                    (getattr(unwrapped, '__name__', repr(obj)), name))
            else:
                v = defaults[index - nrequired]
        args.append(v)

    args = tuple(args)

    if __debug__:
        return debug_call(obj, args)

    return obj(*args)
Esempio n. 49
0
def handle_interface(dotted_path, ob=None):
    """Determine, whether the given path/obj references an interface.
    """
    if ob is None:
        try:
            ob = resolve(dotted_path)
        except ImportError:
            return None
    if not isinstance(removeAllProxies(ob), InterfaceClass):
        return None
    return DocGrokInterface(dotted_path)
 def __call__(self):
     ctxt = removeAllProxies(self.context)
     item = ctxt.participant.activity.process.context.item
     label = zope.component.queryMultiAdapter((item, self.request),
                                              name='label')
     if not label:
         return _(u"Unkown")
     try:
         return translate(label(), context=self.request)
     except Exception:
         return label()
Esempio n. 51
0
def getCatalog():
    sm = getSite().getSiteManager()

    if 'acknowledgementsCatalog' in sm:
        return sm['acknowledgementsCatalog']

    else:
        catalog = AcknowledgementsCatalog()
        event.notify(ObjectCreatedEvent(catalog))
        removeAllProxies(sm)['acknowledgementsCatalog'] = catalog
        return sm['acknowledgementsCatalog']
 def handleFixate(self, action):
     data, errors = self.extractData()
     if errors:
         self.status = self.formErrorsMessage
         return
     history = interfaces.IWorkflowHistory(self.context)
     principal = getattr(self.request, 'principal', None)
     pd = zope.component.getUtility(IProcessDefinition,
                                    name=self.process_id,
                                    context=self.context)
     proc = pd()
     # TODO: Note that we have to remove the security proxy!
     proc.start(getattr(principal, 'id', u"Unkown"),
                datetime.datetime.now(), data['workflow-message'],
                removeAllProxies(history), removeAllProxies(self.context))
     history.append(
         UserNotation(getattr(principal, 'id', u"Unknown"),
                      data['workflow-message']))
     #self.template = ViewPageTemplateFile('fixate_process_started.pt')
     self.request.response.redirect(self.nextURL())
    def testTraverseName(self):
        pub = self.klass(self.db)
        class C(object):
            x = SimpleObject(1)
        ob = C()
        r = self._createRequest('/x', pub)
        component.provideAdapter(TestTraverser, (None, IXMLRPCRequest),
                                 IXMLRPCPublisher)

        ob2 = pub.traverseName(r, ob, 'x')
        self.assertEqual(removeAllProxies(ob2).v, 1)
Esempio n. 54
0
 def download(self):
     upfile = removeAllProxies(self.context.file)
     if self.request is not None:
         self.request.response.setHeader('Content-Type',
                                         self.context.contentType)
         self.request.response.setHeader('Content-Length', upfile.getSize())
         self.request.response.setHeader(\
             'Content-Disposition',
             u'attachment; filename=\"%s\"' % self.context.filename)
     setNoCacheHeaders(self.request.response)
     return upfile.openDetached()
Esempio n. 55
0
 def dumpData(self):
     """
     pretty print for web-interface
     """
     import pprint
     obj = removeAllProxies(self.context)
     pickleAdapter = IPickle(obj)
     if pickleAdapter:
         return pprint.pformat(pickleAdapter.exportAsDict(), \
                                width = 60, depth = 6)
     else:
         return _(u"no pickle adapter")
Esempio n. 56
0
 def getHistory(self):
     """
     special format list of the history for web-view
     """
     retList = []
     obj = removeAllProxies(self.context)
     historyList = obj.history
     for entry in historyList:
         tmpList = entry.getList(['date', 'text', 'level', \
                                  'version', 'bgcolor'])
         retList.append(tmpList )
     retList.sort(lambda a, b: cmp(b[0], a[0]))
     return retList
Esempio n. 57
0
 def __init__(self, obj, tid=None, _history=None):
     self.obj = removeAllProxies(obj)
     if _history is None:
         # Not using IObjectHistory(self.obj) because LP: #1185175
         _history = getObjectHistory(self.obj)
     else:
         assert _history._obj is self.obj
     self.history = _history
     self.tid = None
     self.requestedTid = tid
     self.loadError = None
     self.pickledState = ''
     self._load()
 def renderCell(self, item):
     source = zope.component.createObject(item.source_type, item.comment)
     renderer = zope.component.getMultiAdapter(
         (removeAllProxies(source), self.request), IHTMLRenderer, name=u'')
     intids = zope.component.getUtility(IIntIds, context=self.context)
     cid = intids.getId(item)
     cell = renderer.render(limit=self.limit)
     more_anchor = _('more-link', "[Read more]")
     cell += "<div><a href='%s'>%s</a></div>" % (
         absoluteURL(item.about, self.request) + '/@@comment.html?id=' +
         unicode(cid) + '#tabs',
         translate(more_anchor, context=self.request, default=more_anchor))
     return cell
Esempio n. 59
0
 def getHistory(self):
     """
     return List of history entries for the browser
     """
     retList = []
     obj = removeAllProxies(self.context)
     historyList = obj.history
     for entry in historyList:
         tmpList = entry.getList(['date', 'text', 'level', \
                                  'version', 'bgcolor'])
         retList.append(tmpList)
     retList.sort(lambda a, b: cmp(b[0], a[0]))
     return retList
    def create(self, data):
        obj = Comment()
        form.applyChanges(self, obj, data)
        obj.source_type = 'html'
        obj.about = removeAllProxies(self.context)

        # Grant the current user the Edit permission by assigning him
        # the quotationtool.Creator role, but only locally in the
        # context of the newly created object.
        manager = IPrincipalRoleManager(obj)
        manager.assignRoleToPrincipal('quotationtool.Creator',
                                      self.request.principal.id)

        return obj