def _getHigherLevelUser(self, request, roles=None):
     if roles:
         accessed = self._getPAS()._getObjectContext(
             request["PUBLISHED"], request)[1]
     req_roles = request.roles
     auth = request._auth
     # save response and install new one to prevent side effects
     saved_response = request.response
     try:
         request.response = Response()
         for uf in self._generateHigherLevelUserFolders():
             if req_roles is UNSPECIFIED_ROLES:
                 u = uf.validate(request, auth)
             else:
                 u = uf.validate(request, auth, req_roles)
             if u is None or u is nobody:
                 continue
             # this user folder has authenticated a user able to perform
             #  the request
             if roles:
                 # check in addition that is has one of *roles*
                 if not u.allowed(accessed, roles):
                     # reject this user
                     continue
             return u
     finally:
         request.response = saved_response
Example #2
0
def render_object(obj,
                  path,
                  where,
                  append_html=True,
                  output_root='',
                  raise_errors=False):
    path = path.strip('/')
    assert '..' not in path
    outputfile = os.path.join(where, path)
    outputdir = os.path.dirname(outputfile)
    environ = {'SERVER_NAME': 'localhost', 'SERVER_PORT': '80'}
    stdin = StringIO()
    response = Response(stdout=sys.stdout, stderr=sys.stderr)
    request = Request(stdin, environ, response)
    if output_root:
        request['SERVER_URL'] = relpath(output_root, outputdir)
    setDefaultSkin(request)
    app = Application().__of__(RequestContainer(REQUEST=request))
    obj = obj.__of__(app)
    request.other['VirtualRootPhysicalPath'] = obj.getPhysicalPath()
    obj = obj.unrestrictedTraverse(path)
    if getattr(obj, 'index_html', None) is not None:
        obj = obj.index_html
    try:
        result = mapply(obj, request.args, request)
    except Exception, e:
        print >> sys.stderr, "cannot render %s: %s: %s" % (
            path, e.__class__.__name__, e)
        if raise_errors:
            raise
Example #3
0
 def __init__(self):
     env = {
         'SERVER_NAME': 'nohost',
         'SERVER_PORT': '80',
         'REQUEST_METHOD': 'GET'
     }
     Request.__init__(self, None, env, Response())
Example #4
0
    def publish(self,
                path,
                basic=None,
                env=None,
                extra=None,
                request_method='GET',
                stdin=None,
                handle_errors=True):
        '''Publishes the object at 'path' returning a response object.'''

        from StringIO import StringIO
        from ZPublisher.Request import Request
        from ZPublisher.Response import Response
        from ZPublisher.Publish import publish_module

        # Commit the sandbox for good measure
        transaction.commit()

        if env is None:
            env = {}
        if extra is None:
            extra = {}

        request = self.app.REQUEST

        env['SERVER_NAME'] = request['SERVER_NAME']
        env['SERVER_PORT'] = request['SERVER_PORT']
        env['REQUEST_METHOD'] = request_method

        p = path.split('?')
        if len(p) == 1:
            env['PATH_INFO'] = p[0]
        elif len(p) == 2:
            [env['PATH_INFO'], env['QUERY_STRING']] = p
        else:
            raise TypeError, ''

        if basic:
            env['HTTP_AUTHORIZATION'] = "Basic %s" % base64.encodestring(basic)

        if stdin is None:
            stdin = StringIO()

        outstream = StringIO()
        response = Response(stdout=outstream, stderr=sys.stderr)
        request = Request(stdin, env, response)
        for k, v in extra.items():
            request[k] = v

        publish_module(
            'Zope2',
            debug=not handle_errors,
            request=request,
            response=response,
        )

        return ResponseWrapper(response, outstream, path)
Example #5
0
    def publish(self,
                path,
                basic=None,
                env=None,
                extra=None,
                request_method='GET',
                stdin=None,
                handle_errors=True):
        """
        Mostly pulled from Testing.functional
        """
        from ZPublisher.Request import Request
        from ZPublisher.Response import Response
        from ZPublisher.Publish import publish_module

        transaction.commit()

        if env is None:
            env = {}
        if extra is None:
            extra = {}

        env['SERVER_NAME'] = self.request['SERVER_NAME']
        env['SERVER_PORT'] = self.request['SERVER_PORT']
        env['REQUEST_METHOD'] = request_method

        p = path.split('?')
        if len(p) == 1:
            env['PATH_INFO'] = p[0]
        elif len(p) == 2:
            [env['PATH_INFO'], env['QUERY_STRING']] = p
        else:
            raise TypeError('')

        if basic:
            env['HTTP_AUTHORIZATION'] = "Basic %s" % base64.encodestring(basic)

        if stdin is None:
            stdin = StringIO()

        outstream = StringIO()
        response = Response(stdout=outstream, stderr=sys.stderr)
        request = Request(stdin, env, response)
        if extra:
            # Needed on Plone 3 when adding things to the path in a querystring
            # is not enough.
            for key, value in extra.items():
                request[key] = value

        publish_module('Zope2',
                       debug=not handle_errors,
                       request=request,
                       response=response)

        return ResponseWrapper(response, outstream, path)
    def publish(
        self,
        path,
        basic=None,
        env=None,
        extra=None,
        request_method="GET",
        stdin=None,
        handle_errors=True,
    ):
        """
        Mostly pulled from Testing.functional
        """
        from ZPublisher.Request import Request
        from ZPublisher.Response import Response

        # Note: the next import fail in Python 3, because it needs ZServer.
        from ZPublisher.Publish import publish_module

        transaction.commit()

        if env is None:
            env = {}

        env["SERVER_NAME"] = self.request["SERVER_NAME"]
        env["SERVER_PORT"] = self.request["SERVER_PORT"]
        env["REQUEST_METHOD"] = request_method

        p = path.split("?")
        if len(p) == 1:
            env["PATH_INFO"] = p[0]
        elif len(p) == 2:
            [env["PATH_INFO"], env["QUERY_STRING"]] = p
        else:
            raise TypeError("")

        if basic:
            env["HTTP_AUTHORIZATION"] = "Basic %s" % base64.encodestring(basic)

        if stdin is None:
            stdin = BytesIO()

        outstream = BytesIO()
        response = Response(stdout=outstream, stderr=sys.stderr)
        request = Request(stdin, env, response)

        publish_module("Zope2",
                       debug=not handle_errors,
                       request=request,
                       response=response)

        return ResponseWrapper(response, outstream, path)
Example #7
0
    def __call__(self):

        request = BaseRequest()
        site = self.context.getSite()
        request['PARENTS'] = [site]
        request.steps = list(self.context.getPhysicalPath())
        request['URL'] = site.absolute_url()
        request.response = Response()
        import pdb
        pdb.set_trace()
        request.traverse('who-who')

        return
Example #8
0
 def setBody(self, body, title='', is_error=0, **kw):
     if IStreamIterator.providedBy(body):
         body = ''.join(body)
     Response.setBody(self, body, title, is_error, **kw)
Example #9
0
def http(request_string, handle_errors=True):
    """Execute an HTTP request string via the publisher

    This is used for HTTP doc tests.
    """
    import urllib
    import rfc822
    from cStringIO import StringIO
    from ZPublisher.Response import Response
    from ZPublisher.Test import publish_module
    from AccessControl.SecurityManagement import getSecurityManager
    from AccessControl.SecurityManagement import setSecurityManager

    # Save current Security Manager
    old_sm = getSecurityManager()

    # Commit work done by previous python code.
    transaction.commit()

    # Discard leading white space to make call layout simpler
    request_string = request_string.lstrip()

    # Split off and parse the command line
    l = request_string.find('\n')
    command_line = request_string[:l].rstrip()
    request_string = request_string[l+1:]
    method, path, protocol = command_line.split()
    path = urllib.unquote(path)

    instream = StringIO(request_string)

    env = {"HTTP_HOST": 'localhost',
           "HTTP_REFERER": 'localhost',
           "REQUEST_METHOD": method,
           "SERVER_PROTOCOL": protocol,
           }

    p = path.split('?')
    if len(p) == 1:
        env['PATH_INFO'] = p[0]
    elif len(p) == 2:
        [env['PATH_INFO'], env['QUERY_STRING']] = p
    else:
        raise TypeError, ''

    header_output = HTTPHeaderOutput(
        protocol, ('x-content-type-warning', 'x-powered-by',
                   'bobo-exception-type', 'bobo-exception-file',
                   'bobo-exception-value', 'bobo-exception-line'))

    headers = [split_header(header)
               for header in rfc822.Message(instream).headers]

    # Store request body without headers
    instream = StringIO(instream.read())

    for name, value in headers:
        name = ('_'.join(name.upper().split('-')))
        if name not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
            name = 'HTTP_' + name
        env[name] = value.rstrip()

    if env.has_key('HTTP_AUTHORIZATION'):
        env['HTTP_AUTHORIZATION'] = auth_header(env['HTTP_AUTHORIZATION'])

    outstream = StringIO()
    response = Response(stdout=outstream, stderr=sys.stderr)

    publish_module('Zope2',
                   response=response,
                   stdin=instream,
                   environ=env,
                   debug=not handle_errors,
                  )
    header_output.setResponseStatus(response.getStatus(), response.errmsg)
    header_output.setResponseHeaders(response.headers)
    header_output.appendResponseHeaders(response._cookie_list())
    header_output.appendResponseHeaders(response.accumulated_headers.splitlines())

    # Restore previous security manager, which may have been changed
    # by calling the publish method above
    setSecurityManager(old_sm)

    # Sync connection
    sync()

    return DocResponseWrapper(response, outstream, path, header_output)
Example #10
0
def publish_module(module_name,
                   stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
                   environ=os.environ, debug=0, request=None, response=None,
                   extra={}):
    """ Adapted from from ZPublisher.Test.publish_module:
    but we handle the response status like given from response.getStatus(),
    otherwise plone internal links will return status=200 for status=404 links,
    which will not throw an error.
    """
    must_die = 0
    status = 200
    after_list = [None]
    from ZPublisher.Response import Response
    from ZPublisher.Request import Request
    from ZPublisher.Publish import publish
    from zope.publisher.interfaces import ISkinnable
    from zope.publisher.skinnable import setDefaultSkin
    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request = Request(stdin, environ, response)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            for k, v in extra.items():
                request[k] = v
            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except Unauthorized:
            # Handle Unauthorized separately, otherwise it will be displayed as
            # a redirect to the login form
            status = 200
            response = None
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            # this is our change: otherwise 404 will return 200
            # but we only want "real" 404 - otherwise the list will get full
            # of internal links with edit-links stuff that will return 5xx
            # codes.
            if response.getStatus() in (301, 302, 404):
                status = response.getStatus()

            outputBody = getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response = str(response)
                if response:
                    stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None:
            after_list[0]()

    finally:
        if request is not None:
            request.close()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else:
                code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try:
            raise must_die[0], must_die[1], must_die[2]
        finally:
            must_die = None

    return status, response
Example #11
0
def http(request_string, handle_errors=True):
    """Execute an HTTP request string via the publisher

    This is used for HTTP doc tests.
    """
    import urllib
    import rfc822
    from cStringIO import StringIO
    from ZPublisher.Response import Response
    from ZPublisher.Publish import publish_module

    # Commit work done by previous python code.
    transaction.commit()

    # Discard leading white space to make call layout simpler
    request_string = request_string.lstrip()

    # Split off and parse the command line
    l = request_string.find('\n')
    command_line = request_string[:l].rstrip()
    request_string = request_string[l + 1:]
    method, path, protocol = command_line.split()
    path = urllib.unquote(path)

    instream = StringIO(request_string)

    env = {
        "HTTP_HOST": 'localhost',
        "HTTP_REFERER": 'localhost',
        "REQUEST_METHOD": method,
        "SERVER_PROTOCOL": protocol,
    }

    p = path.split('?', 1)
    if len(p) == 1:
        env['PATH_INFO'] = p[0]
    elif len(p) == 2:
        [env['PATH_INFO'], env['QUERY_STRING']] = p
    else:
        raise TypeError, ''

    header_output = HTTPHeaderOutput(
        protocol,
        ('x-content-type-warning', 'x-powered-by', 'bobo-exception-type',
         'bobo-exception-file', 'bobo-exception-value', 'bobo-exception-line'))

    headers = [
        split_header(header) for header in rfc822.Message(instream).headers
    ]

    # Store request body without headers
    instream = StringIO(instream.read())

    for name, value in headers:
        name = ('_'.join(name.upper().split('-')))
        if name not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
            name = 'HTTP_' + name
        env[name] = value.rstrip()

    if env.has_key('HTTP_AUTHORIZATION'):
        env['HTTP_AUTHORIZATION'] = auth_header(env['HTTP_AUTHORIZATION'])

    outstream = StringIO()
    response = Response(stdout=outstream, stderr=sys.stderr)

    publish_module(
        'Zope2',
        response=response,
        stdin=instream,
        environ=env,
        debug=not handle_errors,
    )
    header_output.setResponseStatus(response.getStatus(), response.errmsg)
    header_output.setResponseHeaders(response.headers)
    header_output.headersl.extend(response._cookie_list())
    header_output.appendResponseHeaders(response.accumulated_headers)

    sync()

    return DocResponseWrapper(response, outstream, path, header_output)
Example #12
0
    def run(self, *args, **kwargs):

        self.payload = kwargs['payload']
        self.template = kwargs['template']
        self.rec_id = kwargs['rec_id']

        site = getSite()

        user = getSecurityManager().getUser()
        acl_users = site.acl_users
        user = user.__of__(acl_users)
        user_id = kwargs['user_id']

        request = BaseRequest()
        request.response = Response()
        request.AUTHENTICATED_USER = user
        request['PARENTS'] = [site]
        request['URL'] = kwargs['url']
        request.steps = []
        request.cookies = {}
        request.form = {}

        import_location = site.unrestrictedTraverse(kwargs['import_path'])

        import_location.REQUEST = request
        site.REQUEST = request

        geo_fields = kwargs['geo_fields']
        self.prop_map = kwargs['properties']
        meta_type = kwargs['meta_type']

        header = self.template
        row = self.payload
        record_number = self.rec_id

        content_type = import_location.getSite().get_pluggable_item(meta_type)
        add_object = content_type['add_method']

        properties = {}
        extra_properties = {}
        address = None

        for column, value in zip(header, row):

            if value == '':
                continue

            if column not in self.prop_map:
                extra_properties[column] = value
                continue

            key = self.prop_map[column]['column']
            widget = self.prop_map[column]['widget']
            widget = widget.__of__(import_location)
            convert = widget.convert_from_user_string
            properties[key] = convert(value)

        try:
            properties = do_geocoding(geo_fields, properties)
        except GeocoderServiceError, e:
            msg = (
                'Warnings: could not find a valid address '
                'for row ${record_number}: ${error}',
                {
                    'record_number': record_number + 1,  # account for header
                    'error': str(e)
                })
            self.warnings.append(msg)
            address = properties.pop(geo_fields['address'])