Example #1
0
    def publishTraverse(self, request, name):
        # Try to get an object using default traversal
        adapter = DefaultPublishTraverse(self.context, request)
        try:
            obj = adapter.publishTraverse(request, name)
            if (not IContentish.providedBy(obj)
                    and not IService.providedBy(obj)):
                raise KeyError

        # If there's no object with the given name, we get a KeyError.
        # In a non-folderish context a key lookup results in an AttributeError.
        except (KeyError, AttributeError):
            # No object, maybe a named rest service
            service = queryMultiAdapter((self.context, request),
                                        name=request._rest_service_id + name)
            if service is None:
                # No service, fallback to regular view
                view = queryMultiAdapter((self.context, request), name=name)
                if view is not None:
                    return view
                raise
            return service
        else:
            # Wrap object to ensure we handle further traversal
            return RESTWrapper(obj, request)
    def test_plone_app_imaging_image_scale(self):
        request = self.portal.REQUEST
        view = self.portal['image'].unrestrictedTraverse('@@images')
        image = view.scale('image', 'mini')
        if not image:
            return

        # Rewrap image scale to leave out the image class
        # implementation. We do this to test the situation where we do
        # not have class-supported publishing (e.g. with schema
        # extension).
        image = image.aq_base.__of__(self.portal)

        adapter = DefaultPublishTraverse(image, request)
        ob2 = adapter.publishTraverse(request, 'index_html')

        os.environ['XSENDFILE_RESPONSEHEADER'] = 'X-SENDFILE'
        request.set('HTTP_X_FORWARDED_FOR', '0.0.0.0')

        ob2()
        content_type = request.RESPONSE.getHeader('content-type')
        self.assertEqual(content_type, 'image/jpeg')

        xsendfile = request.RESPONSE.getHeader('X-SENDFILE')
        self.assertTrue(xsendfile is not None)
Example #3
0
 def publishTraverse(self, request, name):
     """
     Make sure we don't end up in
     Products.Five.browser.metaconfigure.ViewMixinForTemplates's
     publishTraverse.
     """
     adapter = DefaultPublishTraverse(self, request)
     return adapter.publishTraverse(request, name)
Example #4
0
 def publishTraverse(self, request, name):
     """
     Make sure we don't end up in
     Products.Five.browser.metaconfigure.ViewMixinForTemplates's
     publishTraverse.
     """
     adapter = DefaultPublishTraverse(self, request)
     return adapter.publishTraverse(request, name)
 def publishTraverse(self, request, name):
     if name in self.getUniqueCountriesNames().keys():
         self.country = name
         return self
     try:
         return super(PloneInListing, self).publishTraverse(request, name)
     except NotFound:
         default = DefaultPublishTraverse(self, request)
         return default.publishTraverse(request, name)
 def publishTraverse(self, request, name):
     if name in self.getUniqueCountriesNames().keys():
         self.country = name
         return self
     try:
         return super(PloneInListing, self).publishTraverse(request, name)
     except NotFound:
         default = DefaultPublishTraverse(self, request)
         return default.publishTraverse(request, name)
Example #7
0
 def publishTraverse(self, request, name):
     try:
         return self.traverse(name)
     except TraversalError:
         pass
     try:
         return super(TableWidget, self).publishTraverse(request, name)
     except NotFound:
         default = DefaultPublishTraverse(self, request)
         return default.publishTraverse(request, name)
Example #8
0
 def publishTraverse(self, request, name):
     try:
         return self.traverse(name)
     except traversing.interfaces.TraversalError:
         pass
     try:
         return super(BaseSourceFormWrapper, self).publishTraverse(request, name)
     except publisher.interfaces.NotFound:
         default = DefaultPublishTraverse(self, request)
         return default.publishTraverse(request, name)
Example #9
0
 def publishTraverse(self, request, name):
             
     if name in self.object_ids:
         return self.objects.get(name).__of__(self.context)
     else:
         
         import pdb; pdb.set_trace()
         
         default_adapter = DefaultPublishTraverse(object, self)
         ob2 = default_adapter.publishTraverse(self, name)
         return ob2
Example #10
0
 def publishTraverse(self, request, name):
     """ Look up the field whose name matches the next URL path element, and wrap it.
     """
     try:
         return EasyFormFieldContext(self.schema[name], self.request).__of__(self)
     except KeyError:
         return DefaultPublishTraverse(self, request).publishTraverse(request, name)
class MultilanguageTraverse(object):
    implements(IPublishTraverse)
    adapts(IAnnotatable, IHTTPRequest)

    def __init__(self,context,request):
        self.context = context
        self.request = request
        self.default_traverse = DefaultPublishTraverse(context, request)
        self.handler = IMultilanguageURLHandler(context, None)

    def publishTraverse(self, request, name):
        if self.handler is not None:
            ob = self.handler.get_object(name)
            if ob is not None:
                langs = self.handler.get_langs(name)
                if len(langs) == 1:
                    try:
                        portal_languages = getToolByName(self.context, 'portal_languages')
                        portal_languages.REQUEST.set_lazy('set_language', lambda: langs[0])
                        portal_languages.setLanguageBindings()
                    except:
                        pass
                return ob
        try:
            return self.default_traverse.publishTraverse(request, name)
        except NotFound:
            pass
        except KeyError:
            pass
        except AttributeError:
            pass
        raise NotFound(self.context, name, self.request)
Example #12
0
 def publishTraverse(self, request, name):
     if name == 'index_html':
         view = queryMultiAdapter((self.context, request), Interface,
                                  'plone-overview')
         if view is not None:
             return view
     return DefaultPublishTraverse.publishTraverse(self, request, name)
 def publishTraverse(self, request, name):
     if name == 'index_html':
         view = queryMultiAdapter(
             (self.context, request), Interface, 'plone-overview')
         if view is not None:
             return view
     return DefaultPublishTraverse.publishTraverse(self, request, name)
Example #14
0
    def publishTraverse(self, request, name):
        try:
            return DefaultPublishTraverse.publishTraverse(self, request, name)
        except KeyError:
            if ILayer.providedBy(request):
                registry = getUtility(IRegistry)
                settings = registry.forInterface(IRoutesSettings)
                activated_routes = settings.routes

                fullpath = request.physicalPathFromURL(
                    request.get('ACTUAL_URL', ''))
                context_path = self.context.getPhysicalPath()
                fullpath = fullpath[len(context_path):]
                for route_name in activated_routes:
                    route = getRoute(route_name)
                    if not route:
                        continue
                    if route.matches(fullpath, request):
                        fragments = route.fragments
                        fragment = fragments[0]
                        query = route.defaultQuery.copy()
                        query.update(fragment.query(name))
                        return FragmentContext(self.context, request, name,
                            route, fragments[0], fragments[1:],
                            query).__of__(self.context)

            raise
Example #15
0
    def publishTraverse(self, request, name):
        try:
            return DefaultPublishTraverse.publishTraverse(self, request, name)
        except KeyError:
            if ILayer.providedBy(request):
                pprops = getToolByName(self.context, 'portal_properties')
                props = pprops.routes_properties
                activated_routes = props.getProperty('activated_routes', ())

                #path = request.environ['PATH_INFO'].split('/')
                path = request.physicalPathFromURL(request['URL'])
                context_path = self.context.getPhysicalPath()
                path = path[len(context_path):]

                for route_name in activated_routes:
                    route = getRoute(route_name)
                    if not route:
                        continue
                    if route.fragments[0].matches(path[0]):
                        fragments = route.fragments
                        fragment = fragments[0]
                        query = route.defaultQuery.copy()
                        query.update(fragment.query(name))
                        return FragmentContext(self.context, request, name,
                            route, fragments[0], fragments[1:],
                            query).__of__(self.context)
            raise
Example #16
0
    def publishTraverse(self, request, name):
        if name == self.__name__:
            editView = SQLEditView(self, request).__of__(self)
            #we need to know the fti in the field in order to get the correct columns vocabulary
            #from fti.sql_connection and fti.sql_table
            editView.field.context = self
            return editView

        return DefaultPublishTraverse(self, request).publishTraverse(request, name)
Example #17
0
    def test_plone_app_blob_image_not_configured(self):
        request = self.portal.REQUEST
        view = self.portal['image'].unrestrictedTraverse('@@images')
        image = view.publishTraverse(request, 'image')

        # Rewrap image scale to leave out the image class
        # implementation. We do this to test the situation where we do
        # not have class-supported publishing (e.g. with schema
        # extension).
        image = image.aq_base.__of__(self.portal)

        adapter = DefaultPublishTraverse(image, request)
        ob2 = adapter.publishTraverse(request, 'index_html')

        request.set('HTTP_X_FORWARDED_FOR', '0.0.0.0')

        ob2()
        xsendfile = request.RESPONSE.getHeader('X-SENDFILE')
        self.assertIsNone(xsendfile)
Example #18
0
    def publishTraverse(self, request, name):
        """ It's not valid to traverse to anything below a field context.
        """
        # hack to make inline validation work
        # (plone.app.z3cform doesn't know the form is the default view)
        if name == self.__name__:
            return ActionEditView(self, request).__of__(self)

        return DefaultPublishTraverse(self,
                                      request).publishTraverse(request, name)
    def test_plone_app_blob_image_not_configured(self):
        request = self.portal.REQUEST
        view = self.portal['image'].unrestrictedTraverse('@@images')
        image = view.publishTraverse(request, 'image')

        # Rewrap image scale to leave out the image class
        # implementation. We do this to test the situation where we do
        # not have class-supported publishing (e.g. with schema
        # extension).
        image = image.aq_base.__of__(self.portal)

        adapter = DefaultPublishTraverse(image, request)
        ob2 = adapter.publishTraverse(request, 'index_html')

        request.set('HTTP_X_FORWARDED_FOR', '0.0.0.0')

        ob2()
        xsendfile = request.RESPONSE.getHeader('X-SENDFILE')
        self.assertIsNone(xsendfile)
Example #20
0
 def publishTraverse(self, request, name):
     # Traversal in Plone always starts with the site root. Therefore we
     # have to guess if this is a real request for the portal root. What
     # Plone does on portal root is pretty complex, therefore we have to
     # check for multiple different scenarios. It would be good if this
     # could be refactored to be simpler and more reliable.
     if name == '' or name == 'folder_listing':
         return SerializeToJsonView(self.context, request)
     # If this is just the first traversal step, make sure the traversal
     # continues.
     return DefaultPublishTraverse.publishTraverse(self, request, name)
Example #21
0
    def testDefaultPublish(self):
        request = self.folder.REQUEST
        view = self.image.unrestrictedTraverse('@@images')
        image = view.publishTraverse(request, 'image')
        size = image.get_size()

        # Rewrap image scale to leave out the image class
        # implementation. We do this to test the situation where we do
        # not have class-supported publishing (e.g. with schema
        # extension).
        image = image.aq_base.__of__(self.folder)

        from ZPublisher.BaseRequest import DefaultPublishTraverse
        adapter = DefaultPublishTraverse(image, request)
        ob2 = adapter.publishTraverse(request, 'index_html')
        ob2()
        content_type = request.RESPONSE.getHeader('content-type')
        content_length = request.RESPONSE.getHeader('content-length')
        self.assertEqual(content_type, 'image/gif')
        self.assertEqual(content_length, str(size))
Example #22
0
    def test_publishTraverse_to_allowed_name(self):
        # The ``eagle.method`` view has a method ``eagle`` that is registered
        # with ``allowed_attributes`` in pages.zcml. This attribute should be
        # reachable through ``publishTraverse`` on the view.

        folder = self.folder
        view = folder.unrestrictedTraverse('testoid/eagle.method')

        # Publishing traversal with the default adapter should work:

        from ZPublisher.BaseRequest import DefaultPublishTraverse
        request = folder.REQUEST
        adapter = DefaultPublishTraverse(view, request)
        result = adapter.publishTraverse(request, 'eagle')()
        self.assertIn('The eagle has landed', result)

        # Publishing via browser works, too:

        self.browser.open(
            'http://localhost/test_folder_1_/testoid/eagle.method/eagle')
        self.assertEqual('The eagle has landed', self.browser.contents)
Example #23
0
    def fallback(self, request, name):
        """ Fallback
        """
        # Because the following methods of getting a thumbnail are not
        # based on real image fields, we'll look for a fake thumbnail
        # only when the name looks like a thumbnail request
        if (not name.startswith('image_')) or (name.startswith('image_view')):
            return DefaultPublishTraverse.publishTraverse(self, request, name)

        # In some cases we want to fallback on a different image
        # than the one used for the portal type. In this dictionary we can
        # specify images that should be used if the context provides a certain
        # interface. All you have to do is to register a named-utility for
        # IDepictionVocabulary
        overrides = {}
        for voc in getAllUtilitiesRegisteredFor(IDepictionVocabulary):
            overrides.update(
                dict((term.value, term.title) for term in voc(self.context))
            )

        context = self.context
        _fieldname, scale = name.split('_', 1)
        if scale and (scale.lower().endswith('.jpg') or
                      scale.lower().endswith('.png')):
            scale = scale[:-4]

        # Regular imgview
        imgview = queryMultiAdapter((context, request), name='imgview')

        # Fallback imgview
        if (imgview is None) or (not imgview.display(scale)):
            portal = getToolByName(context, 'portal_url').getPortalObject()
            image_obj_id = None
            provided_interfaces = [i.__identifier__
                                   for i in providedBy(context).flattened()]
            for k, v in overrides.items():
                if k in provided_interfaces:
                    image_obj_id = v
                    break

            if image_obj_id is None:
                image_obj_id = context.portal_type.replace(' ', '-').lower()

            tool = queryUtility(IDepictionTool)
            if not tool:
                raise NotFound(portal, 'portal_depiction', request)

            if image_obj_id in tool.objectIds():
                image_obj = tool[image_obj_id]
            else:
                image_obj = tool['generic']
            imgview = getMultiAdapter((image_obj, request), name='imgview')
        return imgview(scale)
Example #24
0
    def test_publishTraverse_to_allowed_interface(self):
        # The ``cheeseburger`` view has a method ``meat`` that is
        # registered via ``allowed_interface`` in pages.zcml. This attribute
        # should be reachable through ``publishTraverse`` on the view.

        folder = self.folder
        view = folder.unrestrictedTraverse('testoid/cheeseburger')

        # Publishing traversal with the default adapter should work:

        from ZPublisher.BaseRequest import DefaultPublishTraverse
        request = folder.REQUEST
        adapter = DefaultPublishTraverse(view, request)
        result = adapter.publishTraverse(request, 'meat')()
        self.assertIn('yummi', result)

        # Publishing via browser works, too:

        self.browser.open(
            'http://localhost/test_folder_1_/testoid/cheeseburger/meat')
        self.assertEqual('yummi', self.browser.contents)
Example #25
0
 def publishTraverse(self, request, name):
     """ Look up the field whose name matches the next URL path element, and wrap it.
     """
     ifaces = list(self.additionalSchemata)
     field = None
     for iface in ifaces:
         if name in list(iface):
             field = iface[name]
     if not field and name in list(self.schema):
         field = self.schema[name]
     if field:
         return SQLFieldContext(field, self.request).__of__(self)
     else: 
         return DefaultPublishTraverse(self, request).publishTraverse(request, name)
Example #26
0
    def test_plone_app_blob_image(self):
        request = self.portal.REQUEST
        view = self.portal['image'].unrestrictedTraverse('@@images')
        image = view.publishTraverse(request, 'image')

        # Rewrap image scale to leave out the image class
        # implementation. We do this to test the situation where we do
        # not have class-supported publishing (e.g. with schema
        # extension).
        image = image.aq_base.__of__(self.portal)

        adapter = DefaultPublishTraverse(image, request)
        ob2 = adapter.publishTraverse(request, 'index_html')

        os.environ['XSENDFILE_RESPONSEHEADER'] = 'X-SENDFILE'
        request.set('HTTP_X_FORWARDED_FOR', '0.0.0.0')

        ob2()
        content_type = request.RESPONSE.getHeader('content-type')
        self.assertEqual(content_type, 'image/gif')

        xsendfile = request.RESPONSE.getHeader('X-SENDFILE')
        self.assertIsNotNone(xsendfile)
        self.assertTrue(os.path.isfile(xsendfile))
Example #27
0
class NavigationRootTraverser(object):
    """Adapter for the navigation traverser using subsites"""

    interface.implements(IPublishTraverse)
    def __init__(self,context,request):
        self.default = DefaultPublishTraverse(context,request)
        self.context = context
        self.request = request

    def publishTraverse(self, request, name):
        obj = self.default.publishTraverse(request, name)
        context = self.context
        if IFrontendLayer.providedBy(request) and not INavigationRoot.providedBy(context):
            interface.alsoProvides(context, INavigationRoot)
        elif not IFrontendLayer.providedBy(request) and INavigationRoot.providedBy(context):
            interface.noLongerProvides(context, INavigationRoot)
        return obj
Example #28
0
    def publishTraverse(self, request, name):
        try:
            fti = getUtility(IDexterityFTI, name=name)
        except ComponentLookupError:
            return DefaultPublishTraverse(self, request).publishTraverse(
                request,
                name
            )

        schema = fti.lookupSchema()
        if 'collective.behavior.sql.behavior.behaviors.ISQLContent' in fti.behaviors:
            schema_context = SQLTypeSchemaContext(
                schema, request, name=name, title=fti.title).__of__(self)
        else:
            schema_context = TypeSchemaContext(
                schema, request, name=name, title=fti.title).__of__(self)
        schema_context.fti = fti
        schema_context.schemaName = u''
        return schema_context
Example #29
0
    def publishTraverse(self, request, name):
        """ 1. Try to find a content type whose name matches the next URL path element.
            2. Look up its schema.
            3. Return a schema context (an acquisition-aware wrapper of the schema).
        """
        try:
            fti = getUtility(IDexterityFTI, name=name)
        except ComponentLookupError:
            return DefaultPublishTraverse(self, request).publishTraverse(
                request, name)

        schema = fti.lookupSchema()
        schema_context = TypeSchemaContext(schema,
                                           request,
                                           name=name,
                                           title=fti.title).__of__(self)
        schema_context.fti = fti
        schema_context.schemaName = u''
        return schema_context
Example #30
0
class NavigationRootTraverser(object):
    """Adapter for the navigation traverser using subsites"""

    interface.implements(IPublishTraverse)

    def __init__(self, context, request):
        self.default = DefaultPublishTraverse(context, request)
        self.context = context
        self.request = request

    def publishTraverse(self, request, name):
        obj = self.default.publishTraverse(request, name)
        context = self.context
        if IFrontendLayer.providedBy(
                request) and not INavigationRoot.providedBy(context):
            interface.alsoProvides(context, INavigationRoot)
        elif not IFrontendLayer.providedBy(
                request) and INavigationRoot.providedBy(context):
            interface.noLongerProvides(context, INavigationRoot)
        return obj
Example #31
0
 def publishTraverse(self, request, name):
     if name.startswith('++'):
         return DefaultPublishTraverse(self, request).publishTraverse(
             request, name)
     return ShippingMethodForm(self.context, request, name)
            return self.get_api().root, ('@@view',)
        except CMISConnectorError, error:
            error.send(request)
            logger.exception('Error while accessing CMIS repository')
            return self.browser, ('@@cmis_error',)

    def publishTraverse(self, request, name):
        try:
            content = self.get_api().traverse(name)
            if content is not None:
                return content
        except CMISConnectorError, error:
            error.send(request)
            logger.exception('Error while accessing CMIS repository')
            return CMISErrorTraverser(self.browser)
        default = DefaultPublishTraverse(self.browser, request)
        return default.publishTraverse(request, name)


class CMISBrowser(Container):
    implements(ICMISBrowser)
    portal_type = "CMIS Browser"
    # Make sure to disable comments
    allow_discussion = False
    security = ClassSecurityInfo()

    browser_description = FieldProperty(ICMISBrowser['browser_description'])
    browser_text = FieldProperty(ICMISBrowser['browser_text'])
    repository_url = FieldProperty(ICMISBrowser['repository_url'])
    title_from_plone = FieldProperty(ICMISBrowser['title_from_plone'])
    repository_name = FieldProperty(ICMISBrowser['repository_name'])
Example #33
0
 def __init__(self, context, request):
     self.default = DefaultPublishTraverse(context, request)
     self.context = context
     self.request = request
Example #34
0
 def __init__(self,context,request):
     self.default = DefaultPublishTraverse(context,request)
     self.context = context
     self.request = request
 def __init__(self,context,request):
     self.context = context
     self.request = request
     self.default_traverse = DefaultPublishTraverse(context, request)
     self.handler = IMultilanguageURLHandler(context, None)
Example #36
0
    def fallback(self, request, name):
        """ Fallback
        """
        # Because the following methods of getting a thumbnail are not
        # based on real image fields, we'll look for a fake thumbnail
        # only when the name looks like a thumbnail request

        if (not name.startswith('image_')) or (name.startswith('image_view')):
            return DefaultPublishTraverse.publishTraverse(self, request, name)

        # In some cases we want to fallback on a different image
        # than the one used for the portal type. In this dictionary we can
        # specify images that should be used if the context provides a certain
        # interface. All you have to do is to register a named-utility for
        # IDepictionVocabulary
        overrides = {}

        for voc in getAllUtilitiesRegisteredFor(IDepictionVocabulary):
            overrides.update(
                dict((term.value, term.title) for term in voc(self.context)))

        context = self.context
        _fieldname, scale = name.split('_', 1)

        if scale and (scale.lower().endswith('.jpg')
                      or scale.lower().endswith('.png')):
            scale = scale[:-4]

        # Regular imgview
        imgview = queryMultiAdapter((context, request), name='imgview')

        # Fallback imgview

        if (imgview is None) or (not imgview.display(scale)):
            portal = getToolByName(context, 'portal_url').getPortalObject()
            image_obj_id = None
            provided_interfaces = [
                i.__identifier__ for i in providedBy(context).flattened()
            ]

            for k, v in overrides.items():
                if k in provided_interfaces:
                    image_obj_id = v

                    break

            if image_obj_id is None:
                image_obj_id = context.portal_type.replace(' ', '-').lower()

            tool = queryUtility(IDepictionTool)

            if not tool:
                raise NotFound(portal, 'portal_depiction', request)

            if image_obj_id in tool.objectIds():
                image_obj = tool[image_obj_id]
            else:
                image_obj = tool['generic']
            imgview = getMultiAdapter((image_obj, request), name='imgview')

        return imgview(scale)
    def getAllowedViews(self):
        """
        This method will return a dict containing the view name as keys
        and filesystem full path to both page template files and python
        files, according if it is a BrowserView or a FSPageTemplate
        """

        pt = getToolByName(self.context, 'portal_types')
        portal_type = self.context.portal_type
        dvt = pt[portal_type]

        result  = {}
        # The following was taken from traverseName function from
        # ZPublisher/BaseRequest.py
        for view in dvt.view_methods:
            if view[:1] in '@+':
                # Process URI segment parameters.
                ns, nm = nsParse(view)
                if ns:
                    try:
                        ob = namespaceLookup(ns, nm, self.context, self.request)
                    except TraversalError:
                        result[view] = {}
                        continue

                    if IAcquirer.providedBy(ob):
                        ob = ob.__of__(self.context)

            else:
                if IPublishTraverse.providedBy(self.context):
                    ob = self.context.publishTraverse(self.request, view)
                else:
                    adapter = queryMultiAdapter((self.context, self.request),
                                                IPublishTraverse)
                    if adapter is None:
                        ## Zope2 doesn't set up its own adapters in a lot of cases
                        ## so we will just use a default adapter.
                        adapter = DefaultPublishTraverse(self.context, self.request)

                    ob = adapter.publishTraverse(self.request, view)


            if isinstance(ob, BrowserView):
                # Taken from five.customerize.browser
                klass = ob.__class__
                base = klass.__bases__[0]
                if base is BrowserView or base is object:
                    py_file = inspect.getsourcefile(klass)
                else:
                    py_file = inspect.getsourcefile(base)
                pt_file = ob.index.filename

                result[view] = {'py':py_file,
                                'pt':pt_file}

            elif isinstance(ob, FSPageTemplate):
                result[view] = {'pt':ob.getObjectFSPath()}

            else:
                result[view] = {}


        return result
 def publishTraverse(self, request, name):
     # Regular CMIS content are not traversable in CMIS.
     default = DefaultPublishTraverse(self, request)
     return default.publishTraverse(request, name)