Пример #1
0
def get_placeholders(request, template=None):
    """
    Return a list of PlaceholderNode found in the given template
    """
    if not template:
        template = get_template_from_request(request)
    try:
        temp = loader.get_template(template)
    except TemplateDoesNotExist:
        return []
    user = request.user
    request.user = AnonymousUser()
    context = RequestContext(request)#details(request, no404=True, only_context=True)
    template = get_template_from_request(request)
    old_page = request.current_page
    request.current_page = "dummy"
    
    context.update({'template':template,
                    'request':request,
                    'display_placeholder_names_only': True,
                    'current_page': "dummy",
                    })
    output = temp.render(context)
    request.user = user
    placeholders = re.findall("<!-- PlaceholderNode: (.+?) -->", output)
    request.current_page = old_page
    return placeholders
Пример #2
0
    def get_form(self, request, obj=None, **kwargs):
        """
        Get PageForm for the Page model and modify its fields depending on
        the request.
        """
        if obj:
            if not obj.has_publish_permission(request):
                self.exclude.append('status')
            else:
                if 'status' in self.exclude:
                    self.exclude.remove('status')
            if not obj.has_softroot_permission(request):
                self.exclude.append('soft_root')
            else:
                if 'soft_root' in self.exclude:
                    self.exclude.remove('soft_root')
        version_id = None
        versioned = False
        if "history" in request.path or 'recover' in request.path:
            versioned = True
            version_id = request.path.split("/")[-2]
        form = super(PageAdmin, self).get_form(request, obj, **kwargs)
        language = get_language_from_request(request, obj)
        form.base_fields['language'].initial = force_unicode(language)
        if obj:
            initial_slug = obj.get_slug(language=language, fallback=False, version_id=version_id, force_reload=True)
            initial_title = obj.get_title(language=language, fallback=False, version_id=version_id)
            form.base_fields['slug'].initial = initial_slug
            form.base_fields['title'].initial = initial_title
        else:
            # Clear out the customisations made above
            # TODO - remove this hack, this is v ugly
            form.base_fields['slug'].initial = u''
            form.base_fields['title'].initial = u''

        template = get_template_from_request(request, obj)
        if settings.CMS_TEMPLATES:
            template_choices = list(settings.CMS_TEMPLATES)
            form.base_fields['template'].choices = template_choices
            form.base_fields['template'].initial = force_unicode(template)
        for placeholder in get_placeholders(request, template):
            if placeholder.name not in self.mandatory_placeholders:
                installed_plugins = plugin_pool.get_all_plugins(placeholder.name)
                plugin_list = []
                if obj:
                    if versioned:
                        from reversion.models import Version
                        version = get_object_or_404(Version, pk=version_id)
                        revs = [related_version.object_version for related_version in version.revision.version_set.all()]
                        plugin_list = []
                        for rev in revs:
                            obj = rev.object
                            if obj.__class__ == CMSPlugin:
                                if obj.language == language and obj.placeholder == placeholder.name:
                                    plugin_list.append(rev.object)
                    else:
                        plugin_list = CMSPlugin.objects.filter(page=obj, language=language, placeholder=placeholder.name).order_by('position')
                widget = PluginEditor(attrs={'installed':installed_plugins, 'list':plugin_list})
                form.base_fields[placeholder.name] = CharField(widget=widget, required=False)
        return form
Пример #3
0
 def get_content(self, request, current_page, context):
     pages = [current_page]
     if self.inherit:
         pages = chain([current_page],
                       current_page.get_cached_ancestors(ascending=True))
     for page in pages:
         template = get_template_from_request(request, page)
         placeholder = self._get_placeholder(current_page, page, context,
                                             self.name)
         if placeholder is None:
             continue
         if not get_plugins(request, placeholder):
             continue
         if hasattr(request, 'placeholder_media'):
             request.placeholder_media = reduce(operator.add, [
                 request.placeholder_media,
                 placeholder.get_media(request, context)
             ])
         #request.placeholder_media += placeholder.get_media(request, context)
         content = render_placeholder(placeholder, context)
         if content:
             return content, placeholder
     placeholder = self._get_placeholder(current_page, current_page,
                                         context, self.name)
     content = render_placeholder(placeholder, context)
     return content, placeholder
Пример #4
0
    def get_fieldsets(self, request, obj=None):
        """
        Add fieldsets of placeholders to the list of already existing
        fieldsets.
        """
        template = get_template_from_request(request, obj)

        if obj:  # edit
            given_fieldsets = deepcopy(self.fieldsets)
            if not obj.has_publish_permission(request):
                l = list(given_fieldsets[0][1]['fields'][2])
                l.remove('published')
                given_fieldsets[0][1]['fields'][2] = tuple(l)
            for placeholder_name in get_placeholders(request, template):
                if placeholder_name not in self.mandatory_placeholders:
                    if placeholder_name in settings.CMS_PLACEHOLDER_CONF and "name" in settings.CMS_PLACEHOLDER_CONF[
                            placeholder_name]:
                        name = settings.CMS_PLACEHOLDER_CONF[placeholder_name][
                            "name"]
                    else:
                        name = placeholder_name
                    given_fieldsets += [(title(name), {
                        'fields': [placeholder_name],
                        'classes': ['plugin-holder']
                    })]
            advanced = given_fieldsets.pop(3)
            if obj.has_advanced_settings_permission(request):
                given_fieldsets.append(advanced)
            if settings.CMS_SEO_FIELDS:
                seo = given_fieldsets.pop(3)
                given_fieldsets.append(seo)
        else:  # new page
            given_fieldsets = deepcopy(self.add_fieldsets)

        return given_fieldsets
Пример #5
0
    def get_fieldsets(self, request, obj=None):
        """
        Add fieldsets of placeholders to the list of already existing
        fieldsets.
        """
        template = get_template_from_request(request, obj)
        
        if obj: # edit
            given_fieldsets = deepcopy(self.fieldsets)
            if not obj.has_publish_permission(request):
                l = list(given_fieldsets[0][1]['fields'][2])
                l.remove('published')
                given_fieldsets[0][1]['fields'][2] = tuple(l)
            for placeholder_name in get_placeholders(request, template):
                if placeholder_name not in self.mandatory_placeholders:
                    if placeholder_name in settings.CMS_PLACEHOLDER_CONF and "name" in settings.CMS_PLACEHOLDER_CONF[placeholder_name]:
                        name = settings.CMS_PLACEHOLDER_CONF[placeholder_name]["name"]
                    else:
                        name = placeholder_name
                    given_fieldsets += [(title(name), {'fields':[placeholder_name], 'classes':['plugin-holder']})]
            advanced = given_fieldsets.pop(3)
            if obj.has_advanced_settings_permission(request):
                given_fieldsets.append(advanced)
            if settings.CMS_SEO_FIELDS:
                seo = given_fieldsets.pop(3)
                given_fieldsets.append(seo) 
        else: # new page
            given_fieldsets = deepcopy(self.add_fieldsets)

        return given_fieldsets
Пример #6
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    lang = get_language_from_request(request)
    site = Site.objects.get_current()
    pages = Page.objects.published().filter(parent__isnull=True).order_by("tree_id")
    current_page, response = None, None
    if pages:
        if page_id:
            current_page = get_object_or_404(Page.objects.published(site), pk=page_id)
        elif slug != None:
            if slug == "":
                current_page = pages[0]
            else:
                path = request.path.replace(reverse('pages-root'), '', 1)
                current_page = _get_current_page(path, lang)
                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:
                    raise Http404('CMS Page not found')
        else:
            current_page = applications_page_check(request)
            #current_page = None
        template_name = get_template_from_request(request, current_page)
    elif not no404:
        raise Http404("no page found for site %s" % unicode(site.name))
    if current_page:  
        has_page_permissions = current_page.has_page_permission(request)
        request._current_page_cache = current_page
    else:
        has_page_permissions = False
        
    return template_name, locals()
Пример #7
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()
Пример #8
0
def cms_settings(request):
    """
    Adds cms-related variables to the context.
    """

    return {
        'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'),
        'CMS_TEMPLATE': lambda: get_template_from_request(request),
    }
Пример #9
0
def cms_settings(request):
    """
    Adds cms-related variables to the context.
    """

    return {
        'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'),
        'CMS_TEMPLATE': lambda: get_template_from_request(request),
    }
Пример #10
0
 def render_toolbar(self, request):
     from cms.plugin_pool import plugin_pool
     from cms.utils.admin import get_admin_menu_item_context
     """
     Renders the Toolbar.
     """
     auth = request.user.is_staff or request.user.is_superuser
     edit = request.session.get('cms_edit', False) and auth
     page = request.current_page
     move_dict = []
     if edit and page:
         template = get_template_from_request(request)
         placeholders = get_placeholders(template)
         for placeholder in placeholders:
             d = {}
             name = cms_settings.CMS_PLACEHOLDER_CONF.get(
                 "%s %s" % (page.get_template(), placeholder),
                 {}).get("name", None)
             if not name:
                 name = cms_settings.CMS_PLACEHOLDER_CONF.get(
                     placeholder, {}).get("name", None)
             if not name:
                 name = title(placeholder)
             else:
                 name = _(name)
             d['name'] = name
             plugins = plugin_pool.get_all_plugins(placeholder, page)
             d['plugins'] = []
             for p in plugins:
                 d['plugins'].append(p.value)
             d['type'] = placeholder
             move_dict.append(d)
         data = safe(simplejson.dumps(move_dict))
     else:
         data = {}
     if auth and page:
         context = get_admin_menu_item_context(request,
                                               page,
                                               filtered=False)
     else:
         context = {}
     context.update({
         'auth': auth,
         'page': page,
         'templates': cms_settings.CMS_TEMPLATES,
         'auth_error': not auth and 'cms_username' in request.POST,
         'placeholder_data': data,
         'edit': edit,
         'moderator': cms_settings.CMS_MODERATOR,
         'CMS_MEDIA_URL': cms_settings.CMS_MEDIA_URL,
     })
     #from django.core.context_processors import csrf
     #context.update(csrf(request))
     return render_to_string('cms/toolbar/toolbar.html', context,
                             RequestContext(request))
Пример #11
0
 def render_toolbar(self, request):
     from cms.plugin_pool import plugin_pool
     from cms.utils.admin import get_admin_menu_item_context
     """
     Renders the Toolbar.
     """
     auth = request.user.is_staff or request.user.is_superuser
     edit = request.session.get('cms_edit', False) and auth
     page = request.current_page
     move_dict = []
     if edit and page:
         template = get_template_from_request(request)
         placeholders = get_placeholders(template)
         for placeholder in placeholders:
             d = {}
             name = cms_settings.CMS_PLACEHOLDER_CONF.get("%s %s" % (page.get_template(), placeholder), {}).get("name", None)
             if not name:
                 name = cms_settings.CMS_PLACEHOLDER_CONF.get(placeholder, {}).get("name", None)
             if not name:
                 name = title(placeholder)
             else:
                 name = _(name)
             d['name'] = name
             plugins = plugin_pool.get_all_plugins(placeholder, page)
             d['plugins'] = []
             for p in plugins:
                 d['plugins'].append(p.value)
             d['type'] = placeholder
             move_dict.append(d)
         data = safe(simplejson.dumps(move_dict))
     else:
         data = {}
     if auth and page:
         context = get_admin_menu_item_context(request, page, filtered=False)
     else:
         context = {}
     context.update({
         'auth':auth,
         'page':page,
         'templates': cms_settings.CMS_TEMPLATES,
         'auth_error':not auth and 'cms_username' in request.POST,
         'placeholder_data':data,
         'edit':edit,
         'moderator': cms_settings.CMS_MODERATOR,
         'CMS_MEDIA_URL': cms_settings.CMS_MEDIA_URL,
     })
     #from django.core.context_processors import csrf
     #context.update(csrf(request))
     return render_to_string('cms/toolbar/toolbar.html', context, RequestContext(request))
Пример #12
0
 def get_content(self, request, page, context):
     from cms.utils.plugins import get_placeholders
     pages = [page]
     if self.inherit:
         pages = chain([page], page.get_cached_ancestors(ascending=True))
     for page in pages:
         template = get_template_from_request(request, page)
         placeholder = page.placeholders.filter(slot__in=get_placeholders(template)).get(slot=self.name)
         if not get_plugins(request, placeholder):
             continue
         request.placeholder_media += placeholder.get_media(request, context)
         content = render_placeholder(placeholder, context)
         if content:
             return content
     return ''
Пример #13
0
 def get_fieldsets(self, request, obj=None):
     """
     Add fieldsets of placeholders to the list of already existing
     fieldsets.
     """
     template = get_template_from_request(request, obj)
     given_fieldsets = deepcopy(self.fieldsets)
     if obj:
         if not obj.has_publish_permission(request):
             given_fieldsets[1][1]['fields'].remove('status')
         if settings.CMS_SOFTROOT and not obj.has_softroot_permission(request):
             given_fieldsets[2][1]['fields'].remove('soft_root')
     for placeholder in get_placeholders(request, template):
         if placeholder.name not in self.mandatory_placeholders:
             given_fieldsets += [(title(placeholder.name), {'fields':[placeholder.name], 'classes':['plugin-holder']})]        
     return given_fieldsets
Пример #14
0
    def change_view(self, request, object_id, extra_context=None):
        """
        The 'change' admin view for the Page model.
        """

        try:
            obj = self.model.objects.get(pk=object_id)
        except self.model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None
        else:
            template = get_template_from_request(request, obj)
            moderation_level, moderation_required = get_test_moderation_level(obj, request.user)
            
            # if there is a delete request for this page
            moderation_delete_request = (settings.CMS_MODERATOR and
                    obj.pagemoderatorstate_set.get_delete_actions(
                    ).count())

            language = get_language_from_request(request, obj)
            #activate(user_lang_set)
            extra_context = {
                'placeholders': get_placeholders(request, template),
                'language': language,
                'traduction_language': settings.CMS_LANGUAGES,
                'show_language_tabs': len(settings.CMS_LANGUAGES) > 1,
                'page': obj,
                'CMS_PERMISSION': settings.CMS_PERMISSION,
                'CMS_MODERATOR': settings.CMS_MODERATOR,
                'has_change_permissions_permission': obj.has_change_permissions_permission(request),
                'has_moderate_permission': obj.has_moderate_permission(request),
                
                'moderation_level': moderation_level,
                'moderation_required': moderation_required,
                'moderator_should_approve': moderator_should_approve(request, obj),
                
                'moderation_delete_request': moderation_delete_request,
            }
        tab_language = request.GET.get("language", None)
        response = super(PageAdmin, self).change_view(request, object_id, extra_context)
        
        if tab_language and response.status_code == 302 and response._headers['location'][1] == request.path :
            location = response._headers['location']
            response._headers['location'] = (location[0], "%s?language=%s" % (location[1], tab_language))
        return response
Пример #15
0
 def get_content(self, request, current_page, context):
     pages = [current_page]
     if self.inherit:
         pages = chain([current_page], current_page.get_cached_ancestors(ascending=True))
     for page in pages:
         template = get_template_from_request(request, page)
         placeholder = self._get_placeholder(current_page, page, context, self.name)
         if placeholder is None:
             continue
         if not get_plugins(request, placeholder):
             continue
         if hasattr(request, 'placeholder_media'):
             request.placeholder_media = reduce(operator.add, [request.placeholder_media, placeholder.get_media(request, context)])
         #request.placeholder_media += placeholder.get_media(request, context)
         content = render_placeholder(placeholder, context)
         if content:
             return content, placeholder
     return '', None
Пример #16
0
def render_page(request, page, current_language, slug):
    """
    Renders a page
    """
    template_name = get_template_from_request(request,
                                              page,
                                              no_current_page=True)
    # fill the context
    if DJANGO_1_7:
        context = RequestContext(request)
    else:
        context = {}
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    response = TemplateResponse(request, template_name, context)

    response.add_post_render_callback(set_page_cache)

    # Add headers for X Frame Options - this really should be changed upon moving to class based views
    xframe_options = page.get_xframe_options()
    # xframe_options can be None if there's no xframe information on the page
    # (eg. a top-level page which has xframe options set to "inherit")
    if xframe_options == Page.X_FRAME_OPTIONS_INHERIT or xframe_options is None:
        # This is when we defer to django's own clickjacking handling
        return response

    # We want to prevent django setting this in their middlewear
    response.xframe_options_exempt = True

    if xframe_options == Page.X_FRAME_OPTIONS_ALLOW:
        # Do nothing, allowed is no header.
        return response
    elif xframe_options == Page.X_FRAME_OPTIONS_SAMEORIGIN:
        response['X-Frame-Options'] = 'SAMEORIGIN'
    elif xframe_options == Page.X_FRAME_OPTIONS_DENY:
        response['X-Frame-Options'] = 'DENY'
    return response
Пример #17
0
def page_to_html(page, language=None, encoding='utf-8'):
    # generate request
    request = CMSRequestFactory().request()
    request.current_page = page

    # generate request context
    context = RequestContext(request)
    context['lang'] = language or app_settings.DEFAULT_LANGUAGE
    context['current_page'] = page

    # generate template response
    template_name = get_template_from_request(request, page)
    response = TemplateResponse(request, template_name, context)
    response.render()

    # generate html
    html = response.content.decode(encoding)

    return html
Пример #18
0
    def change_view(self, request, object_id, extra_context=None):
        """
        The 'change' admin view for the Page model.
        """

        try:
            obj = self.model.objects.get(pk=object_id)
        except self.model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None
        else:
            template = get_template_from_request(request, obj)
            moderation_level, moderation_required = get_test_moderation_level(obj, request.user)

            # if there is a delete request for this page
            moderation_delete_request = (
                settings.CMS_MODERATOR and obj.pagemoderatorstate_set.get_delete_actions().count()
            )

            # activate(user_lang_set)
            extra_context = {
                "placeholders": get_placeholders(request, template),
                "page": obj,
                "CMS_PERMISSION": settings.CMS_PERMISSION,
                "CMS_MODERATOR": settings.CMS_MODERATOR,
                "has_change_permissions_permission": obj.has_change_permissions_permission(request),
                "has_moderate_permission": obj.has_moderate_permission(request),
                "moderation_level": moderation_level,
                "moderation_required": moderation_required,
                "moderator_should_approve": moderator_should_approve(request, obj),
                "moderation_delete_request": moderation_delete_request,
                "show_delete_translation": len(obj.get_languages()) > 1,
            }
            extra_context = self.update_language_tab_context(request, obj, extra_context)
        tab_language = request.GET.get("language", None)
        response = super(PageAdmin, self).change_view(request, object_id, extra_context)

        if tab_language and response.status_code == 302 and response._headers["location"][1] == request.path:
            location = response._headers["location"]
            response._headers["location"] = (location[0], "%s?language=%s" % (location[1], tab_language))
        return response
Пример #19
0
    def change_view(self, request, object_id, extra_context=None):
        """
        The 'change' admin view for the Page model.
        """

        try:
            obj = self.model.objects.get(pk=object_id)
        except self.model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None
        else:
            template = get_template_from_request(request, obj)
            moderation_level, moderation_required = get_test_moderation_level(obj, request.user)
            
            # if there is a delete request for this page
            moderation_delete_request = (settings.CMS_MODERATOR and
                    obj.pagemoderatorstate_set.get_delete_actions(
                    ).count())

            user_lang_set = request.GET.get('language',
                                            django_settings.LANGUAGE_CODE)
            activate(user_lang_set)
            extra_context = {
                'placeholders': get_placeholders(request, template),
                'language': user_lang_set,
                'traduction_language': settings.CMS_LANGUAGES,
                'page': obj,
                'CMS_PERMISSION': settings.CMS_PERMISSION,
                'CMS_MODERATOR': settings.CMS_MODERATOR,
                'has_change_permissions_permission': obj.has_change_permissions_permission(request),
                'has_moderate_permission': obj.has_moderate_permission(request),
                
                'moderation_level': moderation_level,
                'moderation_required': moderation_required,
                'moderator_should_approve': moderator_should_approve(request, obj),
                
                'moderation_delete_request': moderation_delete_request,
            }
        
        return super(PageAdmin, self).change_view(request, object_id, extra_context)
Пример #20
0
 def change_view(self, request, object_id, extra_context=None):
     """
     The 'change' admin view for the Page model.
     """
     try:
         obj = self.model.objects.get(pk=object_id)
     except self.model.DoesNotExist:
         # Don't raise Http404 just yet, because we haven't checked
         # permissions yet. We don't want an unauthenticated user to be able
         # to determine whether a given object exists.
         obj = None
     else:
         template = get_template_from_request(request, obj)
         extra_context = {
             'placeholders': get_placeholders(request, template),
             'language': get_language_from_request(request),
             'traduction_language': settings.CMS_LANGUAGES,
             'page': obj,
         }
     return super(PageAdmin, self).change_view(request, object_id, extra_context)
Пример #21
0
def render_page(request, page, current_language, slug):
    """
    Renders a page
    """
    template_name = get_template_from_request(request, page, no_current_page=True)
    # fill the context
    if DJANGO_1_7:
        context = RequestContext(request)
    else:
        context = {}
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    response = TemplateResponse(request, template_name, context)

    response.add_post_render_callback(set_page_cache)

    # Add headers for X Frame Options - this really should be changed upon moving to class based views
    xframe_options = page.get_xframe_options()
    # xframe_options can be None if there's no xframe information on the page
    # (eg. a top-level page which has xframe options set to "inherit")
    if xframe_options == Page.X_FRAME_OPTIONS_INHERIT or xframe_options is None:
        # This is when we defer to django's own clickjacking handling
        return response

    # We want to prevent django setting this in their middlewear
    response.xframe_options_exempt = True

    if xframe_options == Page.X_FRAME_OPTIONS_ALLOW:
        # Do nothing, allowed is no header.
        return response
    elif xframe_options == Page.X_FRAME_OPTIONS_SAMEORIGIN:
        response['X-Frame-Options'] = 'SAMEORIGIN'
    elif xframe_options == Page.X_FRAME_OPTIONS_DENY:
        response['X-Frame-Options'] = 'DENY'
    return response
Пример #22
0
def get_placeholders(request, template_name):
    """
    Return a list of PlaceholderNode found in the given template
    """
    try:
        temp = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return []
    context = Context()#RequestContext(request)#details(request, no404=True, only_context=True)
    template = get_template_from_request(request)
    request.current_page = "dummy"
    context.update({'template':template,
                    'request':request,
                    'display_placeholder_names_only': True,
                    })
    # lacks - it requests context in admin and eats user messages,
    # standard context will be hopefully enough here
    
    # temp.render(RequestContext(request, context))
    output = temp.render(context)
    return re.findall("<!-- PlaceholderNode: (.+?) -->", output)
Пример #23
0
def details(request, page_id=None, slug=None, template_name=settings.CMS_TEMPLATES[0][0], no404=False):
    lang = get_language_from_request(request)
    site = request.site
    pages = Page.objects.root(site).order_by("tree_id")
    if pages:
        if page_id:
            current_page = get_object_or_404(Page.objects.published(site), pk=page_id)
        elif slug != None:
            if slug == "":
                current_page = pages[0]
            else:
                path = request.path.replace(reverse("pages-root"), "", 1)
                try:
                    current_page = (
                        Page.objects.published(site)
                        .filter(
                            Q(has_url_overwrite=True, url_overwrite=path)
                            | Q(title_set__path=path[:-1], title_set__language=lang, has_url_overwrite=False)
                        )
                        .distinct()
                        .select_related()[0]
                    )
                except IndexError:
                    raise Http404("CMS Page not found")
        else:
            current_page = None
        template_name = get_template_from_request(request, current_page)
    else:
        if no404:  # used for placeholder finder
            current_page = None
        else:
            raise Http404("no page found for site %s" % unicode(site.name))
    if current_page:
        has_page_permissions = current_page.has_page_permission(request)
    else:
        has_page_permissions = False
    if current_page:
        request._current_page_cache = current_page
    return template_name, locals()
Пример #24
0
def get_placeholders(request, template_name):
    """
    Return a list of PlaceholderNode found in the given template
    """
    try:
        temp = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return []
    user = request.user
    request.user = AnonymousUser()
    context = RequestContext(request)#details(request, no404=True, only_context=True)
    template = get_template_from_request(request)
    request.current_page = "dummy"
    
    context.update({'template':template,
                    'request':request,
                    'display_placeholder_names_only': True,
                    'current_page': "dummy",
                    })
    output = temp.render(context)
    request.user = user
    return re.findall("<!-- PlaceholderNode: (.+?) -->", output)
Пример #25
0
def get_placeholders(request, template_name):
    """
    Return a list of PlaceholderNode found in the given template
    """
    try:
        temp = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return []
    context = Context()#RequestContext(request)#details(request, no404=True, only_context=True)
    template = get_template_from_request(request)
    request.current_page = "dummy"
    context.update({'template':template,
                    'request':request,
                    })
    # lacks - it requests context in admin and eats user messages,
    # standard context will be hopefully enough here
    
    # temp.render(RequestContext(request, context))
    temp.render(context)
    
    list = []
    placeholders_recursif(temp.nodelist, list)
    return list
Пример #26
0
def cms_settings(request):
    """
    Adds cms-related variables to the context.
    """
    from menus.menu_pool import MenuRenderer

    @lru_cache.lru_cache(maxsize=None)
    def _get_menu_renderer():
        # We use lru_cache to avoid getting the manager
        # every time this function is called.
        from menus.menu_pool import menu_pool
        return menu_pool.get_renderer(request)

    # Now use lazy() to avoid getting the menu renderer
    # up until the point is needed.
    # lazy() does not memoize results, is why lru_cache is needed.
    _get_menu_renderer = lazy(_get_menu_renderer, MenuRenderer)

    return {
        'cms_menu_renderer': _get_menu_renderer(),
        'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'),
        'CMS_TEMPLATE': lambda: get_template_from_request(request),
    }
Пример #27
0
 def get_fieldsets(self, request, obj=None):
     """
     Add fieldsets of placeholders to the list of already existing
     fieldsets.
     """
     template = get_template_from_request(request, obj)
     
     if obj: # edit
         given_fieldsets = deepcopy(self.fieldsets)
         if not obj.has_publish_permission(request):
             given_fieldsets[0][1]['fields'].remove('published')
         if settings.CMS_SOFTROOT and not obj.has_softroot_permission(request):
             given_fieldsets[2][1]['fields'].remove('soft_root')
         for placeholder in get_placeholders(request, template):
             if placeholder.name not in self.mandatory_placeholders:
                 if placeholder.name in settings.CMS_PLACEHOLDER_CONF and "name" in settings.CMS_PLACEHOLDER_CONF[placeholder.name]:
                     name = settings.CMS_PLACEHOLDER_CONF[placeholder.name]["name"]
                 else:
                     name = placeholder.name
                 given_fieldsets += [(title(name), {'fields':[placeholder.name], 'classes':['plugin-holder']})]
     else: # new page
         given_fieldsets = deepcopy(self.add_fieldsets)
             
     return given_fieldsets
Пример #28
0
    def get_form(self, request, obj=None, **kwargs):
        """
        Get PageForm for the Page model and modify its fields depending on
        the request.
        """
        
        language = get_language_from_request(request, obj)
        
        if obj:
            self.inlines = PAGE_ADMIN_INLINES
            if not obj.has_publish_permission(request) and not 'published' in self.exclude:
                self.exclude.append('published')
            elif 'published' in self.exclude:
                self.exclude.remove('published')

            if not settings.CMS_SOFTROOT and 'soft_root' in self.exclude:
                self.exclude.remove('soft_root')

            form = super(PageAdmin, self).get_form(request, obj, **kwargs)
            version_id = None
            versioned = False
            if "history" in request.path or 'recover' in request.path:
                versioned = True
                version_id = request.path.split("/")[-2]
        else:
            self.inlines = []
            form = PageAddForm

        if obj:
            try:
                title_obj = obj.get_title_obj(language=language, fallback=False, version_id=version_id, force_reload=True)
            except:
                title_obj = EmptyTitle()
            for name in ['slug',
                         'title',
                         'application_urls',
                         'redirect',
                         'meta_description',
                         'meta_keywords', 
                         'menu_title', 
                         'page_title']:
                form.base_fields[name].initial = getattr(title_obj, name)
            if title_obj.overwrite_url:
                form.base_fields['overwrite_url'].initial = title_obj.path
            else:
                form.base_fields['overwrite_url'].initial = ""
            if settings.CMS_TEMPLATES:
                template = get_template_from_request(request, obj)
                template_choices = list(settings.CMS_TEMPLATES)
                form.base_fields['template'].choices = template_choices
                form.base_fields['template'].initial = force_unicode(template)
            
            for placeholder_name in get_placeholders(request, template):
                if placeholder_name not in self.mandatory_placeholders:
                    installed_plugins = plugin_pool.get_all_plugins(placeholder_name)
                    plugin_list = []
                    if obj:
                        if versioned:
                            from reversion.models import Version
                            version = get_object_or_404(Version, pk=version_id)
                            revs = [related_version.object_version for related_version in version.revision.version_set.all()]
                            plugin_list = []
                            plugins = []
                            bases = {}
                            for rev in revs:
                                obj = rev.object
                                if obj.__class__ == CMSPlugin:
                                    if obj.language == language and obj.placeholder == placeholder_name and not obj.parent_id:
                                        if obj.get_plugin_class() == CMSPlugin:
                                            plugin_list.append(obj)
                                        else:
                                            bases[int(obj.pk)] = obj
                                if hasattr(obj, "cmsplugin_ptr_id"): 
                                    plugins.append(obj)
                            for plugin in plugins:
                                if int(plugin.cmsplugin_ptr_id) in bases:
                                    bases[int(plugin.cmsplugin_ptr_id)].set_base_attr(plugin)
                                    plugin_list.append(plugin)
                        else:
                            plugin_list = CMSPlugin.objects.filter(page=obj, language=language, placeholder=placeholder_name, parent=None).order_by('position')
                    widget = PluginEditor(attrs={'installed':installed_plugins, 'list':plugin_list})
                    form.base_fields[placeholder_name] = CharField(widget=widget, required=False)
        else: 
            for name in ['slug','title']:
                form.base_fields[name].initial = u''
            form.base_fields['parent'].initial = request.GET.get('target', None)
            form.base_fields['site'].initial = request.session.get('cms_admin_site', None)
            form.base_fields['template'].initial = settings.CMS_TEMPLATES[0][0]
        return form
Пример #29
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    # get the right model
    context = RequestContext(request)
    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)

    current_language = get_language_from_request(request)

    # Check that the current page is available in the desired (current) language
    available_languages = page.get_languages()

    # We resolve an alternate language for the page if it's not available.
    # Since the "old" details view had an exception for the root page, it is
    # ported here. So no resolution if the slug is ''.
    if (current_language not in available_languages):
        if settings.CMS_LANGUAGE_FALLBACK:
            # If we didn't find the required page in the requested (current)
            # language, let's try to find a suitable fallback in the list of
            # fallback languages (CMS_LANGUAGE_CONF)
            for alt_lang in get_fallback_languages(current_language):
                if alt_lang in available_languages:
                    alt_url = page.get_absolute_url(language=alt_lang,
                                                    fallback=True)
                    path = '/%s%s' % (alt_lang, alt_url)
                    # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    return HttpResponseRedirect(path)
        # There is a page object we can't find a proper language to render it
        _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        app_urls = page.get_application_urls(current_language, False)
        if app_urls:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass

    # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (settings.i18n_installed and redirect_url[0] == "/"
                and not redirect_url.startswith('/%s/' % current_language)):
            redirect_url = "/%s/%s" % (current_language,
                                       redirect_url.lstrip("/"))
        # add language prefix to url
        return HttpResponseRedirect(redirect_url)

    # permission checks
    if 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 = settings.LOGIN_URL, "next", path
        return HttpResponseRedirect('%s?%s=%s' % tup)

    template_name = get_template_from_request(request,
                                              page,
                                              no_current_page=True)
    # fill the context
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    return render_to_response(template_name, context)
Пример #30
0
 def get_form(self, request, obj=None, **kwargs):
     """
     Get PageForm for the Page model and modify its fields depending on
     the request.
     """
     if obj:
         if not obj.has_publish_permission(request):
             self.exclude.append('status')
         else:
             if 'status' in self.exclude:
                 self.exclude.remove('status')
         if not obj.has_softroot_permission(request):
             self.exclude.append('soft_root')
         else:
             if 'soft_root' in self.exclude:
                 self.exclude.remove('soft_root')
     version_id = None
     versioned = False
     if "history" in request.path or 'recover' in request.path:
         versioned = True
         version_id = request.path.split("/")[-2]
     form = super(PageAdmin, self).get_form(request, obj, **kwargs)
     language = get_language_from_request(request, obj)
     form.base_fields['language'].initial = force_unicode(language)
     if 'site' in request.GET.keys():
         form.base_fields['sites'].initial = [int(request.GET['site'])]
     else:
         form.base_fields['sites'].initial = Site.objects.all().values_list('id', flat=True)
     if obj:
         try:
             title_obj = obj.get_title_obj(language=language, fallback=False, version_id=version_id, force_reload=True)
         except:
             title_obj = EmptyTitle()
         for name in ['slug',
                      'title',
                      'application_urls',
                      'overwrite_url',
                      'redirect',
                      'meta_description',
                      'meta_keywords', 
                      'menu_title', 
                      'page_title']:
             form.base_fields[name].initial = getattr(title_obj, name)
     else:
         # Clear out the customisations made above
         # TODO - remove this hack, this is v ugly
         for name in ['slug','title','application_urls','overwrite_url','meta_description','meta_keywords']:
             form.base_fields[name].initial = u''
         form.base_fields['parent'].initial = request.GET.get('target', None)
     form.base_fields['parent'].widget = HiddenInput() 
     template = get_template_from_request(request, obj)
     if settings.CMS_TEMPLATES:
         template_choices = list(settings.CMS_TEMPLATES)
         form.base_fields['template'].choices = template_choices
         form.base_fields['template'].initial = force_unicode(template)
     for placeholder in get_placeholders(request, template):
         if placeholder.name not in self.mandatory_placeholders:
             installed_plugins = plugin_pool.get_all_plugins(placeholder.name)
             plugin_list = []
             if obj:
                 if versioned:
                     from reversion.models import Version
                     version = get_object_or_404(Version, pk=version_id)
                     revs = [related_version.object_version for related_version in version.revision.version_set.all()]
                     plugin_list = []
                     for rev in revs:
                         obj = rev.object
                         if obj.__class__ == CMSPlugin:
                             if obj.language == language and obj.placeholder == placeholder.name and not obj.parent_id:
                                 plugin_list.append(rev.object)
                 else:
                     plugin_list = CMSPlugin.objects.filter(page=obj, language=language, placeholder=placeholder.name, parent=None).order_by('position')
             widget = PluginEditor(attrs={'installed':installed_plugins, 'list':plugin_list})
             form.base_fields[placeholder.name] = CharField(widget=widget, required=False)
     return form
Пример #31
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
Пример #32
0
    def change_view(self, request, object_id, extra_context=None):
        """
        The 'change' admin view for the Page model.
        """

        try:
            obj = self.model.objects.get(pk=object_id)
        except self.model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None
        else:
            template = get_template_from_request(request, obj)
            moderation_level, moderation_required = get_test_moderation_level(
                obj, request.user)

            # if there is a delete request for this page
            moderation_delete_request = (
                settings.CMS_MODERATOR
                and obj.pagemoderatorstate_set.get_delete_actions().count())

            #activate(user_lang_set)
            extra_context = {
                'placeholders':
                get_placeholders(request, template),
                'page':
                obj,
                'CMS_PERMISSION':
                settings.CMS_PERMISSION,
                'CMS_MODERATOR':
                settings.CMS_MODERATOR,
                'ADMIN_MEDIA_URL':
                settings.ADMIN_MEDIA_PREFIX,
                'has_change_permissions_permission':
                obj.has_change_permissions_permission(request),
                'has_moderate_permission':
                obj.has_moderate_permission(request),
                'moderation_level':
                moderation_level,
                'moderation_required':
                moderation_required,
                'moderator_should_approve':
                moderator_should_approve(request, obj),
                'moderation_delete_request':
                moderation_delete_request,
                'show_delete_translation':
                len(obj.get_languages()) > 1
            }
            extra_context = self.update_language_tab_context(
                request, obj, extra_context)
        tab_language = request.GET.get("language", None)
        response = super(PageAdmin, self).change_view(request, object_id,
                                                      extra_context)

        if tab_language and response.status_code == 302 and response._headers[
                'location'][1] == request.path:
            location = response._headers['location']
            response._headers['location'] = (location[0], "%s?language=%s" %
                                             (location[1], tab_language))
        return response
Пример #33
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    from django.core.cache import cache

    if get_cms_setting("PAGE_CACHE") and (
        not hasattr(request, 'toolbar') or (
            not request.toolbar.edit_mode and
            not request.toolbar.show_toolbar and
            not request.user.is_authenticated()
        )
    ):
        cache_content = cache.get(
            _get_cache_key(request),
            version=_get_cache_version()
        )
        if not cache_content is None:
            content, headers = cache_content
            response = HttpResponse(content)
            response._headers = headers
            return response

    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)
    current_language = request.REQUEST.get('language', None)
    if current_language:
        current_language = get_language_code(current_language)
        if not current_language in get_language_list(page.site_id):
            current_language = None
    if current_language is None:
        current_language = get_language_code(getattr(request, 'LANGUAGE_CODE', None))
        if current_language:
            current_language = get_language_code(current_language)
            if not current_language in get_language_list(page.site_id):
                current_language = None
    if current_language is None:
        current_language = get_language_code(get_language())
    # Check that the current page is available in the desired (current) language
    available_languages = []
    page_languages = list(page.get_languages())
    if hasattr(request, 'user') and request.user.is_staff:
        user_languages = get_language_list()
    else:
        user_languages = get_public_languages()
    for frontend_lang in user_languages:
        if frontend_lang in page_languages:
            available_languages.append(frontend_lang)
    # Check that the language is in FRONTEND_LANGUAGES:
    own_urls = [
        'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path),
        '/%s' % request.path,
        request.path,
    ]
    if not current_language in user_languages:
        #are we on root?
        if not slug:
            #redirect to supported language
            languages = []
            for language in available_languages:
                languages.append((language, language))
            if languages:
                with SettingsOverride(LANGUAGES=languages, LANGUAGE_CODE=languages[0][0]):
                    #get supported language
                    new_language = get_language_from_request(request)
                    if new_language in get_public_languages():
                        with force_language(new_language):
                            pages_root = reverse('pages-root')
                            if hasattr(request, 'toolbar') and request.user.is_staff and request.toolbar.edit_mode:
                                request.toolbar.redirect_url = pages_root
                            elif pages_root not in own_urls:
                                return HttpResponseRedirect(pages_root)
            elif not hasattr(request, 'toolbar') or not request.toolbar.redirect_url:
                _handle_no_page(request, slug)
        else:
            return _handle_no_page(request, slug)
    if current_language not in available_languages:
        # If we didn't find the required page in the requested (current)
        # language, let's try to find a fallback
        found = False
        for alt_lang in get_fallback_languages(current_language):
            if alt_lang in available_languages:
                if get_redirect_on_fallback(current_language) or slug == "":
                    with force_language(alt_lang):
                        path = page.get_absolute_url(language=alt_lang, fallback=True)
                        # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    if hasattr(request, 'toolbar') and request.user.is_staff and request.toolbar.edit_mode:
                        request.toolbar.redirect_url = path
                    elif path not in own_urls:
                        return HttpResponseRedirect(path)
                else:
                    found = True
        if not found and (not hasattr(request, 'toolbar') or not request.toolbar.redirect_url):
            # There is a page object we can't find a proper language to render it
            _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        app_urls = page.get_application_urls(current_language, False)
        skip_app = False
        if not page.is_published(current_language) and hasattr(request, 'toolbar') and request.toolbar.edit_mode:
            skip_app = True
        if app_urls and not skip_app:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass
                # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (is_language_prefix_patterns_used() and redirect_url[0] == "/" and not redirect_url.startswith(
                    '/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
            # prevent redirect to self

        if hasattr(request, 'toolbar') and request.user.is_staff and request.toolbar.edit_mode:
            request.toolbar.redirect_url = redirect_url
        elif redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url)

    # permission checks
    if page.login_required and not request.user.is_authenticated():
        return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL)
    if hasattr(request, 'toolbar'):
        request.toolbar.set_object(page)

    template_name = get_template_from_request(request, page, no_current_page=True)
    # fill the context
    context = RequestContext(request)
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    response = TemplateResponse(request, template_name, context)

    response.add_post_render_callback(_cache_page)

    # Add headers for X Frame Options - this really should be changed upon moving to class based views
    xframe_options = page.get_xframe_options()
    if xframe_options == Page.X_FRAME_OPTIONS_INHERIT:
        # This is when we defer to django's own clickjacking handling
        return response

    # We want to prevent django setting this in their middlewear
    response.xframe_options_exempt = True

    if xframe_options == Page.X_FRAME_OPTIONS_ALLOW:
        # Do nothing, allowed is no header.
        return response
    elif xframe_options == Page.X_FRAME_OPTIONS_SAMEORIGIN:
        response['X-Frame-Options'] = 'SAMEORIGIN'
    elif xframe_options == Page.X_FRAME_OPTIONS_DENY:
        response['X-Frame-Options'] = 'DENY'

    return response
Пример #34
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    # get the right model
    context = RequestContext(request)
    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)

    if not page:
        return _handle_no_page(request, slug)

    current_language = get_language_from_request(request)

    # Languages specific to page that the current user can see.
    available_languages = get_languages_for_page_user(page=page, user=request.user)

    attrs = ''
    if 'edit' in request.GET:
        attrs = '?edit=1'
    elif 'preview' in request.GET:
        attrs = '?preview=1'
        if 'draft' in request.GET:
            attrs += '&draft=1'

    # Check that the user has access to this language
    # which is defined in FRONTEND_LANGUAGES:
    if not current_language in get_languages_for_user(user=request.user):
        #are we on root?
        if not slug and available_languages:
            #redirect to supported language
            languages = [(language, language) for language in available_languages]
            with SettingsOverride(LANGUAGES=languages, LANGUAGE_CODE=languages[0][0]):
                # get supported language
                new_language = get_language_from_request(request)
                if new_language in get_public_languages():
                    with force_language(new_language):
                        pages_root = reverse('pages-root')
                        return HttpResponseRedirect(pages_root + attrs)
        else:
            return _handle_no_page(request, slug)

    if current_language not in available_languages:
        fallback_languages = get_fallback_languages_for_page(page, current_language, request.user)
        if fallback_languages:
            if get_redirect_on_fallback(current_language):
                fallback_language = fallback_languages[0]
                with force_language(fallback_language):
                    path = page.get_absolute_url(language=fallback_language, fallback=True) + attrs
                    return HttpResponseRedirect(path)
        else:
            # There is a page object we can't find a proper language to render it
            return _handle_no_page(request, slug)
    else:
        page_path = page.get_absolute_url(language=current_language)
        page_slug = page.get_path(language=current_language) or page.get_slug(language=current_language)
        if slug and slug != page_slug and request.path[:len(page_path)] != page_path:
            # The current language does not match it's slug.
            # Redirect to the current language.
            return HttpResponseRedirect(page_path + attrs)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        try:
            app_urls = page.get_application_urls(current_language, False)
        except Title.DoesNotExist:
            app_urls = []
        if app_urls:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                context.current_app = page.reverse_id if page.reverse_id else app.app_name
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass
        # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (is_language_prefix_patterns_used() and redirect_url[0] == "/"
            and not redirect_url.startswith('/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
            # prevent redirect to self
        own_urls = [
            'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path),
            '/%s' % request.path,
            request.path,
        ]
        if redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url + attrs)

    # permission checks
    if page.login_required and not request.user.is_authenticated():
        return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL)

    template_name = get_template_from_request(request, page, no_current_page=True)

    has_view_permissions = page.has_view_permission(request)

    # fill the context
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = has_view_permissions

    if not has_view_permissions:
        return _handle_no_page(request, slug)
    return render_to_response(template_name, context_instance=context)
Пример #35
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    # get the right model
    context = RequestContext(request)
    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)

    current_language = get_language_from_request(request)
    # Check that the current page is available in the desired (current) language
    available_languages = []
    page_languages = list(page.get_languages())
    if hasattr(request, 'user') and request.user.is_staff:
        user_languages = get_language_list()
    else:
        user_languages = get_public_languages()
    for frontend_lang in user_languages:
        if frontend_lang in page_languages:
            available_languages.append(frontend_lang)
    attrs = ''
    if 'edit' in request.GET:
        attrs = '?edit=1'
    elif 'preview' in request.GET:
        attrs = '?preview=1'
        if 'draft' in request.GET:
            attrs += '&draft=1'
        # Check that the language is in FRONTEND_LANGUAGES:
    if not current_language in user_languages:
        #are we on root?
        if not slug:
            #redirect to supported language
            languages = []
            for language in available_languages:
                languages.append((language, language))
            if languages:
                with SettingsOverride(LANGUAGES=languages, LANGUAGE_CODE=languages[0][0]):
                    #get supported language
                    new_language = get_language_from_request(request)
                    if new_language in get_public_languages():
                        with force_language(new_language):
                            pages_root = reverse('pages-root')
                            return HttpResponseRedirect(pages_root + attrs)
            else:
                _handle_no_page(request, slug)
        else:
            return _handle_no_page(request, slug)
    if current_language not in available_languages:
        # If we didn't find the required page in the requested (current)
        # language, let's try to find a fallback
        found = False
        for alt_lang in get_fallback_languages(current_language):
            if alt_lang in available_languages:
                if get_redirect_on_fallback(current_language):
                    with force_language(alt_lang):
                        path = page.get_absolute_url(language=alt_lang, fallback=True)
                        # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    return HttpResponseRedirect(path + attrs)
                else:
                    found = True
        if not found:
            # There is a page object we can't find a proper language to render it
            _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        try:
            app_urls = page.get_application_urls(current_language, False)
        except Title.DoesNotExist:
            app_urls = []
        if app_urls:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass
                # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (is_language_prefix_patterns_used() and redirect_url[0] == "/"
        and not redirect_url.startswith('/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
            # prevent redirect to self
        own_urls = [
            'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path),
            '/%s' % request.path,
            request.path,
        ]
        if redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url + attrs)

    # permission checks
    if page.login_required and not request.user.is_authenticated():
        return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL)

    template_name = get_template_from_request(request, page, no_current_page=True)
    # fill the context 
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    return TemplateResponse(request, template_name, context)
Пример #36
0
    def get_form(self, request, obj=None, **kwargs):
        """
        Get PageForm for the Page model and modify its fields depending on
        the request.
        """

        language = get_language_from_request(request, obj)

        if obj:
            self.inlines = PAGE_ADMIN_INLINES
            if not obj.has_publish_permission(
                    request) and not 'published' in self.exclude:
                self.exclude.append('published')
            elif 'published' in self.exclude:
                self.exclude.remove('published')

            if not settings.CMS_SOFTROOT and 'soft_root' in self.exclude:
                self.exclude.remove('soft_root')

            form = super(PageAdmin, self).get_form(request, obj, **kwargs)
            version_id = None
            versioned = False
            if "history" in request.path or 'recover' in request.path:
                versioned = True
                version_id = request.path.split("/")[-2]
        else:
            self.inlines = []
            form = PageAddForm

        if obj:
            try:
                title_obj = obj.get_title_obj(language=language,
                                              fallback=False,
                                              version_id=version_id,
                                              force_reload=True)
            except:
                title_obj = EmptyTitle()
            for name in [
                    'slug', 'title', 'application_urls', 'redirect',
                    'meta_description', 'meta_keywords', 'menu_title',
                    'page_title'
            ]:
                form.base_fields[name].initial = getattr(title_obj, name)
            if title_obj.overwrite_url:
                form.base_fields['overwrite_url'].initial = title_obj.path
            else:
                form.base_fields['overwrite_url'].initial = ""
            if settings.CMS_TEMPLATES:
                template = get_template_from_request(request, obj)
                template_choices = list(settings.CMS_TEMPLATES)
                form.base_fields['template'].choices = template_choices
                form.base_fields['template'].initial = force_unicode(template)

            for placeholder_name in get_placeholders(request, template):
                if placeholder_name not in self.mandatory_placeholders:
                    installed_plugins = plugin_pool.get_all_plugins(
                        placeholder_name)
                    plugin_list = []
                    if obj:
                        if versioned:
                            from reversion.models import Version
                            version = get_object_or_404(Version, pk=version_id)
                            revs = [
                                related_version.object_version
                                for related_version in
                                version.revision.version_set.all()
                            ]
                            plugin_list = []
                            plugins = []
                            bases = {}
                            for rev in revs:
                                obj = rev.object
                                if obj.__class__ == CMSPlugin:
                                    if obj.language == language and obj.placeholder == placeholder_name and not obj.parent_id:
                                        if obj.get_plugin_class() == CMSPlugin:
                                            plugin_list.append(obj)
                                        else:
                                            bases[int(obj.pk)] = obj
                                if hasattr(obj, "cmsplugin_ptr_id"):
                                    plugins.append(obj)
                            for plugin in plugins:
                                if int(plugin.cmsplugin_ptr_id) in bases:
                                    bases[int(plugin.cmsplugin_ptr_id
                                              )].set_base_attr(plugin)
                                    plugin_list.append(plugin)
                        else:
                            plugin_list = CMSPlugin.objects.filter(
                                page=obj,
                                language=language,
                                placeholder=placeholder_name,
                                parent=None).order_by('position')
                    widget = PluginEditor(attrs={
                        'installed': installed_plugins,
                        'list': plugin_list
                    })
                    form.base_fields[placeholder_name] = CharField(
                        widget=widget, required=False)
        else:
            for name in ['slug', 'title']:
                form.base_fields[name].initial = u''
            form.base_fields['parent'].initial = request.GET.get(
                'target', None)
            form.base_fields['site'].initial = request.session.get(
                'cms_admin_site', None)
            form.base_fields['template'].initial = settings.CMS_TEMPLATES[0][0]
        return form
Пример #37
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()
Пример #38
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    from django.core.cache import cache

    if get_cms_setting("PAGE_CACHE") and (
            not hasattr(request, 'toolbar') or
        (not request.toolbar.edit_mode and not request.toolbar.show_toolbar
         and not request.user.is_authenticated())):
        cache_content = cache.get(_get_cache_key(request),
                                  version=_get_cache_version())
        if not cache_content is None:
            content, headers = cache_content
            response = HttpResponse(content)
            response._headers = headers
            return response

    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)
    current_language = request.REQUEST.get('language', None)
    if current_language:
        current_language = get_language_code(current_language)
        if not current_language in get_language_list(page.site_id):
            current_language = None
    if current_language is None:
        current_language = get_language_code(
            getattr(request, 'LANGUAGE_CODE', None))
        if current_language:
            current_language = get_language_code(current_language)
            if not current_language in get_language_list(page.site_id):
                current_language = None
    if current_language is None:
        current_language = get_language_code(get_language())
    # Check that the current page is available in the desired (current) language
    available_languages = []
    page_languages = list(page.get_languages())
    if hasattr(request, 'user') and request.user.is_staff:
        user_languages = get_language_list()
    else:
        user_languages = get_public_languages()
    for frontend_lang in user_languages:
        if frontend_lang in page_languages:
            available_languages.append(frontend_lang)
    # Check that the language is in FRONTEND_LANGUAGES:
    own_urls = [
        'http%s://%s%s' %
        ('s' if request.is_secure() else '', request.get_host(), request.path),
        '/%s' % request.path,
        request.path,
    ]
    if not current_language in user_languages:
        #are we on root?
        if not slug:
            #redirect to supported language
            languages = []
            for language in available_languages:
                languages.append((language, language))
            if languages:
                with SettingsOverride(LANGUAGES=languages,
                                      LANGUAGE_CODE=languages[0][0]):
                    #get supported language
                    new_language = get_language_from_request(request)
                    if new_language in get_public_languages():
                        with force_language(new_language):
                            pages_root = reverse('pages-root')
                            if hasattr(
                                    request, 'toolbar'
                            ) and request.user.is_staff and request.toolbar.edit_mode:
                                request.toolbar.redirect_url = pages_root
                            elif pages_root not in own_urls:
                                return HttpResponseRedirect(pages_root)
            elif not hasattr(request,
                             'toolbar') or not request.toolbar.redirect_url:
                _handle_no_page(request, slug)
        else:
            return _handle_no_page(request, slug)
    if current_language not in available_languages:
        # If we didn't find the required page in the requested (current)
        # language, let's try to find a fallback
        found = False
        for alt_lang in get_fallback_languages(current_language):
            if alt_lang in available_languages:
                if get_redirect_on_fallback(current_language) or slug == "":
                    with force_language(alt_lang):
                        path = page.get_absolute_url(language=alt_lang,
                                                     fallback=True)
                        # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    if hasattr(
                            request, 'toolbar'
                    ) and request.user.is_staff and request.toolbar.edit_mode:
                        request.toolbar.redirect_url = path
                    elif path not in own_urls:
                        return HttpResponseRedirect(path)
                else:
                    found = True
        if not found and (not hasattr(request, 'toolbar')
                          or not request.toolbar.redirect_url):
            # There is a page object we can't find a proper language to render it
            _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        app_urls = page.get_application_urls(current_language, False)
        skip_app = False
        if not page.is_published(current_language) and hasattr(
                request, 'toolbar') and request.toolbar.edit_mode:
            skip_app = True
        if app_urls and not skip_app:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass
                # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (is_language_prefix_patterns_used() and redirect_url[0] == "/"
                and not redirect_url.startswith('/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language,
                                       redirect_url.lstrip("/"))
            # prevent redirect to self

        if hasattr(request, 'toolbar'
                   ) and request.user.is_staff and request.toolbar.edit_mode:
            request.toolbar.redirect_url = redirect_url
        elif redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url)

    # permission checks
    if page.login_required and not request.user.is_authenticated():
        return redirect_to_login(urlquote(request.get_full_path()),
                                 settings.LOGIN_URL)
    if hasattr(request, 'toolbar'):
        request.toolbar.set_object(page)

    template_name = get_template_from_request(request,
                                              page,
                                              no_current_page=True)
    # fill the context
    context = RequestContext(request)
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    response = TemplateResponse(request, template_name, context)

    response.add_post_render_callback(_cache_page)

    # Add headers for X Frame Options - this really should be changed upon moving to class based views
    xframe_options = page.get_xframe_options()
    if xframe_options == Page.X_FRAME_OPTIONS_INHERIT:
        # This is when we defer to django's own clickjacking handling
        return response

    # We want to prevent django setting this in their middlewear
    response.xframe_options_exempt = True

    if xframe_options == Page.X_FRAME_OPTIONS_ALLOW:
        # Do nothing, allowed is no header.
        return response
    elif xframe_options == Page.X_FRAME_OPTIONS_SAMEORIGIN:
        response['X-Frame-Options'] = 'SAMEORIGIN'
    elif xframe_options == Page.X_FRAME_OPTIONS_DENY:
        response['X-Frame-Options'] = 'DENY'

    return response
Пример #39
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    # get the right model
    context = RequestContext(request)
    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)
    
    current_language = get_language_from_request(request)
    
    # Check that the current page is available in the desired (current) language
    available_languages = page.get_languages()
    
    # We resolve an alternate language for the page if it's not available.
    # Since the "old" details view had an exception for the root page, it is
    # ported here. So no resolution if the slug is ''.
    if (current_language not in available_languages) and (slug != ''):
        if settings.CMS_LANGUAGE_FALLBACK:
            # If we didn't find the required page in the requested (current) 
            # language, let's try to find a suitable fallback in the list of 
            # fallback languages (CMS_LANGUAGE_CONF)
            for alt_lang in get_fallback_languages(current_language):
                if alt_lang in available_languages:
                    alt_url = page.get_absolute_url(language=alt_lang, fallback=True)
                    path = '/%s%s' % (alt_lang, alt_url)
                    # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    return HttpResponseRedirect(path)
        # There is a page object we can't find a proper language to render it 
        _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        app_urls = page.get_application_urls(current_language, False)
        if app_urls:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass

    # Check if the page has a redirect url defined for this language. 
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if settings.i18n_installed and redirect_url[0] == "/":
            redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
        # add language prefix to url
        return HttpResponseRedirect(redirect_url)
    
    # permission checks
    if 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)

    if page.login_required and not page.has_view_permission(request):
        return HttpResponseForbidden("You don't have the rights to access this resource")
    
    template_name = get_template_from_request(request, page, no_current_page=True)
    # fill the context 
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    return render_to_response(template_name, context)
Пример #40
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()
Пример #41
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    from cms.apphook_pool import apphook_pool
    from cms.appresolver import get_app_urls
    from cms.utils import get_template_from_request, get_language_from_request
    from cms.utils.i18n import get_fallback_languages
    from cms.utils.django_load import load_object
    from cms.utils.page_resolver import get_page_from_request
    from cms.views import _handle_no_page
    from django.conf import settings
    from django.conf.urls import patterns
    from django.core.urlresolvers import resolve, Resolver404

    from django.http import Http404, HttpResponseRedirect
    from django.shortcuts import render_to_response
    from django.template.context import RequestContext
    from django.utils.http import urlquote
    # get the right model
    context = RequestContext(request)
    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)

    current_language = get_language_from_request(request)

    # Check that the current page is available in the desired (current) language
    available_languages = page.get_languages()

    # We resolve an alternate language for the page if it's not available.
    # Since the "old" details view had an exception for the root page, it is
    # ported here. So no resolution if the slug is ''.
    if (current_language not in available_languages):
        if settings.CMS_LANGUAGE_FALLBACK:
            # If we didn't find the required page in the requested (current)
            # language, let's try to find a suitable fallback in the list of
            # fallback languages (CMS_LANGUAGE_CONF)
            for alt_lang in get_fallback_languages(current_language):
                if alt_lang in available_languages:
                    alt_url = page.get_absolute_url(language=alt_lang, fallback=True)
                    path = '/%s%s' % (alt_lang, alt_url)
                    # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    return HttpResponseRedirect(path)
            # There is a page object we can't find a proper language to render it
        _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        app_urls = page.get_application_urls(current_language, False)
        if app_urls:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass

    if page.view_path:
        view = load_object(page.view_path)
        args, kwargs = view.extract_args_kwargs(slug)
        return view(request, *args, **kwargs)

    # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (settings.i18n_installed and redirect_url[0] == "/"
            and not redirect_url.startswith('/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
            # prevent redirect to self
        own_urls = [
            'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path),
            '/%s%s' % (current_language, request.path),
            request.path,
            ]
        if redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url)

    # permission checks
    if 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 = settings.LOGIN_URL , "next", path
        return HttpResponseRedirect('%s?%s=%s' % tup)

    template_name = get_template_from_request(request, page, no_current_page=True)
    # fill the context
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    return render_to_response(template_name, context)
Пример #42
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    # get the right model
    context = RequestContext(request)
    # Get a Page model object from the request
    page = get_page_from_request(request, use_path=slug)
    if not page:
        return _handle_no_page(request, slug)

    current_language = get_language_from_request(request)
    # Check that the current page is available in the desired (current) language
    available_languages = []
    page_languages = page.get_languages()
    user_languages = get_public_languages()
    if hasattr(request, 'user') and request.user.is_staff:
        user_languages = get_language_list()
    for frontend_lang in user_languages:
        if frontend_lang in page_languages:
            available_languages.append(frontend_lang)
    attrs = ''
    if 'edit' in request.GET:
        attrs = '?edit=1'
    elif 'preview' in request.GET:
        attrs = '?preview=1'
        if 'draft' in request.GET:
            attrs += '&draft=1'
    # Check that the language is in FRONTEND_LANGUAGES:
    if not current_language in user_languages:
        #are we on root?
        if not slug:
            #redirect to supported language
            languages = []
            for language in available_languages:
                languages.append((language, language))
            if languages:
                with SettingsOverride(LANGUAGES=languages, LANGUAGE_CODE=languages[0][0]):
                    #get supported language
                    new_language = translation.get_language_from_request(request)
                    if new_language in get_public_languages():
                        with force_language(new_language):
                            pages_root = reverse('pages-root')
                            return HttpResponseRedirect(pages_root + attrs)
            else:
                _handle_no_page(request, slug)
        else:
            return _handle_no_page(request, slug)
    if current_language not in available_languages:
        # If we didn't find the required page in the requested (current)
        # language, let's try to find a fallback
        found = False
        for alt_lang in get_fallback_languages(current_language):
            if alt_lang in available_languages:
                if get_redirect_on_fallback(current_language):
                    with force_language(alt_lang):
                        path = page.get_absolute_url(language=alt_lang, fallback=True)
                        # In the case where the page is not available in the
                    # preferred language, *redirect* to the fallback page. This
                    # is a design decision (instead of rendering in place)).
                    return HttpResponseRedirect(path + attrs)
                else:
                    found = True
        if not found:
            # There is a page object we can't find a proper language to render it
            _handle_no_page(request, slug)

    if apphook_pool.get_apphooks():
        # There are apphooks in the pool. Let's see if there is one for the
        # current page
        # since we always have a page at this point, applications_page_check is
        # pointless
        # page = applications_page_check(request, page, slug)
        # Check for apphooks! This time for real!
        try:
            app_urls = page.get_application_urls(current_language, False)
        except Title.DoesNotExist:
            app_urls = []
        if app_urls:
            app = apphook_pool.get_apphook(app_urls)
            pattern_list = []
            for urlpatterns in get_app_urls(app.urls):
                pattern_list += urlpatterns
            urlpatterns = patterns('', *pattern_list)
            try:
                context.current_app = page.reverse_id if page.reverse_id else app.app_name
                view, args, kwargs = resolve('/', tuple(urlpatterns))
                return view(request, *args, **kwargs)
            except Resolver404:
                pass
        # Check if the page has a redirect url defined for this language.
    redirect_url = page.get_redirect(language=current_language)
    if redirect_url:
        if (settings.USE_I18N and redirect_url[0] == "/"
            and not redirect_url.startswith('/%s/' % current_language)):
            # add language prefix to url
            redirect_url = "/%s/%s" % (current_language, redirect_url.lstrip("/"))
            # prevent redirect to self
        own_urls = [
            'http%s://%s%s' % ('s' if request.is_secure() else '', request.get_host(), request.path),
            '/%s' % request.path,
            request.path,
        ]
        if redirect_url not in own_urls:
            return HttpResponseRedirect(redirect_url + attrs)

    # permission checks
    if page.login_required and not request.user.is_authenticated():
        path = urlquote(request.get_full_path())
        tup = settings.LOGIN_URL, "next", path
        return HttpResponseRedirect('%s?%s=%s' % tup)

    template_name = get_template_from_request(request, page, no_current_page=True)
    # fill the context 
    context['lang'] = current_language
    context['current_page'] = page
    context['has_change_permissions'] = page.has_change_permission(request)
    context['has_view_permissions'] = page.has_view_permission(request)

    if not context['has_view_permissions']:
        return _handle_no_page(request, slug)

    return render_to_response(template_name, context_instance=context)