Ejemplo n.º 1
0
def page_id_url(context, reverse_id, lang=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
    """
    
    request = context.get('request', False)
    if not request:
        return {'content':''}
    if request.current_page == "dummy":
        return {'content': ''}
    PageModel = get_page_model(request)
    
    if lang is None:
        lang = get_language_from_request(request)
    key = 'page_id_url_pid:'+str(reverse_id)+'_l:'+str(lang)+'_type:absolute_url'
    url = cache.get(key)
    if not url:
        try:
            page = PageModel.objects.get(reverse_id=reverse_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':''}
Ejemplo n.º 2
0
 def urlpatterns(self):
     """Create urlresolvers for hookable applications on the fly.
     
     Caches result, so db lookup is required only once, or when the cache
     is reseted.
     """
     if not self._urlpatterns:
         # TODO: will this work with multiple sites? how are they exactly
         # implemerted ?
         # probably will be better to make caching per site
         
         self._urlpatterns, included = [], []
         PageModel = get_page_model() #!TODO: this must be solved!!
         pages = PageModel.objects.get_all_pages_with_application()
         for page in pages:
             # get all titles with application
             title_set = page.title_set.filter(application_urls__gt="")
             for title in title_set:
                 if CMS_FLAT_URLS:
                     mixid = "%s:%s" % (title.slug + "/", title.application_urls)
                 else:
                     mixid = "%s:%s" % (title.path + "/", title.application_urls)
                 if mixid in included:
                     # don't add the same thing twice
                     continue  
                 self._urlpatterns.append(ApplicationRegexUrlResolver(title))
                 included.append(mixid)
     return self._urlpatterns
Ejemplo n.º 3
0
def show_breadcrumb(context, start_level=0, template="cms/breadcrumb.html"):
    request = context['request']
    PageModel = get_page_model(request)
    TitleModel = get_title_model(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 = PageModel.objects.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 = TitleModel.objects.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 = PageModel.objects.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 = PageModel.objects.get_home()
                    if ancestors and ancestors[0].pk != home.pk: 
                        ancestors = [home] + ancestors
                    ids = []
                    for anc in ancestors:
                        ids.append(anc.pk)
                    titles = TitleModel.objects.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
Ejemplo n.º 4
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    # get the right model
    PageModel = get_page_model(request)
    
    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    if 'preview' in request.GET.keys():
        pages = PageModel.objects.all()
    else:
        pages = PageModel.objects.published()
    
    root_pages = pages.filter(parent__isnull=True).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()
Ejemplo n.º 5
0
def ancestor_slug(context, level=0):
    request = context['request']
    PageModel = get_page_model(request)
    TitleModel = get_title_model(request)
    page = request.current_page
    lang = get_language_from_request(request)
    if page:
        ancestors = [page]
        while ancestors[-1].parent:
            ancestors.append(ancestors[-1].parent)
        ancestors.reverse()
        if len(ancestors) <= level:
            return {"content": ""}
        return {"content": ancestors[level].get_slug()}
    else:
        return {"content": ""}
Ejemplo n.º 6
0
def make_tree(request, items, levels, url, ancestors, descendants=False, current_level=0, to_levels=100, active_levels=0):
    """
    builds the tree of all the navigation extender nodes and marks them with some metadata
    """
    PageModel = get_page_model(request)
    
    levels -= 1
    current_level += 1
    found = False
    for item in items:
        item.level = current_level
        if descendants and not found:
            item.descendant = True
        item.ancestors_ascending = ancestors
        if item.get_absolute_url() == url:
            item.selected = True
            levels = active_levels
            descendants = True
            found = True
            last = None
            for anc in ancestors:
                if not isinstance(anc, PageModel) and last:
                    last = None
                    if hasattr(last, 'childrens'):
                        for child in last.childrens:
                            if isinstance(child, PageModel):
                                child.sibling = True
                else:
                    last = anc
                anc.ancestor = True
            if last:
                if hasattr(last, 'childrens'):
                    for child in last.childrens:
                        if isinstance(child, PageModel):
                            child.sibling = True
        elif found:
            item.sibling = True
        if levels == 0 and not hasattr(item, "ancestor" ) or item.level == to_levels:
            item.childrens = []
        else:
            make_tree(request, item.childrens, levels, url, ancestors+[item], descendants, current_level, to_levels, active_levels) 
    if found:
        for item in items:
            if not hasattr(item, "selected"):
                item.sibling = True
Ejemplo n.º 7
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
        PageModel = get_page_model(request)
        page = PageModel.objects.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    
Ejemplo n.º 8
0
def show_placeholder_by_id(context, placeholder_name, reverse_id, lang=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)
    PageModel = get_page_model(request)
    CMSPluginModel = get_cmsplugin_model(request)
    
    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+'_l:'+str(lang)
    content = cache.get(key)
    if not content:
        try:
            page = PageModel.objects.get(reverse_id=reverse_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)

        plugins = CMSPluginModel.objects.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':''}
Ejemplo n.º 9
0
def page_id_url(context, reverse_id, lang=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
    """
    request = context.get('request', False)
    if not request:
        return {'content':''}
    
    PageModel = get_page_model(request)
    
    if lang is None:
        lang = get_language_from_request(request)
    key = 'page_id_url_pid:'+reverse_id+'_l:'+str(lang)+'_type:absolute_url'
    url = cache.get(key)
    if not url:
        try:
            page = PageModel.objects.get(reverse_id=reverse_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 page_id_url 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)

        url = page.get_absolute_url(language=lang)
        cache.set(key, url, settings.CMS_CONTENT_CACHE_DURATION)
    if url:
        return {'content':url}
    return {'content':''}
Ejemplo n.º 10
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']
    PageModel = get_page_model(request)
    TitleModel = get_title_model(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()
        if not hasattr(page, "home_pk_cache"):
            page.home_pk_cache = PageModel.objects.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
        pages = PageModel.objects.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 = TitleModel.objects.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:
                    p.title_cache = title
        from_level = page.level
        to_level = page.level+levels
        extra_active = extra_inactive = levels
    else:
        extenders = PageModel.objects.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
    
    context.update({'children':children,
                    'template':template,
                    'from_level':from_level,
                    'to_level':to_level,
                    'extra_inactive':extra_inactive,
                    'extra_active':extra_active})
    return context
Ejemplo n.º 11
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
    """
    request = context['request']
    PageModel = get_page_model(request)
    TitleModel = get_title_model(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 = PageModel.objects.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
        ids = []
        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 = PageModel.objects.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 = PageModel.objects.get(reverse_id=root_id)
            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 = PageModel.objects.get(pk=soft_root_pk)
        if root_page:
            if isinstance(root_page, int):
                root_page = PageModel.objects.get(pk=root_page)
            if isinstance(root_page, PageModel):
                root_page = PageModel.objects.get(pk=root_page.id)
            elif isinstance(root_page, unicode):
                root_page = PageModel.objects.get(reverse_id=root_page)
            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
        pages = PageModel.objects.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)
        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(TitleModel.objects.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:
                    page.title_cache = title
                    #titles.remove(title)
            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
    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