Пример #1
0
 def test_23_get_page_from_request_with_page_preview(self):
     page = self.create_page()
     request = self.get_request('%s?preview' % page.get_absolute_url())
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         request = self.get_request('%s?preview&draft' % page.get_absolute_url())
         found_page = get_page_from_request(request)
         self.assertTrue(found_page)
         self.assertEqual(found_page.pk, page.pk)
Пример #2
0
 def test_23_get_page_from_request_with_page_preview(self):
     page = self.create_page()
     request = self.get_request('%s?preview' % page.get_absolute_url())
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         request = self.get_request('%s?preview&draft' %
                                    page.get_absolute_url())
         found_page = get_page_from_request(request)
         self.assertTrue(found_page)
         self.assertEqual(found_page.pk, page.pk)
Пример #3
0
 def test_get_page_from_request_with_page_preview(self):
     page = create_page("page", "nav_playground.html", "en")
     request = self.get_request('%s?preview' % page.get_absolute_url())
     request.user.is_staff = False
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         request = self.get_request('%s?preview&draft' % page.get_absolute_url())
         found_page = get_page_from_request(request)
         self.assertTrue(found_page)
         self.assertEqual(found_page.pk, page.pk)
Пример #4
0
 def test_get_page_from_request_with_page_preview(self):
     page = create_page("page", "nav_playground.html", "en")
     request = self.get_request('%s?preview' % page.get_absolute_url())
     request.user.is_staff = False
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
     superuser = self.get_superuser()
     with self.login_user_context(superuser):
         request = self.get_request('%s?preview&draft' % page.get_absolute_url())
         found_page = get_page_from_request(request)
         self.assertTrue(found_page)
         self.assertEqual(found_page.pk, page.pk)
Пример #5
0
 def test_get_page_from_request_on_cms_admin(self):
     page = create_page("page", "nav_playground.html", "en")
     request = self.get_request(
         reverse('admin:cms_page_change', args=(page.pk, )))
     found_page = get_page_from_request(request)
     self.assertTrue(found_page)
     self.assertEqual(found_page.pk, page.pk)
Пример #6
0
    def get_toolbar(self, request):
        form = RequestToolbarForm(request.GET or None)

        if not form.is_valid():
            return HttpResponseBadRequest('Invalid parameters')

        form_data = form.cleaned_data
        cms_path = form_data.get('cms_path') or request.path_info
        origin_url = urlparse(cms_path)
        attached_obj = form_data.get('attached_obj')
        current_page = get_page_from_request(request, use_path=origin_url.path, clean_path=True)

        if attached_obj and current_page and not (attached_obj == current_page):
            return HttpResponseBadRequest('Generic object does not match current page')

        data = QueryDict(query_string=origin_url.query, mutable=True)
        placeholders = request.GET.getlist("placeholders[]")

        if placeholders:
            data.setlist('placeholders[]', placeholders)

        request = copy.copy(request)
        request.GET = data
        request.current_page = current_page
        request.toolbar = CMSToolbar(request, request_path=origin_url.path)
        request.toolbar.set_object(attached_obj or current_page)
        return HttpResponse(request.toolbar.render())
Пример #7
0
 def test_18_get_page_from_request_on_cms_admin(self):
     page = self.create_page()
     request = self.get_request(
         reverse('admin:cms_page_change', args=(page.pk, )))
     found_page = get_page_from_request(request)
     self.assertTrue(found_page)
     self.assertEqual(found_page.pk, page.pk)
Пример #8
0
 def test_get_page_from_request_cached(self):
     mock_page = 'hello world'
     request = self.get_request(
         reverse('admin:sampleapp_category_change', args=(1, )))
     request._current_page_cache = mock_page
     page = get_page_from_request(request)
     self.assertEqual(page, mock_page)
 def check_local_link(self, url):
     if not url.startswith('/'):
         url = '/' + url
     if not url.startswith('/{}/'.format(DEFAULT_LANG)):
         url = '/{}'.format(DEFAULT_LANG) + url
     request = self.get_request(url)
     page = get_page_from_request(request)
     return page
Пример #10
0
 def test_get_page_from_request_cached(self):
     mock_page = 'hello world'
     request = self.get_request(
         reverse('admin:sampleapp_category_change', args=(1,))
     )
     request._current_page_cache = mock_page
     page = get_page_from_request(request)
     self.assertEqual(page, mock_page)
Пример #11
0
 def test_get_page_from_request_on_cms_admin_with_editplugin(self):
     page = create_page("page", "nav_playground.html", "en")
     request = self.get_request(
         reverse('admin:cms_page_change', args=(page.pk,)) + 'edit-plugin/42/'
     )
     found_page = get_page_from_request(request)
     self.assertTrue(found_page)
     self.assertEqual(found_page.pk, page.pk)
Пример #12
0
def item(request, name=None):
    selected_item = CatalogItemModel.objects.filter(name=name)[:1]
    selected_item = selected_item[0] if len(selected_item)>0 else None
    selected_category = selected_item.category if selected_item else []
    items = get_items([selected_category] if selected_item else [])

    page = get_page_from_request(request)
    return render_to_response('plugins/catalog/item.html', {'items':items, 'selected_category': selected_category, 'selected_item':selected_item, 'current_page':page}, context_instance=RequestContext(request))
Пример #13
0
 def test_18_get_page_from_request_on_cms_admin(self):
     page = self.create_page()
     request = self.get_request(
         reverse('admin:cms_page_change', args=(page.pk,))
     )
     found_page = get_page_from_request(request)
     self.assertTrue(found_page)
     self.assertEqual(found_page.pk, page.pk)
Пример #14
0
def category(request, name=None):
    selected_category = CatalogCategoryModel.objects.filter(name=name)[:1]
    if not selected_category and CatalogCategoryModel.objects.count()>0:
        selected_category = CatalogCategoryModel.objects.filter(parent=None).order_by('orderindex', 'name').all()[:1]
    items = get_items(selected_category)

    selected_category = selected_category[0] if selected_category else None
    page = get_page_from_request(request)
    return render_to_response('plugins/catalog/category.html', {'selected_category':selected_category, 'items': items, 'current_page':page}, context_instance=RequestContext(request))
Пример #15
0
 def __get__(self, request, obj_type=None):
     from cms.utils.page_resolver import get_page_from_request
     if not hasattr(request, '_current_page_cache'):
         request._current_page_cache = get_page_from_request(request)
         if not request._current_page_cache:
             # if this is in a apphook
             # find the page the apphook is attached to
             request._current_page_cache = applications_page_check(request)
     return request._current_page_cache
Пример #16
0
 def __get__(self, request, obj_type=None):
     from cms.utils.page_resolver import get_page_from_request
     if not hasattr(request, '_current_page_cache'):
         request._current_page_cache = get_page_from_request(request)
         if not request._current_page_cache:
             # if this is in a apphook
             # find the page the apphook is attached to
             request._current_page_cache = applications_page_check(request)
     return request._current_page_cache
Пример #17
0
 def test_get_page_without_final_slash(self):
     root = create_page("root", "nav_playground.html", "en", slug="root", published=True)
     page = create_page("page", "nav_playground.html", "en", slug="page", published=True, parent=root)
     root.publish()
     page = page.reload()
     page.publish()
     request = self.get_request("/en/page")
     found_page = get_page_from_request(request)
     self.assertIsNotNone(found_page)
     self.assertFalse(found_page.publisher_is_draft)
Пример #18
0
 def test_get_page_without_final_slash(self):
     root = create_page("root", "nav_playground.html", "en", slug="root", 
                        published=True)
     page = create_page("page", "nav_playground.html", "en", slug="page", 
                        published=True, parent=root)
     root.publish()
     page.publish()
     request = self.get_request('/page')
     found_page = get_page_from_request(request)
     self.assertFalse(found_page is None)
Пример #19
0
 def test_get_page_without_final_slash(self):
     root = create_page("root", "nav_playground.html", "en", slug="root", 
                        published=True)
     page = create_page("page", "nav_playground.html", "en", slug="page", 
                        published=True, parent=root)
     root.publish()
     page.publish()
     request = self.get_request('/page')
     found_page = get_page_from_request(request)
     self.assertFalse(found_page is None)
Пример #20
0
    def get(self, request, **kwargs):
        try:
            self.cms_page = get_page_from_request(request,
                                                  use_path=kwargs.get(
                                                      'path', ''))
            self.cms_page_title = self.cms_page.title_set.get(
                language=request.LANGUAGE_CODE)
        except AttributeError:
            return JsonResponse(data={}, status=404)

        return super(SpaCmsPageDetailApiView, self).get(request, **kwargs)
Пример #21
0
def get_page(request):
    # from cms.appresolver import applications_page_check
    from cms.utils.page_resolver import get_page_from_request

    if not hasattr(request, '_current_page_cache'):
        request._current_page_cache = get_page_from_request(request)
        if not request._current_page_cache:
            # if this is in a apphook
            # find the page the apphook is attached to
            request._current_page_cache = applications_page_check(request)
    return request._current_page_cache
Пример #22
0
 def test_get_page_without_final_slash(self):
     root = create_page("root", "nav_playground.html", "en", slug="root",
                        published=True)
     page = create_page("page", "nav_playground.html", "en", slug="page",
                        published=True, parent=root)
     root.publish('en')
     page = page.reload()
     page.publish('en')
     request = self.get_request('/en/page')
     found_page = get_page_from_request(request)
     self.assertIsNotNone(found_page)
     self.assertFalse(found_page.publisher_is_draft)
Пример #23
0
    def process_request(self, request):
        if self.is_admin(request):
            return None
        try:
            page = get_page_from_request(request)
            if page and page.redirects_to:
                if page.id == page.redirects_to.id:
                    return None #disable infinite recursion
                return redirect(page.redirects_to.page_to.get_absolute_url())
        except Exception:
            pass

        return None
Пример #24
0
    def test_ancestor_expired(self):
        yesterday = tz_now() - datetime.timedelta(days=1)
        tomorrow = tz_now() + datetime.timedelta(days=1)
        root = create_page("root", "nav_playground.html", "en", slug="root",
                           published=True)
        page_past = create_page("past", "nav_playground.html", "en", slug="past",
                                publication_end_date=yesterday,
                                published=True, parent=root)
        page_test = create_page("test", "nav_playground.html", "en", slug="test",
                                published=True, parent=page_past)
        page_future = create_page("future", "nav_playground.html", "en", slug="future",
                                  publication_date=tomorrow,
                                  published=True, parent=root)
        page_test_2 = create_page("test", "nav_playground.html", "en", slug="test",
                                  published=True, parent=page_future)

        request = self.get_request(page_test.get_absolute_url())
        page = get_page_from_request(request)
        self.assertEqual(page, None)

        request = self.get_request(page_test_2.get_absolute_url())
        page = get_page_from_request(request)
        self.assertEqual(page, None)
Пример #25
0
    def test_ancestor_expired(self):
        yesterday = tz_now() - datetime.timedelta(days=1)
        tomorrow = tz_now() + datetime.timedelta(days=1)
        root = create_page("root", "nav_playground.html", "en", slug="root",
                           published=True)
        page_past = create_page("past", "nav_playground.html", "en", slug="past",
                                publication_end_date=yesterday,
                                published=True, parent=root)
        page_test = create_page("test", "nav_playground.html", "en", slug="test",
                                published=True, parent=page_past)
        page_future = create_page("future", "nav_playground.html", "en", slug="future",
                                  publication_date=tomorrow,
                                  published=True, parent=root)
        page_test_2 = create_page("test", "nav_playground.html", "en", slug="test",
                                  published=True, parent=page_future)

        request = self.get_request(page_test.get_absolute_url())
        page = get_page_from_request(request)
        self.assertEqual(page, None)

        request = self.get_request(page_test_2.get_absolute_url())
        page = get_page_from_request(request)
        self.assertEqual(page, None)
Пример #26
0
def submit_form_view(request):
    cms_page = get_page_from_request(request)

    if not cms_page:
        return HttpResponseBadRequest()

    template = cms_page.get_template()

    context = {
        'current_app': resolve(request.path).namespace,
        'current_page': cms_page,
    }

    if request.method == 'POST':
        form_plugin_id = request.POST.get('form_plugin_id') or ''

        if not form_plugin_id.isdigit():
            # fail if plugin_id has been tampered with
            return HttpResponseBadRequest()

        try:
            # I believe this could be an issue as we don't check if the form submitted
            # is in anyway tied to this page.
            # But then we have a problem with static placeholders :(
            form_plugin = get_plugin_tree(FormPlugin, pk=form_plugin_id)
        except FormPlugin.DoesNotExist:
            return HttpResponseBadRequest()

        form_plugin_instance = form_plugin.get_plugin_instance()[1]
        # saves the form if it's valid
        form = form_plugin_instance.process_form(form_plugin, request)

        if form.is_valid():
            success_url = form_plugin_instance.get_success_url(
                instance=form_plugin)
            return HttpResponseRedirect(success_url)
    return render_to_response(template,
                              context,
                              context_instance=RequestContext(request))
Пример #27
0
def submit_form_view(request):
    cms_page = get_page_from_request(request)

    if not cms_page:
        return HttpResponseBadRequest()

    template = cms_page.get_template()

    context = {
        'current_app': resolve(request.path).namespace,
        'current_page': cms_page,
    }

    if request.method == 'POST':
        form_plugin_id = request.POST.get('form_plugin_id') or ''

        if not form_plugin_id.isdigit():
            # fail if plugin_id has been tampered with
            return HttpResponseBadRequest()

        try:
            # I believe this could be an issue as we don't check if the form submitted
            # is in anyway tied to this page.
            # But then we have a problem with static placeholders :(
            form_plugin = get_plugin_tree(FormPlugin, pk=form_plugin_id)
        except FormPlugin.DoesNotExist:
            return HttpResponseBadRequest()

        form_plugin_instance = form_plugin.get_plugin_instance()[1]
        # saves the form if it's valid
        form = form_plugin_instance.process_form(form_plugin, request)

        if form.is_valid():
            success_url = form_plugin_instance.get_success_url(instance=form_plugin)
            return HttpResponseRedirect(success_url)
    return render_to_response(template, context, context_instance=RequestContext(request))
Пример #28
0
def advices_item(request, id):
    item = get_object_or_404(CatalogAdviceModel, pk=id)
    page = get_page_from_request(request)
    return render_to_response('plugins/catalog/advices_item.html', {'item':item, 'current_page':page}, context_instance=RequestContext(request))
Пример #29
0
 def test_get_page_from_request_on_non_cms_admin(self):
     request = self.get_request(
         reverse('admin:sampleapp_category_change', args=(1,))
     )
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #30
0
 def test_get_page_from_request_on_cms_admin_nopage(self):
     request = self.get_request(
         reverse('admin:cms_page_change', args=(1,))
     )
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #31
0
 def test_get_page_from_request_on_cms_admin_nopage(self):
     request = self.get_request(reverse('admin:cms_page_change',
                                        args=(1, )))
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #32
0
 def test_get_page_from_request_nopage(self):
     request = self.get_request('/')
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #33
0
def advices_list(request):
    items = CatalogAdviceModel.objects.all()
    page = get_page_from_request(request)
    return render_to_response('plugins/catalog/advices_list.html', {'items':items, 'current_page':page}, context_instance=RequestContext(request))
Пример #34
0
 def test_get_page_from_request_on_non_cms_admin(self):
     request = self.get_request(
         reverse('admin:sampleapp_category_change', args=(1, )))
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #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.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)
Пример #36
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
Пример #37
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)
Пример #38
0
 def test_22_get_page_from_request_with_page_404(self):
     page = self.create_page(published=True)
     page.publish()
     request = self.get_request('/does-not-exist/')
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
Пример #39
0
 def test_22_get_page_from_request_with_page_404(self):
     page = self.create_page(published=True)
     page.publish()
     request = self.get_request('/does-not-exist/')
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
Пример #40
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)
Пример #41
0
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    response_timestamp = now()
    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 = get_page_cache(request)
        if cache_content is not None:
            content, headers, expires_datetime = cache_content
            response = HttpResponse(content)
            response._headers = headers
            # Recalculate the max-age header for this cached response
            max_age = int(
                (expires_datetime - response_timestamp).total_seconds() + 0.5)
            patch_cache_control(response, max_age=max_age)
            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.GET.get('language', None)
    if not current_language:
        current_language = request.POST.get('language', None)
    if current_language:
        current_language = get_language_code(current_language)
        if current_language not 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 current_language not 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 = []
    # this will return all languages in draft mode, and published only in live mode
    page_languages = list(page.get_published_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 current_language not 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:
                # 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 = []
            if app:
                for urlpatterns in get_app_urls(app.get_urls(page, current_language)):
                    pattern_list += urlpatterns
                try:
                    view, args, kwargs = resolve('/', tuple(pattern_list))
                    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)

    response = render_page(request, page, current_language=current_language, slug=slug)
    return response
Пример #42
0
 def test_get_page_from_request_nopage(self):
     request = self.get_request('/')
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #43
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)
Пример #44
0
 def test_get_page_from_request_with_page_404(self):
     page = create_page("page", "nav_playground.html", "en", published=True)
     page.publish('en')
     request = self.get_request('/does-not-exist/')
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
Пример #45
0
 def __get__(self, request, obj_type=None):
     from cms.utils.page_resolver import get_page_from_request
     if not hasattr(request, '_current_page_cache'):
         request._current_page_cache = get_page_from_request(request)
     return request._current_page_cache
Пример #46
0
 def test_get_page_from_request_on_cms_admin_with_editplugin_nopage(self):
     request = self.get_request(
         reverse('admin:cms_page_change', args=(1,)) + 'edit-plugin/42/'
     )
     page = get_page_from_request(request)
     self.assertEqual(page, None)
def details(request, slug):
    """
    The main view of the Django-CMS! Takes a request and a slug, renders the
    page.
    """
    response_timestamp = now()
    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 = get_page_cache(request)
        if cache_content is not None:
            content, headers, expires_datetime = cache_content
            response = HttpResponse(content)
            response._headers = headers
            # Recalculate the max-age header for this cached response
            max_age = int((expires_datetime -
                           response_timestamp).total_seconds() + 0.5)
            patch_cache_control(response, max_age=max_age)
            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.GET.get('language', None)
    if not current_language:
        current_language = request.POST.get('language', None)
    if current_language:
        current_language = get_language_code(current_language)
        if current_language not 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 current_language not 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 = []
    # this will return all languages in draft mode, and published only in live mode
    page_languages = list(page.get_published_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 current_language not 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:
                # 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)
    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.
            if hasattr(
                    request, 'toolbar'
            ) and request.user.is_staff and request.toolbar.edit_mode:
                request.toolbar.redirect_url = page_path
            else:
                return HttpResponseRedirect(page_path)

    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 = []
            if app:
                for urlpatterns in get_app_urls(
                        app.get_urls(page, current_language)):
                    pattern_list += urlpatterns
                try:
                    view, args, kwargs = resolve('/', tuple(pattern_list))
                    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)

    response = render_page(request,
                           page,
                           current_language=current_language,
                           slug=slug)
    return response
Пример #48
0
def video_catalog(request):
    items = CatalogVideoModel.objects.all()
    page = get_page_from_request(request)
    return render_to_response('plugins/catalog/video_catalog.html', {'items':items, 'current_page':page}, context_instance=RequestContext(request))
Пример #49
0
 def test_get_page_from_request_fakeadmin_nopage(self):
     request = self.get_request('/en/admin/')
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #50
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)
Пример #51
0
 def test_get_page_from_request_on_cms_admin_with_editplugin_nopage(self):
     request = self.get_request(
         reverse('admin:cms_page_change', args=(1, )) + 'edit-plugin/42/')
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #52
0
 def test_get_page_from_request_with_page_404(self):
     page = create_page("page", "nav_playground.html", "en", published=True)
     page.publish()
     request = self.get_request('/does-not-exist/')
     found_page = get_page_from_request(request)
     self.assertEqual(found_page, None)
Пример #53
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
Пример #54
0
 def test_get_page_from_request_fakeadmin_nopage(self):
     request = self.get_request('/en/admin/')
     page = get_page_from_request(request)
     self.assertEqual(page, None)
Пример #55
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)