Exemplo n.º 1
0
def applications_page_check(request, current_page=None, path=None):
    """Tries to find if given path was resolved over application. 
    Applications have higher priority than other cms pages. 
    """
    if current_page:
        return current_page
    if path is None:
        # We should get in this branch only if an apphook is active on /
        # This removes the non-CMS part of the URL.
        path = request.path.replace(reverse('pages-root'), '', 1)
    # check if application resolver can resolve this
    for resolver in APP_RESOLVERS:
        try:
            page_id = resolver.resolve_page_id(path)
            # yes, it is application page
            if settings.CMS_MODERATOR:
                page = get_page_queryset(request).get(Q(id=page_id) | Q(publisher_draft=page_id))
            else:
                page = get_page_queryset(request).get(id=page_id)
            # If current page was matched, then we have some override for content
            # from cms, but keep current page. Otherwise return page to which was application assigned.
            return page
        except Resolver404:
            # Raised if the page is not managed by an apphook
            pass
    return None
Exemplo n.º 2
0
def applications_page_check(request, current_page=None, path=None):
    """Tries to find if given path was resolved over application. 
    Applications have higher priority than other cms pages. 
    """
    if current_page:
        return current_page
    if path is None:
        # We should get in this branch only if an apphook is active on /
        # This removes the non-CMS part of the URL.
        path = request.path.replace(reverse('pages-root'), '', 1)
    # check if application resolver can resolve this
    for resolver in APP_RESOLVERS:
        try:
            page_id = resolver.resolve_page_id(path)
            # yes, it is application page
            if settings.CMS_MODERATOR:
                page = get_page_queryset(request).get(Q(id=page_id) | Q(publisher_draft=page_id))
            else:
                page = get_page_queryset(request).get(id=page_id)
            # If current page was matched, then we have some override for content
            # from cms, but keep current page. Otherwise return page to which was application assigned.
            return page
        except Resolver404:
            # Raised if the page is not managed by an apphook
            pass
    return None
Exemplo n.º 3
0
    def _get_page(self, res, ctx=None):
        page_id = res.id
        request = _get_django_request(res=res, ctx=ctx)
        if not page_id: # links like [cms: current page]
            # cms.middleware.page.CurrentPageMiddleware is required for this
            if request.current_page:
                return request.current_page
            # It is not really necessary that the current page is known as plugins can be rendered also outside of pages (like in preview view in admin), we can try to use a hint
            elif request.POST.get('page_id'):
                return moderator.get_page_queryset(request).get(pk=request.POST['page_id'])
            else:
                context = _get_django_context(res=res, ctx=ctx)
                plugin = self._get_plugin(request, context)

                if not plugin:
                    raise cms_models.Page.DoesNotExist()

                try:
                    # TODO: If plugin is used in an app this does not find an anchor page for the app, but this happens only in a preview as otherwise request.current_page works
                    return plugin.placeholder.page_set.get()
                except cms_models.Page.MultipleObjectsReturned as e:
                    # Should not happen
                    raise cms_models.Page.DoesNotExist(e)
        else:
            return moderator.get_page_queryset(request).get(reverse_id=page_id)
Exemplo n.º 4
0
def page_id_url(context, reverse_id, lang=None, site=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    site_id = get_site_id(site)
    request = context.get('request', False)
    if not request:
        return {'content':''}

    if request.current_page == "dummy":
        return {'content': ''}
    
    if lang is None:
        lang = get_language_from_request(request)
    key = 'page_id_url_pid:'+str(reverse_id)+'_l:'+str(lang)+'_site:'+str(site_id)+'_type:absolute_url'
    url = cache.get(key)
    if not url:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id,site=site_id)
            url = page.get_absolute_url(language=lang)
            cache.set(key, url, settings.CMS_CONTENT_CACHE_DURATION)
        except:
            send_missing_mail(reverse_id, request)
        
    if url:
        return {'content':url}
    return {'content':''}
Exemplo n.º 5
0
    def get_nodes(self, request):
        page_queryset = get_page_queryset(request)
        site = Site.objects.get_current()
        lang = get_language_from_request(request)
        filters = {
            'site': site,
        }
        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang
        pages = page_queryset.published().filter(**filters).order_by(
            "tree_id", "lft")
        ids = []
        nodes = []
        first = True
        home_cut = False
        home_children = []
        home = None
        for page in pages:
            if not home:
                home = page

            page.home_pk_cache = home.pk
            if first and page.pk != home.pk:
                home_cut = True
            if (page.parent_id == home.pk
                    or page.parent_id in home_children) and home_cut:
                page.home_cut_cache = True
                home_children.append(page.pk)
            if (page.pk == home.pk
                    and home.in_navigation) or page.pk != home.pk:
                first = False
            ids.append(page.id)
        titles = list(
            get_title_queryset(request).filter(page__in=ids, language=lang))
        for page in pages:  # add the title and slugs and some meta data
            for title in titles:
                if title.page_id == page.pk:
                    if not hasattr(page, "title_cache"):
                        page.title_cache = {}
                    page.title_cache[title.language] = title
                    nodes.append(page_to_node(page, home, home_cut))
                    ids.remove(page.pk)
        if ids:  # get fallback languages
            fallbacks = get_fallback_languages(lang)
            for l in fallbacks:
                titles = list(
                    get_title_queryset(request).filter(page__in=ids,
                                                       language=l))
                for title in titles:
                    for page in pages:  # add the title and slugs and some meta data
                        if title.page_id == page.pk:
                            if not hasattr(page, "title_cache"):
                                page.title_cache = {}
                            page.title_cache[title.language] = title
                            nodes.append(page_to_node(page, home, home_cut))
                            ids.remove(page.pk)
                            break
                if not ids:
                    break
        return nodes
Exemplo n.º 6
0
def show_breadcrumb(context, start_level=0, template="cms/breadcrumb.html"):
    request = context['request']
    page_queryset = get_page_queryset(request)
    title_queryset = get_title_queryset(request) 
    
    page = request.current_page
    if page == "dummy":
        context.update({'ancestors':[]})
        return context
    lang = get_language_from_request(request)
    if page:
        ancestors = list(page.get_ancestors())
        ancestors.append(page)
        home = page_queryset.get_home()
        if ancestors and ancestors[0].pk != home.pk: 
            ancestors = [home] + ancestors
        ids = [page.pk]
        for anc in ancestors:
            ids.append(anc.pk)
        titles = title_queryset.filter(page__in=ids, language=lang)
        for anc in ancestors:
            anc.home_pk_cache = home.pk 
            for title in titles:
                if title.page_id == anc.pk:
                    anc.title_cache = title
        for title in titles:
            if title.page_id == page.pk:
                page.title_cache = title
    else:
        site = Site.objects.get_current()
        ancestors = []
        extenders = page_queryset.published().filter(in_navigation=True, site=site)
        extenders = extenders.exclude(navigation_extenders__isnull=True).exclude(navigation_extenders__exact="")
        for ext in extenders:
            ext.childrens = []
            ext.ancestors_ascending = []
            nodes = get_extended_navigation_nodes(request, 100, [ext], ext.level, 100, 0, False, ext.navigation_extenders)
            if hasattr(ext, "ancestor"):
                selected = find_selected(nodes)
                if selected:
                    ancestors = list(ext.get_ancestors()) + [ext]
                    home = page_queryset.get_home()
                    if ancestors and ancestors[0].pk != home.pk: 
                        ancestors = [home] + ancestors
                    ids = []
                    for anc in ancestors:
                        ids.append(anc.pk)
                    titles = title_queryset.filter(page__in=ids, language=lang)
                    ancs = []
                    for anc in ancestors:
                        anc.home_pk_cache = home.pk
                        anc.ancestors_ascending = ancs[:]
                        ancs += [anc]
                        for title in titles:
                            if title.page_id == anc.pk:
                                anc.title_cache = title
                    ancestors = ancestors + selected.ancestors_ascending[1:] + [selected]
    context.update({'ancestors':ancestors,
                    'template': template})
    return context
Exemplo n.º 7
0
 def render(self, context, instance, placeholder):
     self.render_template = instance.template or SitemapPlugin.render_template
     page_queryset = get_page_queryset(None)
     all_pages = page_queryset.published()
     #.order_by('tree_id', 'parent', 'lft')
     context.update({'pages': all_pages})
     return context
Exemplo n.º 8
0
def show_placeholder_by_id(context, placeholder_name, reverse_id, lang=None, site=None):
    """
    Show the content of a page with a placeholder name and a reverse id in the right language
    This is mostly used if you want to have static content in a template of a page (like a footer)
    """
    request = context.get('request', False)
    site_id = get_site_id(site)
    
    if not request:
        return {'content':''}
    if lang is None:
        lang = get_language_from_request(request)
    key = 'show_placeholder_by_id_pid:'+reverse_id+'_placeholder:'+placeholder_name+'_site:'+str(site_id)+'_l:'+str(lang)
    content = cache.get(key)
    if not content:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id, site=site_id)
        except:
            send_missing_mail(reverse_id, request)
            return {'content':''}
        plugins = get_cmsplugin_queryset(request).filter(page=page, language=lang, placeholder__iexact=placeholder_name, parent__isnull=True).order_by('position').select_related()
        content = ""
        for plugin in plugins:
            content += plugin.render_plugin(context, placeholder_name)

    cache.set(key, content, settings.CMS_CONTENT_CACHE_DURATION)

    if content:
        return {'content':mark_safe(content)}
    return {'content':''}
Exemplo n.º 9
0
def _get_page_by_untyped_arg(page_lookup, request, site_id):
    """
    The `page_lookup` argument can be of any of the following types:
    - Integer: interpreted as `pk` of the desired page
    - String: interpreted as `reverse_id` of the desired page
    - `dict`: a dictionary containing keyword arguments to find the desired page
    (for instance: `{'pk': 1}`)
    - `Page`: you can also pass a Page object directly, in which case there will be no database lookup.
    - `None`: the current page will be used
    """
    if page_lookup is None:
        return request.current_page
    if isinstance(page_lookup, Page):
        return page_lookup
    if isinstance(page_lookup, basestring):
        page_lookup = {'reverse_id': page_lookup}
    elif isinstance(page_lookup, (int, long)):
        page_lookup = {'pk': page_lookup}
    elif not isinstance(page_lookup, dict):
        raise TypeError('The page_lookup argument can be either a Dictionary, Integer, Page, or String.')
    page_lookup.update({'site': site_id})
    try:
        return get_page_queryset(request).get(**page_lookup)
    except Page.DoesNotExist:
        site = Site.objects.get_current()
        subject = _('Page not found on %(domain)s') % {'domain':site.domain}
        body = _("A template tag couldn't find the page with lookup arguments `%(page_lookup)s\n`. "
            "The URL of the request was: http://%(host)s%(path)s") \
            % {'page_lookup': repr(page_lookup), 'host': site.domain, 'path': request.path}
        if settings.DEBUG:
            raise Page.DoesNotExist(body)
        else:
            mail_managers(subject, body, fail_silently=True)
            return None
Exemplo n.º 10
0
def _get_page_by_untyped_arg(page_lookup, request, site_id):
    """
    The `page_lookup` argument can be of any of the following types:
    - Integer: interpreted as `pk` of the desired page
    - String: interpreted as `reverse_id` of the desired page
    - `dict`: a dictionary containing keyword arguments to find the desired page
    (for instance: `{'pk': 1}`)
    - `Page`: you can also pass a Page object directly, in which case there will be no database lookup.
    - `None`: the current page will be used
    """
    if page_lookup is None:
        return request.current_page
    if isinstance(page_lookup, Page):
        return page_lookup
    if isinstance(page_lookup, basestring):
        page_lookup = {'reverse_id': page_lookup}
    elif isinstance(page_lookup, (int, long)):
        page_lookup = {'pk': page_lookup}
    elif not isinstance(page_lookup, dict):
        raise TypeError('The page_lookup argument can be either a Dictionary, Integer, Page, or String.')
    page_lookup.update({'site': site_id})
    try:
        return get_page_queryset(request).get(**page_lookup)
    except Page.DoesNotExist:
        site = Site.objects.get_current()
        subject = _('Page not found on %(domain)s') % {'domain':site.domain}
        body = _("A template tag couldn't find the page with lookup arguments `%(page_lookup)s\n`. "
            "The URL of the request was: http://%(host)s%(path)s") \
            % {'page_lookup': repr(page_lookup), 'host': site.domain, 'path': request.path}
        if settings.DEBUG:
            raise Page.DoesNotExist(body)
        else:
            if settings.SEND_BROKEN_LINK_EMAILS:
                mail_managers(subject, body, fail_silently=True)
            return None
Exemplo n.º 11
0
def page_id_url(context, reverse_id, lang=None, site=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    site_id = get_site_id(site)
    request = context.get('request', False)
    if not request:
        return {'content': ''}

    if request.current_page == "dummy":
        return {'content': ''}

    if lang is None:
        lang = get_language_from_request(request)
    key = 'page_id_url_pid:' + str(reverse_id) + '_l:' + str(
        lang) + '_site:' + str(site_id) + '_type:absolute_url'
    url = cache.get(key)
    if not url:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id,
                                                  site=site_id)
            url = page.get_absolute_url(language=lang)
            cache.set(key, url, settings.CMS_CONTENT_CACHE_DURATION)
        except:
            send_missing_mail(reverse_id, request)

    if url:
        return {'content': url}
    return {'content': ''}
Exemplo n.º 12
0
 def _get_page(self, request):
     if self.reverse_id == None:
         return request.current_page
     site = Site.objects.get_current()    
     try:
         return get_page_queryset(request).get(reverse_id=self.reverse_id, site=site)
     except:
         send_missing_mail(self.reverse_id, request)
Exemplo n.º 13
0
def show_breadcrumb(context, start_level=0, template="cms/breadcrumb.html"):
    request = context['request']
    page_queryset = get_page_queryset(request)
    title_queryset = get_title_queryset(request)

    page = request.current_page
    if page == "dummy":
        context.update({
            'ancestors': [],
            'template': template,
        })
        return context
    lang = get_language_from_request(request)
    if page and not page.navigation_extenders:
        ancestors = ancestors_from_page(page, page_queryset, title_queryset,
                                        lang)
    else:
        site = Site.objects.get_current()
        ancestors = []
        extenders = page_queryset.published().filter(site=site)
        extenders = extenders.exclude(
            navigation_extenders__isnull=True).exclude(
                navigation_extenders__exact="")
        for ext in extenders:
            ext.childrens = []
            ext.ancestors_ascending = []
            nodes = get_extended_navigation_nodes(request, 100, [ext],
                                                  ext.level, 100, 0, False,
                                                  ext.navigation_extenders)
            if hasattr(ext, "ancestor"):
                selected = find_selected(nodes)
                if selected:
                    ancestors = list(ext.get_ancestors()) + [ext]
                    home = page_queryset.get_home()
                    if ancestors and ancestors[0].pk != home.pk:
                        ancestors = [home] + ancestors
                    ids = []
                    for anc in ancestors:
                        ids.append(anc.pk)
                    titles = title_queryset.filter(page__in=ids, language=lang)
                    ancs = []
                    for anc in ancestors:
                        anc.home_pk_cache = home.pk
                        anc.ancestors_ascending = ancs[:]
                        ancs += [anc]
                        for title in titles:
                            if title.page_id == anc.pk:
                                if not hasattr(anc, "title_cache"):
                                    anc.title_cache = {}
                                anc.title_cache[title.language] = title
                    ancestors = ancestors + selected.ancestors_ascending[
                        1:] + [selected]
        if not ancestors and page:
            ancestors = ancestors_from_page(page, page_queryset,
                                            title_queryset, lang)
    context.update({'ancestors': ancestors, 'template': template})
    return context
Exemplo n.º 14
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    # get the right model
    page_queryset = get_page_queryset(request)

    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    if "preview" in request.GET.keys():
        pages = page_queryset.all()
    else:
        pages = page_queryset.published()

    root_pages = pages.all_root().order_by("tree_id")
    current_page, response = None, None
    if root_pages:
        if page_id:
            current_page = get_object_or_404(pages, pk=page_id)
        elif slug != None:
            if slug == "":
                current_page = root_pages[0]
            else:
                if slug.startswith(reverse("pages-root")):
                    path = slug.replace(reverse("pages-root"), "", 1)
                else:
                    path = slug
                if root_pages:
                    home_tree_id = root_pages[0].tree_id
                    home_slug = root_pages[0].get_slug(language=lang)
                else:
                    home_slug = ""
                    home_tree_id = None
                current_page, alternative = get_current_page(path, lang, pages, home_slug, home_tree_id)
                if settings.CMS_APPLICATIONS_URLS:
                    # check if it should'nt point to some application, if yes,
                    # change current page if required
                    current_page = applications_page_check(request, current_page, path)
                if not current_page:
                    if alternative and settings.CMS_LANGUAGE_FALLBACK:
                        return HttpResponseRedirect(alternative)
                    if no404:  # used for placeholder finder
                        current_page = None
                    else:
                        raise Http404('CMS: Page not found for "%s"' % slug)
        else:
            current_page = applications_page_check(request)
            # current_page = None
        template_name = get_template_from_request(request, current_page)
    elif not no404:
        raise Http404("CMS: No page found for site %s" % unicode(site.name))

    if current_page:
        has_change_permissions = current_page.has_change_permission(request)
        request._current_page_cache = current_page
        if current_page.get_redirect(language=lang):
            return HttpResponseRedirect(current_page.get_redirect(language=lang))
    else:
        has_change_permissions = False
    return template_name, locals()
Exemplo n.º 15
0
Arquivo: menu.py Projeto: team-xue/xue
    def get_nodes(self, request):
        usr, nodes = request.user, []

        # much of this init code is the same as cms/menu.py to ensure
        # result compatibility
        # don't need to pass in request, since the tag app is only here
        # to help organize articles, not assist in moderation flow.
        page_queryset = get_page_queryset()
        site = Site.objects.get_current()
        lang = get_language_from_request(request)
        filters = {"site": site}
        if settings.CMS_HIDE_UNTRANSLATED:
            filters["title_set__language"] = lang
        pages = (
            page_queryset.published()
            .filter(**filters)
            .order_by(
                "-creation_date",
                # "tree_id",
                # "lft",
            )
        )

        # menu-building helper vars
        append = nodes.append
        counter = CountingID(1)
        new_id = counter.get

        # Create nodes for tags and related pages in one pass
        for tag in Tag.objects.all():
            # 1. node for tag
            node_id = new_id()
            append(
                NavigationNode(
                    tag.name,
                    reverse("xue.tagfrontend.views.tag_view", args=(tag.pk,)),
                    node_id,
                    # make the pages referrable from CMS templates!
                    attr={"reverse_id": "cmstag_%s" % tag.name},
                )
            )

            # 2. related pages
            # we'll reuse CMS's page_to_node but modify the
            # result node slightly
            for page in pages.filter(tags=tag):
                # get the node as it's returned by the CMS
                # TODO: is the simplified params appropriate?
                page_node = page_to_node(page, page, False)

                # modify it to fit in our tree structure
                page_node.id = new_id()
                page_node.parent_id = node_id
                append(page_node)

        return nodes
Exemplo n.º 16
0
 def get_nodes(self, request):
     page_queryset = get_page_queryset(request)
     site = Site.objects.get_current()
     lang = get_language_from_request(request)
     filters = {
         'site':site,
     }
     if settings.CMS_HIDE_UNTRANSLATED:
         filters['title_set__language'] = lang
     pages = page_queryset.published().filter(**filters).order_by("tree_id", "lft")
     ids = []
     nodes = []
     first = True
     home_cut = False
     home_children = []
     home = None
     for page in pages:
         if not home:
             home = page
         
         page.home_pk_cache = home.pk
         if first and page.pk != home.pk:
             home_cut = True
         if (page.parent_id == home.pk or page.parent_id in home_children) and home_cut:
             page.home_cut_cache = True 
             home_children.append(page.pk)
         if (page.pk == home.pk and home.in_navigation) or page.pk != home.pk:
             first = False
         ids.append(page.id)
     titles = list(get_title_queryset(request).filter(page__in=ids, language=lang))
     for page in pages:# add the title and slugs and some meta data
         for title in titles:
             if title.page_id == page.pk:
                 if not hasattr(page, "title_cache"):
                     page.title_cache = {}
                 page.title_cache[title.language] = title
                 nodes.append(page_to_node(page, home, home_cut))
                 ids.remove(page.pk)
     if ids: # get fallback languages
         fallbacks = get_fallback_languages(lang)
         for l in fallbacks:
             titles = list(get_title_queryset(request).filter(page__in=ids, language=l))
             for title in titles:
                 for page in pages:# add the title and slugs and some meta data
                     if title.page_id == page.pk:
                         if not hasattr(page, "title_cache"):
                             page.title_cache = {}
                         page.title_cache[title.language] = title
                         nodes.append(page_to_node(page, home, home_cut))
                         ids.remove(page.pk)
                         break
             if not ids:
                 break
     return nodes  
Exemplo n.º 17
0
def _show_placeholder_by_id(context, placeholder_name, reverse_id, lang=None,
        site=None, cache_result=True):
    """
    Show the content of a page with a placeholder name and a reverse id in the right language
    This is mostly used if you want to have static content in a template of a page (like a footer)
    """
    request = context.get('request', False)
    site_id = get_site_id(site)
    
    if not request:
        return {'content':''}
    if lang is None:
        lang = get_language_from_request(request)
        
    content = None
    
    if cache_result:
        key = 'show_placeholder_by_id_pid:'+reverse_id+'_placeholder:'+placeholder_name+'_site:'+str(site_id)+'_l:'+str(lang)
        content = cache.get(key)
        
    if not content:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id, site=site_id)
        except:
            if settings.DEBUG:
                raise
            else:
                site = Site.objects.get_current()
                send_mail(_('Reverse ID not found on %(domain)s') % {'domain':site.domain},
                          _("A show_placeholder_by_id template tag didn't found a page with the reverse_id %(reverse_id)s\n"
                            "The url of the page was: http://%(host)s%(path)s") %
                            {'reverse_id':reverse_id, 'host':request.host, 'path':request.path},
                          settings.DEFAULT_FROM_EMAIL,
                          settings.MANAGERS,
                          fail_silently=True)
                return {'content':''}
        plugins = get_cmsplugin_queryset(request).filter(page=page, language=lang, placeholder__iexact=placeholder_name, parent__isnull=True).order_by('position').select_related()
        content = ""
        for plugin in plugins:
            content += plugin.render_plugin(context, placeholder_name)
            
    if cache_result:
        cache.set(key, content, settings.CMS_CONTENT_CACHE_DURATION)

    if content:
        return {'content':mark_safe(content)}
    return {'content':''}
Exemplo n.º 18
0
def applications_page_check(request, current_page=None, path=None):
    """Tries to find if given path was resolved over application. 
    Applications have higher priority than other cms pages. 
    """
    if current_page:
        return current_page
    if path is None:
        path = request.path.replace(reverse('pages-root'), '', 1)
    # check if application resolver can resolve this
    try:
        page_id = dynamic_app_regex_url_resolver.resolve_page_id(path+"/")
        # yes, it is application page
        page = get_page_queryset(request).get(id=page_id)
        # If current page was matched, then we have some override for content
        # from cms, but keep current page. Otherwise return page to which was application assigned.
        return page 
    except Resolver404:
        pass
    return None    
Exemplo n.º 19
0
def applications_page_check(request, current_page=None, path=None):
    """Tries to find if given path was resolved over application. 
    Applications have higher priority than other cms pages. 
    """
    from cms.utils.moderator import get_page_queryset
    if current_page:
        return current_page
    if path is None:
        path = request.path.replace(reverse('pages-root'), '', 1)
    # check if application resolver can resolve this
    try:
        page_id = dynamic_app_regex_url_resolver.resolve_page_id(path + "/")
        # yes, it is application page
        page = get_page_queryset(request).get(id=page_id)
        # If current page was matched, then we have some override for content
        # from cms, but keep current page. Otherwise return page to which was application assigned.
        return page
    except Resolver404:
        pass
    return None
Exemplo n.º 20
0
def show_placeholder_by_id(context,
                           placeholder_name,
                           reverse_id,
                           lang=None,
                           site=None):
    """
    Show the content of a page with a placeholder name and a reverse id in the right language
    This is mostly used if you want to have static content in a template of a page (like a footer)
    """
    request = context.get('request', False)
    site_id = get_site_id(site)

    if not request:
        return {'content': ''}
    if lang is None:
        lang = get_language_from_request(request)
    key = 'show_placeholder_by_id_pid:' + reverse_id + '_placeholder:' + placeholder_name + '_site:' + str(
        site_id) + '_l:' + str(lang)
    content = cache.get(key)
    if not content:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id,
                                                  site=site_id)
        except:
            send_missing_mail(reverse_id, request)
            return {'content': ''}
        plugins = get_cmsplugin_queryset(request).filter(
            page=page,
            language=lang,
            placeholder__iexact=placeholder_name,
            parent__isnull=True).order_by('position').select_related()
        content = ""
        for plugin in plugins:
            content += plugin.render_plugin(context, placeholder_name)

    cache.set(key, content, settings.CMS_CONTENT_CACHE_DURATION)

    if content:
        return {'content': mark_safe(content)}
    return {'content': ''}
Exemplo n.º 21
0
 def items(self):
     page_queryset = get_page_queryset(None)
     all_pages = page_queryset.published().filter(login_required=False)
     return all_pages
Exemplo n.º 22
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
    """
    if 'django.contrib.admin' in settings.INSTALLED_APPS:
        admin_base = reverse('admin:index')
    else:
        admin_base = None
    
    pages_root = urllib.unquote(reverse("pages-root"))
    
    # The following is used by cms.middleware.page.CurrentPageMiddleware
    if hasattr(request, '_current_page_cache'):
        return request._current_page_cache
    
    # Get a basic queryset for Page objects, depending on if we use the 
    # MODERATOR or not.
    page_queryset = get_page_queryset(request)
    site = Site.objects.get_current()
    
    # TODO: Isn't there a permission check needed here?
    if 'preview' in request.GET:
        pages = page_queryset.filter(site=site)
    else:
        pages = page_queryset.published().filter(site=site)
    
    # Check if this is called from an admin request
    if admin_base and request.path.startswith(admin_base):
        # if so, get the page ID to query the page
        page_id = request.path.split('/')[0]
        try:
            page = pages.get(pk=page_id)
        except Page.DoesNotExist:
            return None
        request._current_page_cache = page
        return page
    
    # If use_path is given, someone already did the path cleaning
    if use_path:
        path = use_path
    else:
        # otherwise strip of the non-cms part of the URL 
        path = request.path[len(pages_root):-1]
        
    # Check if there are any pages
    if not pages.all_root():
        return None
    
    # get the home page (needed to get the page)
    try:
        home = pages.get_home()
    except NoHomeFound:
        home = None
    # if there is no path (slashes stripped) and we found a home, this is the
    # home page.
    if not path and home:
        page = home
        request._current_page_cache = page
        return page
    
    # title_set__path=path should be clear, get the pages where the path of the
    # title object is equal to our path.
    q = Q(title_set__path=path)
    if home:
        # if we have a home, also search for all paths prefixed with the
        # home slug that are on the same tree as home, since home isn't ussually
        # called with it's slug, thus it's children don't have the home bit in
        # the request either, thus we need to re-add it.
        q2 = Q()
        q2 = Q(title_set__path='%s/%s' % (home.get_slug(), path))
        q2 &= Q(tree_id=home.tree_id)
        q |= q2
        
    # TODO: We should probably get rid of this odd DB-Gettext thingy, no idea
    # how and why this should work
    if settings.CMS_DBGETTEXT and settings.CMS_DBGETTEXT_SLUGS:
        # ugly hack -- brute force search for reverse path translation:
        from django.utils.translation import ugettext
        from cms.models import Title
        for t in Title.objects.all():
            tpath = '/'.join([ugettext(x) for x in t.path.split('/')])
            if path == tpath:
                q = Q(title_set__path=t.path)
                break
    try:
        page = pages.filter(q).distinct().get()
    except Page.DoesNotExist:
        return None
    request._current_page_cache = page
    return page
Exemplo n.º 23
0
 def items(self):
     from cms.utils.moderator import get_page_queryset
     page_queryset = get_page_queryset(None)
     return page_queryset.all()
Exemplo n.º 24
0
 def items(self):
     from cms.utils.moderator import get_page_queryset
     page_queryset = get_page_queryset(None)
     all_pages = page_queryset.published()
     return all_pages
Exemplo n.º 25
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    # get the right model
    page_queryset = get_page_queryset(request)
    
    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    if 'preview' in request.GET.keys():
        pages = page_queryset.all()
    else:
        pages = page_queryset.published()
    
    root_pages = pages.all_root().order_by("tree_id")
    current_page, response = None, None
    if root_pages:
        if page_id:
            current_page = get_object_or_404(pages, pk=page_id)
        elif slug != None:
            if slug == "":
                current_page = root_pages[0]
            else:
                if slug.startswith(reverse('pages-root')):
                    path = slug.replace(reverse('pages-root'), '', 1)
                else:
                    path = slug
                if root_pages:
                    home_tree_id = root_pages[0].tree_id
                    home_slug = root_pages[0].get_slug(language=lang)
                else:
                    home_slug = ""
                    home_tree_id = None
                current_page, alternative = get_current_page(path, lang, pages, home_slug, home_tree_id)
                if settings.CMS_APPLICATIONS_URLS:
                    # check if it should'nt point to some application, if yes,
                    # change current page if required
                    current_page = applications_page_check(request, current_page, path)
                if not current_page:
                    if alternative and settings.CMS_LANGUAGE_FALLBACK:
                        return HttpResponseRedirect(alternative)
                    if no404:# used for placeholder finder
                        current_page = None
                    else:
                        raise Http404('CMS: Page not found for "%s"' % slug)
        else:
            current_page = applications_page_check(request)
            #current_page = None
        template_name = get_template_from_request(request, current_page)
    elif not no404:
        raise Http404("CMS: No page found for site %s" % unicode(site.name))
    
    if current_page:  
        has_change_permissions = current_page.has_change_permission(request)
        request._current_page_cache = current_page
        if current_page.get_redirect(language=lang):
            return HttpResponseRedirect(current_page.get_redirect(language=lang))
        if current_page.login_required and not request.user.is_authenticated():
            if 'cms.middleware.multilingual.MultilingualURLMiddleware' in django_settings.MIDDLEWARE_CLASSES:
                path = urlquote("/%s%s" % (request.LANGUAGE_CODE, request.get_full_path()))
            else:
                path = urlquote(request.get_full_path())
            tup = django_settings.LOGIN_URL , "next", path
            return HttpResponseRedirect('%s?%s=%s' % tup)
    else:
        has_change_permissions = False
    return template_name, locals()
Exemplo n.º 26
0
def show_sub_menu(context, levels=100, template="cms/sub_menu.html"):
    """Get the root page of the current page and 
    render a nested list of all root's children pages"""
    request = context['request']
    page_queryset = get_page_queryset(request)

    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    children = []
    page = request.current_page
    if page == "dummy":
        context.update({
            'children': [],
            'template': template,
            'from_level': 0,
            'to_level': 0,
            'extra_inactive': 0,
            'extra_active': 0
        })
        return context

    if page:
        page.get_cached_ancestors()
        # this is not required anymore, sice home_pk_cache is a getter
        #if not hasattr(page, "home_pk_cache"):
        #    page.home_pk_cache = page_queryset.get_home(site).pk
        filters = {
            'in_navigation': True,
            'lft__gt': page.lft,
            'rght__lt': page.rght,
            'tree_id': page.tree_id,
            'level__lte': page.level + levels,
            'site': site
        }
        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang
        if not request.user.is_authenticated():
            filters['menu_login_required'] = False
        pages = page_queryset.published().filter(**filters)

        ids = []
        pages = list(pages)
        all_pages = pages[:]

        page.childrens = []
        for p in pages:
            p.descendant = True
            ids.append(p.pk)
        page.selected = True
        page.menu_level = -1
        was_soft_root = False
        if page.soft_root:
            was_soft_root = True
            page.soft_root = False
        find_children(page,
                      pages,
                      levels,
                      levels, [],
                      page.pk,
                      request=request)
        if was_soft_root:
            page.soft_root = True
        children = page.childrens
        titles = get_title_queryset(request).filter(page__in=ids,
                                                    language=lang)
        for p in all_pages:  # add the title and slugs and some meta data
            for title in titles:
                if title.page_id == p.pk:
                    if not hasattr(p, "title_cache"):
                        p.title_cache = {}
                    p.title_cache[title.language] = title
        from_level = page.level
        to_level = page.level + levels
        extra_active = extra_inactive = levels
    else:
        extenders = page_queryset.published().filter(in_navigation=True,
                                                     site=site)
        extenders = extenders.exclude(
            navigation_extenders__isnull=True).exclude(
                navigation_extenders__exact="")
        children = []
        from_level = 0
        to_level = 0
        extra_active = 0
        extra_inactive = 0
        for ext in extenders:
            ext.childrens = []
            ext.ancestors_ascending = []
            nodes = get_extended_navigation_nodes(request, 100, [ext],
                                                  ext.level, 100, levels,
                                                  False,
                                                  ext.navigation_extenders)
            if hasattr(ext, "ancestor"):
                selected = find_selected(nodes)
                if selected:
                    children = selected.childrens
                    from_level = selected.level
                    to_level = from_level + levels
                    extra_active = extra_inactive = levels
    children = navigation.handle_navigation_manipulators(children, request)
    context.update({
        'children': children,
        'template': template,
        'from_level': from_level,
        'to_level': to_level,
        'extra_inactive': extra_inactive,
        'extra_active': extra_active
    })
    return context
Exemplo n.º 27
0
def show_menu(context, from_level=0, to_level=100, extra_inactive=0, extra_active=100, template="cms/menu.html", next_page=None, root_id=None):
    """
    render a nested list of all children of the pages
    from_level: is the start level
    to_level: is the max level rendered
    render_children: if set to True will render all not direct ascendants too
    """
    try:
        # If there's an exception (500), default context_processors may not be called.
        request = context['request']
    except KeyError:
        return {'template': 'cms/empty.html'}
    page_queryset = get_page_queryset(request)
    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    current_page = request.current_page
    if current_page == "dummy":
        context.update({'children':[],
                    'template':template,
                    'from_level':from_level,
                    'to_level':to_level,
                    'extra_inactive':extra_inactive,
                    'extra_active':extra_active})
        return context
    if hasattr(current_page, "home_pk_cache"):
        home_pk = current_page.home_pk_cache
    else:
        try:
            home_pk = page_queryset.get_home(site).pk
        except NoHomeFound:
            home_pk = 0
    if not next_page: #new menu... get all the data so we can save a lot of queries
        
        children = []
        ancestors = []
        if current_page:
            alist = current_page.get_ancestors().values_list('id', 'soft_root')
        else:# maybe the active node is in an extender?
            alist = []
            extenders = page_queryset.published().filter(in_navigation=True, 
                                                        site=site, 
                                                        level__lte=to_level)
            extenders = extenders.exclude(navigation_extenders__isnull=True).exclude( navigation_extenders__exact="")
            for ext in extenders:
                ext.childrens = []
                ext.ancestors_ascending = []
                get_extended_navigation_nodes(request, 100, [ext], ext.level, 100, 100, False, ext.navigation_extenders)
                if hasattr(ext, "ancestor"):
                    alist = list(ext.get_ancestors().values_list('id', 'soft_root'))
                    alist = [(ext.pk, ext.soft_root)] + alist
                    break
        filters = {'in_navigation' : True, 
                   'site' : site,
                   'level__lte' : to_level}
        #check the ancestors for softroots
        soft_root_pk = None
        for p in alist:
            ancestors.append(p[0])
            if p[1]:
                soft_root_pk = p[0]
        #modify filters if we don't start from the root
        root_page = None
        if root_id:
            try:
                root_page = page_queryset.get(reverse_id=root_id, site=site)
            except:
                send_missing_mail(root_id, request)
        else:
            if current_page and current_page.soft_root:
                root_page = current_page
                soft_root_pk = current_page.pk
            elif soft_root_pk:
                root_page = page_queryset.get(pk=soft_root_pk)
        if root_page:
            if isinstance(root_page, int):
                root_page = page_queryset.get(pk=root_page)
            if isinstance(root_page, Page):
                root_page = page_queryset.get(pk=root_page.id)
            elif isinstance(root_page, unicode):
                root_page = page_queryset.get(reverse_id=root_page, site=site)
            filters['tree_id'] = root_page.tree_id
            filters['lft__gt'] = root_page.lft
            filters['rght__lt'] = root_page.rght
            filters['level__lte'] = root_page.level + to_level
            db_from_level = root_page.level + from_level
        else:
            db_from_level = from_level
        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang
        if not request.user.is_authenticated():
            filters['menu_login_required'] = False
        pages = page_queryset.published().filter(**filters).order_by('tree_id', 
                                                                    'parent', 
                                                                    'lft')
        pages = list(pages)
        if root_page:
            pages = [root_page] + pages
        all_pages = pages[:]
        root_level = getattr(root_page, 'level', None)
        ids = []
        for page in pages:# build the tree
            if page.level >= db_from_level:
                ids.append(page.pk)
            if page.level == 0 or page.level == root_level:
                if page.parent_id:
                    page.get_cached_ancestors()
                else:
                    page.ancestors_ascending = []
                page.home_pk_cache = home_pk
                page.menu_level = 0 - from_level
                page.childrens = []
                children.append(page)
                if page.pk == soft_root_pk:
                    page.soft_root = False #ugly hack for the recursive function
                if current_page:
                    pk = current_page.pk
                else:
                    pk = -1
                find_children(page, pages, extra_inactive, extra_active, ancestors, pk, request=request, to_levels=to_level)
                if page.pk == soft_root_pk:
                    page.soft_root = True
        if db_from_level > 0:
            children = cut_levels(children, db_from_level)
        titles = list(get_title_queryset(request).filter(page__in=ids, language=lang))
        for page in all_pages:# add the title and slugs and some meta data
            for title in titles:
                if title.page_id == page.pk:
                    if not hasattr(page, "title_cache"):
                        page.title_cache = {}
                    page.title_cache[title.language] = title
                    ids.remove(page.pk)
            if page.pk in ancestors:
                page.ancestor = True
            if current_page and page.parent_id == current_page.parent_id and not page.pk == current_page.pk:
                page.sibling = True
        if ids:
            fallbacks = get_fallback_languages(lang)
            for l in fallbacks:
                titles = list(get_title_queryset(request).filter(page__in=ids, language=l))
                for page in all_pages:# add the title and slugs and some meta data
                    for title in titles:
                        if title.page_id == page.pk:
                            if not hasattr(page, "title_cache"):
                                page.title_cache = {}
                            page.title_cache[title.language] = title
                            ids.remove(page.pk)
                if not ids:
                    break
        children = navigation.handle_navigation_manipulators(children, request)
    else:
        children = next_page.childrens
    context.update({'children':children,
                    'template':template,
                    'from_level':from_level,
                    'to_level':to_level,
                    'extra_inactive':extra_inactive,
                    'extra_active':extra_active})
    return context
Exemplo n.º 28
0
 def items(self):
     from cms.utils.moderator import get_page_queryset
     page_queryset = get_page_queryset(None)
     all_pages = page_queryset.published().filter(login_required=False)
     return all_pages
Exemplo n.º 29
0
def details(request,
            page_id=None,
            slug=None,
            template_name=settings.CMS_TEMPLATES[0][0],
            no404=False):
    # get the right model
    page_queryset = get_page_queryset(request)

    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    if 'preview' in request.GET.keys():
        pages = page_queryset.filter(site=site)
    else:
        pages = page_queryset.published().filter(site=site)

    current_page, response = None, None
    if pages.all_root():
        if page_id:
            current_page = get_object_or_404(pages, pk=page_id)
        elif slug != None:
            if slug == "":
                current_page = pages.get_home()
            else:
                pages_root = reverse('pages-root')
                path = slug.startswith(
                    pages_root) and slug[len(pages_root):] or slug

                try:
                    home = pages.get_home()
                    current_page, alternative = get_current_page(
                        path, lang, pages, home.get_slug(language=lang),
                        home.tree_id)
                except NoHomeFound:
                    current_page, alternative = get_current_page(
                        path, lang, pages)

                if apphook_pool.get_apphooks():
                    # check if it shouldn't point to some application, if yes,
                    # change current page if required
                    current_page = applications_page_check(
                        request, current_page, path)
                if not current_page:
                    if alternative and settings.CMS_LANGUAGE_FALLBACK:
                        return HttpResponseRedirect(alternative)
                    if no404:  # used for placeholder finder
                        current_page = None
                    else:
                        if not slug and settings.DEBUG:
                            CMS_MEDIA_URL = settings.CMS_MEDIA_URL
                            return "cms/new.html", locals()
                        raise Http404('CMS: Page not found for "%s"' % slug)
        else:
            current_page = applications_page_check(request)
            #current_page = None
        template_name = get_template_from_request(request,
                                                  current_page,
                                                  no_current_page=True)
    elif not no404:
        if not slug and settings.DEBUG:
            CMS_MEDIA_URL = settings.CMS_MEDIA_URL
            return "cms/new.html", locals()
        raise Http404("CMS: No page found for site %s" % unicode(site.name))

    if current_page:
        has_change_permissions = current_page.has_change_permission(request)
        request._current_page_cache = current_page

        redirect_url = current_page.get_redirect(language=lang)
        if redirect_url:
            if settings.i18n_installed and redirect_url[0] == "/":
                redirect_url = "/%s/%s" % (lang, redirect_url.lstrip("/"))
            # add language prefix to url
            return HttpResponseRedirect(redirect_url)

        if current_page.login_required and not request.user.is_authenticated():
            if settings.i18n_installed:
                path = urlquote(
                    "/%s%s" % (request.LANGUAGE_CODE, request.get_full_path()))
            else:
                path = urlquote(request.get_full_path())
            tup = django_settings.LOGIN_URL, "next", path
            return HttpResponseRedirect('%s?%s=%s' % tup)
    else:
        has_change_permissions = False
    return template_name, locals()
Exemplo n.º 30
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    '''
    This is the bitch of the CMS.
    Basically, she does it all. For instance, this is called by a util function 
    to retrieve Models (!), hence the no404 argument.
    
    BADLY NEEDS REFACTORING, BITCH 
    '''
    # get the right model
    page_queryset = get_page_queryset(request)
    
    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    if 'preview' in request.GET.keys():
        pages = page_queryset.filter(site=site)
    else:
        pages = page_queryset.published(site=site)
    
    current_page, response = None, None
    if pages.all_root(): # QUERY!
        # If there is at least one root page (no parent)
        if page_id:
            current_page = get_object_or_404(pages, pk=page_id)# QUERY!
        elif slug != None:
            if slug == "":
                # Gets the first root page (no parent) in the page's tree, 
                # ordered by tree ID
                current_page = pages.get_home()# QUERY!
            else:
                # We have a slug, we get the root using reverse (see ./urls.py) 
                pages_root = reverse('pages-root')
                # If the CMS urls are not the actual root of the url path
                # (http://bullshit.com/blablabla/some/page/slug)
                # Remove the prefix
                # (some/page/slug) 
                if slug.startswith(pages_root):
                    path = slug[len(pages_root):]
                else:  
                    path = slug
                try:
                    home = pages.get_home() # QUERY!
                    current_page, alternative = get_current_page(path, lang, pages, home.get_slug(language=lang), home.tree_id)
                except NoHomeFound:
                    current_page, alternative = get_current_page(path, lang, pages)# QUERY!
                    
                if apphook_pool.get_apphooks():
                    # check if it shouldn't point to some application, if yes,
                    # change current page if required
                    current_page = applications_page_check(request, current_page, path)
                if not current_page:
                    # We still don't have a current page... probably because it 
                    # doesn't exist in the current language, let's lookup for 
                    # the current language's fallback
                    if alternative and settings.CMS_LANGUAGE_FALLBACK:
                        return HttpResponseRedirect(alternative)
                    if no404:# used for placeholder finder
                        current_page = None 
                    else:
                        # "Normal case" - we're being a view
                        if not slug and settings.DEBUG:
                            CMS_MEDIA_URL = settings.CMS_MEDIA_URL
                            # Classic case of "I didn't read the Zen of Python".
                            # This is line 2: "Explicit is better than implicit"
                            return "cms/new.html", locals() # Come on, use a dict!. 
                        raise Http404('CMS: Page not found for "%s"' % slug)
        else:
            # We have an apphook on the root page
            current_page = applications_page_check(request)
            #current_page = None
        template_name = get_template_from_request(request, current_page, no_current_page=True)
    elif not no404: # Double negation: no404 = True
        # If we're not being a view
        if not slug and settings.DEBUG:
            CMS_MEDIA_URL = settings.CMS_MEDIA_URL
            return "cms/new.html", locals() # damn, it should be a dict!
        raise Http404("CMS: No page found for site %s" % unicode(site.name))
    
    if current_page:
        has_change_permissions = current_page.has_change_permission(request)
        request._current_page_cache = current_page
        
        redirect_url = current_page.get_redirect(language=lang)
        if redirect_url:
            if settings.i18n_installed and redirect_url[0] == "/":
                redirect_url = "/%s/%s" % (lang, redirect_url.lstrip("/"))
            # add language prefix to url
            return HttpResponseRedirect(redirect_url)
        
        if current_page.login_required and not request.user.is_authenticated():
            if settings.i18n_installed:
                path = urlquote("/%s%s" % (request.LANGUAGE_CODE, request.get_full_path()))
            else:
                path = urlquote(request.get_full_path())
            tup = django_settings.LOGIN_URL , "next", path
            return HttpResponseRedirect('%s?%s=%s' % tup)
    else:
        has_change_permissions = False
    return template_name, locals() # Ah well, passing the whole context again
Exemplo n.º 31
0
    def get_nodes(self, request):
        page_queryset = get_page_queryset(request)
        site = Site.objects.get_current()
        lang = get_language_from_request(request)
        
        filters = {
            'site':site,
        }
        
        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang
            
        pages = page_queryset.published().filter(**filters).order_by("tree_id", "lft")
        
        ids = []
        nodes = []
        first = True
        home_cut = False
        home_children = []
        home = None
        actual_pages = []
        
        # cache view perms
        visible_pages = get_visible_pages(request, pages, site)
        for page in pages:
            # Pages are ordered by tree_id, therefore the first page is the root
            # of the page tree (a.k.a "home")
            if page.pk not in visible_pages:
                # Don't include pages the user doesn't have access to
                continue
            if not home:
                home = page
            page.home_pk_cache = home.pk
            if first and page.pk != home.pk:
                home_cut = True
            if (page.parent_id == home.pk or page.parent_id in home_children) and home_cut:
                home_children.append(page.pk)
            if (page.pk == home.pk and home.in_navigation) or page.pk != home.pk:
                first = False
            ids.append(page.id)
            actual_pages.append(page)

        titles = list(get_title_queryset(request).filter(page__in=ids, language=lang))
        for page in actual_pages: # add the title and slugs and some meta data
            for title in titles:
                if title.page_id == page.pk:
                    if not hasattr(page, "title_cache"):
                        page.title_cache = {}
                    page.title_cache[title.language] = title
                    nodes.append(page_to_node(page, home, home_cut))
                    ids.remove(page.pk)

        if ids: # get fallback languages
            fallbacks = get_fallback_languages(lang)
            for lang in fallbacks:
                titles = list(get_title_queryset(request).filter(page__in=ids, language=lang))
                for title in titles:
                    for page in actual_pages: # add the title and slugs and some meta data
                        if title.page_id == page.pk:
                            if not hasattr(page, "title_cache"):
                                page.title_cache = {}
                            page.title_cache[title.language] = title
                            nodes.append(page_to_node(page, home, home_cut))
                            ids.remove(page.pk)
                            break
                if not ids:
                    break
        return nodes  
Exemplo n.º 32
0
    def get_nodes(self, request):
        page_queryset = get_page_queryset(request)
        site = Site.objects.get_current()
        lang = get_language_from_request(request)

        filters = {
            'site': site,
        }

        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang

        pages = page_queryset.published().filter(**filters).order_by(
            "tree_id", "lft")

        ids = []
        nodes = []
        first = True
        home_cut = False
        home_children = []
        home = None
        actual_pages = []

        # cache view perms
        visible_pages = get_visible_pages(request, pages, site)
        for page in pages:
            # Pages are ordered by tree_id, therefore the first page is the root
            # of the page tree (a.k.a "home")
            if page.pk not in visible_pages:
                # Don't include pages the user doesn't have access to
                continue
            if not home:
                home = page
            page.home_pk_cache = home.pk
            if first and page.pk != home.pk:
                home_cut = True
            if (page.parent_id == home.pk
                    or page.parent_id in home_children) and home_cut:
                home_children.append(page.pk)
            if (page.pk == home.pk
                    and home.in_navigation) or page.pk != home.pk:
                first = False
            ids.append(page.id)
            actual_pages.append(page)

        titles = list(
            get_title_queryset(request).filter(page__in=ids, language=lang))
        for page in actual_pages:  # add the title and slugs and some meta data
            for title in titles:
                if title.page_id == page.pk:
                    if not hasattr(page, "title_cache"):
                        page.title_cache = {}
                    page.title_cache[title.language] = title
                    nodes.append(page_to_node(page, home, home_cut))
                    ids.remove(page.pk)

        if ids:  # get fallback languages
            fallbacks = get_fallback_languages(lang)
            for l in fallbacks:
                titles = list(
                    get_title_queryset(request).filter(page__in=ids,
                                                       language=l))
                for title in titles:
                    for page in actual_pages:  # add the title and slugs and some meta data
                        if title.page_id == page.pk:
                            if not hasattr(page, "title_cache"):
                                page.title_cache = {}
                            page.title_cache[title.language] = title
                            nodes.append(page_to_node(page, home, home_cut))
                            ids.remove(page.pk)
                            break
                if not ids:
                    break
        return nodes
Exemplo n.º 33
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    # get the right model
    page_queryset = get_page_queryset(request)
    
    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    if 'preview' in request.GET.keys() and request.user.has_perm(Page._meta.app_label + ' ' + Page._meta.get_change_permission()):
        pages = page_queryset.filter(site=site)
    else:
        pages = page_queryset.published().filter(site=site)
    
    current_page, response = None, None
    if pages.all_root():
        if page_id:
            current_page = get_object_or_404(pages, pk=page_id)
        elif slug != None:
            if slug == "":
                current_page = pages.get_home()
            else:
                pages_root = reverse('pages-root')
                path = slug.startswith(pages_root) and slug[len(pages_root):] or slug

                try:
                    home = pages.get_home()
                    current_page, alternative = get_current_page(path, lang, pages, home.get_slug(language=lang), home.tree_id)
                except NoHomeFound:
                    current_page, alternative = get_current_page(path, lang, pages)
                     
                if apphook_pool.get_apphooks():
                    # check if it shouldn't point to some application, if yes,
                    # change current page if required
                    current_page = applications_page_check(request, current_page, path)
                if not current_page:
                    if alternative and settings.CMS_LANGUAGE_FALLBACK:
                        return HttpResponseRedirect(alternative)
                    if no404:# used for placeholder finder
                        current_page = None
                    else:
                        if not slug and settings.DEBUG:
                            CMS_MEDIA_URL = settings.CMS_MEDIA_URL
                            return "cms/new.html", locals()
                        raise Http404('CMS: Page not found for "%s"' % slug)
        else:
            current_page = applications_page_check(request)
            #current_page = None
        template_name = get_template_from_request(request, current_page, no_current_page=True)
    elif not no404:
        if not slug and settings.DEBUG:
            CMS_MEDIA_URL = settings.CMS_MEDIA_URL
            return "cms/new.html", locals()
        raise Http404("CMS: No page found for site %s" % unicode(site.name))
    
    if current_page:
        has_change_permissions = current_page.has_change_permission(request)
        request._current_page_cache = current_page
        
        redirect_url = current_page.get_redirect(language=lang)
        if redirect_url:
            if settings.i18n_installed and redirect_url[0] == "/":
                redirect_url = "/%s/%s" % (lang, redirect_url.lstrip("/"))
            # add language prefix to url
            return HttpResponseRedirect(redirect_url)
        
        if current_page.login_required and not request.user.is_authenticated():
            if settings.i18n_installed:
                path = urlquote("/%s%s" % (request.LANGUAGE_CODE, request.get_full_path()))
            else:
                path = urlquote(request.get_full_path())
            tup = django_settings.LOGIN_URL , "next", path
            return HttpResponseRedirect('%s?%s=%s' % tup)
    else:
        has_change_permissions = False
    return template_name, locals()
Exemplo n.º 34
0
 def items(self):
     from cms.utils.moderator import get_page_queryset
     page_queryset = get_page_queryset(None)
     all_pages = page_queryset.published().filter(login_required=False)
     return all_pages
Exemplo n.º 35
0
def show_sub_menu(context, levels=100, template="cms/sub_menu.html"):
    """Get the root page of the current page and 
    render a nested list of all root's children pages"""
    request = context['request']
    page_queryset = get_page_queryset(request)
    
    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    children = []
    page = request.current_page
    if page == "dummy":
        context.update({'children':[],
                        'template':template,
                        'from_level':0,
                        'to_level':0,
                        'extra_inactive':0,
                        'extra_active':0
                        })
        return context
    
    if page:
        page.get_cached_ancestors()
        # this is not required anymore, sice home_pk_cache is a getter 
        #if not hasattr(page, "home_pk_cache"):
        #    page.home_pk_cache = page_queryset.get_home(site).pk
        filters = {'in_navigation':True, 
                  'lft__gt':page.lft, 
                  'rght__lt':page.rght, 
                  'tree_id':page.tree_id, 
                  'level__lte':page.level+levels, 
                  'site':site}
        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang
        if not request.user.is_authenticated():
            filters['menu_login_required'] = False
        pages = page_queryset.published().filter(**filters)
       
        ids = []
        pages = list(pages)
        all_pages = pages[:]
        
        page.childrens = []
        for p in pages:
            p.descendant  = True
            ids.append(p.pk)
        page.selected = True
        page.menu_level = -1
        was_soft_root = False
        if page.soft_root:
            was_soft_root = True
            page.soft_root = False
        find_children(page, pages, levels, levels, [], page.pk, request=request)
        if was_soft_root:
            page.soft_root = True
        children = page.childrens
        titles = get_title_queryset(request).filter(page__in=ids, language=lang)
        for p in all_pages:# add the title and slugs and some meta data
            for title in titles:
                if title.page_id == p.pk:
                    if not hasattr(page, "title_cache"):
                        page.title_cache = {}
                    page.title_cache[title.language] = title
        from_level = page.level
        to_level = page.level+levels
        extra_active = extra_inactive = levels
    else:
        extenders = page_queryset.published().filter(in_navigation=True, site=site)
        extenders = extenders.exclude(navigation_extenders__isnull=True).exclude(navigation_extenders__exact="")
        children = []
        from_level = 0
        to_level = 0
        extra_active = 0
        extra_inactive = 0
        for ext in extenders:
            ext.childrens = []
            ext.ancestors_ascending = []
            nodes = get_extended_navigation_nodes(request, 100, [ext], ext.level, 100, levels, False, ext.navigation_extenders)
            if hasattr(ext, "ancestor"):
                selected = find_selected(nodes)
                if selected:
                    children = selected.childrens
                    from_level = selected.level
                    to_level =  from_level+levels
                    extra_active = extra_inactive = levels
    children = navigation.handle_navigation_manipulators(children, request)
    context.update({'children':children,
                    'template':template,
                    'from_level':from_level,
                    'to_level':to_level,
                    'extra_inactive':extra_inactive,
                    'extra_active':extra_active})
    return context
Exemplo n.º 36
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
    """
    if 'django.contrib.admin' in settings.INSTALLED_APPS:
        admin_base = reverse('admin:index')
    else:
        admin_base = None

    pages_root = urllib.unquote(reverse("pages-root"))

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

    # Get a basic queryset for Page objects, depending on if we use the
    # MODERATOR or not.
    page_queryset = get_page_queryset(request)
    site = Site.objects.get_current()

    # Check if this is called from an admin request
    if admin_base and request.path.startswith(admin_base):
        # if so, get the page ID to query the page
        page_id = [bit for bit in request.path.split('/') if bit][-1]
        if not page_id or not page_id.isdigit():
            page = None
        else:
            try:
                page = Page.objects.get(pk=page_id)
            except Page.DoesNotExist:
                return None
        request._current_page_cache = page
        return page

    # TODO: Isn't there a permission check needed here?
    if 'preview' in request.GET:
        pages = page_queryset.filter(site=site)
    else:
        pages = page_queryset.published().filter(site=site)

    # If use_path is given, someone already did the path cleaning
    if use_path:
        path = use_path
    else:
        # otherwise strip of the non-cms part of the URL
        path = request.path[len(pages_root):-1]

    # Check if there are any pages
    if not pages.all_root():
        return None

    # get the home page (needed to get the page)
    try:
        home = pages.get_home()
    except NoHomeFound:
        home = None
    # if there is no path (slashes stripped) and we found a home, this is the
    # home page.
    if not path and home:
        page = home
        request._current_page_cache = page
        return page

    # title_set__path=path should be clear, get the pages where the path of the
    # title object is equal to our path.
    if settings.CMS_FLAT_URLS:
        q = Q(title_set__slug=path)
    else:
        q = Q(title_set__path=path)
        if home:
            # if we have a home, also search for all paths prefixed with the
            # home slug that are on the same tree as home, since home isn't ussually
            # called with it's slug, thus it's children don't have the home bit in
            # the request either, thus we need to re-add it.
            q2 = Q()
            q2 = Q(title_set__path='%s/%s' % (home.get_slug(), path))
            q2 &= Q(tree_id=home.tree_id)
            q |= q2

    if settings.CMS_DBGETTEXT and settings.CMS_DBGETTEXT_SLUGS:  # pragma: no cover
        #=======================================================================
        # WARNING: CMS_DBGETTEXT WILL BE DEPRECATED IN 2.2!
        #=======================================================================
        from django.utils.translation import ugettext
        from cms.models import Title
        for t in Title.objects.all():
            tpath = '/'.join([ugettext(x) for x in t.path.split('/')])
            if path == tpath:
                q = Q(title_set__path=t.path)
                break
    try:
        page = pages.filter(q).distinct().get()
    except Page.DoesNotExist:
        return None

    request._current_page_cache = page
    return page
Exemplo n.º 37
0
def show_menu(context,
              from_level=0,
              to_level=100,
              extra_inactive=0,
              extra_active=100,
              template="cms/menu.html",
              next_page=None,
              root_id=None):
    """
    render a nested list of all children of the pages
    from_level: is the start level
    to_level: is the max level rendered
    render_children: if set to True will render all not direct ascendants too
    """
    try:
        # If there's an exception (500), default context_processors may not be called.
        request = context['request']
    except KeyError:
        return {'template': 'cms/content.html'}
    page_queryset = get_page_queryset(request)
    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    current_page = request.current_page
    if current_page == "dummy":
        context.update({
            'children': [],
            'template': template,
            'from_level': from_level,
            'to_level': to_level,
            'extra_inactive': extra_inactive,
            'extra_active': extra_active
        })
        return context
    if hasattr(current_page, "home_pk_cache"):
        home_pk = current_page.home_pk_cache
    else:
        try:
            home_pk = page_queryset.get_home(site).pk
        except NoHomeFound:
            home_pk = 0
    if not next_page:  #new menu... get all the data so we can save a lot of queries

        children = []
        ancestors = []
        alist = None
        if current_page:
            alist = current_page.get_ancestors().values_list('id', 'soft_root')
        if not alist:  # == None:# maybe the active node is in an extender?
            alist = []
            extenders = page_queryset.published().filter(in_navigation=True,
                                                         site=site,
                                                         level__lte=to_level)
            extenders = extenders.exclude(
                navigation_extenders__isnull=True).exclude(
                    navigation_extenders__exact="")
            for ext in extenders:
                ext.childrens = []
                ext.ancestors_ascending = []
                get_extended_navigation_nodes(request, 100, [ext], ext.level,
                                              100, 100, False,
                                              ext.navigation_extenders)
                if hasattr(ext, "ancestor"):
                    alist = list(ext.get_ancestors().values_list(
                        'id', 'soft_root'))
                    alist = [(ext.pk, ext.soft_root)] + alist
                    break
        filters = {'in_navigation': True, 'site': site, 'level__lte': to_level}
        #check the ancestors for softroots
        soft_root_pk = None
        for p in alist:
            ancestors.append(p[0])
            if p[1]:
                soft_root_pk = p[0]
        #modify filters if we don't start from the root
        root_page = None
        if root_id:
            try:
                root_page = page_queryset.get(reverse_id=root_id, site=site)
            except:
                send_missing_mail(root_id, request)
        else:
            if current_page and current_page.soft_root:
                root_page = current_page
                soft_root_pk = current_page.pk
            elif soft_root_pk:
                root_page = page_queryset.get(pk=soft_root_pk)
        if root_page:
            if isinstance(root_page, int):
                root_page = page_queryset.get(pk=root_page)
            if isinstance(root_page, Page):
                root_page = page_queryset.get(pk=root_page.id)
            elif isinstance(root_page, unicode):
                root_page = page_queryset.get(reverse_id=root_page, site=site)
            filters['tree_id'] = root_page.tree_id
            filters['lft__gt'] = root_page.lft
            filters['rght__lt'] = root_page.rght
            filters['level__lte'] = root_page.level + to_level
            db_from_level = root_page.level + from_level
        else:
            db_from_level = from_level
        if settings.CMS_HIDE_UNTRANSLATED:
            filters['title_set__language'] = lang
        if not request.user.is_authenticated():
            filters['menu_login_required'] = False
        pages = page_queryset.published().filter(**filters).order_by(
            'tree_id', 'parent', 'lft')
        pages = list(pages)
        if root_page:
            pages = [root_page] + pages
        all_pages = pages[:]
        root_level = getattr(root_page, 'level', None)
        ids = []
        current = None
        for page in pages:  # build the tree
            if current_page and current_page.pk == page.pk:
                current = page
            if page.level >= db_from_level:
                ids.append(page.pk)
            if page.level == 0 or page.level == root_level:
                if page.parent_id:
                    page.get_cached_ancestors()
                else:
                    page.ancestors_ascending = []
                page.home_pk_cache = home_pk
                page.menu_level = 0 - from_level
                page.childrens = []
                children.append(page)
                if page.pk == soft_root_pk:
                    page.soft_root = False  #ugly hack for the recursive function
                if current_page and not current_page.navigation_extenders:
                    pk = current_page.pk
                else:
                    pk = -1
                find_children(page,
                              pages,
                              extra_inactive,
                              extra_active,
                              ancestors,
                              pk,
                              request=request,
                              to_levels=to_level)
                if page.pk == soft_root_pk:
                    page.soft_root = True
        if db_from_level > 0:
            children = cut_levels(children, db_from_level)
        titles = list(
            get_title_queryset(request).filter(page__in=ids, language=lang))
        for page in all_pages:  # add the title and slugs and some meta data
            for title in titles:
                if title.page_id == page.pk:
                    if not hasattr(page, "title_cache"):
                        page.title_cache = {}
                    page.title_cache[title.language] = title
                    ids.remove(page.pk)
            if current_page and page.pk == current_page.pk and not getattr(
                    current, 'ancestor', False):
                page.selected = True
                if hasattr(page, "childrens"):
                    mark_descendants(page.childrens)
            if page.pk in ancestors:
                page.ancestor = True
            if current_page and page.parent_id == current_page.parent_id and not page.pk == current_page.pk and not getattr(
                    current, 'ancestor', False):
                page.sibling = True
        if ids:
            fallbacks = get_fallback_languages(lang)
            for l in fallbacks:
                titles = list(
                    get_title_queryset(request).filter(page__in=ids,
                                                       language=l))
                for page in all_pages:  # add the title and slugs and some meta data
                    for title in titles:
                        if title.page_id == page.pk:
                            if not hasattr(page, "title_cache"):
                                page.title_cache = {}
                            page.title_cache[title.language] = title
                            ids.remove(page.pk)
                if not ids:
                    break
        children = navigation.handle_navigation_manipulators(children, request)
    else:
        children = next_page.childrens
    context.update({
        'children': children,
        'template': template,
        'from_level': from_level,
        'to_level': to_level,
        'extra_inactive': extra_inactive,
        'extra_active': extra_active
    })
    return context
Exemplo n.º 38
0
 def items(self):
     page_queryset = get_page_queryset(None)
     all_pages = page_queryset.published()
     return all_pages