示例#1
0
 def test_switch_moderator_off(self):
     with force_language("en"):
         pages_root = unquote(reverse("pages-root"))
         page1 = create_page('page', 'nav_playground.html', 'en', published=True)
         path = page1.get_absolute_url()[len(pages_root):].strip('/')
         page2 = get_page_from_path(path)
         self.assertEqual(page1.get_absolute_url(), page2.get_absolute_url())
 def test_switch_moderator_off(self):
     with force_language("en"):
         pages_root = unquote(reverse("pages-root"))
         page1 = create_page('page',
                             'nav_playground.html',
                             'en',
                             published=True)
         path = page1.get_absolute_url()[len(pages_root):].strip('/')
         page2 = get_page_from_path(path)
         self.assertEqual(page1.get_absolute_url(),
                          page2.get_absolute_url())
def is_valid_url(url, instance, create_links=True, site=None):
    """ Checks for conflicting urls
    """
    page_root = unquote(reverse("pages-root"))
    if url and url != page_root:
        # Url sanity check via regexp
        if not any_path_re.match(url):
            raise ValidationError(_('Invalid URL, use /my/url format.'))
            # We only check page FK to site object to allow is_valid_url check on
        # incomplete Page instances
        if not site and instance.site_id:
            site = instance.site
            # Retrieve complete queryset of pages with corresponding URL
        # This uses the same resolving function as ``get_page_from_path``
        if url.startswith(page_root):
            url = url[len(page_root):]
        page_qs = get_page_queryset_from_path(url.strip('/'), site=site)
        url_clashes = []
        # If queryset has pages checks for conflicting urls
        if page_qs is not None:
            # If single page is returned create a list for interface compat
            if isinstance(page_qs, Page):
                page_qs = [page_qs]
            for page in page_qs:
                # Every page in the queryset except the current one is a conflicting page
                # We have to exclude both copies of the page
                if page and page.publisher_public.pk != instance.pk:
                    if create_links:
                        # Format return message with page url
                        url_clashes.append(
                            '<a href="%(page_url)s%(pk)s" target="_blank">%(page_title)s</a>'
                            % {
                                'page_url':
                                reverse('admin:cms_page_changelist'),
                                'pk': page.pk,
                                'page_title': force_unicode(page),
                            })
                    else:
                        # Just return the page name
                        url_clashes.append("'%s'" % page)
            if url_clashes:
                # If clashing pages exist raise the exception
                raise ValidationError(
                    mark_safe(
                        ungettext_lazy(
                            'Page %(pages)s has the same url \'%(url)s\' as current page "%(instance)s".',
                            'Pages %(pages)s have the same url \'%(url)s\' as current page "%(instance)s".',
                            len(url_clashes)) % {
                                'pages': ', '.join(url_clashes),
                                'url': url,
                                'instance': instance
                            }))
    return True
示例#4
0
def is_valid_url(url, instance, create_links=True, site=None):
    """ Checks for conflicting urls
    """
    page_root = unquote(reverse("pages-root"))
    if url and url != page_root:
        # Url sanity check via regexp
        if not any_path_re.match(url):
            raise ValidationError(_("Invalid URL, use /my/url format."))
            # We only check page FK to site object to allow is_valid_url check on
        # incomplete Page instances
        if not site and instance.site_id:
            site = instance.site
            # Retrieve complete queryset of pages with corresponding URL
        # This uses the same resolving function as ``get_page_from_path``
        if url.startswith(page_root):
            url = url[len(page_root) :]
        page_qs = get_page_queryset_from_path(url.strip("/"), site=site, draft=instance.publisher_is_draft)
        url_clashes = []
        # If queryset has pages checks for conflicting urls
        for page in page_qs:
            # Every page in the queryset except the current one is a conflicting page
            # We have to exclude both copies of the page
            if page and page.publisher_public_id != instance.pk and page.pk != instance.pk:
                if create_links:
                    # Format return message with page url
                    url_clashes.append(
                        '<a href="%(page_url)s%(pk)s" target="_blank">%(page_title)s</a>'
                        % {
                            "page_url": reverse("admin:cms_page_changelist"),
                            "pk": page.pk,
                            "page_title": force_unicode(page),
                        }
                    )
                else:
                    # Just return the page name
                    url_clashes.append("'%s'" % page)
        if url_clashes:
            # If clashing pages exist raise the exception
            raise ValidationError(
                mark_safe(
                    ungettext_lazy(
                        "Page %(pages)s has the same url '%(url)s' as current page \"%(instance)s\".",
                        "Pages %(pages)s have the same url '%(url)s' as current page \"%(instance)s\".",
                        len(url_clashes),
                    )
                    % {"pages": ", ".join(url_clashes), "url": url, "instance": instance}
                )
            )
    return True
def get_page_from_request(request, use_path=None):
    """
    Gets the current page from a request object.
    
    URLs can be of the following form (this should help understand the code):
    http://server.whatever.com/<some_path>/"pages-root"/some/page/slug
    
    <some_path>: This can be anything, and should be stripped when resolving
        pages names. This means the CMS is not installed at the root of the 
        server's URLs.
    "pages-root" This is the root of Django urls for the CMS. It is, in essence
        an empty page slug (slug == '')
        
    The page slug can then be resolved to a Page model object
    """

    # The following is used by cms.middleware.page.CurrentPageMiddleware
    if hasattr(request, '_current_page_cache'):
        return request._current_page_cache

    draft = use_draft(request)
    preview = 'preview' in request.GET

    # If use_path is given, someone already did the path cleaning
    if use_path is not None:
        path = use_path
    else:
        path = request.path
        pages_root = unquote(reverse("pages-root"))
        # otherwise strip off the non-cms part of the URL
        if 'django.contrib.admin' in settings.INSTALLED_APPS:
            admin_base = reverse('admin:index')
        else:
            admin_base = None
        if path.startswith(pages_root) and (not admin_base or
                                            not path.startswith(admin_base)):
            path = path[len(pages_root):]
            # and strip any final slash
        if path.endswith("/"):
            path = path[:-1]

    page = get_page_from_path(path, preview, draft)
    if draft and page and not page.has_change_permission(request):
        page = get_page_from_path(path, preview, draft=False)

    request._current_page_cache = page
    return page
示例#6
0
def get_page_from_request(request, use_path=None):
    """
    Gets the current page from a request object.
    
    URLs can be of the following form (this should help understand the code):
    http://server.whatever.com/<some_path>/"pages-root"/some/page/slug
    
    <some_path>: This can be anything, and should be stripped when resolving
        pages names. This means the CMS is not installed at the root of the 
        server's URLs.
    "pages-root" This is the root of Django urls for the CMS. It is, in essence
        an empty page slug (slug == '')
        
    The page slug can then be resolved to a Page model object
    """

    # The following is used by cms.middleware.page.CurrentPageMiddleware
    if hasattr(request, '_current_page_cache'):
        return request._current_page_cache

    draft = use_draft(request)
    preview = 'preview' in request.GET

    # If use_path is given, someone already did the path cleaning
    if use_path is not None:
        path = use_path
    else:
        path = request.path
        pages_root = unquote(reverse("pages-root"))
        # otherwise strip off the non-cms part of the URL
        if 'django.contrib.admin' in settings.INSTALLED_APPS:
            admin_base = reverse('admin:index')
        else:
            admin_base = None
        if path.startswith(pages_root) and (not admin_base or not path.startswith(admin_base)):
            path = path[len(pages_root):]
            # and strip any final slash
        if path.endswith("/"):
            path = path[:-1]

    page = get_page_from_path(path, preview, draft)
    if draft and page and not page.has_change_permission(request):
        page = get_page_from_path(path, preview, draft=False)

    request._current_page_cache = page
    return page
示例#7
0
def is_valid_url(url, instance, create_links=True, site=None):
    """ Checks for conflicting urls
    """
    page_root = unquote(reverse("pages-root"))
    if url and url != page_root:
        # Url sanity check via regexp
        if not any_path_re.match(url):
            raise ValidationError(_('Invalid URL, use /my/url format.'))
            # We only check page FK to site object to allow is_valid_url check on
        # incomplete Page instances
        if not site and instance.site_id:
            site = instance.site
            # Retrieve complete queryset of pages with corresponding URL
        # This uses the same resolving function as ``get_page_from_path``
        if url.startswith(page_root):
            url = url[len(page_root):]
        page_qs = get_page_queryset_from_path(url.strip('/'), site=site)
        url_clashes = []
        # If queryset has pages checks for conflicting urls
        if page_qs is not None:
            # If single page is returned create a list for interface compat
            if isinstance(page_qs, Page):
                page_qs = [page_qs]
            for page in page_qs:
                # Every page in the queryset except the current one is a conflicting page
                # We have to exclude both copies of the page
                if page and page.publisher_public.pk != instance.pk:
                    if create_links:
                        # Format return message with page url
                        url_clashes.append('<a href="%(page_url)s%(pk)s" target="_blank">%(page_title)s</a>' % {
                            'page_url': reverse('admin:cms_page_changelist'), 'pk': page.pk,
                            'page_title': force_unicode(page),
                        })
                    else:
                        # Just return the page name
                        url_clashes.append("'%s'" % page)
            if url_clashes:
                # If clashing pages exist raise the exception
                raise ValidationError(mark_safe(
                    ungettext_lazy('Page %(pages)s has the same url \'%(url)s\' as current page "%(instance)s".',
                                   'Pages %(pages)s have the same url \'%(url)s\' as current page "%(instance)s".',
                                   len(url_clashes)) %
                    {'pages': ', '.join(url_clashes), 'url': url, 'instance': instance}))
    return True
示例#8
0
 def get_context(self, context, start_level, template, only_visible):
     try:
         # If there's an exception (500), default context_processors may not be called.
         request = context['request']
     except KeyError:
         return {'template': 'cms/content.html'}
     if not (isinstance(start_level, int) or start_level.isdigit()):
         only_visible = template
         template = start_level
         start_level = 0
     try:
         only_visible = bool(int(only_visible))
     except:
         only_visible = bool(only_visible)
     ancestors = []
     nodes = menu_pool.get_nodes(request, breadcrumb=True)
     selected = None
     home = None
     for node in nodes:
         if node.selected:
             selected = node
         if node.get_absolute_url() == unquote(reverse("pages-root")):
             home = node
     if selected and selected != home:
         node = selected
         while node:
             if node.visible or not only_visible:
                 ancestors.append(node)
             node = node.parent
     if not ancestors or (ancestors and ancestors[-1] != home) and home:
         ancestors.append(home)
     ancestors.reverse()
     if len(ancestors) >= start_level:
         ancestors = ancestors[start_level:]
     else:
         ancestors = []
     context.update({'ancestors': ancestors,
         'template': template})
     return context
 def get_context(self, context, start_level, template, only_visible):
     try:
         # If there's an exception (500), default context_processors may not be called.
         request = context['request']
     except KeyError:
         return {'template': 'cms/content.html'}
     if not (isinstance(start_level, int) or start_level.isdigit()):
         only_visible = template
         template = start_level
         start_level = 0
     try:
         only_visible = bool(int(only_visible))
     except:
         only_visible = bool(only_visible)
     ancestors = []
     nodes = menu_pool.get_nodes(request, breadcrumb=True)
     selected = None
     home = None
     for node in nodes:
         if node.selected:
             selected = node
         if node.get_absolute_url() == unquote(reverse("pages-root")):
             home = node
     if selected and selected != home:
         node = selected
         while node:
             if node.visible or not only_visible:
                 ancestors.append(node)
             node = node.parent
     if not ancestors or (ancestors and ancestors[-1] != home) and home:
         ancestors.append(home)
     ancestors.reverse()
     if len(ancestors) >= start_level:
         ancestors = ancestors[start_level:]
     else:
         ancestors = []
     context.update({'ancestors': ancestors, 'template': template})
     return context
示例#10
0
 def get_pages_root(self):
     return unquote(reverse("pages-root"))
示例#11
0
 def get_pages_root(self):
     return unquote(reverse("pages-root"))
示例#12
0
 def _get_path(self, parsed):
     # If there are parameters, add them
     if parsed[3]:
         return unquote(parsed[2] + ";" + parsed[3])
     else:
         return unquote(parsed[2])