Exemple #1
0
    def decorator(context, request):
        script_name = ''

        # first consider URL routing
        if request.matched_route:
            matchdictCopy = {}
            matchdictCopy.update(request.matchdict)
            matchdictCopy['subpath'] = ''
            script_name = request.matched_route.generate(matchdictCopy)

        # now consider traversed paths
        traversed = request.traversed
        vroot_path = request.virtual_root_path or ()
        view_name = request.view_name
        subpath = request.subpath or ()
        script_tuple = traversed[len(vroot_path):]
        script_list = [ quote_path_segment(name) for name in script_tuple ]
        if view_name:
            script_list.append(quote_path_segment(view_name))
        script_name = script_name + '/' + '/'.join(script_list)
        path_list = [ quote_path_segment(name) for name in subpath ]
        path_info = '/' + '/'.join(path_list)
        request.environ['PATH_INFO'] = path_info
        script_name = request.environ['SCRIPT_NAME'] + script_name
        if script_name.endswith('/'):
            script_name = script_name[:-1]
        request.environ['SCRIPT_NAME'] = script_name
        return request.get_response(wrapped)
    def generator(dict):
        newdict = {}
        for k, v in dict.items():
            if PY3: # pragma: no cover
                if v.__class__ is binary_type:
                    # url_quote below needs a native string, not bytes on Py3
                    v = v.decode('utf-8')
            else:
                if v.__class__ is text_type:
                    # url_quote below needs bytes, not unicode on Py2
                    v = v.encode('utf-8')

            if k == remainder:
                # a stararg argument
                if is_nonstr_iter(v):
                    v = '/'.join([quote_path_segment(x) for x in v]) # native
                else:
                    if v.__class__ not in string_types:
                        v = str(v)
                    v = quote_path_segment(v, safe='/')
            else:
                if v.__class__ not in string_types:
                    v = str(v)
                # v may be bytes (py2) or native string (py3)
                v = quote_path_segment(v)

            # at this point, the value will be a native string
            newdict[k] = v

        result = gen % newdict # native string result
        return result
Exemple #3
0
    def generator(dict):
        newdict = {}
        for k, v in dict.items():
            if PY3:  # pragma: no cover
                if v.__class__ is binary_type:
                    # url_quote below needs a native string, not bytes on Py3
                    v = v.decode('utf-8')
            else:
                if v.__class__ is text_type:
                    # url_quote below needs bytes, not unicode on Py2
                    v = v.encode('utf-8')

            if k == remainder:
                # a stararg argument
                if is_nonstr_iter(v):
                    v = '/'.join([quote_path_segment(x, safe='/')
                                  for x in v])  # native
                else:
                    if v.__class__ not in string_types:
                        v = str(v)
                    v = quote_path_segment(v, safe='/')
            else:
                if v.__class__ not in string_types:
                    v = str(v)
                # v may be bytes (py2) or native string (py3)
                v = quote_path_segment(v, safe='/')

            # at this point, the value will be a native string
            newdict[k] = v

        result = gen % newdict  # native string result
        return result
Exemple #4
0
def intranets_info(context, request):
    """Get information for the footer and intranets listing"""
    intranets_info = []
    intranets = find_intranets(context)
    if intranets:
        intranets_url = resource_url(intranets, request)
        for name, entry in intranets.items():
            try:
                content_iface = get_content_type(entry)
            except ValueError:
                continue
            if content_iface == ICommunity:
                if not has_permission('view', entry, request):
                    continue
                href = '%s%s/' % (intranets_url, quote_path_segment(name))
                intranets_info.append({
                    'title':
                    entry.title,
                    'intranet_href':
                    href,
                    'edit_href':
                    href + '/edit_intranet.html',
                })
        # Sort the list
        def intranet_sort(x, y):
            if x['title'] > y['title']:
                return 1
            else:
                return -1

        intranets_info.sort(intranet_sort)
    return intranets_info
Exemple #5
0
 def intranets_info(self):
     """Get information for the footer and intranets listing"""
     if self._intranets_info is None:
         intranets_info = []
         intranets = find_intranets(self.context)
         if not intranets:
             # Maybe there aren't any intranets defined yet
             return []
         request = self.request
         intranets_url = resource_url(intranets, request)
         for name, entry in intranets.items():
             try:
                 content_iface = get_content_type(entry)
             except ValueError:
                 continue
             href = '%s%s/' % (intranets_url, quote_path_segment(name))
             if content_iface == ICommunity:
                 intranets_info.append({
                         'title': entry.title,
                         'intranet_href': href,
                         'edit_href': href + '/edit_intranet.html',
                         })
         # Sort the list
         def intranet_sort(x, y):
             if x['title'] > y['title']:
                 return 1
             else:
                 return -1
         self._intranets_info = sorted(intranets_info, intranet_sort)
     return self._intranets_info
Exemple #6
0
    def __json__(self) -> Json:
        result = self.as_dict()
        links = self.get_links()
        registry = self.request.registry

        # Add external links
        for name, link_fabric in get_external_links(self.resource, registry):
            if name in links:
                # Don't overwrite the link added by resource
                continue
            link = link_fabric.get_link(self.request)
            if not link:
                continue
            link = {'href': link}
            if link_fabric.templated:
                link['templated'] = True
            links[name] = link

        # Add links to sub-resources
        self_url = links['self']['href']
        for name, _ in self.resource.get_sub_resources(registry):
            if name in links:
                # Don't overwrite the link added by resource
                continue
            links[name] = {'href': self_url + quote_path_segment(name) + '/'}
        result['_links'] = links
        return result
def intranets_info(context, request):
    """Get information for the footer and intranets listing"""
    intranets_info = []
    intranets = find_intranets(context)
    if intranets:
        intranets_url = resource_url(intranets, request)
        for name, entry in intranets.items():
            try:
                content_iface = get_content_type(entry)
            except ValueError:
                continue
            if content_iface == ICommunity:
                if not has_permission('view', entry, request):
                    continue
                href = '%s%s/' % (intranets_url, quote_path_segment(name))
                intranets_info.append({
                        'title': entry.title,
                        'intranet_href': href,
                        'edit_href': href + '/edit_intranet.html',
                        })
        # Sort the list
        def intranet_sort(x, y):
            if x['title'] > y['title']:
                return 1
            else:
                return -1
        intranets_info.sort(intranet_sort)
    return intranets_info
Exemple #8
0
def _secure_path(path_tuple):
    if '' in path_tuple:
        return None
    for item in path_tuple:
        for val in ['.', '/']:
            if item.startswith(val):
                return None
    return '/'.join([quote_path_segment(x) for x in path_tuple])
Exemple #9
0
 def decorator(context, request):
     traversed = request.traversed
     vroot_path = request.virtual_root_path or ()
     view_name = request.view_name
     subpath = request.subpath or ()
     script_tuple = traversed[len(vroot_path):]
     script_list = [ quote_path_segment(name) for name in script_tuple ]
     if view_name:
         script_list.append(quote_path_segment(view_name))
     script_name =  '/' + '/'.join(script_list)
     path_list = [ quote_path_segment(name) for name in subpath ]
     path_info = '/' + '/'.join(path_list)
     request.environ['PATH_INFO'] = path_info
     script_name = request.environ['SCRIPT_NAME'] + script_name
     if script_name.endswith('/'):
         script_name = script_name[:-1]
     request.environ['SCRIPT_NAME'] = script_name
     return request.get_response(wrapped)
Exemple #10
0
 def decorator(context, request):
     traversed = request.traversed
     vroot_path = request.virtual_root_path or ()
     view_name = request.view_name
     subpath = request.subpath or ()
     script_tuple = traversed[len(vroot_path):]
     script_list = [quote_path_segment(name) for name in script_tuple]
     if view_name:
         script_list.append(quote_path_segment(view_name))
     script_name = '/' + '/'.join(script_list)
     path_list = [quote_path_segment(name) for name in subpath]
     path_info = '/' + '/'.join(path_list)
     request.environ['PATH_INFO'] = path_info
     script_name = request.environ['SCRIPT_NAME'] + script_name
     if script_name.endswith('/'):
         script_name = script_name[:-1]
     request.environ['SCRIPT_NAME'] = script_name
     return request.get_response(wrapped)
Exemple #11
0
 def generator(dict):
     newdict = {}
     for k, v in dict.items():
         if v.__class__ is text_type:
             v = native_(v, "utf-8")
         if k == star and is_nonstr_iter(v):
             v = "/".join([quote_path_segment(x) for x in v])
         elif k != star:
             if v.__class__ not in string_types:
                 v = str(v)
             v = url_quote(v, safe="")
         newdict[k] = v
     return gen % newdict
Exemple #12
0
 def generator(dict):
     newdict = {}
     for k, v in dict.items():
         if v.__class__ is text_type:
             v = native_(v, 'utf-8')
         if k == star and is_nonstr_iter(v):
             v = '/'.join([quote_path_segment(x) for x in v])
         elif k != star:
             if v.__class__ not in string_types:
                 v = str(v)
             v = url_quote(v, safe='')
         newdict[k] = v
     return gen % newdict
Exemple #13
0
 def generator(dict):
     newdict = {}
     for k, v in dict.items():
         if isinstance(v, unicode):
             v = v.encode('utf-8')
         if k == star and hasattr(v, '__iter__'):
             v = '/'.join([quote_path_segment(x) for x in v])
         elif k != star:
             try:
                 v = url_quote(v)
             except TypeError:
                 pass
         newdict[k] = v
     return gen % newdict
Exemple #14
0
 def generator(dict):
     newdict = {}
     for k, v in dict.items():
         if isinstance(v, unicode):
             v = v.encode('utf-8')
         if k == star and hasattr(v, '__iter__'):
             v = '/'.join([quote_path_segment(x) for x in v])
         elif k != star:
             try:
                 v = url_quote(v)
             except TypeError:
                 pass
         newdict[k] = v
     return gen % newdict
def _compile_route(route):
    # This function really wants to consume Unicode patterns natively, but if
    # someone passes us a bytestring, we allow it by converting it to Unicode
    # using the ASCII decoding.  We decode it using ASCII because we don't
    # want to accept bytestrings with high-order characters in them here as
    # we have no idea what the encoding represents.
    if route.__class__ is not text_type:
        try:
            route = text_(route, 'ascii')
        except UnicodeDecodeError:
            raise ValueError(
                'The pattern value passed to add_route must be '
                'either a Unicode string or a plain string without '
                'any non-ASCII characters (you provided %r).' % route)

    if old_route_re.search(route) and not route_re.search(route):
        route = old_route_re.sub(update_pattern, route)

    if not route.startswith('/'):
        route = '/' + route

    remainder = None
    if star_at_end.search(route):
        route, remainder = route.rsplit('*', 1)

    pat = route_re.split(route)

    # every element in "pat" will be Unicode (regardless of whether the
    # route_re regex pattern is itself Unicode or str)
    pat.reverse()
    rpat = []
    gen = []
    prefix = pat.pop() # invar: always at least one element (route='/'+route)

    # We want to generate URL-encoded URLs, so we url-quote the prefix, being
    # careful not to quote any embedded slashes.  We have to replace '%' with
    # '%%' afterwards, as the strings that go into "gen" are used as string
    # replacement targets.
    gen.append(quote_path_segment(prefix, safe='/').replace('%', '%%')) # native
    rpat.append(re.escape(prefix)) # unicode

    while pat:
        name = pat.pop() # unicode
        name = name[1:-1]
        if ':' in name:
            name, reg = name.split(':')
        else:
            reg = '[^/]+'
        gen.append('%%(%s)s' % native_(name)) # native
        name = '(?P<%s>%s)' % (name, reg) # unicode
        rpat.append(name)
        s = pat.pop() # unicode
        if s:
            rpat.append(re.escape(s)) # unicode
            # We want to generate URL-encoded URLs, so we url-quote this
            # literal in the pattern, being careful not to quote the embedded
            # slashes.  We have to replace '%' with '%%' afterwards, as the
            # strings that go into "gen" are used as string replacement
            # targets.  What is appended to gen is a native string.
            gen.append(quote_path_segment(s, safe='/').replace('%', '%%'))

    if remainder:
        rpat.append('(?P<%s>.*?)' % remainder) # unicode
        gen.append('%%(%s)s' % native_(remainder)) # native

    pattern = ''.join(rpat) + '$' # unicode

    match = re.compile(pattern).match
    def matcher(path):
        # This function really wants to consume Unicode patterns natively,
        # but if someone passes us a bytestring, we allow it by converting it
        # to Unicode using the ASCII decoding.  We decode it using ASCII
        # because we don't want to accept bytestrings with high-order
        # characters in them here as we have no idea what the encoding
        # represents.
        if path.__class__ is not text_type:
            path = text_(path, 'ascii')
        m = match(path)
        if m is None:
            return None
        d = {}
        for k, v in m.groupdict().items():
            # k and v will be Unicode 2.6.4 and lower doesnt accept unicode
            # kwargs as **kw, so we explicitly cast the keys to native
            # strings in case someone wants to pass the result as **kw
            nk = native_(k, 'ascii')
            if k == remainder:
                d[nk] = split_path_info(v)
            else:
                d[nk] = v
        return d

    gen = ''.join(gen)
    def generator(dict):
        newdict = {}
        for k, v in dict.items():
            if PY3: # pragma: no cover
                if v.__class__ is binary_type:
                    # url_quote below needs a native string, not bytes on Py3
                    v = v.decode('utf-8')
            else:
                if v.__class__ is text_type:
                    # url_quote below needs bytes, not unicode on Py2
                    v = v.encode('utf-8')

            if k == remainder:
                # a stararg argument
                if is_nonstr_iter(v):
                    v = '/'.join([quote_path_segment(x) for x in v]) # native
                else:
                    if v.__class__ not in string_types:
                        v = str(v)
                    v = quote_path_segment(v, safe='/')
            else:
                if v.__class__ not in string_types:
                    v = str(v)
                # v may be bytes (py2) or native string (py3)
                v = quote_path_segment(v)

            # at this point, the value will be a native string
            newdict[k] = v

        result = gen % newdict # native string result
        return result

    return matcher, generator
Exemple #16
0
def _join_elements(elements):
    return '/'.join([quote_path_segment(s, safe=':@&+$,') for s in elements])
Exemple #17
0
def _join_elements(elements):
    return '/'.join([quote_path_segment(s, safe=':@&+$,') for s in elements])
Exemple #18
0
def _join_elements(elements):
    return '/'.join(
        [quote_path_segment(s, safe=PATH_SEGMENT_SAFE) for s in elements])
Exemple #19
0
    def _callFUT(self, s):
        from pyramid.traversal import quote_path_segment

        return quote_path_segment(s)
Exemple #20
0
 def _callFUT(self, s):
     from pyramid.traversal import quote_path_segment
     return quote_path_segment(s)
Exemple #21
0
def _join_elements(elements):
    return '/'.join([quote_path_segment(s) for s in elements])
Exemple #22
0
def _join_elements(elements):
    return "/".join([quote_path_segment(s, safe=":@&+$,") for s in elements])
Exemple #23
0
def _join_elements(elements):
    return '/'.join([quote_path_segment(s, safe=PATH_SEGMENT_SAFE) for s in elements])
Exemple #24
0
def _compile_route(route):
    # This function really wants to consume Unicode patterns natively, but if
    # someone passes us a bytestring, we allow it by converting it to Unicode
    # using the ASCII decoding.  We decode it using ASCII because we don't
    # want to accept bytestrings with high-order characters in them here as
    # we have no idea what the encoding represents.
    if route.__class__ is not str:
        try:
            route = text_(route, 'ascii')
        except UnicodeDecodeError:
            raise ValueError(
                'The pattern value passed to add_route must be '
                'either a Unicode string or a plain string without '
                'any non-ASCII characters (you provided %r).' % route)

    if old_route_re.search(route) and not route_re.search(route):
        route = old_route_re.sub(update_pattern, route)

    if not route.startswith('/'):
        route = '/' + route

    remainder = None
    if star_at_end.search(route):
        route, remainder = route.rsplit('*', 1)

    pat = route_re.split(route)

    # every element in "pat" will be Unicode (regardless of whether the
    # route_re regex pattern is itself Unicode or str)
    pat.reverse()
    rpat = []
    gen = []
    prefix = pat.pop()  # invar: always at least one element (route='/'+route)

    # We want to generate URL-encoded URLs, so we url-quote the prefix, being
    # careful not to quote any embedded slashes.  We have to replace '%' with
    # '%%' afterwards, as the strings that go into "gen" are used as string
    # replacement targets.
    gen.append(quote_path_segment(prefix, safe='/').replace('%',
                                                            '%%'))  # native
    rpat.append(re.escape(prefix))  # unicode

    while pat:
        name = pat.pop()  # unicode
        name = name[1:-1]
        if ':' in name:
            # reg may contain colons as well,
            # so we must strictly split name into two parts
            name, reg = name.split(':', 1)
        else:
            reg = '[^/]+'
        gen.append('%%(%s)s' % name)  # native
        name = '(?P<%s>%s)' % (name, reg)  # unicode
        rpat.append(name)
        s = pat.pop()  # unicode
        if s:
            rpat.append(re.escape(s))  # unicode
            # We want to generate URL-encoded URLs, so we url-quote this
            # literal in the pattern, being careful not to quote the embedded
            # slashes.  We have to replace '%' with '%%' afterwards, as the
            # strings that go into "gen" are used as string replacement
            # targets.  What is appended to gen is a native string.
            gen.append(quote_path_segment(s, safe='/').replace('%', '%%'))

    if remainder:
        rpat.append('(?P<%s>.*?)' % remainder)  # unicode
        gen.append('%%(%s)s' % remainder)  # native

    pattern = ''.join(rpat) + '$'  # unicode

    match = re.compile(pattern).match

    def matcher(path):
        m = match(path)
        if m is None:
            return None
        d = {}
        for k, v in m.groupdict().items():
            if k == remainder:
                d[k] = split_path_info(v)
            else:
                d[k] = v
        return d

    gen = ''.join(gen)

    def q(v):
        return quote_path_segment(v, safe=PATH_SAFE)

    def generator(dict):
        newdict = {}
        for k, v in dict.items():
            if v.__class__ is bytes:
                # url_quote below needs a native string
                v = v.decode('utf-8')

            if k == remainder:
                # a stararg argument
                if is_nonstr_iter(v):
                    v = '/'.join([q(x) for x in v])  # native
                else:
                    if v.__class__ is not str:
                        v = str(v)
                    v = q(v)
            else:
                if v.__class__ is not str:
                    v = str(v)
                v = q(v)

            # at this point, the value will be a native string
            newdict[k] = v

        result = gen % newdict  # native string result
        return result

    return matcher, generator
Exemple #25
0
 def q(v):
     return quote_path_segment(v, safe=PATH_SAFE)
Exemple #26
0
 def q(v):
     return quote_path_segment(v, safe=PATH_SAFE)